From 574e8559b505ff3342050576156462f45bb474ca Mon Sep 17 00:00:00 2001 From: JP Cen Date: Wed, 12 Jun 2024 17:07:01 -0400 Subject: [PATCH] 0.9.29 --- main.js | 49518 ++++++++++++++++++++++++------------------------ manifest.json | 2 +- 2 files changed, 24862 insertions(+), 24658 deletions(-) diff --git a/main.js b/main.js index 31f6b64..540bae5 100644 --- a/main.js +++ b/main.js @@ -8306,7 +8306,7 @@ var require_lodash = __commonJS({ } return true; } - function isEqual2(value, other) { + function isEqual3(value, other) { return baseIsEqual(value, other); } function isEqualWith(value, other, customizer) { @@ -9419,7 +9419,7 @@ var require_lodash = __commonJS({ lodash.isDate = isDate4; lodash.isElement = isElement; lodash.isEmpty = isEmpty; - lodash.isEqual = isEqual2; + lodash.isEqual = isEqual3; lodash.isEqualWith = isEqualWith; lodash.isError = isError; lodash.isFinite = isFinite2; @@ -28581,7 +28581,7 @@ function iterateTreeInSelection(selection2, state, iterateFns) { } // src/adapters/obsidian/ui/editors/markdownView/flowEditor/flowEditor.tsx -var import_react178 = __toESM(require_react()); +var import_react180 = __toESM(require_react()); // src/adapters/obsidian/ui/editors/markdownView/flowEditor/flowStateFields.ts var import_state2 = require("@codemirror/state"); @@ -28646,17 +28646,20 @@ var T = class { "ordered-list": "Numbered List", todo: "To-do List", quote: "Quote", + internal: "Link to Note", + context: "Embed Existing Context", + flow: "Embed Note or Space", + board: "New Board", divider: "Divider", - note: "Link to Note", - link: "Link", + note: "Note Block", + link: "Web Link", callout: "Callout", bookmark: "Bookmark", - table: "Table", + table: "New Table", codeblock: "Code Block", toggle: "Toggle", emoji: "Emoji", image: "Image", - flow: "Linked Note", newNote: "New Note", tag: "Tag", makeMenu: "Flow Menu", @@ -28797,6 +28800,7 @@ var T = class { removeFromSpace: "Unpin from Space", removeFromWaypoints: "Unpin from Waypoints", editCode: "Edit Code", + editProperties: "Edit Properties", deleteProperty: "Delete Property", hideProperty: "Hide Property", unhideProperty: "Unhide Property", @@ -33046,12 +33050,16 @@ var SpaceManager = class { } saveTableSchema(path2, schemaId, saveSchema) { return this.adapterForPath(path2).saveTableSchema(path2, schemaId, saveSchema).then((f2) => { - return this.superstate.reloadContextByPath(path2); + if (f2) + return this.superstate.reloadContextByPath(path2); + return f2; }); } saveTable(path2, table, force) { return this.adapterForPath(path2).saveTable(path2, table, force).then((f2) => { - return this.superstate.reloadContextByPath(path2); + if (f2) + return this.superstate.reloadContextByPath(path2); + return f2; }); } deleteTable(path2, name317) { @@ -33078,13 +33086,13 @@ var SpaceManager = class { return this.adapterForPath(path2).readAllFrames(path2); } createFrame(path2, schema) { - return this.adapterForPath(path2).createFrame(path2, schema); + return this.adapterForPath(path2).createFrame(path2, schema).then((f2) => this.superstate.reloadFrames(this.spaceInfoForPath(path2))); } deleteFrame(path2, name317) { return this.adapterForPath(path2).deleteFrame(path2, name317); } saveFrameSchema(path2, schemaId, saveSchema) { - return this.adapterForPath(path2).saveFrameSchema(path2, schemaId, saveSchema); + return this.adapterForPath(path2).saveFrameSchema(path2, schemaId, saveSchema).then((f2) => this.superstate.reloadFrames(this.spaceInfoForPath(path2))); } saveFrame(path2, frame) { return this.adapterForPath(path2).saveFrame(path2, frame).then((f2) => this.superstate.reloadFrames(this.spaceInfoForPath(path2))).then((f2) => this.superstate.dispatchEvent("frameStateUpdated", { path: this.spaceInfoForPath(path2).path, schemaId: frame.schema.id })); @@ -33219,196 +33227,102 @@ var SpaceManager = class { } }; -// src/core/react/components/UI/Modals/InputModal.tsx -var import_react = __toESM(require_react()); -var InputModal = (props) => { - const [value, setValue] = (0, import_react.useState)(props.value); - const save = () => { - props.saveValue(value); - props.hide(); - }; - const ref2 = (0, import_react.useRef)(null); - (0, import_react.useEffect)(() => { - if (ref2?.current) { - ref2.current.focus(); - } - }, [ref2]); - return /* @__PURE__ */ import_react.default.createElement("div", { - className: "mk-layout-column mk-gap-8" - }, /* @__PURE__ */ import_react.default.createElement("input", { - ref: ref2, - value, - type: "text", - onChange: (e5) => setValue(e5.target.value), - className: "mk-input mk-input-large", - style: { - width: "100%" - }, - onKeyDown: (e5) => { - if (e5.key === "Enter") - save(); - } - }), /* @__PURE__ */ import_react.default.createElement("div", { - className: "mk-modal-actions" - }, /* @__PURE__ */ import_react.default.createElement("button", { - onClick: () => save() - }, props.saveLabel), /* @__PURE__ */ import_react.default.createElement("button", { - onClick: () => props.hide() - }, i18n_default.buttons.cancel))); +// src/core/utils/contexts/links.ts +var valueContainsLink = (link, value) => { + return parseMultiString(value).some((f2) => link == parseLinkString(f2)); }; - -// src/core/react/components/UI/Modals/StickerModal.tsx -var import_react2 = __toESM(require_react()); - -// src/utils/stickers.ts -var emojiFromString = (emoji) => { - let html; - try { - html = unifiedToNative(emoji); - } catch { - html = emoji; - } - return html; +var replaceLinkInValue = (link, newLink, value) => { + return serializeMultiString(parseMultiString(value).map((f2) => parseLinkString(f2) == link ? newLink : link)); }; -function parseStickerString(input) { - if (!input) { - return ["", ""]; +var removeLinkInValue = (link, value) => { + return serializeMultiString(parseMultiString(value).filter((f2) => f2 != link)); +}; +var linkColumns = (cols) => { + return cols.filter((f2) => f2.type.startsWith("link") || f2.type.startsWith("context")); +}; +var removeLinksInRow = (manager, row2, link, cols) => { + if (cols.length == 0) { + return row2; } - const match2 = input.match(/^(.*?)\s*\/\/\s*(.*)$/); - if (match2) { - return [match2[1], match2[2]]; - } else { - return ["", input]; + const deltaRow = cols.reduce((p, c3) => { + if (valueContainsLink(link, row2[c3.name])) { + const newValue = removeLinkInValue(link, row2[c3.name]); + manager.saveProperties(row2[PathPropertyName], { [c3.name]: parseMDBValue(c3.type, newValue) }); + return { ...p, [c3.name]: newValue }; + } + return p; + }, {}); + return { ...row2, ...deltaRow }; +}; +var renameLinksInRow = (manager, row2, link, newLink, cols) => { + if (cols.length == 0) { + return row2; } -} -var unifiedToNative = (unified) => { - const unicodes = unified.split("-"); - const codePoints = unicodes.map((u3) => `0x${u3}`); - return String.fromCodePoint(...codePoints); + const deltaRow = cols.reduce((p, c3) => { + if (valueContainsLink(link, row2[c3.name])) { + const newValue = replaceLinkInValue(link, newLink, row2[c3.name]); + manager.saveProperties(row2[PathPropertyName], { [c3.name]: parseMDBValue(c3.type, newValue) }); + return { ...p, [c3.name]: newValue }; + } + return p; + }, {}); + return { ...row2, ...deltaRow }; }; -// src/core/react/components/UI/Modals/StickerModal.tsx -var StickerModal = (props) => { - const [query, setQuery] = (0, import_react2.useState)(""); - const [allStickers, setAllStickers] = (0, import_react2.useState)([]); - const [stickers, setStickers] = (0, import_react2.useState)([]); - const [selectedSticker, setSelectedSticker] = (0, import_react2.useState)(null); - const htmlFromSticker = (sticker) => { - if (sticker.type == "emoji") { - return emojiFromString(sticker.html); - } - return sticker.html; +// src/core/utils/contexts/pathUpdates.ts +var renameRowForPath = (spaceTable, paths, newPath) => { + return { + ...spaceTable, + rows: spaceTable.rows.map( + (f2) => f2[PathPropertyName] == paths ? { ...f2, [PathPropertyName]: newPath } : f2 + ) }; - (0, import_react2.useEffect)(() => { - const _allImages = []; - _allImages.push(...props.ui.allStickers()); - setAllStickers(_allImages); - }, []); - const categories = (0, import_react2.useMemo)( - () => new Set(allStickers.map((f2) => f2.type)), - [allStickers] - ); - const [page, setPage] = (0, import_react2.useState)(1); - const loadNextPage = (0, import_react2.useCallback)(() => { - setPage((p) => p + 1); - }, [page]); - const loaderRef = (0, import_react2.useRef)(null); - (0, import_react2.useEffect)(() => { - const observer = new IntersectionObserver((entries) => { - const target = entries[0]; - if (target.isIntersecting) { - loadNextPage(); - } - }); - if (loaderRef.current) { - observer.observe(loaderRef.current); - } - return () => { - if (loaderRef.current) { - observer.unobserve(loaderRef.current); - } - }; - }, [loadNextPage]); - const [selectedCategory, setSelectedCategory] = (0, import_react2.useState)(null); - (0, import_react2.useEffect)(() => { - setStickers( - allStickers.filter( - (f2) => f2.name.includes(query) && (selectedCategory == null || f2.type == selectedCategory) - ).slice(0, page * 250) - ); - }, [query, allStickers, page, selectedCategory]); - const handleInputChange = (event) => { - setQuery(event.target.value); +}; +var removeRowForPath = (spaceTable, paths) => { + return { + ...spaceTable, + rows: spaceTable.rows.filter( + (f2) => f2[PathPropertyName] != paths + ) }; - const handleKeyDown = (event) => { - const currentIndex = selectedSticker; - if (event.key === "ArrowUp" && currentIndex > 0) { - setSelectedSticker(currentIndex - 1); - } else if (event.key === "ArrowDown" && currentIndex < stickers.length - 1) { - setSelectedSticker(currentIndex + 1); - } else if (event.key === "Enter") { - props.selectedSticker( - stickers[selectedSticker].type + "//" + stickers[selectedSticker].value - ); - props.hide(); - } +}; +var removeRowsForPath = (spaceTable, paths) => { + return { + ...spaceTable, + rows: spaceTable.rows.filter( + (f2) => !paths.includes(f2[PathPropertyName]) + ) + }; +}; +var reorderRowsForPath = (spaceTable, paths, index2) => { + const rows = spaceTable.rows.filter( + (f2) => paths.includes(f2[PathPropertyName]) + ); + return { + ...spaceTable, + rows: insertMulti(spaceTable.rows.filter( + (f2) => !paths.includes(f2[PathPropertyName]) + ), index2, rows) }; - const ref2 = (0, import_react2.useRef)(null); - (0, import_react2.useEffect)(() => { - if (ref2.current) { - ref2.current.focus(); - } - }, [ref2.current]); - return /* @__PURE__ */ import_react2.default.createElement(import_react2.default.Fragment, null, /* @__PURE__ */ import_react2.default.createElement("input", { - value: query, - onChange: handleInputChange, - onKeyDown: handleKeyDown, - placeholder: i18n_default.labels.findStickers, - className: "mk-input mk-input-large mk-border-bottom", - ref: ref2 - }), /* @__PURE__ */ import_react2.default.createElement("div", { - className: "mk-menu-sections" - }, /* @__PURE__ */ import_react2.default.createElement("div", { - onClick: () => setSelectedCategory(null), - className: `${selectedCategory == null ? "is-active" : ""} mk-menu-section` - }, "All"), [...categories].map((f2) => /* @__PURE__ */ import_react2.default.createElement("div", { - key: f2, - onClick: () => setSelectedCategory(f2), - className: `${selectedCategory == f2 ? "is-active" : ""} mk-menu-section` - }, f2))), /* @__PURE__ */ import_react2.default.createElement("div", { - className: "mk-layout-row mk-layout-wrap mk-gap-4 mk-padding-12 mk-layout-scroll" - }, stickers.map((icon, i4) => /* @__PURE__ */ import_react2.default.createElement("div", { - key: i4, - onClick: () => { - props.selectedSticker( - stickers[i4].type + "//" + stickers[i4].value - ); - props.hide(); - }, - className: selectedSticker === i4 ? "selected mk-padding-4 mk-border-radius-4 mk-hover" : "mk-padding-4 mk-border-radius-4 mk-hover" - }, /* @__PURE__ */ import_react2.default.createElement("div", { - dangerouslySetInnerHTML: { __html: htmlFromSticker(icon) }, - className: "mk-sticker" - }))), /* @__PURE__ */ import_react2.default.createElement("div", { - ref: loaderRef - }))); }; -var StickerModal_default = StickerModal; + +// src/core/utils/contexts/context.ts +var import_lodash5 = __toESM(require_lodash()); // node_modules/@dnd-kit/sortable/dist/sortable.esm.js -var import_react6 = __toESM(require_react()); +var import_react4 = __toESM(require_react()); // node_modules/@dnd-kit/core/dist/core.esm.js -var import_react5 = __toESM(require_react()); +var import_react3 = __toESM(require_react()); var import_react_dom = __toESM(require_react_dom()); // node_modules/@dnd-kit/utilities/dist/utilities.esm.js -var import_react3 = __toESM(require_react()); +var import_react = __toESM(require_react()); function useCombinedRefs() { for (var _len = arguments.length, refs = new Array(_len), _key = 0; _key < _len; _key++) { refs[_key] = arguments[_key]; } - return (0, import_react3.useMemo)( + return (0, import_react.useMemo)( () => (node) => { refs.forEach((ref2) => ref2(node)); }, @@ -33469,13 +33383,13 @@ function getOwnerDocument(target) { } return document; } -var useIsomorphicLayoutEffect = canUseDOM ? import_react3.useLayoutEffect : import_react3.useEffect; +var useIsomorphicLayoutEffect = canUseDOM ? import_react.useLayoutEffect : import_react.useEffect; function useEvent(handler) { - const handlerRef = (0, import_react3.useRef)(handler); + const handlerRef = (0, import_react.useRef)(handler); useIsomorphicLayoutEffect(() => { handlerRef.current = handler; }); - return (0, import_react3.useCallback)(function() { + return (0, import_react.useCallback)(function() { for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } @@ -33483,11 +33397,11 @@ function useEvent(handler) { }, []); } function useInterval() { - const intervalRef = (0, import_react3.useRef)(null); - const set = (0, import_react3.useCallback)((listener, duration) => { + const intervalRef = (0, import_react.useRef)(null); + const set = (0, import_react.useCallback)((listener, duration) => { intervalRef.current = setInterval(listener, duration); }, []); - const clear = (0, import_react3.useCallback)(() => { + const clear = (0, import_react.useCallback)(() => { if (intervalRef.current !== null) { clearInterval(intervalRef.current); intervalRef.current = null; @@ -33499,7 +33413,7 @@ function useLatestValue(value, dependencies314) { if (dependencies314 === void 0) { dependencies314 = [value]; } - const valueRef = (0, import_react3.useRef)(value); + const valueRef = (0, import_react.useRef)(value); useIsomorphicLayoutEffect(() => { if (valueRef.current !== value) { valueRef.current = value; @@ -33508,8 +33422,8 @@ function useLatestValue(value, dependencies314) { return valueRef; } function useLazyMemo(callback, dependencies314) { - const valueRef = (0, import_react3.useRef)(); - return (0, import_react3.useMemo)( + const valueRef = (0, import_react.useRef)(); + return (0, import_react.useMemo)( () => { const newValue = callback(valueRef.current); valueRef.current = newValue; @@ -33520,8 +33434,8 @@ function useLazyMemo(callback, dependencies314) { } function useNodeRef(onChange) { const onChangeHandler = useEvent(onChange); - const node = (0, import_react3.useRef)(null); - const setNodeRef = (0, import_react3.useCallback)( + const node = (0, import_react.useRef)(null); + const setNodeRef = (0, import_react.useCallback)( (element) => { if (element !== node.current) { onChangeHandler == null ? void 0 : onChangeHandler(element, node.current); @@ -33533,15 +33447,15 @@ function useNodeRef(onChange) { return [node, setNodeRef]; } function usePrevious(value) { - const ref2 = (0, import_react3.useRef)(); - (0, import_react3.useEffect)(() => { + const ref2 = (0, import_react.useRef)(); + (0, import_react.useEffect)(() => { ref2.current = value; }, [value]); return ref2.current; } var ids = {}; function useUniqueId(prefix, value) { - return (0, import_react3.useMemo)(() => { + return (0, import_react.useMemo)(() => { if (value) { return value; } @@ -33675,7 +33589,7 @@ function findFirstFocusableNode(element) { } // node_modules/@dnd-kit/accessibility/dist/accessibility.esm.js -var import_react4 = __toESM(require_react()); +var import_react2 = __toESM(require_react()); var hiddenStyles = { display: "none" }; @@ -33684,7 +33598,7 @@ function HiddenText(_ref) { id: id3, value } = _ref; - return import_react4.default.createElement("div", { + return import_react2.default.createElement("div", { id: id3, style: hiddenStyles }, value); @@ -33707,7 +33621,7 @@ function LiveRegion(_ref) { clipPath: "inset(100%)", whiteSpace: "nowrap" }; - return import_react4.default.createElement("div", { + return import_react2.default.createElement("div", { id: id3, style: visuallyHidden, role: "status", @@ -33716,8 +33630,8 @@ function LiveRegion(_ref) { }, announcement); } function useAnnouncement() { - const [announcement, setAnnouncement] = (0, import_react4.useState)(""); - const announce = (0, import_react4.useCallback)((value) => { + const [announcement, setAnnouncement] = (0, import_react2.useState)(""); + const announce = (0, import_react2.useCallback)((value) => { if (value != null) { setAnnouncement(value); } @@ -33729,10 +33643,10 @@ function useAnnouncement() { } // node_modules/@dnd-kit/core/dist/core.esm.js -var DndMonitorContext = /* @__PURE__ */ (0, import_react5.createContext)(null); +var DndMonitorContext = /* @__PURE__ */ (0, import_react3.createContext)(null); function useDndMonitor(listener) { - const registerListener = (0, import_react5.useContext)(DndMonitorContext); - (0, import_react5.useEffect)(() => { + const registerListener = (0, import_react3.useContext)(DndMonitorContext); + (0, import_react3.useEffect)(() => { if (!registerListener) { throw new Error("useDndMonitor must be used within a children of "); } @@ -33741,12 +33655,12 @@ function useDndMonitor(listener) { }, [listener, registerListener]); } function useDndMonitorProvider() { - const [listeners] = (0, import_react5.useState)(() => /* @__PURE__ */ new Set()); - const registerListener = (0, import_react5.useCallback)((listener) => { + const [listeners] = (0, import_react3.useState)(() => /* @__PURE__ */ new Set()); + const registerListener = (0, import_react3.useCallback)((listener) => { listeners.add(listener); return () => listeners.delete(listener); }, [listeners]); - const dispatch = (0, import_react5.useCallback)((_ref) => { + const dispatch = (0, import_react3.useCallback)((_ref) => { let { type, event @@ -33807,11 +33721,11 @@ function Accessibility(_ref) { announcement } = useAnnouncement(); const liveRegionId = useUniqueId("DndLiveRegion"); - const [mounted, setMounted] = (0, import_react5.useState)(false); - (0, import_react5.useEffect)(() => { + const [mounted, setMounted] = (0, import_react3.useState)(false); + (0, import_react3.useEffect)(() => { setMounted(true); }, []); - useDndMonitor((0, import_react5.useMemo)(() => ({ + useDndMonitor((0, import_react3.useMemo)(() => ({ onDragStart(_ref2) { let { active @@ -33866,10 +33780,10 @@ function Accessibility(_ref) { if (!mounted) { return null; } - const markup = import_react5.default.createElement(import_react5.default.Fragment, null, import_react5.default.createElement(HiddenText, { + const markup = import_react3.default.createElement(import_react3.default.Fragment, null, import_react3.default.createElement(HiddenText, { id: hiddenTextDescribedById, value: screenReaderInstructions.draggable - }), import_react5.default.createElement(LiveRegion, { + }), import_react3.default.createElement(LiveRegion, { id: liveRegionId, announcement })); @@ -33889,7 +33803,7 @@ var Action; function noop() { } function useSensor(sensor, options) { - return (0, import_react5.useMemo)( + return (0, import_react3.useMemo)( () => ({ sensor, options: options != null ? options : {} @@ -33901,7 +33815,7 @@ function useSensors() { for (var _len = arguments.length, sensors = new Array(_len), _key = 0; _key < _len; _key++) { sensors[_key] = arguments[_key]; } - return (0, import_react5.useMemo)( + return (0, import_react3.useMemo)( () => [...sensors].filter((sensor) => sensor != null), [...sensors] ); @@ -35125,15 +35039,15 @@ function useAutoScroller(_ref) { disabled: !enabled }); const [setAutoScrollInterval, clearAutoScrollInterval] = useInterval(); - const scrollSpeed = (0, import_react5.useRef)({ + const scrollSpeed = (0, import_react3.useRef)({ x: 0, y: 0 }); - const scrollDirection = (0, import_react5.useRef)({ + const scrollDirection = (0, import_react3.useRef)({ x: 0, y: 0 }); - const rect = (0, import_react5.useMemo)(() => { + const rect = (0, import_react3.useMemo)(() => { switch (activator) { case AutoScrollActivator.Pointer: return pointerCoordinates ? { @@ -35146,8 +35060,8 @@ function useAutoScroller(_ref) { return draggingRect; } }, [activator, draggingRect, pointerCoordinates]); - const scrollContainerRef = (0, import_react5.useRef)(null); - const autoScroll = (0, import_react5.useCallback)(() => { + const scrollContainerRef = (0, import_react3.useRef)(null); + const autoScroll = (0, import_react3.useCallback)(() => { const scrollContainer = scrollContainerRef.current; if (!scrollContainer) { return; @@ -35156,8 +35070,8 @@ function useAutoScroller(_ref) { const scrollTop = scrollSpeed.current.y * scrollDirection.current.y; scrollContainer.scrollBy(scrollLeft, scrollTop); }, []); - const sortedScrollableAncestors = (0, import_react5.useMemo)(() => order === TraversalOrder.TreeOrder ? [...scrollableAncestors].reverse() : scrollableAncestors, [order, scrollableAncestors]); - (0, import_react5.useEffect)( + const sortedScrollableAncestors = (0, import_react3.useMemo)(() => order === TraversalOrder.TreeOrder ? [...scrollableAncestors].reverse() : scrollableAncestors, [order, scrollableAncestors]); + (0, import_react3.useEffect)( () => { if (!enabled || !scrollableAncestors.length || !rect) { clearAutoScrollInterval(); @@ -35266,7 +35180,7 @@ function useCachedNode(draggableNodes, id3) { }, [node, id3]); } function useCombineActivators(sensors, getSyntheticHandler) { - return (0, import_react5.useMemo)(() => sensors.reduce((accumulator, sensor) => { + return (0, import_react3.useMemo)(() => sensors.reduce((accumulator, sensor) => { const { sensor: Sensor } = sensor; @@ -35294,16 +35208,16 @@ function useDroppableMeasuring(containers, _ref) { dependencies: dependencies314, config: config4 } = _ref; - const [queue, setQueue] = (0, import_react5.useState)(null); + const [queue, setQueue] = (0, import_react3.useState)(null); const { frequency, measure, strategy } = config4; - const containersRef = (0, import_react5.useRef)(containers); + const containersRef = (0, import_react3.useRef)(containers); const disabled = isDisabled(); const disabledRef = useLatestValue(disabled); - const measureDroppableContainers = (0, import_react5.useCallback)(function(ids2) { + const measureDroppableContainers = (0, import_react3.useCallback)(function(ids2) { if (ids2 === void 0) { ids2 = []; } @@ -35317,7 +35231,7 @@ function useDroppableMeasuring(containers, _ref) { return value.concat(ids2.filter((id3) => !value.includes(id3))); }); }, [disabledRef]); - const timeoutId = (0, import_react5.useRef)(null); + const timeoutId = (0, import_react3.useRef)(null); const droppableRects = useLazyMemo((previousValue) => { if (disabled && !dragging) { return defaultValue; @@ -35343,10 +35257,10 @@ function useDroppableMeasuring(containers, _ref) { } return previousValue; }, [containers, queue, dragging, disabled, measure]); - (0, import_react5.useEffect)(() => { + (0, import_react3.useEffect)(() => { containersRef.current = containers; }, [containers]); - (0, import_react5.useEffect)( + (0, import_react3.useEffect)( () => { if (disabled) { return; @@ -35355,7 +35269,7 @@ function useDroppableMeasuring(containers, _ref) { }, [dragging, disabled] ); - (0, import_react5.useEffect)( + (0, import_react3.useEffect)( () => { if (queue && queue.length > 0) { setQueue(null); @@ -35363,7 +35277,7 @@ function useDroppableMeasuring(containers, _ref) { }, [JSON.stringify(queue)] ); - (0, import_react5.useEffect)( + (0, import_react3.useEffect)( () => { if (disabled || typeof frequency !== "number" || timeoutId.current !== null) { return; @@ -35411,7 +35325,7 @@ function useMutationObserver(_ref) { disabled } = _ref; const handleMutations = useEvent(callback); - const mutationObserver = (0, import_react5.useMemo)(() => { + const mutationObserver = (0, import_react3.useMemo)(() => { if (disabled || typeof window === "undefined" || typeof window.MutationObserver === "undefined") { return void 0; } @@ -35420,7 +35334,7 @@ function useMutationObserver(_ref) { } = window; return new MutationObserver2(handleMutations); }, [handleMutations, disabled]); - (0, import_react5.useEffect)(() => { + (0, import_react3.useEffect)(() => { return () => mutationObserver == null ? void 0 : mutationObserver.disconnect(); }, [mutationObserver]); return mutationObserver; @@ -35431,7 +35345,7 @@ function useResizeObserver(_ref) { disabled } = _ref; const handleResize = useEvent(callback); - const resizeObserver = (0, import_react5.useMemo)( + const resizeObserver = (0, import_react3.useMemo)( () => { if (disabled || typeof window === "undefined" || typeof window.ResizeObserver === "undefined") { return void 0; @@ -35443,7 +35357,7 @@ function useResizeObserver(_ref) { }, [disabled] ); - (0, import_react5.useEffect)(() => { + (0, import_react3.useEffect)(() => { return () => resizeObserver == null ? void 0 : resizeObserver.disconnect(); }, [resizeObserver]); return resizeObserver; @@ -35455,7 +35369,7 @@ function useRect(element, measure, fallbackRect) { if (measure === void 0) { measure = defaultMeasure; } - const [rect, measureRect] = (0, import_react5.useReducer)(reducer3, null); + const [rect, measureRect] = (0, import_react3.useReducer)(reducer3, null); const mutationObserver = useMutationObserver({ callback(records) { if (!element) { @@ -35511,7 +35425,7 @@ function useRectDelta(rect) { } var defaultValue$1 = []; function useScrollableAncestors(node) { - const previousNode = (0, import_react5.useRef)(node); + const previousNode = (0, import_react3.useRef)(node); const ancestors = useLazyMemo((previousValue) => { if (!node) { return defaultValue$1; @@ -35521,15 +35435,15 @@ function useScrollableAncestors(node) { } return getScrollableAncestors(node); }, [node]); - (0, import_react5.useEffect)(() => { + (0, import_react3.useEffect)(() => { previousNode.current = node; }, [node]); return ancestors; } function useScrollOffsets(elements) { - const [scrollCoordinates, setScrollCoordinates] = (0, import_react5.useState)(null); - const prevElements = (0, import_react5.useRef)(elements); - const handleScroll = (0, import_react5.useCallback)((event) => { + const [scrollCoordinates, setScrollCoordinates] = (0, import_react3.useState)(null); + const prevElements = (0, import_react3.useRef)(elements); + const handleScroll = (0, import_react3.useCallback)((event) => { const scrollingElement = getScrollableElement(event.target); if (!scrollingElement) { return; @@ -35542,7 +35456,7 @@ function useScrollOffsets(elements) { return new Map(scrollCoordinates2); }); }, []); - (0, import_react5.useEffect)(() => { + (0, import_react3.useEffect)(() => { const previousElements = prevElements.current; if (elements !== previousElements) { cleanup(previousElements); @@ -35570,7 +35484,7 @@ function useScrollOffsets(elements) { }); } }, [handleScroll, elements]); - return (0, import_react5.useMemo)(() => { + return (0, import_react3.useMemo)(() => { if (elements.length) { return scrollCoordinates ? Array.from(scrollCoordinates.values()).reduce((acc, coordinates) => add(acc, coordinates), defaultCoordinates) : getScrollOffsets(elements); } @@ -35581,14 +35495,14 @@ function useScrollOffsetsDelta(scrollOffsets, dependencies314) { if (dependencies314 === void 0) { dependencies314 = []; } - const initialScrollOffsets = (0, import_react5.useRef)(null); - (0, import_react5.useEffect)( + const initialScrollOffsets = (0, import_react3.useRef)(null); + (0, import_react3.useEffect)( () => { initialScrollOffsets.current = null; }, dependencies314 ); - (0, import_react5.useEffect)(() => { + (0, import_react3.useEffect)(() => { const hasScrollOffsets = scrollOffsets !== defaultCoordinates; if (hasScrollOffsets && !initialScrollOffsets.current) { initialScrollOffsets.current = scrollOffsets; @@ -35600,7 +35514,7 @@ function useScrollOffsetsDelta(scrollOffsets, dependencies314) { return initialScrollOffsets.current ? subtract(scrollOffsets, initialScrollOffsets.current) : defaultCoordinates; } function useSensorSetup(sensors) { - (0, import_react5.useEffect)( + (0, import_react3.useEffect)( () => { if (!canUseDOM) { return; @@ -35626,7 +35540,7 @@ function useSensorSetup(sensors) { ); } function useSyntheticListeners(listeners, id3) { - return (0, import_react5.useMemo)(() => { + return (0, import_react3.useMemo)(() => { return listeners.reduce((acc, _ref) => { let { eventName, @@ -35640,7 +35554,7 @@ function useSyntheticListeners(listeners, id3) { }, [listeners, id3]); } function useWindowRect(element) { - return (0, import_react5.useMemo)(() => element ? getWindowClientRect(element) : null, [element]); + return (0, import_react3.useMemo)(() => element ? getWindowClientRect(element) : null, [element]); } var defaultValue$2 = []; function useRects(elements, measure) { @@ -35649,7 +35563,7 @@ function useRects(elements, measure) { } const [firstElement] = elements; const windowRect = useWindowRect(firstElement ? getWindow(firstElement) : null); - const [rects, measureRects] = (0, import_react5.useReducer)(reducer3, defaultValue$2); + const [rects, measureRects] = (0, import_react3.useReducer)(reducer3, defaultValue$2); const resizeObserver = useResizeObserver({ callback: measureRects }); @@ -35686,8 +35600,8 @@ function useDragOverlayMeasuring(_ref) { let { measure } = _ref; - const [rect, setRect] = (0, import_react5.useState)(null); - const handleResize = (0, import_react5.useCallback)((entries) => { + const [rect, setRect] = (0, import_react3.useState)(null); + const handleResize = (0, import_react3.useCallback)((entries) => { for (const { target } of entries) { @@ -35707,7 +35621,7 @@ function useDragOverlayMeasuring(_ref) { const resizeObserver = useResizeObserver({ callback: handleResize }); - const handleNodeChange = (0, import_react5.useCallback)((element) => { + const handleNodeChange = (0, import_react3.useCallback)((element) => { const node = getMeasurableNode(element); resizeObserver == null ? void 0 : resizeObserver.disconnect(); if (node) { @@ -35716,7 +35630,7 @@ function useDragOverlayMeasuring(_ref) { setRect(node ? measure(node) : null); }, [measure, resizeObserver]); const [nodeRef, setRef] = useNodeRef(handleNodeChange); - return (0, import_react5.useMemo)(() => ({ + return (0, import_react3.useMemo)(() => ({ nodeRef, rect, setRef @@ -35804,8 +35718,8 @@ var defaultInternalContext = { over: null, measureDroppableContainers: noop }; -var InternalContext = /* @__PURE__ */ (0, import_react5.createContext)(defaultInternalContext); -var PublicContext = /* @__PURE__ */ (0, import_react5.createContext)(defaultPublicContext); +var InternalContext = /* @__PURE__ */ (0, import_react3.createContext)(defaultInternalContext); +var PublicContext = /* @__PURE__ */ (0, import_react3.createContext)(defaultPublicContext); function getInitialState() { return { draggable: { @@ -35939,10 +35853,10 @@ function RestoreFocus(_ref) { active, activatorEvent, draggableNodes - } = (0, import_react5.useContext)(InternalContext); + } = (0, import_react3.useContext)(InternalContext); const previousActivatorEvent = usePrevious(activatorEvent); const previousActiveId = usePrevious(active == null ? void 0 : active.id); - (0, import_react5.useEffect)(() => { + (0, import_react3.useEffect)(() => { if (disabled) { return; } @@ -35993,7 +35907,7 @@ function applyModifiers(modifiers, _ref) { }, transform) : transform; } function useMeasuringConfiguration(config4) { - return (0, import_react5.useMemo)( + return (0, import_react3.useMemo)( () => ({ draggable: { ...defaultMeasuringConfiguration.draggable, @@ -36018,7 +35932,7 @@ function useLayoutShiftScrollCompensation(_ref) { initialRect, config: config4 = true } = _ref; - const initialized = (0, import_react5.useRef)(false); + const initialized = (0, import_react3.useRef)(false); const { x: x2, y: y3 @@ -36059,7 +35973,7 @@ function useLayoutShiftScrollCompensation(_ref) { } }, [activeNode, x2, y3, initialRect, measure]); } -var ActiveDraggableContext = /* @__PURE__ */ (0, import_react5.createContext)({ +var ActiveDraggableContext = /* @__PURE__ */ (0, import_react3.createContext)({ ...defaultCoordinates, scaleX: 1, scaleY: 1 @@ -36070,7 +35984,7 @@ var Status; Status2[Status2["Initializing"] = 1] = "Initializing"; Status2[Status2["Initialized"] = 2] = "Initialized"; })(Status || (Status = {})); -var DndContext = /* @__PURE__ */ (0, import_react5.memo)(function DndContext2(_ref) { +var DndContext = /* @__PURE__ */ (0, import_react3.memo)(function DndContext2(_ref) { var _sensorContext$curren, _dragOverlay$nodeRef$, _dragOverlay$rect, _over$rect; let { id: id3, @@ -36083,10 +35997,10 @@ var DndContext = /* @__PURE__ */ (0, import_react5.memo)(function DndContext2(_r modifiers, ...props } = _ref; - const store = (0, import_react5.useReducer)(reducer, void 0, getInitialState); + const store = (0, import_react3.useReducer)(reducer, void 0, getInitialState); const [state, dispatch] = store; const [dispatchMonitorEvent, registerMonitorListener] = useDndMonitorProvider(); - const [status, setStatus] = (0, import_react5.useState)(Status.Uninitialized); + const [status, setStatus] = (0, import_react3.useState)(Status.Uninitialized); const isInitialized = status === Status.Initialized; const { draggable: { @@ -36099,11 +36013,11 @@ var DndContext = /* @__PURE__ */ (0, import_react5.memo)(function DndContext2(_r } } = state; const node = activeId ? draggableNodes.get(activeId) : null; - const activeRects = (0, import_react5.useRef)({ + const activeRects = (0, import_react3.useRef)({ initial: null, translated: null }); - const active = (0, import_react5.useMemo)(() => { + const active = (0, import_react3.useMemo)(() => { var _node$data; return activeId != null ? { id: activeId, @@ -36111,12 +36025,12 @@ var DndContext = /* @__PURE__ */ (0, import_react5.memo)(function DndContext2(_r rect: activeRects } : null; }, [activeId, node]); - const activeRef = (0, import_react5.useRef)(null); - const [activeSensor, setActiveSensor] = (0, import_react5.useState)(null); - const [activatorEvent, setActivatorEvent] = (0, import_react5.useState)(null); + const activeRef = (0, import_react3.useRef)(null); + const [activeSensor, setActiveSensor] = (0, import_react3.useState)(null); + const [activatorEvent, setActivatorEvent] = (0, import_react3.useState)(null); const latestProps = useLatestValue(props, Object.values(props)); const draggableDescribedById = useUniqueId("DndDescribedBy", id3); - const enabledDroppableContainers = (0, import_react5.useMemo)(() => droppableContainers.getEnabled(), [droppableContainers]); + const enabledDroppableContainers = (0, import_react3.useMemo)(() => droppableContainers.getEnabled(), [droppableContainers]); const measuringConfiguration = useMeasuringConfiguration(measuring); const { droppableRects, @@ -36128,7 +36042,7 @@ var DndContext = /* @__PURE__ */ (0, import_react5.memo)(function DndContext2(_r config: measuringConfiguration.droppable }); const activeNode = useCachedNode(draggableNodes, activeId); - const activationCoordinates = (0, import_react5.useMemo)(() => activatorEvent ? getEventCoordinates(activatorEvent) : null, [activatorEvent]); + const activationCoordinates = (0, import_react3.useMemo)(() => activatorEvent ? getEventCoordinates(activatorEvent) : null, [activatorEvent]); const autoScrollOptions = getAutoScrollerOptions(); const initialActiveNodeRect = useInitialRect(activeNode, measuringConfiguration.draggable.measure); useLayoutShiftScrollCompensation({ @@ -36139,7 +36053,7 @@ var DndContext = /* @__PURE__ */ (0, import_react5.memo)(function DndContext2(_r }); const activeNodeRect = useRect(activeNode, measuringConfiguration.draggable.measure, initialActiveNodeRect); const containerNodeRect = useRect(activeNode ? activeNode.parentElement : null); - const sensorContext = (0, import_react5.useRef)({ + const sensorContext = (0, import_react3.useRef)({ activatorEvent: null, active: null, activeNode, @@ -36197,10 +36111,10 @@ var DndContext = /* @__PURE__ */ (0, import_react5.memo)(function DndContext2(_r pointerCoordinates }) : null; const overId = getFirstCollision(collisions, "id"); - const [over, setOver] = (0, import_react5.useState)(null); + const [over, setOver] = (0, import_react3.useState)(null); const appliedTranslate = usesDragOverlay ? modifiedTranslate : add(modifiedTranslate, activeNodeScrollDelta); const transform = adjustScale(appliedTranslate, (_over$rect = over == null ? void 0 : over.rect) != null ? _over$rect : null, activeNodeRect); - const instantiateSensor = (0, import_react5.useCallback)( + const instantiateSensor = (0, import_react3.useCallback)( (event, _ref2) => { let { sensor: Sensor, @@ -36317,7 +36231,7 @@ var DndContext = /* @__PURE__ */ (0, import_react5.memo)(function DndContext2(_r }, [draggableNodes] ); - const bindActivatorToSensorInstantiator = (0, import_react5.useCallback)((handler, sensor) => { + const bindActivatorToSensorInstantiator = (0, import_react3.useCallback)((handler, sensor) => { return (event, active2) => { const nativeEvent = event.nativeEvent; const activeDraggableNode = draggableNodes.get(active2); @@ -36344,7 +36258,7 @@ var DndContext = /* @__PURE__ */ (0, import_react5.memo)(function DndContext2(_r setStatus(Status.Initialized); } }, [activeNodeRect, status]); - (0, import_react5.useEffect)( + (0, import_react3.useEffect)( () => { const { onDragMove @@ -36378,7 +36292,7 @@ var DndContext = /* @__PURE__ */ (0, import_react5.memo)(function DndContext2(_r }, [scrollAdjustedTranslate.x, scrollAdjustedTranslate.y] ); - (0, import_react5.useEffect)( + (0, import_react3.useEffect)( () => { const { active: active2, @@ -36450,7 +36364,7 @@ var DndContext = /* @__PURE__ */ (0, import_react5.memo)(function DndContext2(_r scrollableAncestors, scrollableAncestorRects }); - const publicContext = (0, import_react5.useMemo)(() => { + const publicContext = (0, import_react3.useMemo)(() => { const context = { active, activeNode, @@ -36472,7 +36386,7 @@ var DndContext = /* @__PURE__ */ (0, import_react5.memo)(function DndContext2(_r }; return context; }, [active, activeNode, activeNodeRect, activatorEvent, collisions, containerNodeRect, dragOverlay, draggableNodes, droppableContainers, droppableRects, over, measureDroppableContainers, scrollableAncestors, scrollableAncestorRects, measuringConfiguration, measuringScheduled, windowRect]); - const internalContext = (0, import_react5.useMemo)(() => { + const internalContext = (0, import_react3.useMemo)(() => { const context = { activatorEvent, activators, @@ -36488,17 +36402,17 @@ var DndContext = /* @__PURE__ */ (0, import_react5.memo)(function DndContext2(_r }; return context; }, [activatorEvent, activators, active, activeNodeRect, dispatch, draggableDescribedById, draggableNodes, over, measureDroppableContainers]); - return import_react5.default.createElement(DndMonitorContext.Provider, { + return import_react3.default.createElement(DndMonitorContext.Provider, { value: registerMonitorListener - }, import_react5.default.createElement(InternalContext.Provider, { + }, import_react3.default.createElement(InternalContext.Provider, { value: internalContext - }, import_react5.default.createElement(PublicContext.Provider, { + }, import_react3.default.createElement(PublicContext.Provider, { value: publicContext - }, import_react5.default.createElement(ActiveDraggableContext.Provider, { + }, import_react3.default.createElement(ActiveDraggableContext.Provider, { value: transform - }, children)), import_react5.default.createElement(RestoreFocus, { + }, children)), import_react3.default.createElement(RestoreFocus, { disabled: (accessibility == null ? void 0 : accessibility.restoreFocus) === false - })), import_react5.default.createElement(Accessibility, { + })), import_react3.default.createElement(Accessibility, { ...accessibility, hiddenTextDescribedById: draggableDescribedById })); @@ -36517,7 +36431,7 @@ var DndContext = /* @__PURE__ */ (0, import_react5.memo)(function DndContext2(_r }; } }); -var NullContext = /* @__PURE__ */ (0, import_react5.createContext)(null); +var NullContext = /* @__PURE__ */ (0, import_react3.createContext)(null); var defaultRole = "button"; var ID_PREFIX = "Droppable"; function useDraggable(_ref) { @@ -36536,14 +36450,14 @@ function useDraggable(_ref) { ariaDescribedById, draggableNodes, over - } = (0, import_react5.useContext)(InternalContext); + } = (0, import_react3.useContext)(InternalContext); const { role = defaultRole, roleDescription = "draggable", tabIndex = 0 } = attributes != null ? attributes : {}; const isDragging = (active == null ? void 0 : active.id) === id3; - const transform = (0, import_react5.useContext)(isDragging ? ActiveDraggableContext : NullContext); + const transform = (0, import_react3.useContext)(isDragging ? ActiveDraggableContext : NullContext); const [node, setNodeRef] = useNodeRef(); const [activatorNode, setActivatorNodeRef] = useNodeRef(); const listeners = useSyntheticListeners(activators, id3); @@ -36566,7 +36480,7 @@ function useDraggable(_ref) { }, [draggableNodes, id3] ); - const memoizedAttributes = (0, import_react5.useMemo)(() => ({ + const memoizedAttributes = (0, import_react3.useMemo)(() => ({ role, tabIndex, "aria-disabled": disabled, @@ -36589,7 +36503,7 @@ function useDraggable(_ref) { }; } function useDndContext() { - return (0, import_react5.useContext)(PublicContext); + return (0, import_react3.useContext)(PublicContext); } var ID_PREFIX$1 = "Droppable"; var defaultResizeObserverConfig = { @@ -36608,13 +36522,13 @@ function useDroppable(_ref) { dispatch, over, measureDroppableContainers - } = (0, import_react5.useContext)(InternalContext); - const previous = (0, import_react5.useRef)({ + } = (0, import_react3.useContext)(InternalContext); + const previous = (0, import_react3.useRef)({ disabled }); - const resizeObserverConnected = (0, import_react5.useRef)(false); - const rect = (0, import_react5.useRef)(null); - const callbackId = (0, import_react5.useRef)(null); + const resizeObserverConnected = (0, import_react3.useRef)(false); + const rect = (0, import_react3.useRef)(null); + const callbackId = (0, import_react3.useRef)(null); const { disabled: resizeObserverDisabled, updateMeasurementsFor, @@ -36624,7 +36538,7 @@ function useDroppable(_ref) { ...resizeObserverConfig }; const ids2 = useLatestValue(updateMeasurementsFor != null ? updateMeasurementsFor : id3); - const handleResize = (0, import_react5.useCallback)( + const handleResize = (0, import_react3.useCallback)( () => { if (!resizeObserverConnected.current) { resizeObserverConnected.current = true; @@ -36644,7 +36558,7 @@ function useDroppable(_ref) { callback: handleResize, disabled: resizeObserverDisabled || !active }); - const handleNodeChange = (0, import_react5.useCallback)((newElement, previousElement) => { + const handleNodeChange = (0, import_react3.useCallback)((newElement, previousElement) => { if (!resizeObserver) { return; } @@ -36658,7 +36572,7 @@ function useDroppable(_ref) { }, [resizeObserver]); const [nodeRef, setNodeRef] = useNodeRef(handleNodeChange); const dataRef = useLatestValue(data2); - (0, import_react5.useEffect)(() => { + (0, import_react3.useEffect)(() => { if (!resizeObserver || !nodeRef.current) { return; } @@ -36687,7 +36601,7 @@ function useDroppable(_ref) { }, [id3] ); - (0, import_react5.useEffect)(() => { + (0, import_react3.useEffect)(() => { if (disabled !== previous.current.disabled) { dispatch({ type: Action.SetDroppableDisabled, @@ -36712,8 +36626,8 @@ function AnimationManager(_ref) { animation, children } = _ref; - const [clonedChildren, setClonedChildren] = (0, import_react5.useState)(null); - const [element, setElement] = (0, import_react5.useState)(null); + const [clonedChildren, setClonedChildren] = (0, import_react3.useState)(null); + const [element, setElement] = (0, import_react3.useState)(null); const previousChildren = usePrevious(children); if (!children && !clonedChildren && previousChildren) { setClonedChildren(previousChildren); @@ -36732,7 +36646,7 @@ function AnimationManager(_ref) { setClonedChildren(null); }); }, [animation, clonedChildren, element]); - return import_react5.default.createElement(import_react5.default.Fragment, null, children, clonedChildren ? (0, import_react5.cloneElement)(clonedChildren, { + return import_react3.default.createElement(import_react3.default.Fragment, null, children, clonedChildren ? (0, import_react3.cloneElement)(clonedChildren, { ref: setElement }) : null); } @@ -36746,9 +36660,9 @@ function NullifiedContextProvider(_ref) { let { children } = _ref; - return import_react5.default.createElement(InternalContext.Provider, { + return import_react3.default.createElement(InternalContext.Provider, { value: defaultInternalContext - }, import_react5.default.createElement(ActiveDraggableContext.Provider, { + }, import_react3.default.createElement(ActiveDraggableContext.Provider, { value: defaultTransform }, children)); } @@ -36760,7 +36674,7 @@ var defaultTransition = (activatorEvent) => { const isKeyboardActivator = isKeyboardEvent(activatorEvent); return isKeyboardActivator ? "transform 250ms ease" : void 0; }; -var PositionedOverlay = /* @__PURE__ */ (0, import_react5.forwardRef)((_ref, ref2) => { +var PositionedOverlay = /* @__PURE__ */ (0, import_react3.forwardRef)((_ref, ref2) => { let { as, activatorEvent, @@ -36791,7 +36705,7 @@ var PositionedOverlay = /* @__PURE__ */ (0, import_react5.forwardRef)((_ref, ref transition: typeof transition === "function" ? transition(activatorEvent) : transition, ...style }; - return import_react5.default.createElement(as, { + return import_react3.default.createElement(as, { className, style: styles2, ref: ref2 @@ -36981,7 +36895,7 @@ function createDefaultDropAnimation(options) { } var key = 0; function useKey(id3) { - return (0, import_react5.useMemo)(() => { + return (0, import_react3.useMemo)(() => { if (id3 == null) { return; } @@ -36989,7 +36903,7 @@ function useKey(id3) { return key; }, [id3]); } -var DragOverlay = /* @__PURE__ */ import_react5.default.memo((_ref) => { +var DragOverlay = /* @__PURE__ */ import_react3.default.memo((_ref) => { let { adjustScale: adjustScale2 = false, children, @@ -37015,7 +36929,7 @@ var DragOverlay = /* @__PURE__ */ import_react5.default.memo((_ref) => { scrollableAncestorRects, windowRect } = useDndContext(); - const transform = (0, import_react5.useContext)(ActiveDraggableContext); + const transform = (0, import_react3.useContext)(ActiveDraggableContext); const key2 = useKey(active == null ? void 0 : active.id); const modifiedTransform = applyModifiers(modifiers, { activatorEvent, @@ -37038,9 +36952,9 @@ var DragOverlay = /* @__PURE__ */ import_react5.default.memo((_ref) => { measuringConfiguration }); const ref2 = initialRect ? dragOverlay.setRef : void 0; - return import_react5.default.createElement(NullifiedContextProvider, null, import_react5.default.createElement(AnimationManager, { + return import_react3.default.createElement(NullifiedContextProvider, null, import_react3.default.createElement(AnimationManager, { animation: dropAnimation - }, active && key2 ? import_react5.default.createElement(PositionedOverlay, { + }, active && key2 ? import_react3.default.createElement(PositionedOverlay, { key: key2, id: active.id, ref: ref2, @@ -37181,7 +37095,7 @@ function getItemGap$1(clientRects, index2, activeIndex) { return nextRect ? nextRect.top - (currentRect.top + currentRect.height) : previousRect ? currentRect.top - (previousRect.top + previousRect.height) : 0; } var ID_PREFIX2 = "Sortable"; -var Context = /* @__PURE__ */ import_react6.default.createContext({ +var Context = /* @__PURE__ */ import_react4.default.createContext({ activeIndex: -1, containerId: ID_PREFIX2, disableTransforms: false, @@ -37212,11 +37126,11 @@ function SortableContext(_ref) { } = useDndContext(); const containerId = useUniqueId(ID_PREFIX2, id3); const useDragOverlay = Boolean(dragOverlay.rect !== null); - const items = (0, import_react6.useMemo)(() => userDefinedItems.map((item) => typeof item === "object" && "id" in item ? item.id : item), [userDefinedItems]); + const items = (0, import_react4.useMemo)(() => userDefinedItems.map((item) => typeof item === "object" && "id" in item ? item.id : item), [userDefinedItems]); const isDragging = active != null; const activeIndex = active ? items.indexOf(active.id) : -1; const overIndex = over ? items.indexOf(over.id) : -1; - const previousItemsRef = (0, import_react6.useRef)(items); + const previousItemsRef = (0, import_react4.useRef)(items); const itemsHaveChanged = !itemsEqual(items, previousItemsRef.current); const disableTransforms = overIndex !== -1 && activeIndex === -1 || itemsHaveChanged; const disabled = normalizeDisabled(disabledProp); @@ -37225,10 +37139,10 @@ function SortableContext(_ref) { measureDroppableContainers(items); } }, [itemsHaveChanged, items, isDragging, measureDroppableContainers]); - (0, import_react6.useEffect)(() => { + (0, import_react4.useEffect)(() => { previousItemsRef.current = items; }, [items]); - const contextValue = (0, import_react6.useMemo)( + const contextValue = (0, import_react4.useMemo)( () => ({ activeIndex, containerId, @@ -37242,7 +37156,7 @@ function SortableContext(_ref) { }), [activeIndex, containerId, disabled.draggable, disabled.droppable, disableTransforms, items, overIndex, droppableRects, useDragOverlay, strategy] ); - return import_react6.default.createElement(Context.Provider, { + return import_react4.default.createElement(Context.Provider, { value: contextValue }, children); } @@ -37298,8 +37212,8 @@ function useDerivedTransform(_ref) { node, rect } = _ref; - const [derivedTransform, setDerivedtransform] = (0, import_react6.useState)(null); - const previousIndex = (0, import_react6.useRef)(index2); + const [derivedTransform, setDerivedtransform] = (0, import_react4.useState)(null); + const previousIndex = (0, import_react4.useRef)(index2); useIsomorphicLayoutEffect(() => { if (!disabled && index2 !== previousIndex.current && node.current) { const initial = rect.current; @@ -37322,7 +37236,7 @@ function useDerivedTransform(_ref) { previousIndex.current = index2; } }, [disabled, index2, node, rect]); - (0, import_react6.useEffect)(() => { + (0, import_react4.useEffect)(() => { if (derivedTransform) { setDerivedtransform(null); } @@ -37351,10 +37265,10 @@ function useSortable(_ref) { overIndex, useDragOverlay, strategy: globalStrategy - } = (0, import_react6.useContext)(Context); + } = (0, import_react4.useContext)(Context); const disabled = normalizeLocalDisabled(localDisabled, globalDisabled); const index2 = items.indexOf(id3); - const data2 = (0, import_react6.useMemo)(() => ({ + const data2 = (0, import_react4.useMemo)(() => ({ sortable: { containerId, index: index2, @@ -37362,7 +37276,7 @@ function useSortable(_ref) { }, ...customData }), [containerId, customData, index2, items]); - const itemsAfterCurrentSortable = (0, import_react6.useMemo)(() => items.slice(items.indexOf(id3)), [items, id3]); + const itemsAfterCurrentSortable = (0, import_react4.useMemo)(() => items.slice(items.indexOf(id3)), [items, id3]); const { rect, node, @@ -37417,7 +37331,7 @@ function useSortable(_ref) { overIndex }) : index2; const activeId = active == null ? void 0 : active.id; - const previous = (0, import_react6.useRef)({ + const previous = (0, import_react4.useRef)({ activeId, items, newIndex, @@ -37444,7 +37358,7 @@ function useSortable(_ref) { node, rect }); - (0, import_react6.useEffect)(() => { + (0, import_react4.useEffect)(() => { if (isSorting && previous.current.newIndex !== newIndex) { previous.current.newIndex = newIndex; } @@ -37455,7 +37369,7 @@ function useSortable(_ref) { previous.current.items = items; } }, [isSorting, newIndex, containerId, items]); - (0, import_react6.useEffect)(() => { + (0, import_react4.useEffect)(() => { if (activeId === previous.current.activeId) { return; } @@ -37634,88 +37548,6 @@ function isAfter2(a4, b2) { return a4.data.current.sortable.index < b2.data.current.sortable.index; } -// src/core/utils/contexts/links.ts -var valueContainsLink = (link, value) => { - return parseMultiString(value).some((f2) => link == parseLinkString(f2)); -}; -var replaceLinkInValue = (link, newLink, value) => { - return serializeMultiString(parseMultiString(value).map((f2) => parseLinkString(f2) == link ? newLink : link)); -}; -var removeLinkInValue = (link, value) => { - return serializeMultiString(parseMultiString(value).filter((f2) => f2 != link)); -}; -var linkColumns = (cols) => { - return cols.filter((f2) => f2.type.startsWith("link") || f2.type.startsWith("context")); -}; -var removeLinksInRow = (manager, row2, link, cols) => { - if (cols.length == 0) { - return row2; - } - const deltaRow = cols.reduce((p, c3) => { - if (valueContainsLink(link, row2[c3.name])) { - const newValue = removeLinkInValue(link, row2[c3.name]); - manager.saveProperties(row2[PathPropertyName], { [c3.name]: parseMDBValue(c3.type, newValue) }); - return { ...p, [c3.name]: newValue }; - } - return p; - }, {}); - return { ...row2, ...deltaRow }; -}; -var renameLinksInRow = (manager, row2, link, newLink, cols) => { - if (cols.length == 0) { - return row2; - } - const deltaRow = cols.reduce((p, c3) => { - if (valueContainsLink(link, row2[c3.name])) { - const newValue = replaceLinkInValue(link, newLink, row2[c3.name]); - manager.saveProperties(row2[PathPropertyName], { [c3.name]: parseMDBValue(c3.type, newValue) }); - return { ...p, [c3.name]: newValue }; - } - return p; - }, {}); - return { ...row2, ...deltaRow }; -}; - -// src/core/utils/contexts/pathUpdates.ts -var renameRowForPath = (spaceTable, paths, newPath) => { - return { - ...spaceTable, - rows: spaceTable.rows.map( - (f2) => f2[PathPropertyName] == paths ? { ...f2, [PathPropertyName]: newPath } : f2 - ) - }; -}; -var removeRowForPath = (spaceTable, paths) => { - return { - ...spaceTable, - rows: spaceTable.rows.filter( - (f2) => f2[PathPropertyName] != paths - ) - }; -}; -var removeRowsForPath = (spaceTable, paths) => { - return { - ...spaceTable, - rows: spaceTable.rows.filter( - (f2) => !paths.includes(f2[PathPropertyName]) - ) - }; -}; -var reorderRowsForPath = (spaceTable, paths, index2) => { - const rows = spaceTable.rows.filter( - (f2) => paths.includes(f2[PathPropertyName]) - ); - return { - ...spaceTable, - rows: insertMulti(spaceTable.rows.filter( - (f2) => !paths.includes(f2[PathPropertyName]) - ), index2, rows) - }; -}; - -// src/core/utils/contexts/context.ts -var import_lodash5 = __toESM(require_lodash()); - // src/core/assets/placeholders.ts var uiPlaceholders = { "image-select": ` @@ -37763,7 +37595,7 @@ var isTouchScreen = (ui) => ui.primaryInteractionType() == 0 /* Touch */; var isPhone = (ui) => ui.getScreenType() == 0 /* Phone */; // src/core/react/components/UI/Menus/menu.tsx -var import_react7 = __toESM(require_react()); +var import_react5 = __toESM(require_react()); var MenuWrapper = (props) => { const sensors = useSensors( useSensor(MouseSensor, { @@ -37781,9 +37613,9 @@ var MenuWrapper = (props) => { coordinateGetter: sortableKeyboardCoordinates }) ); - const ref2 = import_react7.default.useRef(null); - const [isReady, setIsReady] = import_react7.default.useState(false); - (0, import_react7.useEffect)(() => { + const ref2 = import_react5.default.useRef(null); + const [isReady, setIsReady] = import_react5.default.useState(false); + (0, import_react5.useEffect)(() => { const onKeyDown = (e5) => { if (e5.key == "Escape") { props.hide(); @@ -37818,7 +37650,7 @@ var MenuWrapper = (props) => { props.ui.inputManager.off("keydown", onKeyDown); }; }, [props.hide]); - (0, import_react7.useEffect)(() => { + (0, import_react5.useEffect)(() => { if (!isPhone(props.ui)) return; const resizeObserver = new ResizeObserver((entries) => { @@ -37829,7 +37661,7 @@ var MenuWrapper = (props) => { resizeObserver.observe(ref2.current); return () => resizeObserver.disconnect(); }, [props.rect]); - return /* @__PURE__ */ import_react7.default.createElement(DndContext, { + return /* @__PURE__ */ import_react5.default.createElement(DndContext, { sensors, collisionDetection: closestCenter, measuring: { @@ -37837,7 +37669,7 @@ var MenuWrapper = (props) => { strategy: MeasuringStrategy.Always } } - }, /* @__PURE__ */ import_react7.default.createElement("div", { + }, /* @__PURE__ */ import_react5.default.createElement("div", { className: `mk-menu-wrapper ${!isPhone(props.ui) || isReady ? "mk-ready" : ""}`, ref: ref2 }, props.children)); @@ -37868,12 +37700,12 @@ var showMenu = (props) => { const root = props.ui.createRoot(portalElement); const updateRoot = (newProps) => { root.render( - /* @__PURE__ */ import_react7.default.createElement(MenuWrapper, { + /* @__PURE__ */ import_react5.default.createElement(MenuWrapper, { rect: props.rect, ui: props.ui, hide: () => hide(), anchor: props.anchor - }, (0, import_react7.cloneElement)(props.fc, { + }, (0, import_react5.cloneElement)(props.fc, { hide: () => hide(), ...newProps })) @@ -37909,13 +37741,13 @@ var showMenu = (props) => { }; // src/core/react/components/UI/Menus/selectMenu.tsx -var import_react8 = __toESM(require_react()); +var import_react6 = __toESM(require_react()); var showSelectMenu = (rect, optionProps, defaultAnchor, onHide) => { return showMenu({ ui: optionProps.ui, rect, anchor: defaultAnchor, - fc: /* @__PURE__ */ import_react8.default.createElement(SelectMenu_default, { + fc: /* @__PURE__ */ import_react6.default.createElement(SelectMenu_default, { ...optionProps }), onHide @@ -43292,7 +43124,7 @@ var generateCodeForProp = (value, isClosure, type) => { try { func = isMultiLine && !isClosure && !codeBlock.startsWith("(") && !isObject4 ? new Function(`with(this) { ${codeBlock} }`) : new Function(`with(this) { return ${codeBlock}; }`); } catch (e5) { - console.log(e5, value); + console.log(e5, codeBlock, value); } return func; }; @@ -45804,6 +45636,33 @@ var insertRows = (folder, rows, index2) => { var updateRowAtIndex = (folder, row2, index2) => { return { ...folder, rows: folder.rows.map((f2, i4) => i4 == index2 ? row2 : f2) }; }; +var updateTableValue = async (manager, space2, schema, index2, field, value, rank) => { + processTable( + manager, + space2, + schema, + async (f2) => { + let newMDB = { + ...f2, + rows: f2.rows.map( + (f3, i4) => i4 == index2 ? { + ...f3, + [field]: value + } : f3 + ) + }; + if (rank) + newMDB = { + ...newMDB, + rows: arrayMove(newMDB.rows, index2, rank) + }; + if (!import_lodash5.default.isEqual(f2, newMDB)) { + await saveContext(manager, space2, newMDB); + } + return newMDB; + } + ); +}; var updateContextValue = async (manager, space2, path2, field, value, _updateFunction, rank) => { manager.contextForSpace(space2.path).then( (f2) => { @@ -45952,6 +45811,15 @@ var addRowInTable = async (manager, row2, context, table, index2) => { return newDB; }); }; +var deleteRowInTable = async (manager, context, table, index2) => { + return processTable(manager, context, table, async (mdb, space2) => { + const newDB = { ...mdb, rows: mdb.rows.filter((f2, i4) => i4 != index2) }; + if (!import_lodash5.default.isEqual(mdb, newDB)) { + await saveContext(manager, space2, newDB); + } + return newDB; + }); +}; var renameLinkInContexts = async (manager, oldPath, newPath, spaces2) => { const promises = spaces2.map((space2) => { return processContext(manager, space2, async (mdb, space3) => { @@ -46027,6 +45895,212 @@ var removePathsInContext = async (manager, paths, space2) => { }); }; +// src/core/react/components/UI/Menus/contexts/rowContextMenu.tsx +var import_react74 = __toESM(require_react()); + +// src/core/react/components/UI/Menus/menu/SelectionMenu.tsx +var menuInput = (value, setValue) => ({ + name: "", + type: 2 /* Input */, + value, + onValueChange: setValue +}); +var menuSection = (name317) => ({ + name: name317, + type: -2 /* Section */, + disabled: true +}); +var menuSeparator = { + name: "", + type: -1 /* Separator */, + disabled: true +}; +var defaultMenu = (ui, options) => ({ + ui, + multi: false, + value: [], + editable: false, + options, + searchable: false, + showAll: true +}); + +// src/core/react/components/UI/Modals/InputModal.tsx +var import_react7 = __toESM(require_react()); +var InputModal = (props) => { + const [value, setValue] = (0, import_react7.useState)(props.value); + const save = () => { + props.saveValue(value); + props.hide(); + }; + const ref2 = (0, import_react7.useRef)(null); + (0, import_react7.useEffect)(() => { + if (ref2?.current) { + ref2.current.focus(); + } + }, [ref2]); + return /* @__PURE__ */ import_react7.default.createElement("div", { + className: "mk-layout-column mk-gap-8" + }, /* @__PURE__ */ import_react7.default.createElement("input", { + ref: ref2, + value, + type: "text", + onChange: (e5) => setValue(e5.target.value), + className: "mk-input mk-input-large", + style: { + width: "100%" + }, + onKeyDown: (e5) => { + if (e5.key === "Enter") + save(); + } + }), /* @__PURE__ */ import_react7.default.createElement("div", { + className: "mk-modal-actions" + }, /* @__PURE__ */ import_react7.default.createElement("button", { + onClick: () => save() + }, props.saveLabel), /* @__PURE__ */ import_react7.default.createElement("button", { + onClick: () => props.hide() + }, i18n_default.buttons.cancel))); +}; + +// src/core/react/components/UI/Modals/StickerModal.tsx +var import_react8 = __toESM(require_react()); + +// src/utils/stickers.ts +var emojiFromString = (emoji) => { + let html; + try { + html = unifiedToNative(emoji); + } catch { + html = emoji; + } + return html; +}; +function parseStickerString(input) { + if (!input) { + return ["", ""]; + } + const match2 = input.match(/^(.*?)\s*\/\/\s*(.*)$/); + if (match2) { + return [match2[1], match2[2]]; + } else { + return ["", input]; + } +} +var unifiedToNative = (unified) => { + const unicodes = unified.split("-"); + const codePoints = unicodes.map((u3) => `0x${u3}`); + return String.fromCodePoint(...codePoints); +}; + +// src/core/react/components/UI/Modals/StickerModal.tsx +var StickerModal = (props) => { + const [query, setQuery] = (0, import_react8.useState)(""); + const [allStickers, setAllStickers] = (0, import_react8.useState)([]); + const [stickers, setStickers] = (0, import_react8.useState)([]); + const [selectedSticker, setSelectedSticker] = (0, import_react8.useState)(null); + const htmlFromSticker = (sticker) => { + if (sticker.type == "emoji") { + return emojiFromString(sticker.html); + } + return sticker.html; + }; + (0, import_react8.useEffect)(() => { + const _allImages = []; + _allImages.push(...props.ui.allStickers()); + setAllStickers(_allImages); + }, []); + const categories = (0, import_react8.useMemo)( + () => new Set(allStickers.map((f2) => f2.type)), + [allStickers] + ); + const [page, setPage] = (0, import_react8.useState)(1); + const loadNextPage = (0, import_react8.useCallback)(() => { + setPage((p) => p + 1); + }, [page]); + const loaderRef = (0, import_react8.useRef)(null); + (0, import_react8.useEffect)(() => { + const observer = new IntersectionObserver((entries) => { + const target = entries[0]; + if (target.isIntersecting) { + loadNextPage(); + } + }); + if (loaderRef.current) { + observer.observe(loaderRef.current); + } + return () => { + if (loaderRef.current) { + observer.unobserve(loaderRef.current); + } + }; + }, [loadNextPage]); + const [selectedCategory, setSelectedCategory] = (0, import_react8.useState)(null); + (0, import_react8.useEffect)(() => { + setStickers( + allStickers.filter( + (f2) => f2.name.includes(query) && (selectedCategory == null || f2.type == selectedCategory) + ).slice(0, page * 250) + ); + }, [query, allStickers, page, selectedCategory]); + const handleInputChange = (event) => { + setQuery(event.target.value); + }; + const handleKeyDown = (event) => { + const currentIndex = selectedSticker; + if (event.key === "ArrowUp" && currentIndex > 0) { + setSelectedSticker(currentIndex - 1); + } else if (event.key === "ArrowDown" && currentIndex < stickers.length - 1) { + setSelectedSticker(currentIndex + 1); + } else if (event.key === "Enter") { + props.selectedSticker( + stickers[selectedSticker].type + "//" + stickers[selectedSticker].value + ); + props.hide(); + } + }; + const ref2 = (0, import_react8.useRef)(null); + (0, import_react8.useEffect)(() => { + if (ref2.current) { + ref2.current.focus(); + } + }, [ref2.current]); + return /* @__PURE__ */ import_react8.default.createElement(import_react8.default.Fragment, null, /* @__PURE__ */ import_react8.default.createElement("input", { + value: query, + onChange: handleInputChange, + onKeyDown: handleKeyDown, + placeholder: i18n_default.labels.findStickers, + className: "mk-input mk-input-large mk-border-bottom", + ref: ref2 + }), /* @__PURE__ */ import_react8.default.createElement("div", { + className: "mk-menu-sections" + }, /* @__PURE__ */ import_react8.default.createElement("div", { + onClick: () => setSelectedCategory(null), + className: `${selectedCategory == null ? "is-active" : ""} mk-menu-section` + }, "All"), [...categories].map((f2) => /* @__PURE__ */ import_react8.default.createElement("div", { + key: f2, + onClick: () => setSelectedCategory(f2), + className: `${selectedCategory == f2 ? "is-active" : ""} mk-menu-section` + }, f2))), /* @__PURE__ */ import_react8.default.createElement("div", { + className: "mk-layout-row mk-layout-wrap mk-gap-4 mk-padding-12 mk-layout-scroll" + }, stickers.map((icon, i4) => /* @__PURE__ */ import_react8.default.createElement("div", { + key: i4, + onClick: () => { + props.selectedSticker( + stickers[i4].type + "//" + stickers[i4].value + ); + props.hide(); + }, + className: selectedSticker === i4 ? "selected mk-padding-4 mk-border-radius-4 mk-hover" : "mk-padding-4 mk-border-radius-4 mk-hover" + }, /* @__PURE__ */ import_react8.default.createElement("div", { + dangerouslySetInnerHTML: { __html: htmlFromSticker(icon) }, + className: "mk-sticker" + }))), /* @__PURE__ */ import_react8.default.createElement("div", { + ref: loaderRef + }))); +}; +var StickerModal_default = StickerModal; + // node_modules/@babel/runtime/helpers/esm/extends.js function _extends() { _extends = Object.assign ? Object.assign.bind() : function(target) { @@ -87686,33 +87760,6 @@ var ConfirmationModal = (props) => { }, i18n_default.buttons.cancel))); }; -// src/core/react/components/UI/Menus/menu/SelectionMenu.tsx -var menuInput = (value, setValue) => ({ - name: "", - type: 2 /* Input */, - value, - onValueChange: setValue -}); -var menuSection = (name317) => ({ - name: name317, - type: -2 /* Section */, - disabled: true -}); -var menuSeparator = { - name: "", - type: -1 /* Separator */, - disabled: true -}; -var defaultMenu = (ui, options) => ({ - ui, - multi: false, - value: [], - editable: false, - options, - searchable: false, - showAll: true -}); - // src/core/utils/color/gradient.ts var typeName = (name317) => `${name317}-gradient(`; var stringifyGradient = (gradient) => { @@ -87972,8 +88019,7 @@ var showColorPickerMenu = (superstate, rect, value, setValue, stayOpen) => { }; // src/core/react/components/UI/Menus/properties/selectSpaceMenu.tsx -var showSpacesMenu = (e5, superstate, saveLink, includeDefaults, canAdd) => { - const offset2 = e5.target.getBoundingClientRect(); +var showSpacesMenu = (offset2, superstate, saveLink, includeDefaults, canAdd) => { const options = [...superstate.allSpaces(true)].filter((f2) => includeDefaults || f2.type != "default").map((f2) => ({ name: f2.name, value: f2.path, @@ -88023,8 +88069,9 @@ var triggerMultiPathMenu = (superstate, selectedPaths, e5) => { name: i18n_default.buttons.addToSpace, icon: "ui//pin", onClick: (e6) => { + const offset2 = e6.target.getBoundingClientRect(); showSpacesMenu( - e6, + offset2, superstate, (link) => { dropPathsInSpaceAtIndex( @@ -88078,7 +88125,8 @@ var triggerMultiPathMenu = (superstate, selectedPaths, e5) => { name: i18n_default.menu.moveFile, icon: "ui//paper-plane", onClick: (e6) => { - showSpacesMenu(e6, superstate, (link) => { + const offset2 = e6.target.getBoundingClientRect(); + showSpacesMenu(offset2, superstate, (link) => { paths.forEach((f2) => { movePathToSpace(superstate, f2, link); }); @@ -88138,8 +88186,9 @@ var showPathContextMenu = (superstate, path2, space2, rect, anchor, triggerRenam name: i18n_default.buttons.addToSpace, icon: "ui//pin", onClick: (e5) => { + const offset2 = e5.target.getBoundingClientRect(); showSpacesMenu( - e5, + offset2, superstate, (link) => { dropPathsInSpaceAtIndex(superstate, [path2], link, -1, "link"); @@ -88239,7 +88288,8 @@ var showPathContextMenu = (superstate, path2, space2, rect, anchor, triggerRenam name: i18n_default.menu.moveFile, icon: "ui//paper-plane", onClick: (e5) => { - showSpacesMenu(e5, superstate, (link) => { + const offset2 = e5.target.getBoundingClientRect(); + showSpacesMenu(offset2, superstate, (link) => { const item = superstate.pathsIndex.get(path2); superstate.spaceManager.renamePath(path2, movePath(path2, link)); }); @@ -88274,16032 +88324,14073 @@ var showPathContextMenu = (superstate, path2, space2, rect, anchor, triggerRenam return false; }; -// src/utils/sanitizers.ts -var sanitizeSQLStatement = (name317) => { - try { - return name317?.replace(/'/g, `''`); - } catch (e5) { - console.log(e5, name317); - return ""; +// src/core/react/components/UI/Menus/navigator/spaceContextMenu.tsx +var import_react47 = __toESM(require_react()); + +// src/core/react/components/SpaceEditor/SpacePropertyEditor.tsx +var import_react25 = __toESM(require_react()); + +// src/core/react/components/UI/Menus/contexts/newSpacePropertyMenu.tsx +var import_react24 = __toESM(require_react()); + +// node_modules/@lezer/javascript/node_modules/@lezer/common/dist/index.js +var DefaultBufferLength = 1024; +var nextPropID = 0; +var Range2 = class { + constructor(from, to2) { + this.from = from; + this.to = to2; } }; -var sanitizeColumnName = (name317) => { - if (name317?.charAt(0) == "_") { - return sanitizeColumnName(name317.substring(1)); +var NodeProp = class { + constructor(config4 = {}) { + this.id = nextPropID++; + this.perNode = !!config4.perNode; + this.deserialize = config4.deserialize || (() => { + throw new Error("This node type doesn't define a deserialize function"); + }); } - return name317?.replace(/"/g, ``); -}; -var sanitizeTableName = (name317) => { - return name317?.replace(/[^a-z0-9+]+/gi, ""); -}; -var illegalRe = /[\/\?<>\\:\*\|":]/g; -var controlRe = /[\x00-\x1f\x80-\x9f]/g; -var reservedRe = /^\.+$/; -var windowsReservedRe = /^(con|prn|aux|nul|com[0-9]|lpt[0-9])(\..*)?$/i; -var sanitizeFileName = (name317) => { - const replacement = ""; - return name317.replace(illegalRe, replacement).replace(controlRe, replacement).replace(reservedRe, replacement).replace(windowsReservedRe, replacement); -}; - -// src/core/superstate/api.ts -var API = class { - constructor(superstate) { - this.frame = { - update: (property, value, path2, saveState) => { - if (property.startsWith("$contexts")) { - const { context, prop: prop2 } = parseContextNode(property); - if (context && prop2) - this.context.update(context, path2, prop2, value); - } else { - const linkedNode = parseLinkedNode(property); - if (linkedNode.node && linkedNode.prop) { - saveState({ - [linkedNode.node]: { - props: { - [linkedNode.prop]: value - } - } - }); - } - } - } - }; - this.properties = { - color: (property, value) => { - if (property?.type?.includes("option")) { - const fields = parseFieldValue(property.value, property.type); - const option = fields.options?.find((f2) => f2.value == value); - if (option?.color.length > 0) - return option.color; - } - return "var(--mk-ui-background-contrast)"; - }, - sticker: (property) => stickerForField(property), - value: (type, value) => { - if (!type) - return value; - return parseMDBValue(type, value); - } - }; - this.path = { - label: (path2) => { - return this.superstate.pathsIndex.get(path2)?.label; - }, - open: (path2, target) => { - this.superstate.ui.openPath(path2, target); - }, - create: (name317, space2, type, content3) => { - if (content3 instanceof Promise) { - return content3.then((c3) => { - newPathInSpace(this.superstate, this.superstate.spacesIndex.get(space2), type, name317, true, c3); - }); - } - return newPathInSpace(this.superstate, this.superstate.spacesIndex.get(space2), type, name317, true, content3); - }, - setProperty: (path2, property, value) => { - if (value instanceof Promise) { - value.then((v2) => { - saveProperties(this.superstate, path2, { - [property]: v2 - }); - }); - return; - } - saveProperties(this.superstate, path2, { - [property]: value - }); - }, - contextMenu: (e5, path2) => { - showPathContextMenu(this.superstate, path2, null, { x: e5.clientX, y: e5.clientY, width: 0, height: 0 }); - } - }; - this.commands = { - run: (action, parameters, contexts) => { - return this.superstate.cli.runCommand(action, { instanceProps: { ...parameters, $api: this, $contexts: contexts }, props: {}, iterations: 0 }); - }, - formula: (formula, parameters, contexts) => { - return runFormulaWithContext(this.superstate.formulaContext, this.superstate.pathsIndex, formula, contexts.$properties, parameters, contexts?.$contexts?.$space?.path); - } - }; - this.buttonCommand = (action, parameters, contexts, saveState) => { - alert("Button actions have been upgraded, please rebind your buttons to use the new API."); - }; - this.table = { - select: (path2, table) => { - return this.superstate.spaceManager.readTable(path2, table)?.then((f2) => f2?.rows); - }, - update: (path2, table, index2, row2) => { - const space2 = this.superstate.spacesIndex.get(path2); - if (space2) - return updateTableRow(this.superstate.spaceManager, space2.space, table, index2, row2); - }, - insert: (path2, schema, row2) => { - const space2 = this.superstate.spacesIndex.get(path2); - if (space2) - return addRowInTable(this.superstate.spaceManager, row2, space2.space, schema); - return Promise.resolve(); - }, - create: (path2, table, properties3) => { - const newSchema = { - id: sanitizeTableName(table), - name: table, - type: "db" - }; - this.superstate.spaceManager.createTable( - path2, - newSchema - ); - } - }; - this.context = { - select: (path2, table) => { - return this.superstate.contextsIndex.get(path2)?.tables[table]?.rows; - }, - update: (path2, file, field, value) => { - const space2 = this.superstate.spacesIndex.get(path2); - if (space2) - updateValueInContext(this.superstate.spaceManager, file, field, value, space2.space); - }, - insert: (path2, schema, name317, row2) => { - if (schema == defaultContextSchemaID) { - newPathInSpace(this.superstate, this.superstate.spacesIndex.get(path2), "md", name317, true).then((f2) => { - if (row2) - saveProperties(this.superstate, f2, { - ...row2 - }); - }); - } - } + add(match2) { + if (this.perNode) + throw new RangeError("Can't add per-node props to node types"); + if (typeof match2 != "function") + match2 = NodeType.match(match2); + return (type) => { + let result = match2(type); + return result === void 0 ? null : [this, result]; }; - this.date = { - parse: (date) => { - return new Date(date?.replace(/-/g, "/").replace(/T.+/, "")); - }, - daysInMonth: (date) => { - return new Date(date.getFullYear(), date.getMonth() + 1, 0).getDate(); - }, - format: (date, format8) => { - return formatDate(this.superstate, date, format8 ?? "yyyy-MM-dd"); - }, - component: (date, component) => { - if (component == "year") - return date.getFullYear(); - if (component == "month") - return date.getMonth() + 1; - if (component == "day") - return date.getDate(); - if (component == "dayOfWeek") - return date.getDay(); - if (component == "hour") - return date.getHours(); - if (component == "minute") - return date.getMinutes(); - if (component == "second") - return date.getSeconds(); - }, - offset: (date, offset2, type) => { - const newDate = new Date(date); - if (type == "day") - newDate.setDate(newDate.getDate() + offset2); - if (type == "month") - newDate.setMonth(newDate.getMonth() + offset2); - if (type == "year") - newDate.setFullYear(newDate.getFullYear() + offset2); - return newDate; - }, - now: () => { - return new Date(); - }, - range: (start, end, format8) => { - const dates = []; - const current3 = new Date(start); - while (current3 <= end) { - dates.push(formatDate(this.superstate, current3, format8 ?? "yyyy-MM-dd")); - current3.setDate(current3.getDate() + 1); + } +}; +NodeProp.closedBy = new NodeProp({ deserialize: (str) => str.split(" ") }); +NodeProp.openedBy = new NodeProp({ deserialize: (str) => str.split(" ") }); +NodeProp.group = new NodeProp({ deserialize: (str) => str.split(" ") }); +NodeProp.contextHash = new NodeProp({ perNode: true }); +NodeProp.lookAhead = new NodeProp({ perNode: true }); +NodeProp.mounted = new NodeProp({ perNode: true }); +var noProps = /* @__PURE__ */ Object.create(null); +var NodeType = class { + constructor(name317, props, id3, flags = 0) { + this.name = name317; + this.props = props; + this.id = id3; + this.flags = flags; + } + static define(spec) { + let props = spec.props && spec.props.length ? /* @__PURE__ */ Object.create(null) : noProps; + let flags = (spec.top ? 1 : 0) | (spec.skipped ? 2 : 0) | (spec.error ? 4 : 0) | (spec.name == null ? 8 : 0); + let type = new NodeType(spec.name || "", props, spec.id, flags); + if (spec.props) + for (let src of spec.props) { + if (!Array.isArray(src)) + src = src(type); + if (src) { + if (src[0].perNode) + throw new RangeError("Can't store a per-node prop on a node type"); + props[src[0].id] = src[1]; } - return dates; } - }; - this.superstate = superstate; + return type; } -}; - -// src/core/types/indexMap.ts -var _IndexMap = class { - constructor() { - this.map = /* @__PURE__ */ new Map(); - this.invMap = /* @__PURE__ */ new Map(); + prop(prop2) { + return this.props[prop2.id]; } - get(key2) { - const result = this.map.get(key2); - if (result) { - return new Set(result); - } else { - return /* @__PURE__ */ new Set(); - } + get isTop() { + return (this.flags & 1) > 0; } - getInverse(value) { - return this.invMap.get(value) || _IndexMap.EMPTY_SET; + get isSkipped() { + return (this.flags & 2) > 0; } - set(key2, values2) { - if (!values2.size) { - this.delete(key2); - return this; + get isError() { + return (this.flags & 4) > 0; + } + get isAnonymous() { + return (this.flags & 8) > 0; + } + is(name317) { + if (typeof name317 == "string") { + if (this.name == name317) + return true; + let group = this.prop(NodeProp.group); + return group ? group.indexOf(name317) > -1 : false; } - const oldValues = this.map.get(key2); - if (oldValues) { - for (const value of oldValues) { - if (!values2.has(key2)) - this.invMap.get(value)?.delete(key2); + return this.id == name317; + } + static match(map4) { + let direct = /* @__PURE__ */ Object.create(null); + for (let prop2 in map4) + for (let name317 of prop2.split(" ")) + direct[name317] = map4[prop2]; + return (node) => { + for (let groups = node.prop(NodeProp.group), i4 = -1; i4 < (groups ? groups.length : 0); i4++) { + let found = direct[i4 < 0 ? node.name : groups[i4]]; + if (found) + return found; } - } - this.map.set(key2, values2); - for (const value of values2) { - if (!this.invMap.has(value)) - this.invMap.set(value, /* @__PURE__ */ new Set([key2])); - else - this.invMap.get(value)?.add(key2); - } - return this; + }; } - setInverse(key2, values2) { - if (!values2.size) { - this.deleteInverse(key2); - return this; - } - const oldValues = this.invMap.get(key2); - if (oldValues) { - for (const value of oldValues) { - if (!values2.has(key2)) - this.map.get(value)?.delete(key2); +}; +NodeType.none = new NodeType("", /* @__PURE__ */ Object.create(null), 0, 8); +var NodeSet = class { + constructor(types2) { + this.types = types2; + for (let i4 = 0; i4 < types2.length; i4++) + if (types2[i4].id != i4) + throw new RangeError("Node type ids should correspond to array positions when creating a node set"); + } + extend(...props) { + let newTypes = []; + for (let type of this.types) { + let newProps = null; + for (let source of props) { + let add4 = source(type); + if (add4) { + if (!newProps) + newProps = Object.assign({}, type.props); + newProps[add4[0].id] = add4[1]; + } } + newTypes.push(newProps ? new NodeType(type.name, newProps, type.id, type.flags) : type); } - this.invMap.set(key2, values2); - for (const value of values2) { - if (!this.map.has(value)) - this.map.set(value, /* @__PURE__ */ new Set([key2])); - else - this.map.get(value)?.add(key2); - } - return this; + return new NodeSet(newTypes); } - delete(key2) { - const oldValues = this.map.get(key2); - if (!oldValues) - return false; - this.map.delete(key2); - for (const value of oldValues) { - this.invMap.get(value)?.delete(key2); +}; +var CachedNode = /* @__PURE__ */ new WeakMap(); +var CachedInnerNode = /* @__PURE__ */ new WeakMap(); +var IterMode; +(function(IterMode4) { + IterMode4[IterMode4["ExcludeBuffers"] = 1] = "ExcludeBuffers"; + IterMode4[IterMode4["IncludeAnonymous"] = 2] = "IncludeAnonymous"; + IterMode4[IterMode4["IgnoreMounts"] = 4] = "IgnoreMounts"; + IterMode4[IterMode4["IgnoreOverlays"] = 8] = "IgnoreOverlays"; +})(IterMode || (IterMode = {})); +var Tree = class { + constructor(type, children, positions, length, props) { + this.type = type; + this.children = children; + this.positions = positions; + this.length = length; + this.props = null; + if (props && props.length) { + this.props = /* @__PURE__ */ Object.create(null); + for (let [prop2, value] of props) + this.props[typeof prop2 == "number" ? prop2 : prop2.id] = value; } - return true; } - deleteInverse(key2) { - const oldValues = this.invMap.get(key2); - if (!oldValues) - return false; - this.invMap.delete(key2); - for (const value of oldValues) { - this.map.get(value)?.delete(key2); + toString() { + let mounted = this.prop(NodeProp.mounted); + if (mounted && !mounted.overlay) + return mounted.tree.toString(); + let children = ""; + for (let ch of this.children) { + let str = ch.toString(); + if (str) { + if (children) + children += ","; + children += str; + } } - return true; - } - rename(oldKey, newKey) { - const oldValues = this.map.get(oldKey); - if (!oldValues) - return false; - this.delete(oldKey); - this.set(newKey, oldValues); - return true; + return !this.type.name ? children : (/\W/.test(this.type.name) && !this.type.isError ? JSON.stringify(this.type.name) : this.type.name) + (children.length ? "(" + children + ")" : ""); } - renameInverse(oldKey, newKey) { - const oldValues = this.invMap.get(oldKey); - if (!oldValues) - return false; - this.deleteInverse(oldKey); - this.setInverse(newKey, oldValues); - return true; + cursor(mode2 = 0) { + return new TreeCursor(this.topNode, mode2); } - clear() { - this.map.clear(); - this.invMap.clear(); + cursorAt(pos, side = 0, mode2 = 0) { + let scope = CachedNode.get(this) || this.topNode; + let cursor2 = new TreeCursor(scope); + cursor2.moveTo(pos, side); + CachedNode.set(this, cursor2._tree); + return cursor2; } -}; -var IndexMap = _IndexMap; -IndexMap.EMPTY_SET = Object.freeze(/* @__PURE__ */ new Set()); - -// src/core/utils/contexts/predicate/filter.ts -var listEquals = (value, filterValue) => { - const valueList = value ? parseMultiString(value) : []; - const strings = filterValue ? parseMultiString(filterValue) : []; - return strings.every((f2) => valueList.some((g) => g == f2)) && valueList.every((f2) => strings.some((g) => g == f2)); -}; -var stringEqual = (value, filterValue) => { - return value == filterValue; -}; -var empty2 = (value, filterValue) => { - return (value ?? "").length == 0; -}; -var stringCompare = (value, filterValue) => { - return (value ?? "").toLowerCase().includes((filterValue ?? "").toLowerCase()); -}; -var greaterThan = (value, filterValue) => { - return parseFloat(value) > parseFloat(filterValue); -}; -var lessThan = (value, filterValue) => { - return parseInt(value) < parseInt(filterValue); -}; -var dateAfter = (value, filterValue) => { - const dateValue = isNaN(Date.parse(value)) ? new Date(parseInt(value)) : new Date(value); - const dateFilterValue = isNaN(Date.parse(filterValue)) ? new Date(parseInt(filterValue)) : new Date(filterValue); - return dateValue.valueOf() >= dateFilterValue.valueOf(); -}; -var dateBefore = (value, filterValue) => { - const dateValue = isNaN(Date.parse(value)) ? new Date(parseInt(value)) : new Date(value); - const dateFilterValue = isNaN(Date.parse(filterValue)) ? new Date(parseInt(filterValue)) : new Date(filterValue); - return dateValue.valueOf() < dateFilterValue.valueOf(); -}; -var listIncludes = (value, filterValue) => { - const valueList = value ? parseMultiString(value) : []; - const strings = filterValue ? parseMultiString(filterValue) : []; - if (valueList.length == 0) - return false; - return strings.some((f2) => valueList.some((g) => g == f2)); -}; -var isSameDay2 = (value, filterValue) => { - if (!value) - return false; - const inputDate = new Date(`${value.toString().replace(".", ":")}`); - const currentDate = new Date(`${filterValue}`); - return inputDate.getMonth() === currentDate.getMonth() && inputDate.getDate() === currentDate.getDate(); -}; -var isSameDayAsToday = (value) => { - if (!value) - return false; - const inputDate = new Date(`${value.toString()}T00:00`); - const currentDate = new Date(); - return inputDate.getMonth() === currentDate.getMonth() && inputDate.getDate() === currentDate.getDate(); -}; -var filterReturnForCol = (col, filter4, row2, properties3) => { - if (!col) - return true; - const filterType = filterFnTypes[filter4?.fn]; - let result = true; - if (filterType && filterType.fn) { - const value = filter4.fType == "property" ? properties3[filter4.value] : filter4.value; - result = filterType.fn(row2[filter4.field], value); + get topNode() { + return new TreeNode2(this, 0, 0, null); } - return result; -}; - -// src/core/utils/contexts/predicate/filterFns/filterFnTypes.ts -var filterFnTypes = { - isNotEmpty: { - type: ["text", "file", "number", "option", "option-multi", "link", "link-multi", "image"], - fn: (v2, f2) => !empty2(v2, ""), - valueType: "none" - }, - isEmpty: { - type: ["text", "file", "number", "option", "option-multi", "link", "link-multi", "image"], - fn: (v2, f2) => empty2(v2, ""), - valueType: "none" - }, - include: { - fn: (v2, f2) => stringCompare(v2, f2), - type: ["text", "file", "link", "image"], - valueType: "text" - }, - notInclude: { - type: ["text", "file", "link", "image"], - fn: (v2, f2) => !stringCompare(v2, f2), - valueType: "text" - }, - is: { - type: ["text"], - fn: (v2, f2) => stringEqual(v2, f2), - valueType: "text" - }, - isNot: { - type: ["text"], - fn: (v2, f2) => !stringEqual(v2, f2), - valueType: "text" - }, - equal: { - type: ["number"], - fn: (v2, f2) => stringEqual(v2, f2), - valueType: "number" - }, - isLink: { - type: ["link", "context"], - fn: (v2, f2) => stringEqual(v2, f2), - valueType: "link" - }, - isNotLink: { - type: ["link", "context"], - fn: (v2, f2) => !stringEqual(v2, f2), - valueType: "link" - }, - isGreatThan: { - type: ["number"], - fn: (v2, f2) => greaterThan(v2, f2), - valueType: "number" - }, - isLessThan: { - type: ["number"], - fn: (v2, f2) => lessThan(v2, f2), - valueType: "number" - }, - isLessThanOrEqual: { - type: ["number"], - fn: (v2, f2) => !greaterThan(v2, f2), - valueType: "number" - }, - isGreatThanOrEqual: { - type: ["number"], - fn: (v2, f2) => !lessThan(v2, f2), - valueType: "number" - }, - dateBefore: { - type: ["date"], - fn: (v2, f2) => dateBefore(v2, f2), - valueType: "date" - }, - dateAfter: { - type: ["date"], - fn: (v2, f2) => dateAfter(v2, f2), - valueType: "date" - }, - isSameDate: { - type: ["date"], - fn: (v2, f2) => isSameDay2(v2, f2), - valueType: "date" - }, - isSameDateAsToday: { - type: ["date"], - fn: (v2, f2) => isSameDayAsToday(v2, f2), - valueType: "none" - }, - isExactList: { - type: ["option", "option-multi", "link-multi", "context-multi", "tags-multi"], - fn: (v2, f2) => listEquals(v2, f2), - valueType: "list" - }, - isAnyInList: { - type: ["option", "context", "link", "option-multi", "link-multi", "context-multi", "tags-multi"], - fn: (v2, f2) => listIncludes(v2, f2), - valueType: "list" - }, - isNoneInList: { - type: ["option", "context", "link", "option-multi", "link-multi", "context-multi", "tags-multi"], - fn: (v2, f2) => !listIncludes(v2, f2), - valueType: "list" - }, - isTrue: { - type: ["boolean"], - fn: (v2, f2) => v2 == "true", - valueType: "none" - }, - isFalse: { - type: ["boolean"], - fn: (v2, f2) => v2 != "true", - valueType: "none" + resolve(pos, side = 0) { + let node = resolveNode(CachedNode.get(this) || this.topNode, pos, side, false); + CachedNode.set(this, node); + return node; } -}; - -// src/core/utils/spaces/query.ts -var filterPathsForAny = (paths, filters, props) => { - const newArray = filters.reduce((p, c3) => { - const [result, remaining] = p; - const filteredPaths = c3.type == "context" ? filterContext(remaining, c3, props) : c3.type == "path" ? filterPathCache(remaining, c3, props) : c3.type == "frontmatter" ? filterFM(remaining, c3, props) : filterPathProperties(remaining, c3, props); - const diffArray = remaining.filter((x2) => !filteredPaths.includes(x2)); - return [[...result, ...filteredPaths], diffArray]; - }, [[], paths]); - return newArray[0]; -}; -var filterPathsForAll = (paths, filters, props) => { - return filters.reduce((p, c3) => { - return c3.type == "context" ? filterContext(p, c3, props) : c3.type == "path" ? filterPathCache(p, c3, props) : c3.type == "frontmatter" ? filterFM(p, c3, props) : filterPathProperties(p, c3, props); - }, paths); -}; -var filterContext = (paths, def, props) => { - const filterFn = filterFnTypes[def.fn]; - if (!filterFn || filterFn.valueType != "none" && def.value.length == 0) { - return []; + resolveInner(pos, side = 0) { + let node = resolveNode(CachedInnerNode.get(this) || this.topNode, pos, side, true); + CachedInnerNode.set(this, node); + return node; } - return paths.filter((f2) => { - const [contextPath, field] = def.field.split("."); - const fm = f2.metadata?.property; - if (!f2.spaces?.includes(contextPath)) - return false; - if (!fm || !fm[field]) { - return false; - } - let result = true; - if (filterFn) { - const value = def.fType == "property" ? props[def.value] : def.value; - result = filterFn.fn(parseProperty(field, fm[field]), value); + iterate(spec) { + let { enter, leave, from = 0, to: to2 = this.length } = spec; + for (let c3 = this.cursor((spec.mode || 0) | IterMode.IncludeAnonymous); ; ) { + let entered = false; + if (c3.from <= to2 && c3.to >= from && (c3.type.isAnonymous || enter(c3) !== false)) { + if (c3.firstChild()) + continue; + entered = true; + } + for (; ; ) { + if (entered && leave && !c3.type.isAnonymous) + leave(c3); + if (c3.nextSibling()) + break; + if (!c3.parent()) + return; + entered = true; + } } + } + prop(prop2) { + return !prop2.perNode ? this.type.prop(prop2) : this.props ? this.props[prop2.id] : void 0; + } + get propValues() { + let result = []; + if (this.props) + for (let id3 in this.props) + result.push([+id3, this.props[id3]]); return result; - }); + } + balance(config4 = {}) { + return this.children.length <= 8 ? this : balanceRange(NodeType.none, this.children, this.positions, 0, this.children.length, 0, this.length, (children, positions, length) => new Tree(this.type, children, positions, length, this.propValues), config4.makeTree || ((children, positions, length) => new Tree(NodeType.none, children, positions, length))); + } + static build(data2) { + return buildTree(data2); + } }; -var filterFM = (paths, def, props) => { - const filterFn = filterFnTypes[def.fn]; - if (!filterFn || filterFn.valueType != "none" && def.value.length == 0) { - return []; +Tree.empty = new Tree(NodeType.none, [], [], 0); +var FlatBufferCursor = class { + constructor(buffer, index2) { + this.buffer = buffer; + this.index = index2; + } + get id() { + return this.buffer[this.index - 4]; + } + get start() { + return this.buffer[this.index - 3]; + } + get end() { + return this.buffer[this.index - 2]; + } + get size() { + return this.buffer[this.index - 1]; + } + get pos() { + return this.index; + } + next() { + this.index -= 4; + } + fork() { + return new FlatBufferCursor(this.buffer, this.index); } - return paths.filter((f2) => { - const fm = f2.metadata?.property; - if (!fm || fm[def.field] === void 0) { - return false; - } - let result = true; - if (filterFn) { - const value = def.fType == "property" ? props[def.value] : def.value; - result = filterFn.fn(parseProperty(def.field, fm[def.field]), value); - } - return result; - }); }; -var filterPathCache = (paths, def, props) => { - const filterFn = filterFnTypes[def.fn]; - if (!filterFn || filterFn.valueType != "none" && def.value.length == 0) { - return []; +var TreeBuffer = class { + constructor(buffer, length, set) { + this.buffer = buffer; + this.length = length; + this.set = set; } - return paths.filter((f2) => { - let value = ""; - if (def.field == "outlinks") { - value = serializeMultiString(f2.outlinks ?? []); - } else if (def.field == "inlinks") { - value = serializeMultiString(f2.inlinks ?? []); - } else if (def.field == "tags") { - value = serializeMultiString(f2.tags ?? []); - } - let result = true; - if (filterFn) { - const defValue = def.fType == "property" ? props[def.value] : def.value; - result = filterFn.fn(value, defValue); + get type() { + return NodeType.none; + } + toString() { + let result = []; + for (let index2 = 0; index2 < this.buffer.length; ) { + result.push(this.childString(index2)); + index2 = this.buffer[index2 + 3]; } - return result; - }); -}; -var filterPathProperties = (paths, def, props) => { - const filterFn = filterFnTypes[def.fn]; - if (!filterFn || filterFn.valueType != "none" && def.value.length == 0) { - return []; + return result.join(","); } - return paths.filter((f2) => { - let result = true; - if (filterFn) { - const value = def.fType == "property" ? props[def.value] : def.value; - result = filterFn.fn(f2.metadata?.[def.type]?.[def.field], value); + childString(index2) { + let id3 = this.buffer[index2], endIndex = this.buffer[index2 + 3]; + let type = this.set.types[id3], result = type.name; + if (/\W/.test(result) && !type.isError) + result = JSON.stringify(result); + index2 += 4; + if (endIndex == index2) + return result; + let children = []; + while (index2 < endIndex) { + children.push(this.childString(index2)); + index2 = this.buffer[index2 + 3]; } - return result; - }); -}; -var pathByDef = (filters, path2, props) => { - const pathInFilter = filters.reduce((p, c3) => { - if (!p || c3.filters.length == 0) - return false; - const result = c3.type == "any" ? filterPathsForAny([path2], c3.filters, props).length > 0 : filterPathsForAll([path2], c3.filters, props).length > 0; - return result; - }, true); - return pathInFilter; -}; - -// src/core/utils/superstate/parser.ts -var parsePathState = (cache2) => { - return safelyParseJSON(cache2); -}; - -// src/core/utils/superstate/serializer.ts -var serializePathState = (pathState) => { - return JSON.stringify(pathState); -}; -var stringifyJob = (job) => `${job.type}:${job.path}`; - -// src/core/superstate/superstate.ts -var import_lodash9 = __toESM(require_lodash()); - -// src/schemas/kits/slides.ts -var slidesNode = { - def: { - icon: "ui//gem" - }, - node: { - icon: "ui//gem", - schemaId: "slides", - parentId: "", - name: "Slides", - rank: 0, - id: "slides", - styles: {}, - type: "slides", - props: { - value: "" - }, - types: { - value: "string" + return result + "(" + children.join(",") + ")"; + } + findChild(startIndex, endIndex, dir, pos, side) { + let { buffer } = this, pick = -1; + for (let i4 = startIndex; i4 != endIndex; i4 = buffer[i4 + 3]) { + if (checkSide(side, pos, buffer[i4 + 1], buffer[i4 + 2])) { + pick = i4; + if (dir > 0) + break; + } } + return pick; } -}; -var slideNode = { - def: { - icon: "ui//gem" - }, - node: { - icon: "ui//gem", - schemaId: "slide", - parentId: "", - name: "Slide", - rank: 0, - id: "slide", - styles: {}, - type: "slide", - props: { - value: "" - }, - types: { - value: "string" + slice(startI, endI, from, to2) { + let b2 = this.buffer; + let copy = new Uint16Array(endI - startI); + for (let i4 = startI, j = 0; i4 < endI; ) { + copy[j++] = b2[i4++]; + copy[j++] = b2[i4++] - from; + copy[j++] = b2[i4++] - from; + copy[j++] = b2[i4++] - startI; } + return new TreeBuffer(copy, to2 - from, this.set); } }; -var deltaNode = { - def: { - icon: "ui//gem" - }, - node: { - icon: "ui//gem", - schemaId: "delta", - parentId: "", - name: "Delta", - rank: 0, - id: "delta", - styles: {}, - type: "delta" +function checkSide(side, pos, from, to2) { + switch (side) { + case -2: + return from < pos; + case -1: + return to2 >= pos && from < pos; + case 0: + return from < pos && to2 > pos; + case 1: + return from <= pos && to2 > pos; + case 2: + return to2 > pos; + case 4: + return true; } -}; - -// src/schemas/kits/ui.ts -var groupableTypes = ["content", "group", "container", "column", "list", "slides", "slide"]; -var listNode = { - def: { - id: "list", - icon: "ui//list" - }, - node: { - icon: "ui//list", - schemaId: "list", - parentId: "", - name: "List", - rank: 0, - id: "list", - styles: {}, - type: "list", - props: { - value: "" - }, - types: { - value: "multi" +} +function enterUnfinishedNodesBefore(node, pos) { + let scan = node.childBefore(pos); + while (scan) { + let last = scan.lastChild; + if (!last || last.to != scan.to) + break; + if (last.type.isError && last.from == last.to) { + node = scan; + scan = last.prevSibling; + } else { + scan = last; } } -}; -var listItemNode = { - def: { - id: "listItem", - icon: "ui//list" - }, - node: { - icon: "ui//list", - schemaId: "listItem", - parentId: "", - name: "List Item", - rank: 0, - id: "listItem", - styles: {}, - type: "listItem", - props: { - value: "" - }, - types: { - value: "object" + return node; +} +function resolveNode(node, pos, side, overlays) { + var _a; + while (node.from == node.to || (side < 1 ? node.from >= pos : node.from > pos) || (side > -1 ? node.to <= pos : node.to < pos)) { + let parent = !overlays && node instanceof TreeNode2 && node.index < 0 ? null : node.parent; + if (!parent) + return node; + node = parent; + } + let mode2 = overlays ? 0 : IterMode.IgnoreOverlays; + if (overlays) + for (let scan = node, parent = scan.parent; parent; scan = parent, parent = scan.parent) { + if (scan instanceof TreeNode2 && scan.index < 0 && ((_a = parent.enter(pos, side, mode2)) === null || _a === void 0 ? void 0 : _a.from) != scan.from) + node = parent; } + for (; ; ) { + let inner = node.enter(pos, side, mode2); + if (!inner) + return node; + node = inner; } -}; -var dividerNode = { - def: { - id: "divider", - icon: "ui//minus", - description: i18n_default.frames.divider.description - }, - node: { - icon: "ui//minus", - schemaId: "divider", - parentId: "", - name: i18n_default.frames.divider.label, - rank: 0, - id: "divider", - type: "frame", - styles: { - width: `'100%'`, - height: `'16px'`, - borderBottom: `'1px solid var(--mk-ui-divider)'` +} +var TreeNode2 = class { + constructor(_tree, from, index2, _parent) { + this._tree = _tree; + this.from = from; + this.index = index2; + this._parent = _parent; + } + get type() { + return this._tree.type; + } + get name() { + return this._tree.type.name; + } + get to() { + return this.from + this._tree.length; + } + nextChild(i4, dir, pos, side, mode2 = 0) { + for (let parent = this; ; ) { + for (let { children, positions } = parent._tree, e5 = dir > 0 ? children.length : -1; i4 != e5; i4 += dir) { + let next = children[i4], start = positions[i4] + parent.from; + if (!checkSide(side, pos, start, start + next.length)) + continue; + if (next instanceof TreeBuffer) { + if (mode2 & IterMode.ExcludeBuffers) + continue; + let index2 = next.findChild(0, next.buffer.length, dir, pos - start, side); + if (index2 > -1) + return new BufferNode(new BufferContext(parent, next, i4, start), null, index2); + } else if (mode2 & IterMode.IncludeAnonymous || (!next.type.isAnonymous || hasChild(next))) { + let mounted; + if (!(mode2 & IterMode.IgnoreMounts) && next.props && (mounted = next.prop(NodeProp.mounted)) && !mounted.overlay) + return new TreeNode2(mounted.tree, start, i4, parent); + let inner = new TreeNode2(next, start, i4, parent); + return mode2 & IterMode.IncludeAnonymous || !inner.type.isAnonymous ? inner : inner.nextChild(dir < 0 ? next.children.length - 1 : 0, dir, pos, side); + } + } + if (mode2 & IterMode.IncludeAnonymous || !parent.type.isAnonymous) + return null; + if (parent.index >= 0) + i4 = parent.index + dir; + else + i4 = dir < 0 ? -1 : parent._parent._tree.children.length; + parent = parent._parent; + if (!parent) + return null; + } + } + get firstChild() { + return this.nextChild(0, 1, 0, 4); + } + get lastChild() { + return this.nextChild(this._tree.children.length - 1, -1, 0, 4); + } + childAfter(pos) { + return this.nextChild(0, 1, pos, 2); + } + childBefore(pos) { + return this.nextChild(this._tree.children.length - 1, -1, pos, -2); + } + enter(pos, side, mode2 = 0) { + let mounted; + if (!(mode2 & IterMode.IgnoreOverlays) && (mounted = this._tree.prop(NodeProp.mounted)) && mounted.overlay) { + let rPos = pos - this.from; + for (let { from, to: to2 } of mounted.overlay) { + if ((side > 0 ? from <= rPos : from < rPos) && (side < 0 ? to2 >= rPos : to2 > rPos)) + return new TreeNode2(mounted.tree, mounted.overlay[0].from + this.from, -1, this); + } } + return this.nextChild(0, 1, pos, side, mode2); + } + nextSignificantParent() { + let val = this; + while (val.type.isAnonymous && val._parent) + val = val._parent; + return val; + } + get parent() { + return this._parent ? this._parent.nextSignificantParent() : null; + } + get nextSibling() { + return this._parent && this.index >= 0 ? this._parent.nextChild(this.index + 1, 1, 0, 4) : null; + } + get prevSibling() { + return this._parent && this.index >= 0 ? this._parent.nextChild(this.index - 1, -1, 0, 4) : null; + } + cursor(mode2 = 0) { + return new TreeCursor(this, mode2); + } + get tree() { + return this._tree; + } + toTree() { + return this._tree; + } + resolve(pos, side = 0) { + return resolveNode(this, pos, side, false); + } + resolveInner(pos, side = 0) { + return resolveNode(this, pos, side, true); + } + enterUnfinishedNodesBefore(pos) { + return enterUnfinishedNodesBefore(this, pos); + } + getChild(type, before = null, after = null) { + let r2 = getChildren(this, type, before, after); + return r2.length ? r2[0] : null; + } + getChildren(type, before = null, after = null) { + return getChildren(this, type, before, after); + } + toString() { + return this._tree.toString(); + } + get node() { + return this; + } + matchContext(context) { + return matchNodeContext(this, context); } }; -var countdownNode = { - def: { - id: "countdown", - icon: "ui//clock" - }, - node: { - icon: "ui//clock", - schemaId: "countdown", - parentId: "", - name: "Countdown", - rank: 0, - id: "countdown", - type: "group", - props: { - date: "" - }, - types: { - date: "date" +function getChildren(node, type, before, after) { + let cur = node.cursor(), result = []; + if (!cur.firstChild()) + return result; + if (before != null) { + while (!cur.type.is(before)) + if (!cur.nextSibling()) + return result; + } + for (; ; ) { + if (after != null && cur.type.is(after)) + return result; + if (cur.type.is(type)) + result.push(cur.node); + if (!cur.nextSibling()) + return after == null ? result : []; + } +} +function matchNodeContext(node, context, i4 = context.length - 1) { + for (let p = node.parent; i4 >= 0; p = p.parent) { + if (!p) + return false; + if (!p.type.isAnonymous) { + if (context[i4] && context[i4] != p.name) + return false; + i4--; } - }, - children: [ - { - ...textNode, - node: { - ...textNode.node, - props: { - date: "", - value: `var _second = 1000; - var _minute = _second * 60; - var _hour = _minute * 60; - var _day = _hour * 24; - var timer; - var distance = new Date($root.props['date'])-$api.date.now(); - var days = Math.floor(distance / _day); - var hours = Math.floor((distance % _day) / _hour); - var minutes = Math.floor((distance % _hour) / _minute); - var seconds = Math.floor((distance % _minute) / _second); - return days + ":" + hours + ":" + minutes + ':' + seconds;` - }, - types: { - date: "date", - value: "string" - }, - actions: { - onRun: `setTimeout(() => $saveState({}), 1000)` - } - } + } + return true; +} +var BufferContext = class { + constructor(parent, buffer, index2, start) { + this.parent = parent; + this.buffer = buffer; + this.index = index2; + this.start = start; + } +}; +var BufferNode = class { + constructor(context, _parent, index2) { + this.context = context; + this._parent = _parent; + this.index = index2; + this.type = context.buffer.set.types[context.buffer.buffer[index2]]; + } + get name() { + return this.type.name; + } + get from() { + return this.context.start + this.context.buffer.buffer[this.index + 1]; + } + get to() { + return this.context.start + this.context.buffer.buffer[this.index + 2]; + } + child(dir, pos, side) { + let { buffer } = this.context; + let index2 = buffer.findChild(this.index + 4, buffer.buffer[this.index + 3], dir, pos - this.context.start, side); + return index2 < 0 ? null : new BufferNode(this.context, this, index2); + } + get firstChild() { + return this.child(1, 0, 4); + } + get lastChild() { + return this.child(-1, 0, 4); + } + childAfter(pos) { + return this.child(1, pos, 2); + } + childBefore(pos) { + return this.child(-1, pos, -2); + } + enter(pos, side, mode2 = 0) { + if (mode2 & IterMode.ExcludeBuffers) + return null; + let { buffer } = this.context; + let index2 = buffer.findChild(this.index + 4, buffer.buffer[this.index + 3], side > 0 ? 1 : -1, pos - this.context.start, side); + return index2 < 0 ? null : new BufferNode(this.context, this, index2); + } + get parent() { + return this._parent || this.context.parent.nextSignificantParent(); + } + externalSibling(dir) { + return this._parent ? null : this.context.parent.nextChild(this.context.index + dir, dir, 0, 4); + } + get nextSibling() { + let { buffer } = this.context; + let after = buffer.buffer[this.index + 3]; + if (after < (this._parent ? buffer.buffer[this._parent.index + 3] : buffer.buffer.length)) + return new BufferNode(this.context, this._parent, after); + return this.externalSibling(1); + } + get prevSibling() { + let { buffer } = this.context; + let parentStart = this._parent ? this._parent.index + 4 : 0; + if (this.index == parentStart) + return this.externalSibling(-1); + return new BufferNode(this.context, this._parent, buffer.findChild(parentStart, this.index, -1, 0, 4)); + } + cursor(mode2 = 0) { + return new TreeCursor(this, mode2); + } + get tree() { + return null; + } + toTree() { + let children = [], positions = []; + let { buffer } = this.context; + let startI = this.index + 4, endI = buffer.buffer[this.index + 3]; + if (endI > startI) { + let from = buffer.buffer[this.index + 1], to2 = buffer.buffer[this.index + 2]; + children.push(buffer.slice(startI, endI, from, to2)); + positions.push(0); } - ] + return new Tree(this.type, children, positions, this.to - this.from); + } + resolve(pos, side = 0) { + return resolveNode(this, pos, side, false); + } + resolveInner(pos, side = 0) { + return resolveNode(this, pos, side, true); + } + enterUnfinishedNodesBefore(pos) { + return enterUnfinishedNodesBefore(this, pos); + } + toString() { + return this.context.buffer.childString(this.index); + } + getChild(type, before = null, after = null) { + let r2 = getChildren(this, type, before, after); + return r2.length ? r2[0] : null; + } + getChildren(type, before = null, after = null) { + return getChildren(this, type, before, after); + } + get node() { + return this; + } + matchContext(context) { + return matchNodeContext(this, context); + } }; -var buttonNode = { - id: "button", - def: { - id: "button", - icon: "ui//mouse-pointer-click", - description: i18n_default.frames.button.description - }, - node: { - icon: "ui//mouse-pointer-click", - schemaId: "button", - parentId: "", - name: i18n_default.frames.button.label, - rank: 0, - id: "button", - type: "group", - props: { - icon: "", - label: "", - iconSize: "18", - action: "", - actionValue: "" - }, - types: { - icon: "icon", - iconSize: "number", - label: "text", - action: "option", - actionValue: "super" - }, - propsAttrs: { - action: JSON.stringify({ - name: i18n_default.properties.super.whenClicked, - icon: "ui//mouse-pointer-click" - }), - actionValue: JSON.stringify({ - name: i18n_default.properties.super.performAction - }) - }, - propsValue: { - icon: JSON.stringify({ - alias: "Icon" - }), - label: JSON.stringify({ - alias: "Label" - }), - iconSize: JSON.stringify({ - alias: "Icon Size" - }), - action: JSON.stringify({ - alias: "Action", - options: [], - source: "$super" - }), - actionValue: JSON.stringify({ - alias: "Action Properties", - dynamic: true, - field: "action" - }) - }, - actions: { - onClick: `$api.commands.run(button.props.action, button.props.actionValue, $contexts, $saveState)` - }, - styles: { - class: `'mk-button'`, - gap: `'4px'` +var TreeCursor = class { + constructor(node, mode2 = 0) { + this.mode = mode2; + this.buffer = null; + this.stack = []; + this.index = 0; + this.bufferNode = null; + if (node instanceof TreeNode2) { + this.yieldNode(node); + } else { + this._tree = node.context.parent; + this.buffer = node.context; + for (let n3 = node._parent; n3; n3 = n3._parent) + this.stack.unshift(n3.index); + this.bufferNode = node; + this.yieldBuf(node.index); } - }, - children: [ - { - ...iconNode, - node: { - ...iconNode.node, - props: { - value: `button.props.icon` - }, - styles: { - "--icon-size": 'button.props.iconSize+"px"' - } + } + get name() { + return this.type.name; + } + yieldNode(node) { + if (!node) + return false; + this._tree = node; + this.type = node.type; + this.from = node.from; + this.to = node.to; + return true; + } + yieldBuf(index2, type) { + this.index = index2; + let { start, buffer } = this.buffer; + this.type = type || buffer.set.types[buffer.buffer[index2]]; + this.from = start + buffer.buffer[index2 + 1]; + this.to = start + buffer.buffer[index2 + 2]; + return true; + } + yield(node) { + if (!node) + return false; + if (node instanceof TreeNode2) { + this.buffer = null; + return this.yieldNode(node); + } + this.buffer = node.context; + return this.yieldBuf(node.index, node.type); + } + toString() { + return this.buffer ? this.buffer.buffer.childString(this.index) : this._tree.toString(); + } + enterChild(dir, pos, side) { + if (!this.buffer) + return this.yield(this._tree.nextChild(dir < 0 ? this._tree._tree.children.length - 1 : 0, dir, pos, side, this.mode)); + let { buffer } = this.buffer; + let index2 = buffer.findChild(this.index + 4, buffer.buffer[this.index + 3], dir, pos - this.buffer.start, side); + if (index2 < 0) + return false; + this.stack.push(this.index); + return this.yieldBuf(index2); + } + firstChild() { + return this.enterChild(1, 0, 4); + } + lastChild() { + return this.enterChild(-1, 0, 4); + } + childAfter(pos) { + return this.enterChild(1, pos, 2); + } + childBefore(pos) { + return this.enterChild(-1, pos, -2); + } + enter(pos, side, mode2 = this.mode) { + if (!this.buffer) + return this.yield(this._tree.enter(pos, side, mode2)); + return mode2 & IterMode.ExcludeBuffers ? false : this.enterChild(1, pos, side); + } + parent() { + if (!this.buffer) + return this.yieldNode(this.mode & IterMode.IncludeAnonymous ? this._tree._parent : this._tree.parent); + if (this.stack.length) + return this.yieldBuf(this.stack.pop()); + let parent = this.mode & IterMode.IncludeAnonymous ? this.buffer.parent : this.buffer.parent.nextSignificantParent(); + this.buffer = null; + return this.yieldNode(parent); + } + sibling(dir) { + if (!this.buffer) + return !this._tree._parent ? false : this.yield(this._tree.index < 0 ? null : this._tree._parent.nextChild(this._tree.index + dir, dir, 0, 4, this.mode)); + let { buffer } = this.buffer, d4 = this.stack.length - 1; + if (dir < 0) { + let parentStart = d4 < 0 ? 0 : this.stack[d4] + 4; + if (this.index != parentStart) + return this.yieldBuf(buffer.findChild(parentStart, this.index, -1, 0, 4)); + } else { + let after = buffer.buffer[this.index + 3]; + if (after < (d4 < 0 ? buffer.buffer.length : buffer.buffer[this.stack[d4] + 3])) + return this.yieldBuf(after); + } + return d4 < 0 ? this.yield(this.buffer.parent.nextChild(this.buffer.index + dir, dir, 0, 4, this.mode)) : false; + } + nextSibling() { + return this.sibling(1); + } + prevSibling() { + return this.sibling(-1); + } + atLastNode(dir) { + let index2, parent, { buffer } = this; + if (buffer) { + if (dir > 0) { + if (this.index < buffer.buffer.buffer.length) + return false; + } else { + for (let i4 = 0; i4 < this.index; i4++) + if (buffer.buffer.buffer[i4 + 3] < this.index) + return false; } - }, - { ...textNode, node: { ...textNode.node, props: { value: `button.props.label` } } } - ] -}; -var tabsNode = { - id: "tabs", - def: { - id: "tabs", - icon: "ui//tabs" - }, - node: { - icon: "ui//tabs", - schemaId: "tabs", - parentId: "", - name: i18n_default.commands.tabs, - rank: 0, - id: "tabs", - type: "group", - props: { - currentTab: "0", - tabs: "[{'name': 'Tab 1', 'view': ''}, {'name': 'Tab 2', 'view': ''}]" - }, - propsValue: { - tabs: JSON.stringify({ - alias: "Tabs", - typeName: "Tab", - type: { - name: { - type: "text", - value: JSON.stringify({ alias: "Label" }) - }, - view: { - type: "link", - value: JSON.stringify({ alias: "Page" }) - } + ({ index: index2, parent } = buffer); + } else { + ({ index: index2, _parent: parent } = this._tree); + } + for (; parent; { index: index2, _parent: parent } = parent) { + if (index2 > -1) + for (let i4 = index2 + dir, e5 = dir < 0 ? -1 : parent._tree.children.length; i4 != e5; i4 += dir) { + let child = parent._tree.children[i4]; + if (this.mode & IterMode.IncludeAnonymous || child instanceof TreeBuffer || !child.type.isAnonymous || hasChild(child)) + return false; } - }), - currentTab: JSON.stringify({ - alias: "Selected Tab" - }) - }, - types: { - tabs: "object-multi", - currentTab: "number" - }, - styles: { - layout: `'row'`, - width: `'100%'`, - gap: `'8px'` } - }, - children: [ - frameRootWithProps( - { ...listNode, children: [ - frameRootWithProps({ ...listItemNode, children: [ - frameRootWithProps( - textNode, - { - value: `listItem.props.value.name` - }, - { - padding: `'4px 8px'`, - color: `$root.props.currentTab == listItem.props._index ? 'var(--mk-ui-text-primary)' : 'var(--mk-ui-text-tertiary)'`, - borderBottom: `$root.props.currentTab == listItem.props._index ? '2px solid var(--mk-ui-active)' : 'none'` - }, - { - onClick: `$saveState({$root: {props: {currentTab: listItem.props._index}}})` + return true; + } + move(dir, enter) { + if (enter && this.enterChild(dir, 0, 4)) + return true; + for (; ; ) { + if (this.sibling(dir)) + return true; + if (this.atLastNode(dir) || !this.parent()) + return false; + } + } + next(enter = true) { + return this.move(1, enter); + } + prev(enter = true) { + return this.move(-1, enter); + } + moveTo(pos, side = 0) { + while (this.from == this.to || (side < 1 ? this.from >= pos : this.from > pos) || (side > -1 ? this.to <= pos : this.to < pos)) + if (!this.parent()) + break; + while (this.enterChild(1, pos, side)) { + } + return this; + } + get node() { + if (!this.buffer) + return this._tree; + let cache2 = this.bufferNode, result = null, depth = 0; + if (cache2 && cache2.context == this.buffer) { + scan: + for (let index2 = this.index, d4 = this.stack.length; d4 >= 0; ) { + for (let c3 = cache2; c3; c3 = c3._parent) + if (c3.index == index2) { + if (index2 == this.index) + return c3; + result = c3; + depth = d4 + 1; + break scan; } - ) - ] }, {}) - ] }, - { value: `$root.props.tabs` }, - { - layout: `'row'`, - columnGap: `'8px'`, - flexWrap: `'wrap'`, - rowGap: `'4px'` + index2 = this.stack[--d4]; + } + } + for (let i4 = depth; i4 < this.stack.length; i4++) + result = new BufferNode(this.buffer, result, this.stack[i4]); + return this.bufferNode = new BufferNode(this.buffer, result, this.index); + } + get tree() { + return this.buffer ? null : this._tree._tree; + } + iterate(enter, leave) { + for (let depth = 0; ; ) { + let mustLeave = false; + if (this.type.isAnonymous || enter(this) !== false) { + if (this.firstChild()) { + depth++; + continue; + } + if (!this.type.isAnonymous) + mustLeave = true; } - ), - frameRootWithProps( - flowNode, - { - value: `$root.props.tabs[$root.props.currentTab].view` - }, - { - padding: `'0px'`, - "--mk-expanded": `true`, - "--mk-min-mode": `true` - }, - {} - ) - ] + for (; ; ) { + if (mustLeave && leave) + leave(this); + mustLeave = this.type.isAnonymous; + if (this.nextSibling()) + break; + if (!depth) + return; + this.parent(); + depth--; + mustLeave = true; + } + } + } + matchContext(context) { + if (!this.buffer) + return matchNodeContext(this.node, context); + let { buffer } = this.buffer, { types: types2 } = buffer.set; + for (let i4 = context.length - 1, d4 = this.stack.length - 1; i4 >= 0; d4--) { + if (d4 < 0) + return matchNodeContext(this.node, context, i4); + let type = types2[buffer.buffer[this.stack[d4]]]; + if (!type.isAnonymous) { + if (context[i4] && context[i4] != type.name) + return false; + i4--; + } + } + return true; + } }; -var fieldNode = { - id: "field", - def: { - id: "field", - description: i18n_default.frames.field.description - }, - node: { - schemaId: "field", - parentId: "", - name: i18n_default.frames.field.label, - rank: 0, - id: "field", - type: "group", - props: { - type: "", - value: "", - sticker: "", - property: "" - }, - types: { - value: "text", - type: "text", - sticker: "text", - property: "object" - }, - styles: { - "--font-text-size": `'14px'`, - fontSize: `'14px'`, - hidden: `$root.props.value?.length == 0` +function hasChild(tree) { + return tree.children.some((ch) => ch instanceof TreeBuffer || !ch.type.isAnonymous || hasChild(ch)); +} +function buildTree(data2) { + var _a; + let { buffer, nodeSet, maxBufferLength = DefaultBufferLength, reused = [], minRepeatType = nodeSet.types.length } = data2; + let cursor2 = Array.isArray(buffer) ? new FlatBufferCursor(buffer, buffer.length) : buffer; + let types2 = nodeSet.types; + let contextHash = 0, lookAhead = 0; + function takeNode(parentStart, minPos, children2, positions2, inRepeat) { + let { id: id3, start, end, size: size2 } = cursor2; + let lookAheadAtStart = lookAhead; + while (size2 < 0) { + cursor2.next(); + if (size2 == -1) { + let node2 = reused[id3]; + children2.push(node2); + positions2.push(start - parentStart); + return; + } else if (size2 == -3) { + contextHash = id3; + return; + } else if (size2 == -4) { + lookAhead = id3; + return; + } else { + throw new RangeError(`Unrecognized record size: ${size2}`); + } } - }, - children: [ - frameRootWithProps({ ...groupNode, children: [ - frameRootWithProps( - textNode, - { - value: `$root.props.value` - }, - { - padding: `'4px 8px'`, - borderRadius: `'4px'`, - background: `$api.properties.color($root.props.property, $root.props.value)`, - hidden: `$root.props.type != 'option'` - } - ), - frameRootWithProps( - textNode, - { - value: `$root.props.value` - }, - { - hidden: `$root.props.type != 'text' && $root.props.type != 'number' && $root.props.type != 'fileprop'` - } - ), - frameRootWithProps( - { ...groupNode, children: [ - frameRootWithProps(iconNode, { value: `'ui//check'` }, { background: `'var(--mk-ui-active)'`, "width": `'16px'`, height: `'16px'` }), - frameRootWithProps(textNode, { value: `$root.props.property?.name` }) - ] }, - {}, - { - layout: `'row'`, - gap: `'4px'`, - layoutAlign: `'w'`, - height: `'auto'`, - hidden: `$root.props.type != 'boolean'` - } - ), - frameRootWithProps( - imageNode, - { - value: `$root.props.value` - }, - { - width: `'50px'`, - height: `'50px'`, - hidden: `$root.props.type != 'image'` + let type = types2[id3], node, buffer2; + let startPos = start - parentStart; + if (end - start <= maxBufferLength && (buffer2 = findBufferSize(cursor2.pos - minPos, inRepeat))) { + let data3 = new Uint16Array(buffer2.size - buffer2.skip); + let endPos = cursor2.pos - buffer2.size, index2 = data3.length; + while (cursor2.pos > endPos) + index2 = copyToBuffer(buffer2.start, data3, index2); + node = new TreeBuffer(data3, end - buffer2.start, nodeSet); + startPos = buffer2.start - parentStart; + } else { + let endPos = cursor2.pos - size2; + cursor2.next(); + let localChildren = [], localPositions = []; + let localInRepeat = id3 >= minRepeatType ? id3 : -1; + let lastGroup = 0, lastEnd = end; + while (cursor2.pos > endPos) { + if (localInRepeat >= 0 && cursor2.id == localInRepeat && cursor2.size >= 0) { + if (cursor2.end <= lastEnd - maxBufferLength) { + makeRepeatLeaf(localChildren, localPositions, start, lastGroup, cursor2.end, lastEnd, localInRepeat, lookAheadAtStart); + lastGroup = localChildren.length; + lastEnd = cursor2.end; + } + cursor2.next(); + } else { + takeNode(start, endPos, localChildren, localPositions, localInRepeat); } - ), - frameRootWithProps( - iconNode, - { - value: `$root.props.value` - }, - { - hidden: `$root.props.type != 'icon'` + } + if (localInRepeat >= 0 && lastGroup > 0 && lastGroup < localChildren.length) + makeRepeatLeaf(localChildren, localPositions, start, lastGroup, start, lastEnd, localInRepeat, lookAheadAtStart); + localChildren.reverse(); + localPositions.reverse(); + if (localInRepeat > -1 && lastGroup > 0) { + let make = makeBalanced(type); + node = balanceRange(type, localChildren, localPositions, 0, localChildren.length, 0, end - start, make, make); + } else { + node = makeTree(type, localChildren, localPositions, end - start, lookAheadAtStart - end); + } + } + children2.push(node); + positions2.push(startPos); + } + function makeBalanced(type) { + return (children2, positions2, length2) => { + let lookAhead2 = 0, lastI = children2.length - 1, last, lookAheadProp; + if (lastI >= 0 && (last = children2[lastI]) instanceof Tree) { + if (!lastI && last.type == type && last.length == length2) + return last; + if (lookAheadProp = last.prop(NodeProp.lookAhead)) + lookAhead2 = positions2[lastI] + last.length + lookAheadProp; + } + return makeTree(type, children2, positions2, length2, lookAhead2); + }; + } + function makeRepeatLeaf(children2, positions2, base2, i4, from, to2, type, lookAhead2) { + let localChildren = [], localPositions = []; + while (children2.length > i4) { + localChildren.push(children2.pop()); + localPositions.push(positions2.pop() + base2 - from); + } + children2.push(makeTree(nodeSet.types[type], localChildren, localPositions, to2 - from, lookAhead2 - to2)); + positions2.push(from - base2); + } + function makeTree(type, children2, positions2, length2, lookAhead2 = 0, props) { + if (contextHash) { + let pair2 = [NodeProp.contextHash, contextHash]; + props = props ? [pair2].concat(props) : [pair2]; + } + if (lookAhead2 > 25) { + let pair2 = [NodeProp.lookAhead, lookAhead2]; + props = props ? [pair2].concat(props) : [pair2]; + } + return new Tree(type, children2, positions2, length2, props); + } + function findBufferSize(maxSize, inRepeat) { + let fork = cursor2.fork(); + let size2 = 0, start = 0, skip = 0, minStart = fork.end - maxBufferLength; + let result = { size: 0, start: 0, skip: 0 }; + scan: + for (let minPos = fork.pos - maxSize; fork.pos > minPos; ) { + let nodeSize4 = fork.size; + if (fork.id == inRepeat && nodeSize4 >= 0) { + result.size = size2; + result.start = start; + result.skip = skip; + skip += 4; + size2 += 4; + fork.next(); + continue; } - ), - frameRootWithProps( - flowNode, - { - value: `$root.props.value` - }, - { - hidden: `$root.props.type != 'link' && $root.props.type != 'file' && $root.props.type != 'context'`, - padding: `'0px'` + let startPos = fork.pos - nodeSize4; + if (nodeSize4 < 0 || startPos < minPos || fork.start < minStart) + break; + let localSkipped = fork.id >= minRepeatType ? 4 : 0; + let nodeStart = fork.start; + fork.next(); + while (fork.pos > startPos) { + if (fork.size < 0) { + if (fork.size == -3) + localSkipped += 4; + else + break scan; + } else if (fork.id >= minRepeatType) { + localSkipped += 4; + } + fork.next(); } - ) - ] }, {}, { - layout: `'row'`, - layoutAlign: `'w'`, - height: `'auto'`, - gap: `'8px'`, - minHeight: `'24px'`, - hidden: `!($root.props.value?.length > 0) || $root.props.type?.contains('multi')` - }), - frameRootWithProps( - { ...listNode, children: [ - frameRootWithProps({ ...listItemNode, children: [ - frameRootWithProps( - textNode, - { - value: `listItem.props.value` - }, - { - padding: `'4px 8px'`, - borderRadius: `'4px'`, - background: `$api.properties.color($root.props.property, listItem.props.value)`, - hidden: `$root.props.type != 'option-multi' && $root.props.type != 'tags'` - } - ), - frameRootWithProps( - flowNode, - { - value: `listItem.props.value` - }, - { - hidden: `$root.props.type != 'link-multi' && $root.props.type != 'context-multi'`, - padding: `'0px'` - } - ) - ] }, {}) - ] }, - { value: `$api.properties.value($root.props.type, $root.props.value)` }, - { - layout: `'row'`, - columnGap: `'8px'`, - flexWrap: `'wrap'`, - rowGap: `'4px'`, - hidden: `!$root.props.type?.includes('multi')` + start = nodeStart; + size2 += nodeSize4; + skip += localSkipped; } - ) - ] -}; -var previewNode = { - id: "preview", - def: { - id: "preview" - }, - node: { - schemaId: "preview", - parentId: "", - name: "Preview", - rank: 0, - id: "preview", - type: "group", - props: { - path: "", - width: `"50px"`, - height: `'50px'`, - radius: `'8px'`, - padding: `'16px'` - }, - types: { - path: "link", - width: "text", - height: "text", - radius: "text", - padding: "text" - }, - styles: { - background: `'var(--background-secondary)'`, - height: `$root.props.height`, - borderRadius: `$root.props.radius`, - overflow: `'hidden'` + if (inRepeat < 0 || size2 == maxSize) { + result.size = size2; + result.start = start; + result.skip = skip; } - }, - children: [ - frameRootWithProps( - imageNode, - { - value: `$api.path.label(preview.props.path)?.thumbnail` - }, - { - width: `$root.props.width`, - height: `$root.props.height`, - hidden: `$api.path.label(preview.props.path)?.thumbnail?.length == 0`, - borderRadius: `$root.props.radius` + return result.size > 4 ? result : void 0; + } + function copyToBuffer(bufferStart, buffer2, index2) { + let { id: id3, start, end, size: size2 } = cursor2; + cursor2.next(); + if (size2 >= 0 && id3 < minRepeatType) { + let startIndex = index2; + if (size2 > 4) { + let endPos = cursor2.pos - (size2 - 4); + while (cursor2.pos > endPos) + index2 = copyToBuffer(bufferStart, buffer2, index2); } - ), - frameRootWithProps( - iconNode, - { - value: `$api.path.label(preview.props.path)?.sticker` - }, - { - width: `$root.props.width`, - height: `$root.props.height`, - hidden: `$api.path.label(preview.props.path)?.thumbnail?.length > 0`, - borderRadius: `$root.props.radius`, - background: `$api.path.label(preview.props.path)?.color`, - padding: `$root.props.padding`, - overflow: `'hidden'` + buffer2[--index2] = startIndex; + buffer2[--index2] = end - bufferStart; + buffer2[--index2] = start - bufferStart; + buffer2[--index2] = id3; + } else if (size2 == -3) { + contextHash = id3; + } else if (size2 == -4) { + lookAhead = id3; + } + return index2; + } + let children = [], positions = []; + while (cursor2.pos > 0) + takeNode(data2.start || 0, data2.bufferStart || 0, children, positions, -1); + let length = (_a = data2.length) !== null && _a !== void 0 ? _a : children.length ? positions[0] + children[0].length : 0; + return new Tree(types2[data2.topID], children.reverse(), positions.reverse(), length); +} +var nodeSizeCache = /* @__PURE__ */ new WeakMap(); +function nodeSize(balanceType, node) { + if (!balanceType.isAnonymous || node instanceof TreeBuffer || node.type != balanceType) + return 1; + let size2 = nodeSizeCache.get(node); + if (size2 == null) { + size2 = 1; + for (let child of node.children) { + if (child.type != balanceType || !(child instanceof Tree)) { + size2 = 1; + break; } - ) - ] -}; -var ratingNode = { - id: "rating", - def: { - id: "rating", - icon: "ui//star" - }, - node: { - icon: "ui//star", - schemaId: "rating", - parentId: "", - name: i18n_default.commands.rating, - rank: 0, - id: "rating", - type: "group", - props: { - value: "5", - icon: `'ui//star'` - }, - types: { - value: "number", - icon: "icon" - }, - styles: { - layout: `'row'`, - height: `'16px'` + size2 += nodeSize(balanceType, child); } - }, - children: [ - frameRootWithProps(iconNode, { - value: `$root.props.icon` - }, { - width: `$root.styles.height`, - height: `$root.styles.height`, - hidden: `$root.props.value < 1` - }), - frameRootWithProps(iconNode, { - value: `$root.props.icon` - }, { - width: `$root.styles.height`, - height: `$root.styles.height`, - hidden: `$root.props.value < 2` - }), - frameRootWithProps(iconNode, { - value: `$root.props.icon` - }, { - width: `$root.styles.height`, - height: `$root.styles.height`, - hidden: `$root.props.value < 3` - }), - frameRootWithProps(iconNode, { - value: `$root.props.icon` - }, { - width: `$root.styles.height`, - height: `$root.styles.height`, - hidden: `$root.props.value < 4` - }), - frameRootWithProps(iconNode, { - value: `$root.props.icon` - }, { - width: `$root.styles.height`, - height: `$root.styles.height`, - hidden: `$root.props.value < 5` - }) - ] -}; -var callout = { - id: "callout", - def: { - id: "callout", - icon: "ui//callout" - }, - node: { - icon: "ui//callout", - schemaId: "callout", - parentId: "", - name: i18n_default.commands.callout, - rank: 0, - id: "callout", - type: "group", - props: { - icon: "", - note: "" - }, - types: { - icon: "icon", - note: "link" - }, - styles: { - borderRadius: `'8px'`, - background: `'var(--mk-ui-background-contrast)'`, - width: `'100%'`, - layout: `'row'`, - gap: `'8px'`, - padding: `'16px'` + nodeSizeCache.set(node, size2); + } + return size2; +} +function balanceRange(balanceType, children, positions, from, to2, start, length, mkTop, mkTree) { + let total = 0; + for (let i4 = from; i4 < to2; i4++) + total += nodeSize(balanceType, children[i4]); + let maxChild = Math.ceil(total * 1.5 / 8); + let localChildren = [], localPositions = []; + function divide3(children2, positions2, from2, to3, offset2) { + for (let i4 = from2; i4 < to3; ) { + let groupFrom = i4, groupStart = positions2[i4], groupSize = nodeSize(balanceType, children2[i4]); + i4++; + for (; i4 < to3; i4++) { + let nextSize = nodeSize(balanceType, children2[i4]); + if (groupSize + nextSize >= maxChild) + break; + groupSize += nextSize; + } + if (i4 == groupFrom + 1) { + if (groupSize > maxChild) { + let only = children2[groupFrom]; + divide3(only.children, only.positions, 0, only.children.length, positions2[groupFrom] + offset2); + continue; + } + localChildren.push(children2[groupFrom]); + } else { + let length2 = positions2[i4 - 1] + children2[i4 - 1].length - groupStart; + localChildren.push(balanceRange(balanceType, children2, positions2, groupFrom, i4, groupStart, length2, null, mkTree)); + } + localPositions.push(groupStart + offset2 - start); } - }, - children: [ - frameRootWithProps(iconNode, { - value: `callout.props.icon` - }, { - width: `'18px'`, - height: `'18px'` - }), - frameRootWithProps({ - ...contentNode, - children: [ - frameRootWithProps(flowNode, { - value: `callout.props.note` - }, { - width: `'100%'`, - "--mk-expanded": `true`, - "--mk-min-mode": `true` - }) - ] - }, {}, { - width: `'auto'`, - flex: `'1'` - }) - ] -}; -var toggleNode = { - id: "toggle", - def: { - id: "toggle", - icon: "ui//collapse-solid", - description: i18n_default.frames.toggle.description - }, - node: { - icon: "ui//collapse-solid", - schemaId: "toggle", - parentId: "", - name: i18n_default.commands.toggle, - rank: 0, - id: "toggle", - type: "group", - props: { - value: "false", - label: "", - note: "" - }, - types: { - value: "boolean", - label: "text", - note: "link" - }, - styles: { - width: `'100%'` + } + divide3(children, positions, from, to2, 0); + return (mkTop || mkTree)(localChildren, localPositions, length); +} +var Parser4 = class { + startParse(input, fragments, ranges) { + if (typeof input == "string") + input = new StringInput(input); + ranges = !ranges ? [new Range2(0, input.length)] : ranges.length ? ranges.map((r2) => new Range2(r2.from, r2.to)) : [new Range2(0, 0)]; + return this.createParse(input, fragments || [], ranges); + } + parse(input, fragments, ranges) { + let parse7 = this.startParse(input, fragments, ranges); + for (; ; ) { + let done = parse7.advance(); + if (done) + return done; } - }, - children: [ - frameRootWithProps( - { - ...slidesNode, - children: [ - frameRootWithProps( - { - ...slideNode, - children: [ - frameRootWithProps( - { ...deltaNode, node: { ...deltaNode.node, ref: "icon" } }, - {}, - { - transform: `'rotate(90deg)'` - } - ) - ] - }, - { value: "true" } - ), - frameRootWithProps( - { - ...slideNode, - children: [ - frameRootWithProps( - { ...deltaNode, node: { ...deltaNode.node, ref: "icon" } }, - {}, - { - transform: `'rotate(0deg)'` - } - ) - ] - }, - { value: "false" } - ) - ] - }, - { - value: `'value'` - } - ), - frameRootWithProps({ - ...groupNode, - children: [ - { - ...iconNode, - node: { - ...iconNode.node, - props: { - value: `'ui//collapse-solid'` - }, - styles: { - width: `'16px'`, - height: `'16px'`, - transform: `'rotate(90deg)'` - }, - actions: { - onClick: `$saveState({ toggle: {props: { value: !toggle.props.value }} })` - } - } - }, - { ...textNode, node: { ...textNode.node, props: { value: `toggle.props.label` } } } - ] - }, {}, { - height: `'auto'`, - layoutAlign: `'w'`, - gap: `'8px'`, - layout: `'row'` - }), - frameRootWithProps({ - ...contentNode, - children: [ - frameRootWithProps(flowNode, { - value: `toggle.props.note` - }, { - width: `'auto'`, - flex: `'1'`, - "--mk-expanded": `true`, - "--mk-min-mode": `true` - }) - ] - }, {}, { paddingLeft: `'24px'`, hidden: `!toggle.props.value` }) - ] + } }; -var progressNode = { - id: "progress", - def: { - id: "progress", - icon: "ui//pie-chart" - }, - node: { - icon: "ui//pie-chart", - schemaId: "progress", - parentId: "", - name: i18n_default.commands.progress, - rank: 0, - id: "progress", - type: "group", - props: { - value: "50", - max: "100", - color: "'var(--background-modifier-form-field)'", - backgroundColor: `'var(--color-orange)'` - }, - types: { - value: "number", - max: "number", - color: "color", - backgroundColor: "color" - }, - styles: { - background: `$root.props.color`, - height: `'10px'`, - width: `'100px'`, - borderRadius: `'5px'` +var StringInput = class { + constructor(string4) { + this.string = string4; + } + get length() { + return this.string.length; + } + chunk(from) { + return this.string.slice(from); + } + get lineChunks() { + return false; + } + read(from, to2) { + return this.string.slice(from, to2); + } +}; +var stoppedInner = new NodeProp({ perNode: true }); + +// node_modules/@lezer/javascript/node_modules/@lezer/lr/dist/index.js +var Stack = class { + constructor(p, stack, state, reducePos, pos, score, buffer, bufferBase, curContext, lookAhead = 0, parent) { + this.p = p; + this.stack = stack; + this.state = state; + this.reducePos = reducePos; + this.pos = pos; + this.score = score; + this.buffer = buffer; + this.bufferBase = bufferBase; + this.curContext = curContext; + this.lookAhead = lookAhead; + this.parent = parent; + } + toString() { + return `[${this.stack.filter((_15, i4) => i4 % 3 == 0).concat(this.state)}]@${this.pos}${this.score ? "!" + this.score : ""}`; + } + static start(p, state, pos = 0) { + let cx = p.parser.context; + return new Stack(p, [], state, pos, pos, 0, [], 0, cx ? new StackContext(cx, cx.start) : null, 0, null); + } + get context() { + return this.curContext ? this.curContext.context : null; + } + pushState(state, start) { + this.stack.push(this.state, start, this.bufferBase + this.buffer.length); + this.state = state; + } + reduce(action) { + let depth = action >> 19, type = action & 65535; + let { parser: parser3 } = this.p; + let dPrec = parser3.dynamicPrecedence(type); + if (dPrec) + this.score += dPrec; + if (depth == 0) { + this.pushState(parser3.getGoto(this.state, type, true), this.reducePos); + if (type < parser3.minRepeatTerm) + this.storeNode(type, this.reducePos, this.reducePos, 4, true); + this.reduceContext(type, this.reducePos); + return; } - }, - children: [ - { - ...groupNode, - node: { - ...groupNode.node, - styles: { - width: `$root.props.value/$root.props.max*100+'%'`, - height: `'100%'`, - borderRadius: `'5px'`, - background: `$root.props.backgroundColor`, - display: `'block'` + let base2 = this.stack.length - (depth - 1) * 3 - (action & 262144 ? 6 : 0); + let start = this.stack[base2 - 2]; + let bufferBase = this.stack[base2 - 1], count3 = this.bufferBase + this.buffer.length - bufferBase; + if (type < parser3.minRepeatTerm || action & 131072) { + let pos = parser3.stateFlag(this.state, 1) ? this.pos : this.reducePos; + this.storeNode(type, start, pos, count3 + 4, true); + } + if (action & 262144) { + this.state = this.stack[base2]; + } else { + let baseStateID = this.stack[base2 - 3]; + this.state = parser3.getGoto(baseStateID, type, true); + } + while (this.stack.length > base2) + this.stack.pop(); + this.reduceContext(type, start); + } + storeNode(term, start, end, size2 = 4, isReduce = false) { + if (term == 0 && (!this.stack.length || this.stack[this.stack.length - 1] < this.buffer.length + this.bufferBase)) { + let cur = this, top = this.buffer.length; + if (top == 0 && cur.parent) { + top = cur.bufferBase - cur.parent.bufferBase; + cur = cur.parent; + } + if (top > 0 && cur.buffer[top - 4] == 0 && cur.buffer[top - 1] > -1) { + if (start == end) + return; + if (cur.buffer[top - 2] >= start) { + cur.buffer[top - 2] = end; + return; } } } - ] -}; -var circularProgressNode = { - id: "circularProgress", - def: { - id: "circularProgress", - icon: "ui//pie-chart" - }, - node: { - icon: "ui//pie-chart", - schemaId: "circularProgress", - parentId: "", - name: i18n_default.commands.circularProgress, - rank: 0, - id: "circularProgress", - type: "group", - props: { - value: "50", - max: "100", - color: `'var(--color-orange)'`, - backgroundColor: "'var(--background-modifier-form-field)'", - ringWidth: "5" - }, - types: { - value: "number", - color: "color", - max: "number", - backgroundColor: "color", - ringWidth: "number" - }, - styles: { - height: `'100px'`, - width: `'100px'` + if (!isReduce || this.pos == end) { + this.buffer.push(term, start, end, size2); + } else { + let index2 = this.buffer.length; + if (index2 > 0 && this.buffer[index2 - 4] != 0) + while (index2 > 0 && this.buffer[index2 - 2] > end) { + this.buffer[index2] = this.buffer[index2 - 4]; + this.buffer[index2 + 1] = this.buffer[index2 - 3]; + this.buffer[index2 + 2] = this.buffer[index2 - 2]; + this.buffer[index2 + 3] = this.buffer[index2 - 1]; + index2 -= 4; + if (size2 > 4) + size2 -= 4; + } + this.buffer[index2] = term; + this.buffer[index2 + 1] = start; + this.buffer[index2 + 2] = end; + this.buffer[index2 + 3] = size2; } - }, - children: [ - frameRootWithProps( - groupNode, - {}, - { - background: "`conic-gradient(${$root.props.color} ${$root.props.value/$root.props.max*100}%, ${$root.props.backgroundColor} 0)`", - "maskImage": "`radial-gradient(circle calc(calc(${$root.styles.width} - ${$root.props.ringWidth}px) / 2) at calc(50%) calc(50%),transparent 100%,black 0%)`", - height: `'100%'`, - width: `'100%'`, - borderRadius: `'50%'` + } + shift(action, next, nextEnd) { + let start = this.pos; + if (action & 131072) { + this.pushState(action & 65535, this.pos); + } else if ((action & 262144) == 0) { + let nextState = action, { parser: parser3 } = this.p; + if (nextEnd > this.pos || next <= parser3.maxNode) { + this.pos = nextEnd; + if (!parser3.stateFlag(nextState, 1)) + this.reducePos = nextEnd; } - ) - ] -}; -var cardNode = { - id: "card", - def: { - id: "card", - icon: "ui//mouse-pointer-click" - }, - node: { - icon: "ui//mouse-pointer-click", - schemaId: "card", - parentId: "", - name: i18n_default.commands.card, - rank: 0, - id: "card", - type: "group", - props: { - icon: "", - label: "" - }, - types: { - icon: "icon", - label: "text" - }, - actions: {}, - styles: { - borderRadius: `'10px'`, - background: `'var(--background-primary-alt)'`, - width: `'160px'`, - height: `'80px'`, - padding: `'16px'`, - border: `'thin solid var(--mk-ui-divider)'` + this.pushState(nextState, start); + this.shiftContext(next, start); + if (next <= parser3.maxNode) + this.buffer.push(next, start, nextEnd, 4); + } else { + this.pos = nextEnd; + this.shiftContext(next, start); + if (next <= this.p.parser.maxNode) + this.buffer.push(next, start, nextEnd, 4); } - }, - children: [ - { - ...iconNode, - node: { - ...iconNode.node, - props: { - value: `card.props.icon` + } + apply(action, next, nextEnd) { + if (action & 65536) + this.reduce(action); + else + this.shift(action, next, nextEnd); + } + useNode(value, next) { + let index2 = this.p.reused.length - 1; + if (index2 < 0 || this.p.reused[index2] != value) { + this.p.reused.push(value); + index2++; + } + let start = this.pos; + this.reducePos = this.pos = start + value.length; + this.pushState(next, start); + this.buffer.push(index2, start, this.reducePos, -1); + if (this.curContext) + this.updateContext(this.curContext.tracker.reuse(this.curContext.context, value, this, this.p.stream.reset(this.pos - value.length))); + } + split() { + let parent = this; + let off = parent.buffer.length; + while (off > 0 && parent.buffer[off - 2] > parent.reducePos) + off -= 4; + let buffer = parent.buffer.slice(off), base2 = parent.bufferBase + off; + while (parent && base2 == parent.bufferBase) + parent = parent.parent; + return new Stack(this.p, this.stack.slice(), this.state, this.reducePos, this.pos, this.score, buffer, base2, this.curContext, this.lookAhead, parent); + } + recoverByDelete(next, nextEnd) { + let isNode3 = next <= this.p.parser.maxNode; + if (isNode3) + this.storeNode(next, this.pos, nextEnd, 4); + this.storeNode(0, this.pos, nextEnd, isNode3 ? 8 : 4); + this.pos = this.reducePos = nextEnd; + this.score -= 190; + } + canShift(term) { + for (let sim = new SimulatedStack(this); ; ) { + let action = this.p.parser.stateSlot(sim.state, 4) || this.p.parser.hasAction(sim.state, term); + if ((action & 65536) == 0) + return true; + if (action == 0) + return false; + sim.reduce(action); + } + } + recoverByInsert(next) { + if (this.stack.length >= 300) + return []; + let nextStates = this.p.parser.nextStates(this.state); + if (nextStates.length > 4 << 1 || this.stack.length >= 120) { + let best = []; + for (let i4 = 0, s4; i4 < nextStates.length; i4 += 2) { + if ((s4 = nextStates[i4 + 1]) != this.state && this.p.parser.hasAction(s4, next)) + best.push(nextStates[i4], s4); + } + if (this.stack.length < 120) + for (let i4 = 0; best.length < 4 << 1 && i4 < nextStates.length; i4 += 2) { + let s4 = nextStates[i4 + 1]; + if (!best.some((v2, i5) => i5 & 1 && v2 == s4)) + best.push(nextStates[i4], s4); } + nextStates = best; + } + let result = []; + for (let i4 = 0; i4 < nextStates.length && result.length < 4; i4 += 2) { + let s4 = nextStates[i4 + 1]; + if (s4 == this.state) + continue; + let stack = this.split(); + stack.pushState(s4, this.pos); + stack.storeNode(0, stack.pos, stack.pos, 4, true); + stack.shiftContext(nextStates[i4], this.pos); + stack.score -= 200; + result.push(stack); + } + return result; + } + forceReduce() { + let reduce2 = this.p.parser.stateSlot(this.state, 5); + if ((reduce2 & 65536) == 0) + return false; + let { parser: parser3 } = this.p; + if (!parser3.validAction(this.state, reduce2)) { + let depth = reduce2 >> 19, term = reduce2 & 65535; + let target = this.stack.length - depth * 3; + if (target < 0 || parser3.getGoto(this.stack[target], term, false) < 0) + return false; + this.storeNode(0, this.reducePos, this.reducePos, 4, true); + this.score -= 100; + } + this.reducePos = this.pos; + this.reduce(reduce2); + return true; + } + forceAll() { + while (!this.p.parser.stateFlag(this.state, 2)) { + if (!this.forceReduce()) { + this.storeNode(0, this.pos, this.pos, 4, true); + break; } - }, - { ...textNode, node: { ...textNode.node, props: { value: `card.props.label` } } } - ] + } + return this; + } + get deadEnd() { + if (this.stack.length != 3) + return false; + let { parser: parser3 } = this.p; + return parser3.data[parser3.stateSlot(this.state, 1)] == 65535 && !parser3.stateSlot(this.state, 4); + } + restart() { + this.state = this.stack[0]; + this.stack.length = 0; + } + sameState(other) { + if (this.state != other.state || this.stack.length != other.stack.length) + return false; + for (let i4 = 0; i4 < this.stack.length; i4 += 3) + if (this.stack[i4] != other.stack[i4]) + return false; + return true; + } + get parser() { + return this.p.parser; + } + dialectEnabled(dialectID) { + return this.p.parser.dialect.flags[dialectID]; + } + shiftContext(term, start) { + if (this.curContext) + this.updateContext(this.curContext.tracker.shift(this.curContext.context, term, this, this.p.stream.reset(start))); + } + reduceContext(term, start) { + if (this.curContext) + this.updateContext(this.curContext.tracker.reduce(this.curContext.context, term, this, this.p.stream.reset(start))); + } + emitContext() { + let last = this.buffer.length - 1; + if (last < 0 || this.buffer[last] != -3) + this.buffer.push(this.curContext.hash, this.reducePos, this.reducePos, -3); + } + emitLookAhead() { + let last = this.buffer.length - 1; + if (last < 0 || this.buffer[last] != -4) + this.buffer.push(this.lookAhead, this.reducePos, this.reducePos, -4); + } + updateContext(context) { + if (context != this.curContext.context) { + let newCx = new StackContext(this.curContext.tracker, context); + if (newCx.hash != this.curContext.hash) + this.emitContext(); + this.curContext = newCx; + } + } + setLookAhead(lookAhead) { + if (lookAhead > this.lookAhead) { + this.emitLookAhead(); + this.lookAhead = lookAhead; + } + } + close() { + if (this.curContext && this.curContext.tracker.strict) + this.emitContext(); + if (this.lookAhead > 0) + this.emitLookAhead(); + } }; -var linkNode = { - id: "link", - def: { - id: "link", - icon: "ui//link" - }, - node: { - icon: "ui//link", - schemaId: "link", - parentId: "", - name: i18n_default.commands.link, - rank: 0, - id: "link", - type: "group", - props: { - link: "", - label: `$api.path.label(link.props.link)?.name`, - sticker: `$api.path.label(link.props.link)?.sticker` - }, - styles: { - class: `'mk-a'`, - layout: '"row"' - }, - actions: { - onClick: "$api.path.open(link.props.link, false)" - }, - types: { - link: "link", - label: "text", - sticker: "sticker" +var StackContext = class { + constructor(tracker, context) { + this.tracker = tracker; + this.context = context; + this.hash = tracker.strict ? tracker.hash(context) : 0; + } +}; +var Recover; +(function(Recover2) { + Recover2[Recover2["Insert"] = 200] = "Insert"; + Recover2[Recover2["Delete"] = 190] = "Delete"; + Recover2[Recover2["Reduce"] = 100] = "Reduce"; + Recover2[Recover2["MaxNext"] = 4] = "MaxNext"; + Recover2[Recover2["MaxInsertStackDepth"] = 300] = "MaxInsertStackDepth"; + Recover2[Recover2["DampenInsertStackDepth"] = 120] = "DampenInsertStackDepth"; +})(Recover || (Recover = {})); +var SimulatedStack = class { + constructor(start) { + this.start = start; + this.state = start.state; + this.stack = start.stack; + this.base = this.stack.length; + } + reduce(action) { + let term = action & 65535, depth = action >> 19; + if (depth == 0) { + if (this.stack == this.start.stack) + this.stack = this.stack.slice(); + this.stack.push(this.state, 0, 0); + this.base += 3; + } else { + this.base -= (depth - 1) * 3; } - }, - children: [ - { ...iconNode, node: { ...iconNode.node, props: { value: `link.props.sticker` }, styles: { - width: `'18px'`, - height: `'18px'` - } } }, - { ...textNode, node: { ...textNode.node, props: { value: `link.props.label` } } } - ] + let goto = this.start.p.parser.getGoto(this.stack[this.base - 3], term, true); + this.state = goto; + } }; - -// src/schemas/kits/calendar.ts -var eventItem = { - def: { - id: "eventItem", - type: "listItem" - }, - node: { - type: "group", - id: "$root", - schemaId: "$root", - name: i18n_default.frames.event.label, - rank: 0 - }, - id: "$root", - children: [ - frameRootWithProps( - flowNode, - { - value: `$contexts.$context['_keyValue']` - }, - { - padding: `'0'`, - "--font-text-weight": `'bold'` - } - ) - ] +var StackBufferCursor = class { + constructor(stack, pos, index2) { + this.stack = stack; + this.pos = pos; + this.index = index2; + this.buffer = stack.buffer; + if (this.index == 0) + this.maybeNext(); + } + static create(stack, pos = stack.bufferBase + stack.buffer.length) { + return new StackBufferCursor(stack, pos, pos - stack.bufferBase); + } + maybeNext() { + let next = this.stack.parent; + if (next != null) { + this.index = this.stack.bufferBase - next.bufferBase; + this.stack = next; + this.buffer = next.buffer; + } + } + get id() { + return this.buffer[this.index - 4]; + } + get start() { + return this.buffer[this.index - 3]; + } + get end() { + return this.buffer[this.index - 2]; + } + get size() { + return this.buffer[this.index - 1]; + } + next() { + this.index -= 4; + this.pos -= 4; + if (this.index == 0) + this.maybeNext(); + } + fork() { + return new StackBufferCursor(this.stack, this.pos, this.index); + } }; -var dateGroup = { - def: { - id: "dateGroup", - type: "listGroup" - }, - node: { - type: "group", - props: { _groupValue: "" }, - styles: { - layout: `'column'`, - background: `'var(--mk-ui-background-variant)'`, - padding: `'6px'`, - height: `'150px'`, - overflow: `'hidden'`, - width: `'100%'` - }, - id: "$root", - schemaId: "$root", - name: "Date", - rank: 0 - }, - id: "$root", - children: [ - frameRootWithProps( - textNode, - { - value: `$api.date.component($api.date.parse($root.props['_groupValue']), 'day')` - }, - { - padding: `'4px'`, - "--font-text-weight": `'bold'` - } - ), - frameRootWithProps( - contentNode, - {}, - { - gap: `'2px'`, - layout: `'column'` - } - ) - ] +var CachedToken = class { + constructor() { + this.start = -1; + this.value = -1; + this.end = -1; + this.extended = -1; + this.lookAhead = 0; + this.mask = 0; + this.context = 0; + } }; -var calendarView = { - def: { - id: "calendarView", - type: "listView" - }, - node: { - type: "group", - props: { - year: `$api.date.component($api.date.offset($api.date.now(), $root.props.offset, 'month'), 'year')`, - month: `$api.date.component($api.date.offset($api.date.now(), $root.props.offset, 'month'), 'month')`, - offset: `0`, - startOfMonth: `$root.props.year+'-'+$root.props.month+'-01'`, - endOfMonth: `$root.props.year+'-'+$root.props.month+'-'+$api.date.daysInMonth($api.date.parse($root.props.startOfMonth))`, - dayOfWeek: `$api.date.component($api.date.parse($root.props.startOfMonth), 'dayOfWeek')`, - groupFilter: `'isSameDate'`, - groupOptions: `$api.date.range($api.date.parse($root.props.startOfMonth), $api.date.parse($root.props.endOfMonth))` - }, - id: "$root", - schemaId: "$root", - name: i18n_default.frames.calendar.label, - rank: 0 - }, - id: "$root", - children: [ - frameRootWithProps( - { ...groupNode, children: [ - frameRootWithProps( - { ...groupNode, children: [ - frameRootWithProps(textNode, { - value: `$api.date.format($api.date.parse($root.props.startOfMonth), 'MMMM')` - }, { - padding: `'8px'`, - "--font-text-weight": `'bold'`, - "class": `'mk-t-h1'` - }), - frameRootWithProps({ ...groupNode, children: [ - kitWithProps(buttonNode, { - icon: `'ui//chevron-left'` - }, {}, { - onClick: `$saveState({$root: {props: {offset: $root.props.offset - 1}}})` - }), - kitWithProps(buttonNode, { - label: `'Today'` - }, {}, { - onClick: `$saveState({$root: {props: {offset: 0}}})` - }), - kitWithProps(buttonNode, { - icon: `'ui//chevron-right'` - }, {}, { - onClick: `$saveState({$root: {props: {offset: $root.props.offset + 1}}})` - }) - ] }, {}, { layout: `'row'` }) - ] }, - {}, - { - width: `'100%'` - } - ) - ] }, - {} - ), - frameRootWithProps( - { - ...groupNode, - children: [ - frameRootWithProps(textNode, { - value: `'Sunday'` - }, { - padding: `'8px'`, - "--font-text-weight": `'bold'` - }), - frameRootWithProps(textNode, { - value: `'Monday'` - }, { - padding: `'8px'`, - "--font-text-weight": `'bold'` - }), - frameRootWithProps(textNode, { - value: `'Tuesday'` - }, { - padding: `'8px'`, - "--font-text-weight": `'bold'` - }), - frameRootWithProps(textNode, { - value: `'Wednesday'` - }, { - padding: `'8px'`, - "--font-text-weight": `'bold'` - }), - frameRootWithProps(textNode, { - value: `'Thursday'` - }, { - padding: `'8px'`, - "--font-text-weight": `'bold'` - }), - frameRootWithProps(textNode, { - value: `'Friday'` - }, { - padding: `'8px'`, - "--font-text-weight": `'bold'` - }), - frameRootWithProps(textNode, { - value: `'Saturday'` - }, { - padding: `'8px'`, - "--font-text-weight": `'bold'` - }) - ] - }, - {}, - { - width: `'100%'`, - height: `'auto'`, - layout: `'grid'`, - "--mk-grid-columns": `'7'`, - "--mk-grid-width": `'0'` - } - ), - frameRootWithProps( - { ...contentNode, children: [ - frameRootWithProps( - groupNode, - {}, - { - gridColumn: `'span '+$root.props.dayOfWeek` - } - ) - ] }, - {}, - { - padding: `'8px'`, - layout: `'grid'`, - "--mk-grid-columns": `'7'`, - "--mk-grid-width": `'0'`, - gap: `'1px'` +var nullToken = new CachedToken(); +var InputStream = class { + constructor(input, ranges) { + this.input = input; + this.ranges = ranges; + this.chunk = ""; + this.chunkOff = 0; + this.chunk2 = ""; + this.chunk2Pos = 0; + this.next = -1; + this.token = nullToken; + this.rangeIndex = 0; + this.pos = this.chunkPos = ranges[0].from; + this.range = ranges[0]; + this.end = ranges[ranges.length - 1].to; + this.readNext(); + } + resolveOffset(offset2, assoc) { + let range2 = this.range, index2 = this.rangeIndex; + let pos = this.pos + offset2; + while (pos < range2.from) { + if (!index2) + return null; + let next = this.ranges[--index2]; + pos -= range2.from - next.to; + range2 = next; + } + while (assoc < 0 ? pos > range2.to : pos >= range2.to) { + if (index2 == this.ranges.length - 1) + return null; + let next = this.ranges[++index2]; + pos += next.from - range2.to; + range2 = next; + } + return pos; + } + peek(offset2) { + let idx = this.chunkOff + offset2, pos, result; + if (idx >= 0 && idx < this.chunk.length) { + pos = this.pos + offset2; + result = this.chunk.charCodeAt(idx); + } else { + let resolved = this.resolveOffset(offset2, 1); + if (resolved == null) + return -1; + pos = resolved; + if (pos >= this.chunk2Pos && pos < this.chunk2Pos + this.chunk2.length) { + result = this.chunk2.charCodeAt(pos - this.chunk2Pos); + } else { + let i4 = this.rangeIndex, range2 = this.range; + while (range2.to <= pos) + range2 = this.ranges[++i4]; + this.chunk2 = this.input.chunk(this.chunk2Pos = pos); + if (pos + this.chunk2.length > range2.to) + this.chunk2 = this.chunk2.slice(0, range2.to - pos); + result = this.chunk2.charCodeAt(0); } - ) - ] -}; - -// src/schemas/kits/list.ts -var fieldsView = { - id: "fieldsView", - def: { - id: "fieldsView" - }, - node: { - schemaId: "fieldsView", - parentId: "", - name: "Properties", - rank: 0, - id: "fieldsView", - type: "group" - }, - children: [frameRootWithProps({ ...listNode, children: [ - frameRootWithProps({ ...listItemNode, children: [ - kitWithProps(fieldNode, { - sticker: `$api.properties.sticker(listItem.props.value)`, - type: "listItem.props.value.type", - value: "$contexts[listItem.props.value.table.length > 0 ? listItem.props.value.table : $contexts.$context._path]?.[listItem.props.value.name]", - property: "listItem.props.value" - }) - ] }, {}, { - layout: `'row'`, - gap: `'8px'`, - hidden: "!($contexts[listItem.props.value.table.length > 0 ? listItem.props.value.table : $contexts.$context._path]?.[listItem.props.value.name].length > 0)" - }) - ] }, { - value: `$contexts.$context._properties.filter(f => f.primary != 'true')` - }, { - layout: `'column'`, - gap: `'4px'` - })] -}; -var coverListItem = { - def: { - id: "coverListItem", - type: "listItem" - }, - node: { - type: "group", - id: "$root", - schemaId: "$root", - name: "Cover Item", - rank: 0, - props: {}, - styles: { - layout: `"column"` } - }, - id: "$root", - children: [ - frameRootWithProps( - imageNode, - { - value: `$api.path.label($contexts.$context['_keyValue'])?.thumbnail` - }, - { - borderRadius: `'8px'`, - width: `'200px'`, - height: `'300px'` + if (pos >= this.token.lookAhead) + this.token.lookAhead = pos + 1; + return result; + } + acceptToken(token, endOffset = 0) { + let end = endOffset ? this.resolveOffset(endOffset, -1) : this.pos; + if (end == null || end < this.token.start) + throw new RangeError("Token end out of bounds"); + this.token.value = token; + this.token.end = end; + } + getChunk() { + if (this.pos >= this.chunk2Pos && this.pos < this.chunk2Pos + this.chunk2.length) { + let { chunk, chunkPos } = this; + this.chunk = this.chunk2; + this.chunkPos = this.chunk2Pos; + this.chunk2 = chunk; + this.chunk2Pos = chunkPos; + this.chunkOff = this.pos - this.chunkPos; + } else { + this.chunk2 = this.chunk; + this.chunk2Pos = this.chunkPos; + let nextChunk = this.input.chunk(this.pos); + let end = this.pos + nextChunk.length; + this.chunk = end > this.range.to ? nextChunk.slice(0, this.range.to - this.pos) : nextChunk; + this.chunkPos = this.pos; + this.chunkOff = 0; + } + } + readNext() { + if (this.chunkOff >= this.chunk.length) { + this.getChunk(); + if (this.chunkOff == this.chunk.length) + return this.next = -1; + } + return this.next = this.chunk.charCodeAt(this.chunkOff); + } + advance(n3 = 1) { + this.chunkOff += n3; + while (this.pos + n3 >= this.range.to) { + if (this.rangeIndex == this.ranges.length - 1) + return this.setDone(); + n3 -= this.range.to - this.pos; + this.range = this.ranges[++this.rangeIndex]; + this.pos = this.range.from; + } + this.pos += n3; + if (this.pos >= this.token.lookAhead) + this.token.lookAhead = this.pos + 1; + return this.readNext(); + } + setDone() { + this.pos = this.chunkPos = this.end; + this.range = this.ranges[this.rangeIndex = this.ranges.length - 1]; + this.chunk = ""; + return this.next = -1; + } + reset(pos, token) { + if (token) { + this.token = token; + token.start = pos; + token.lookAhead = pos + 1; + token.value = token.extended = -1; + } else { + this.token = nullToken; + } + if (this.pos != pos) { + this.pos = pos; + if (pos == this.end) { + this.setDone(); + return this; } - ), - frameRootWithProps( - flowNode, - { - value: `$contexts.$context['_keyValue']` - }, - { - padding: `'4px'` + while (pos < this.range.from) + this.range = this.ranges[--this.rangeIndex]; + while (pos >= this.range.to) + this.range = this.ranges[++this.rangeIndex]; + if (pos >= this.chunkPos && pos < this.chunkPos + this.chunk.length) { + this.chunkOff = pos - this.chunkPos; + } else { + this.chunk = ""; + this.chunkOff = 0; } - ) - ] + this.readNext(); + } + return this; + } + read(from, to2) { + if (from >= this.chunkPos && to2 <= this.chunkPos + this.chunk.length) + return this.chunk.slice(from - this.chunkPos, to2 - this.chunkPos); + if (from >= this.chunk2Pos && to2 <= this.chunk2Pos + this.chunk2.length) + return this.chunk2.slice(from - this.chunk2Pos, to2 - this.chunk2Pos); + if (from >= this.range.from && to2 <= this.range.to) + return this.input.read(from, to2); + let result = ""; + for (let r2 of this.ranges) { + if (r2.from >= to2) + break; + if (r2.to > from) + result += this.input.read(Math.max(r2.from, from), Math.min(r2.to, to2)); + } + return result; + } }; -var imageListItem = { - def: { - id: "imageListItem", - type: "listItem" - }, - node: { - type: "group", - id: "$root", - schemaId: "$root", - name: "Image Item", - rank: 0, - props: { - _selected: `$root.props['_selectedIndex'] == $contexts.$context['_index']` - }, - styles: { - layout: `"row"`, - padding: `'4px'` - }, - actions: { - onClick: `$saveState({ $root: {props: {_selectedIndex: $contexts.$context['_index']}} });`, - onDoubleClick: `$api.path.open($contexts.$context['_keyValue'], false)` +var TokenGroup = class { + constructor(data2, id3) { + this.data = data2; + this.id = id3; + } + token(input, stack) { + readToken(this.data, input, stack, this.id); + } +}; +TokenGroup.prototype.contextual = TokenGroup.prototype.fallback = TokenGroup.prototype.extend = false; +var ExternalTokenizer = class { + constructor(token, options = {}) { + this.token = token; + this.contextual = !!options.contextual; + this.fallback = !!options.fallback; + this.extend = !!options.extend; + } +}; +function readToken(data2, input, stack, group) { + let state = 0, groupMask = 1 << group, { parser: parser3 } = stack.p, { dialect } = parser3; + scan: + for (; ; ) { + if ((groupMask & data2[state]) == 0) + break; + let accEnd = data2[state + 1]; + for (let i4 = state + 3; i4 < accEnd; i4 += 2) + if ((data2[i4 + 1] & groupMask) > 0) { + let term = data2[i4]; + if (dialect.allows(term) && (input.token.value == -1 || input.token.value == term || parser3.overrides(term, input.token.value))) { + input.acceptToken(term); + break; + } + } + for (let next = input.next, low = 0, high = data2[state + 2]; low < high; ) { + let mid = low + high >> 1; + let index2 = accEnd + mid + (mid << 1); + let from = data2[index2], to2 = data2[index2 + 1]; + if (next < from) + high = mid; + else if (next >= to2) + low = mid + 1; + else { + state = data2[index2 + 2]; + input.advance(); + continue scan; + } + } + break; } - }, - id: "$root", - children: [ - frameRootWithProps( - imageNode, - { - value: `$api.path.label($contexts.$context['_keyValue'])?.thumbnail` - }, - { - borderRadius: `'8px'` +} +function decodeArray(input, Type = Uint16Array) { + if (typeof input != "string") + return input; + let array = null; + for (let pos = 0, out = 0; pos < input.length; ) { + let value = 0; + for (; ; ) { + let next = input.charCodeAt(pos++), stop = false; + if (next == 126) { + value = 65535; + break; } - ) - ] -}; -var flowListItem = { - def: { - id: "flowListItem", - type: "listItem" - }, - node: { - type: "group", - id: "$root", - schemaId: "$root", - name: "Flow Item", - rank: 0, - props: { - _selected: `$root.props['_selectedIndex'] == $contexts.$context['_index']`, - expanded: "true", - seamless: "false" - }, - types: { - expanded: "boolean", - seamless: "boolean" - }, - propsValue: { - expanded: { - alias: "Expanded" - }, - seamless: { - alias: "Seamless" + if (next >= 92) + next--; + if (next >= 34) + next--; + let digit = next - 32; + if (digit >= 46) { + digit -= 46; + stop = true; } - }, - styles: { - layout: `"row"`, - gap: `'8px'` - }, - actions: {} - }, - id: "$root", - children: [ - frameRootWithProps( - flowNode, - { - value: `$contexts.$context['_keyValue']` - }, - { - "--mk-expanded": `$root.props.expanded`, - "--mk-min-mode": `$root.props.seamless`, - padding: `'4px'`, - marginBottom: `'8px'` + value += digit; + if (stop) + break; + value *= 46; + } + if (array) + array[out++] = value; + else + array = new Type(value); + } + return array; +} +var verbose = typeof process != "undefined" && process.env && /\bparse\b/.test(process.env.LOG); +var stackIDs = null; +var Safety; +(function(Safety2) { + Safety2[Safety2["Margin"] = 25] = "Margin"; +})(Safety || (Safety = {})); +function cutAt(tree, pos, side) { + let cursor2 = tree.cursor(IterMode.IncludeAnonymous); + cursor2.moveTo(pos); + for (; ; ) { + if (!(side < 0 ? cursor2.childBefore(pos) : cursor2.childAfter(pos))) + for (; ; ) { + if ((side < 0 ? cursor2.to < pos : cursor2.from > pos) && !cursor2.type.isError) + return side < 0 ? Math.max(0, Math.min(cursor2.to - 1, pos - 25)) : Math.min(tree.length, Math.max(cursor2.from + 1, pos + 25)); + if (side < 0 ? cursor2.prevSibling() : cursor2.nextSibling()) + break; + if (!cursor2.parent()) + return side < 0 ? 0 : tree.length; } - ) - ] -}; -var cardsListItem = { - def: { - id: "cardsListItem", - type: "listItem" - }, - node: { - type: "group", - id: "$root", - schemaId: "$root", - name: "Cards Item", - rank: 0, - props: { - _selected: `$root.props['_selectedIndex'] == $contexts.$context['_index']`, - coverProperty: `'File'` - }, - types: { - coverProperty: "option" - }, - propsValue: { - coverProperty: { - alias: "Cover Image", - source: `$properties` + } +} +var FragmentCursor = class { + constructor(fragments, nodeSet) { + this.fragments = fragments; + this.nodeSet = nodeSet; + this.i = 0; + this.fragment = null; + this.safeFrom = -1; + this.safeTo = -1; + this.trees = []; + this.start = []; + this.index = []; + this.nextFragment(); + } + nextFragment() { + let fr = this.fragment = this.i == this.fragments.length ? null : this.fragments[this.i++]; + if (fr) { + this.safeFrom = fr.openStart ? cutAt(fr.tree, fr.from + fr.offset, 1) - fr.offset : fr.from; + this.safeTo = fr.openEnd ? cutAt(fr.tree, fr.to + fr.offset, -1) - fr.offset : fr.to; + while (this.trees.length) { + this.trees.pop(); + this.start.pop(); + this.index.pop(); } - }, - styles: { - layout: `"column"`, - overflow: `'hidden'`, - borderRadius: `'8px'`, - width: `'100%'`, - height: `'100%'`, - border: `'1px solid var(--mk-ui-border)'`, - boxShadow: `'var(--mk-shadow-card)'` - }, - actions: { - onClick: `$saveState({ $root: {props: {_selectedIndex: $contexts.$context['_index']}} });`, - onDoubleClick: `$api.path.open($contexts.$context['_keyValue'], false)` + this.trees.push(fr.tree); + this.start.push(-fr.offset); + this.index.push(0); + this.nextStart = this.safeFrom; + } else { + this.nextStart = 1e9; } - }, - id: "$root", - children: [ - frameRootWithProps( - { - ...slidesNode, - children: [ - frameRootWithProps( - { - ...slideNode, - children: [ - frameRootWithProps( - { ...deltaNode, node: { ...deltaNode.node, ref: "$root" } }, - {}, - { - background: `'var(--mk-ui-background-selected)'` - } - ) - ] - }, - { value: "true" } - ), - frameRootWithProps( - { - ...slideNode, - children: [ - frameRootWithProps( - { ...deltaNode, node: { ...deltaNode.node, ref: "$root" } }, - {}, - { - background: `'var(--mk-ui-background)'` - } - ) - ] - }, - { value: "false" } - ) - ] - }, - { - value: `'_selected'` + } + nodeAt(pos) { + if (pos < this.nextStart) + return null; + while (this.fragment && this.safeTo <= pos) + this.nextFragment(); + if (!this.fragment) + return null; + for (; ; ) { + let last = this.trees.length - 1; + if (last < 0) { + this.nextFragment(); + return null; } - ), - frameRootWithProps( - { ...groupNode, children: [ - frameRootWithProps( - imageNode, - { - value: `$api.path.label($contexts[$contexts.$context['_path']][$root.props.coverProperty])?.thumbnail` - }, - { - width: `'100%'`, - height: `'80px'` - } - ) - ] }, - {}, - { - width: `'100%'`, - height: `'80px'`, - background: `'var(--mk-ui-background-contrast)'` + let top = this.trees[last], index2 = this.index[last]; + if (index2 == top.children.length) { + this.trees.pop(); + this.start.pop(); + this.index.pop(); + continue; } - ), - frameRootWithProps( - { ...groupNode, children: [ - frameRootWithProps( - iconNode, - { - value: `$api.path.label($contexts.$context['_keyValue'])?.sticker` - }, - { - width: `'32px'`, - height: `'32px'`, - padding: `'4px'`, - "--icon-size": `'24px'`, - borderRadius: `'4px'`, - overflow: `'hidden'`, - background: `$api.path.label($contexts.$context['_keyValue'])?.color` - } - ) - ] }, - {}, - { - width: `'32px'`, - height: `'32px'`, - marginTop: `'-16px'`, - marginLeft: `'4px'`, - borderRadius: `'4px'`, - background: `'var(--mk-ui-background-contrast)'` + let next = top.children[index2]; + let start = this.start[last] + top.positions[index2]; + if (start > pos) { + this.nextStart = start; + return null; } - ), - { - ...groupNode, - node: { - ...groupNode.node, - styles: { - gap: `'8px'`, - padding: `'8px'`, - flex: `'1'` - } - }, - children: [ - frameRootWithProps( - textNode, - { - value: `$api.path.label($contexts.$context['_keyValue'])?.name` - }, - { - "--font-text-weight": `'var(--bold-weight)'` + if (next instanceof Tree) { + if (start == pos) { + if (start < this.safeFrom) + return null; + let end = start + next.length; + if (end <= this.safeTo) { + let lookAhead = next.prop(NodeProp.lookAhead); + if (!lookAhead || end + lookAhead < this.fragment.to) + return next; } - ), - kitWithProps(fieldsView, {}, { marginTop: `'8px'` }) - ] + } + this.index[last]++; + if (start + next.length >= Math.max(this.safeFrom, pos)) { + this.trees.push(next); + this.start.push(start); + this.index.push(0); + } + } else { + this.index[last]++; + this.nextStart = start + next.length; + } } - ] + } }; -var cardListItem = { - def: { - id: "cardListItem", - type: "listItem" - }, - node: { - type: "group", - id: "$root", - schemaId: "$root", - name: "Card Item", - rank: 0, - props: { - _selected: `$root.props['_selectedIndex'] == $contexts.$context['_index']` - }, - styles: { - layout: `"column"`, - overflow: `'hidden'`, - borderRadius: `'8px'`, - width: `'100%'`, - border: `'1px solid var(--mk-ui-border)'` - }, - actions: { - onClick: `$saveState({ $root: {props: {_selectedIndex: $contexts.$context['_index']}} });`, - onDoubleClick: `$api.path.open($contexts.$context['_keyValue'], false)` - } - }, - id: "$root", - children: [ - frameRootWithProps( - { - ...slidesNode, - children: [ - frameRootWithProps( - { - ...slideNode, - children: [ - frameRootWithProps( - { ...deltaNode, node: { ...deltaNode.node, ref: "$root" } }, - {}, - { - background: `'var(--mk-ui-background-selected)'` - } - ) - ] - }, - { value: "true" } - ), - frameRootWithProps( - { - ...slideNode, - children: [ - frameRootWithProps( - { ...deltaNode, node: { ...deltaNode.node, ref: "$root" } }, - {}, - { - background: `'var(--mk-ui-background)'` - } - ) - ] - }, - { value: "false" } - ) - ] - }, - { - value: `'_selected'` - } - ), - frameRootWithProps( - imageNode, - { - value: `$api.path.label($contexts.$context['_keyValue'])?.thumbnail` - }, - { - width: `'100%'`, - maxHeight: `'80px'` +var TokenCache = class { + constructor(parser3, stream) { + this.stream = stream; + this.tokens = []; + this.mainToken = null; + this.actions = []; + this.tokens = parser3.tokenizers.map((_15) => new CachedToken()); + } + getActions(stack) { + let actionIndex = 0; + let main = null; + let { parser: parser3 } = stack.p, { tokenizers } = parser3; + let mask = parser3.stateSlot(stack.state, 3); + let context = stack.curContext ? stack.curContext.hash : 0; + let lookAhead = 0; + for (let i4 = 0; i4 < tokenizers.length; i4++) { + if ((1 << i4 & mask) == 0) + continue; + let tokenizer2 = tokenizers[i4], token = this.tokens[i4]; + if (main && !tokenizer2.fallback) + continue; + if (tokenizer2.contextual || token.start != stack.pos || token.mask != mask || token.context != context) { + this.updateCachedToken(token, tokenizer2, stack); + token.mask = mask; + token.context = context; } - ), - { - ...groupNode, - node: { - ...groupNode.node, - styles: { - gap: `'8px'`, - padding: `'8px'`, - flex: `'1'` + if (token.lookAhead > token.end + 25) + lookAhead = Math.max(token.lookAhead, lookAhead); + if (token.value != 0) { + let startIndex = actionIndex; + if (token.extended > -1) + actionIndex = this.addActions(stack, token.extended, token.end, actionIndex); + actionIndex = this.addActions(stack, token.value, token.end, actionIndex); + if (!tokenizer2.extend) { + main = token; + if (actionIndex > startIndex) + break; } - }, - children: [ - frameRootWithProps( - textNode, - { - value: `$api.path.label($contexts.$context['_keyValue'])?.name` - }, - { - "--font-text-weight": `'var(--bold-weight)'` - } - ), - kitWithProps(fieldsView, {}) - ] + } } - ] -}; -var listItem = { - def: { - id: "rowItem", - type: "listItem" - }, - node: { - type: "group", - id: "$root", - schemaId: "$root", - name: "List View", - rank: 0, - props: { - _selected: `$root.props['_selectedIndex'] == $contexts.$context['_index']` - }, - styles: { - layout: `"row"`, - gap: `'12px'`, - padding: `'4px'`, - overflow: `'hidden'`, - width: `'100%'` - }, - actions: { - onClick: `$saveState({ $root: {props: {_selectedIndex: $contexts.$context['_index']}} });`, - onDoubleClick: `$api.path.open($contexts.$context['_keyValue'], false)`, - onContextMenu: `$api.path.contextMenu($event, $contexts.$context['_keyValue'])` + while (this.actions.length > actionIndex) + this.actions.pop(); + if (lookAhead) + stack.setLookAhead(lookAhead); + if (!main && stack.pos == this.stream.end) { + main = new CachedToken(); + main.value = stack.p.parser.eofTerm; + main.start = main.end = stack.pos; + actionIndex = this.addActions(stack, main.value, main.end, actionIndex); } - }, - id: "$root", - children: [ - frameRootWithProps( - { - ...slidesNode, - children: [ - frameRootWithProps( - { - ...slideNode, - children: [ - frameRootWithProps( - { ...deltaNode, node: { ...deltaNode.node, ref: "$root" } }, - {}, - { - background: `'var(--mk-ui-background-selected)'` - } - ) - ] - }, - { value: "true" } - ), - frameRootWithProps( - { - ...slideNode, - children: [ - frameRootWithProps( - { ...deltaNode, node: { ...deltaNode.node, ref: "$root" } }, - {}, - { - background: `'transparent'` - } - ) - ] - }, - { value: "false" } - ) - ] - }, - { - value: `'_selected'` - } - ), - kitWithProps( - previewNode, - { - path: `$contexts.$context['_keyValue']`, - width: `'32px'`, - height: `'32px'`, - padding: `'8px'`, - radius: `'4px'` - }, - { - borderRadius: `'4px'`, - background: `'var(--background-secondary)'` - } - ), - { - ...groupNode, - node: { - ...groupNode.node, - styles: { - gap: `'8px'`, - flex: `'1'`, - padding: `'2px'`, - layout: `'column'`, - layoutAlign: `'w'` + this.mainToken = main; + return this.actions; + } + getMainToken(stack) { + if (this.mainToken) + return this.mainToken; + let main = new CachedToken(), { pos, p } = stack; + main.start = pos; + main.end = Math.min(pos + 1, p.stream.end); + main.value = pos == p.stream.end ? p.parser.eofTerm : 0; + return main; + } + updateCachedToken(token, tokenizer2, stack) { + tokenizer2.token(this.stream.reset(stack.pos, token), stack); + if (token.value > -1) { + let { parser: parser3 } = stack.p; + for (let i4 = 0; i4 < parser3.specialized.length; i4++) + if (parser3.specialized[i4] == token.value) { + let result = parser3.specializers[i4](this.stream.read(token.start, token.end), stack); + if (result >= 0 && stack.p.parser.dialect.allows(result >> 1)) { + if ((result & 1) == 0) + token.value = result >> 1; + else + token.extended = result >> 1; + break; + } } - }, - children: [ - frameRootWithProps( - textNode, - { - value: `$api.path.label($contexts.$context['_keyValue'])?.name` - }, - { - "--font-text-size": `'14px'`, - "--font-text-weight": `'var(--bold-weight)'` + } else { + token.value = 0; + token.end = Math.min(stack.p.stream.end, stack.pos + 1); + } + } + putAction(action, token, end, index2) { + for (let i4 = 0; i4 < index2; i4 += 3) + if (this.actions[i4] == action) + return index2; + this.actions[index2++] = action; + this.actions[index2++] = token; + this.actions[index2++] = end; + return index2; + } + addActions(stack, token, end, index2) { + let { state } = stack, { parser: parser3 } = stack.p, { data: data2 } = parser3; + for (let set = 0; set < 2; set++) { + for (let i4 = parser3.stateSlot(state, set ? 2 : 1); ; i4 += 3) { + if (data2[i4] == 65535) { + if (data2[i4 + 1] == 1) { + i4 = pair(data2, i4 + 2); + } else { + if (index2 == 0 && data2[i4 + 1] == 2) + index2 = this.putAction(pair(data2, i4 + 2), token, end, index2); + break; } - ) - ] + } + if (data2[i4] == token) + index2 = this.putAction(pair(data2, i4 + 1), token, end, index2); + } } - ] + return index2; + } }; -var detailItem = { - def: { - id: "detailItem", - type: "listItem" - }, - node: { - type: "group", - id: "$root", - schemaId: "$root", - name: "Detail View", - rank: 0, - props: { - _selected: `$root.props['_selectedIndex'] == $contexts.$context['_index']` - }, - styles: { - layout: `"row"`, - gap: `'12px'`, - padding: `'8px'`, - overflow: `'hidden'`, - width: `'100%'` - }, - actions: { - onClick: `$saveState({ $root: {props: {_selectedIndex: $contexts.$context['_index']}} });`, - onDoubleClick: `$api.path.open($contexts.$context['_keyValue'], false)`, - onContextMenu: `$api.path.contextMenu($event, $contexts.$context['_keyValue'])` - } - }, - id: "$root", - children: [ - frameRootWithProps( - { - ...slidesNode, - children: [ - frameRootWithProps( - { - ...slideNode, - children: [ - frameRootWithProps( - { ...deltaNode, node: { ...deltaNode.node, ref: "$root" } }, - {}, - { - background: `'var(--mk-ui-background-selected)'` - } - ) - ] - }, - { value: "true" } - ), - frameRootWithProps( - { - ...slideNode, - children: [ - frameRootWithProps( - { ...deltaNode, node: { ...deltaNode.node, ref: "$root" } }, - {}, - { - background: `'transparent'` - } - ) - ] - }, - { value: "false" } - ) - ] - }, - { - value: `'_selected'` - } - ), - kitWithProps( - previewNode, - { - path: `$contexts.$context['_keyValue']`, - radius: `'4px'`, - width: `'50px'`, - height: `'50px'` - }, - { - height: `'50px'`, - borderRadius: `'8px'`, - background: `'var(--background-secondary)'` - } - ), - { - ...groupNode, - node: { - ...groupNode.node, - styles: { - gap: `'8px'`, - flex: `'1'`, - padding: `'2px'`, - layout: `'column'`, - borderBottom: `'thin solid var(--mk-ui-border)'` - } - }, - children: [ - frameRootWithProps( - textNode, - { - value: `$api.path.label($contexts.$context['_keyValue'])?.name` - }, - { - "--font-text-size": `'18px'`, - "--font-text-weight": `'var(--bold-weight)'` +var Rec; +(function(Rec2) { + Rec2[Rec2["Distance"] = 5] = "Distance"; + Rec2[Rec2["MaxRemainingPerStep"] = 3] = "MaxRemainingPerStep"; + Rec2[Rec2["MinBufferLengthPrune"] = 500] = "MinBufferLengthPrune"; + Rec2[Rec2["ForceReduceLimit"] = 10] = "ForceReduceLimit"; + Rec2[Rec2["CutDepth"] = 15e3] = "CutDepth"; + Rec2[Rec2["CutTo"] = 9e3] = "CutTo"; +})(Rec || (Rec = {})); +var Parse = class { + constructor(parser3, input, fragments, ranges) { + this.parser = parser3; + this.input = input; + this.ranges = ranges; + this.recovering = 0; + this.nextStackID = 9812; + this.minStackPos = 0; + this.reused = []; + this.stoppedAt = null; + this.stream = new InputStream(input, ranges); + this.tokens = new TokenCache(parser3, this.stream); + this.topTerm = parser3.top[1]; + let { from } = ranges[0]; + this.stacks = [Stack.start(this, parser3.top[0], from)]; + this.fragments = fragments.length && this.stream.end - from > parser3.bufferLength * 4 ? new FragmentCursor(fragments, parser3.nodeSet) : null; + } + get parsedPos() { + return this.minStackPos; + } + advance() { + let stacks = this.stacks, pos = this.minStackPos; + let newStacks = this.stacks = []; + let stopped, stoppedTokens; + for (let i4 = 0; i4 < stacks.length; i4++) { + let stack = stacks[i4]; + for (; ; ) { + this.tokens.mainToken = null; + if (stack.pos > pos) { + newStacks.push(stack); + } else if (this.advanceStack(stack, newStacks, stacks)) { + continue; + } else { + if (!stopped) { + stopped = []; + stoppedTokens = []; } - ), - frameRootWithProps(textNode, { - value: `$api.path.label($contexts.$context['_keyValue'])?.preview` - }, { - "--font-text-size": `'14px'`, - "--font-text-color": `'var(--mk-ui-text-tertiary)'` - }), - kitWithProps(fieldsView, {}) - ] - } - ] -}; -var newItemNode = { - id: "newItem", - def: { - id: "newItem" - }, - node: { - schemaId: "newItem", - parentId: "", - name: "New Item", - rank: 0, - id: "newItem", - type: "group", - props: { - space: "", - schema: "", - group: "", - groupValue: "" - }, - types: { - space: "text", - schema: "text", - group: "text", - groupValue: "text" - }, - actions: {}, - styles: { - gap: `'4px'` - } - }, - children: [ - { - ...inputNode, - node: { - ...inputNode.node, - styles: { ...inputNode.node.styles, placeholder: `'+ New Item'`, border: `'none'`, background: `'transparent'` }, - actions: { - onEnter: `$api.context.insert($root.props.space, $root.props.schema, $value, {[$root.props.group]: $root.props.groupValue}); $event.currentTarget.value = ''` + stopped.push(stack); + let tok = this.tokens.getMainToken(stack); + stoppedTokens.push(tok.value, tok.end); } + break; } } - ] -}; -var listGroup = { - def: { - id: "listGroup", - type: "listGroup" - }, - node: { - type: "group", - props: { - _groupType: ``, - _groupField: ``, - _groupValue: ``, - showNew: "true" - }, - types: { - _groupType: "text", - _groupField: "text", - _groupValue: "text", - showNew: "boolean" - }, - propsValue: { - showNew: { - alias: "New Item Button" - } - }, - id: "$root", - schemaId: "$root", - name: "Rows", - rank: 0 - }, - id: "$root", - children: [ - kitWithProps(fieldNode, { - type: `$root.props['_groupType']`, - value: `$root.props['_groupValue']` - }), - frameRootWithProps(contentNode, {}, { - layout: `'column'`, - alignItems: `'stretch'` - }), - kitWithProps(newItemNode, { - space: `$contexts.$context['_path']`, - schema: `$contexts.$context['_schema']`, - group: `$root.props['_groupField']`, - groupValue: `$root.props['_groupValue']` - }, { - hidden: `!$root.props['showNew']` - }) - ] -}; -var columnGroup = { - def: { - id: "columnGroup", - type: "listGroup" - }, - node: { - type: "group", - props: { - _groupType: ``, - _groupField: "", - _groupValue: ``, - showNew: "true" - }, - types: { - _groupType: "text", - _groupField: "text", - _groupValue: "text", - showNew: "boolean" - }, - propsValue: { - showNew: { - alias: "New Item Button" + if (!newStacks.length) { + let finished = stopped && findFinished(stopped); + if (finished) + return this.stackToTree(finished); + if (this.parser.strict) { + if (verbose && stopped) + console.log("Stuck with token " + (this.tokens.mainToken ? this.parser.getName(this.tokens.mainToken.value) : "none")); + throw new SyntaxError("No parse at " + pos); } - }, - styles: { - layout: `'column'`, - width: `'262px'`, - background: `'var(--mk-ui-background-variant)'`, - borderRadius: `'8px'`, - padding: `'6px'` - }, - id: "$root", - schemaId: "$root", - name: "Columns", - rank: 0 - }, - id: "$root", - children: [ - kitWithProps(fieldNode, { - type: `$root.props['_groupType']`, - value: `$root.props['_groupValue']` - }), - frameRootWithProps( - contentNode, - {}, - { - gap: `'8px'`, - layout: `'column'`, - width: `'100%'`, - alignItems: `'stretch'` + if (!this.recovering) + this.recovering = 5; + } + if (this.recovering && stopped) { + let finished = this.stoppedAt != null && stopped[0].pos > this.stoppedAt ? stopped[0] : this.runRecovery(stopped, stoppedTokens, newStacks); + if (finished) + return this.stackToTree(finished.forceAll()); + } + if (this.recovering) { + let maxRemaining = this.recovering == 1 ? 1 : this.recovering * 3; + if (newStacks.length > maxRemaining) { + newStacks.sort((a4, b2) => b2.score - a4.score); + while (newStacks.length > maxRemaining) + newStacks.pop(); } - ), - frameRootWithProps( - { ...groupNode, children: [kitWithProps( - newItemNode, - { - space: `$contexts.$context['_path']`, - schema: `$contexts.$context['_schema']`, - group: `$root.props['_groupField']`, - groupValue: `$root.props['_groupValue']` - }, - { - hidden: `!$root.props['showNew']` + if (newStacks.some((s4) => s4.reducePos > pos)) + this.recovering--; + } else if (newStacks.length > 1) { + outer: + for (let i4 = 0; i4 < newStacks.length - 1; i4++) { + let stack = newStacks[i4]; + for (let j = i4 + 1; j < newStacks.length; j++) { + let other = newStacks[j]; + if (stack.sameState(other) || stack.buffer.length > 500 && other.buffer.length > 500) { + if ((stack.score - other.score || stack.buffer.length - other.buffer.length) > 0) { + newStacks.splice(j--, 1); + } else { + newStacks.splice(i4--, 1); + continue outer; + } + } + } } - )] }, - {}, - { - height: `'auto'`, - marginTop: `'8px'`, - borderRadius: `'8px'`, - width: `'250px'`, - border: `'1px solid var(--mk-ui-border)'`, - background: `'var(--mk-ui-background)'` - } - ) - ] -}; -var rowGroup = { - def: { - id: "rowGroup", - type: "listGroup" - }, - node: { - type: "group", - props: { - _groupType: ``, - _groupField: "", - _groupValue: `` - }, - types: { - _groupType: "text", - _groupField: "text", - _groupValue: "text" - }, - styles: { - layout: `'column'`, - padding: `'6px'`, - gap: `'8px'` - }, - id: "$root", - schemaId: "$root", - name: "Catalog Group", - rank: 0 - }, - id: "$root", - children: [ - kitWithProps(fieldNode, { - type: `$root.props['_groupType']`, - value: `$root.props['_groupValue']` - }), - frameRootWithProps( - contentNode, - {}, - { - gap: `'8px'`, - layout: `'row'`, - width: `'100%'`, - overflow: `'scroll'` - } - ) - ] -}; -var gridGroup = { - def: { - id: "gridGroup", - type: "listGroup" - }, - node: { - type: "group", - props: { - _groupType: ``, - _groupField: "", - _groupValue: `` - }, - types: { - _groupType: "text", - _groupField: "text", - _groupValue: "text" - }, - styles: { - layout: `'column'`, - padding: `'6px'`, - gap: `'8px'` - }, - id: "$root", - schemaId: "$root", - name: "Grid Group", - rank: 0 - }, - id: "$root", - children: [ - kitWithProps(fieldNode, { - type: `$root.props['_groupType']`, - value: `$root.props['_groupValue']` - }), - frameRootWithProps( - contentNode, - {}, - { - gap: `'8px'`, - layout: `'grid'`, - width: `'100%'`, - "--mk-grid-columns": `'auto-fill'`, - "--mk-grid-width": `'250px'` - } - ) - ] -}; -var masonryGroup = { - def: { - id: "masonryGroup", - type: "listGroup" - }, - node: { - type: "group", - props: {}, - id: "$root", - schemaId: "$root", - name: "Masonry", - rank: 0, - styles: { - layout: `'column'` } - }, - id: "$root", - children: [ - kitWithProps(fieldNode, { - type: `$root.props['_groupType']`, - value: `$root.props['_groupValue']` - }), - frameRootWithProps( - contentNode, - {}, - { - padding: `'8px'`, - layout: `'masonry'` - } - ) - ] -}; -var listView = { - def: { - id: "listView", - type: "listView" - }, - node: { - type: "group", - props: {}, - id: "$root", - schemaId: "$root", - name: "List View", - rank: 0 - }, - id: "$root", - children: [ - contentNode - ] -}; -var columnView = { - def: { - id: "columnView", - type: "listView" - }, - node: { - type: "group", - props: {}, - id: "$root", - schemaId: "$root", - name: "Column View", - rank: 0 - }, - id: "$root", - children: [ - frameRootWithProps( - contentNode, - {}, - { - padding: `'8px'`, - layout: `'row'`, - gap: `'8px'` - } - ) - ] -}; - -// src/core/utils/commands/filter.ts -var filterForAny = (props, filters) => { - return filters.reduce((p, c3) => { - if (p == true) - return true; - return props ? filterForProps(props, c3) : false; - }, false); -}; -var filterForProps = (props, def) => { - const filterFn = filterFnTypes[def.fn]; - let result = true; - if (filterFn) { - result = filterFn.fn(parseProperty(def.field, props[def.field]), def.value); + this.minStackPos = newStacks[0].pos; + for (let i4 = 1; i4 < newStacks.length; i4++) + if (newStacks[i4].pos < this.minStackPos) + this.minStackPos = newStacks[i4].pos; + return null; } - return result; -}; -var filterPathsForAll2 = (props, filters) => { - return filters.reduce((p, c3) => { - if (p == false) - return false; - return props ? filterForProps(props, c3) : false; - }, true); -}; -var resultForFilters = (filters, props) => { - const pathInFilter = filters.reduce((p, c3) => { - if (!p || c3.filters.length == 0) - return false; - const result = c3.type == "any" ? filterForAny(props, c3.filters) : filterPathsForAll2(props, c3.filters); - return result; - }, true); - return pathInFilter; -}; - -// src/core/utils/commands/actions.ts -var import_lodash8 = __toESM(require_lodash()); -var parseActionString = (actionString) => { - return safelyParseJSON(actionString); -}; -var runActionString = async (superstate, actionString, instance) => { - const actionTree = parseActionString(actionString); - return runActionTree(superstate, actionTree, instance); -}; -var runActionTree = async (superstate, actionTree, instance) => { - if (instance.iterations > superstate.settings.actionMaxSteps) { - alert("Max steps reached, you can change this in settings."); - return; + stopAt(pos) { + if (this.stoppedAt != null && this.stoppedAt < pos) + throw new RangeError("Can't move stoppedAt forward"); + this.stoppedAt = pos; } - const newInstance = { - ...instance, - iterations: instance.iterations + 1, - props: { - ...actionTree?.props ?? {}, - ...Object.keys(actionTree.linked ?? {}).reduce( - (p, c3) => ({ ...p, [c3]: instance.instanceProps[actionTree.linked[c3]] }), - {} - ), - ...actionTree.result ? { [actionTree.result]: instance.result } : {} + advanceStack(stack, stacks, split) { + let start = stack.pos, { parser: parser3 } = this; + let base2 = verbose ? this.stackID(stack) + " -> " : ""; + if (this.stoppedAt != null && start > this.stoppedAt) + return stack.forceReduce() ? stack : null; + if (this.fragments) { + let strictCx = stack.curContext && stack.curContext.tracker.strict, cxHash = strictCx ? stack.curContext.hash : 0; + for (let cached = this.fragments.nodeAt(start); cached; ) { + let match2 = this.parser.nodeSet.types[cached.type.id] == cached.type ? parser3.getGoto(stack.state, cached.type.id) : -1; + if (match2 > -1 && cached.length && (!strictCx || (cached.prop(NodeProp.contextHash) || 0) == cxHash)) { + stack.useNode(cached, match2); + if (verbose) + console.log(base2 + this.stackID(stack) + ` (via reuse of ${parser3.getName(cached.type.id)})`); + return true; + } + if (!(cached instanceof Tree) || cached.children.length == 0 || cached.positions[0] > 0) + break; + let inner = cached.children[0]; + if (inner instanceof Tree && cached.positions[0] == 0) + cached = inner; + else + break; + } } - }; - const action = superstate.cli.commandForAction(actionTree.action); - if (action.schema.type == "builtin") { - if (action.schema.id == "loop" && (0, import_lodash8.isArray)(instance.result)) { - const loopResults = await Promise.all( - instance.result.map( - (item) => Promise.all( - actionTree.children.map( - (child) => runActionTree(superstate, child, resultInstance) - ) - ).then((results) => results[results.length - 1]) - ) - ); - return loopResults; + let defaultReduce = parser3.stateSlot(stack.state, 4); + if (defaultReduce > 0) { + stack.reduce(defaultReduce); + if (verbose) + console.log(base2 + this.stackID(stack) + ` (via always-reduce ${parser3.getName(defaultReduce & 65535)})`); + return true; } - if (action.schema.id == "filter") { - const result2 = resultForFilters( - actionTree.props.$function, - newInstance.instanceProps - ); - if (!result2) { - return; + if (stack.stack.length >= 15e3) { + while (stack.stack.length > 9e3 && stack.forceReduce()) { } } - } - let result; - try { - if (action.schema.type == "api") { - const [namespace, method] = action.schema.id.split("."); - result = await superstate.api[namespace]?.[method]?.(...action.fields.map((f2) => newInstance.props[f2.name])); - } else { - result = await superstate.cli.runCommand( - actionTree.action, - newInstance - ); + let actions = this.tokens.getActions(stack); + for (let i4 = 0; i4 < actions.length; ) { + let action = actions[i4++], term = actions[i4++], end = actions[i4++]; + let last = i4 == actions.length || !split; + let localStack = last ? stack : stack.split(); + localStack.apply(action, term, end); + if (verbose) + console.log(base2 + this.stackID(localStack) + ` (via ${(action & 65536) == 0 ? "shift" : `reduce of ${parser3.getName(action & 65535)}`} for ${parser3.getName(term)} @ ${start}${localStack == stack ? "" : ", split"})`); + if (last) + return true; + else if (localStack.pos > start) + stacks.push(localStack); + else + split.push(localStack); } - } catch (e5) { - console.error(e5); + return false; } - const resultInstance = { - ...newInstance, - result - }; - if (actionTree.children?.length === 0) - return result; - const childrenResults = await Promise.all( - actionTree.children.map( - (child) => runActionTree(superstate, child, resultInstance) - ) - ); - return childrenResults[childrenResults.length - 1]; -}; - -// src/core/utils/frames/runner.ts -var executeTreeNode = async (_treeNode, store, executionContext) => { - const treeNode = _treeNode; - if (store.prevState[treeNode.id] && treeNode.node.type != "content") { - let skipped = false; - if (treeNode.node.type == "slides" || treeNode.node.type == "slide" || treeNode.node.type == "delta") { - skipped = false; - } else { - const childDepCheck = (treeNode.execPropsOptions.children ?? []).some((f2) => Object.keys(store.newState).includes(f2)); - const sameProps = Object.keys(store.newState[treeNode.id]?.props ?? {}).every((f2) => store.newState[treeNode.id]?.props[f2] == store.prevState[treeNode.id]?.props[f2]); - const sameStyles = Object.keys(store.newState[treeNode.id]?.styles ?? {}).every((f2) => store.newState[treeNode.id]?.styles[f2] == store.prevState[treeNode.id]?.styles[f2]); - const sameDepValues = treeNode.execPropsOptions.deps.every((f2) => { - if (f2[0] == "$api") - return true; - if (store.newState[f2[0]]?.[f2[1]]?.[f2[2]] === void 0) - return true; - return store.newState[f2[0]]?.[f2[1]]?.[f2[2]] === store.prevState[f2[0]]?.[f2[1]]?.[f2[2]]; - }); - if (sameProps && sameStyles && sameDepValues && !childDepCheck) { - skipped = true; + advanceFully(stack, newStacks) { + let pos = stack.pos; + for (; ; ) { + if (!this.advanceStack(stack, null, null)) + return false; + if (stack.pos > pos) { + pushStackDedup(stack, newStacks); + return true; } } - if (skipped) - return { id: executionContext.runID, root: executionContext.root, exec: treeNode, state: store.state, slides: store.slides, newState: store.newState, prevState: store.prevState }; - } - let execState = await executeNode(treeNode, store, executionContext.contexts, executionContext.api); - if (treeNode.node.type == "list") { - let uid = 0; - treeNode.children = ensureArray(execState.state[treeNode.id].props.value).flatMap((f2, i4) => treeNode.execPropsOptions.template.map((n3) => { - const [tree, m4] = linkTreeNodes({ ...n3, node: { ...n3.node, props: { ...n3.node.props, _index: `${i4}`, value: `${treeNode.id}.props.value[${i4}]` } } }, uid); - uid = m4; - return buildExecutable(tree); - })); - } - if (typeof execState.state[treeNode.id]?.actions?.onRun == "function") { - execState.state[treeNode.id].actions?.onRun( - null, - null, - execState, - (s4) => { - executionContext.saveState(s4, { state: execState.state, slides: execState.slides, root: executionContext.root, exec: executionContext.exec, id: executionContext.runID }); - }, - executionContext.api - ); } - treeNode.children = [ - ...treeNode.children.filter((b2) => b2.node.type == "slides"), - ...treeNode.children.filter((b2) => b2.node.type != "slides") - ]; - for (let i4 = 0; i4 < treeNode.children.length; i4++) { - const [newState, newNode2] = await executeTreeNode(treeNode.children[i4], execState, executionContext).then((f2) => [{ state: f2.state, newState: f2.newState, slides: f2.slides, prevState: f2.prevState }, f2.exec]); - execState = newState; - treeNode.children[i4] = newNode2; - if (newNode2.node.type == "slides") { - const prop2 = newState.state[newNode2.id].props.value; - const state = newState.state[newNode2.node.parentId]?.props[prop2]; - let currentSlide; - if (executionContext.selectedSlide) { - currentSlide = newNode2.children.find((f2) => f2.id == executionContext.selectedSlide); + runRecovery(stacks, tokens, newStacks) { + let finished = null, restarted = false; + for (let i4 = 0; i4 < stacks.length; i4++) { + let stack = stacks[i4], token = tokens[i4 << 1], tokenEnd = tokens[(i4 << 1) + 1]; + let base2 = verbose ? this.stackID(stack) + " -> " : ""; + if (stack.deadEnd) { + if (restarted) + continue; + restarted = true; + stack.restart(); + if (verbose) + console.log(base2 + this.stackID(stack) + " (restarted)"); + let done = this.advanceFully(stack, newStacks); + if (done) + continue; } - if (state !== null && !currentSlide) { - currentSlide = newNode2.children.find((f2) => newState.state[f2.id].props.value == state); + let force = stack.split(), forceBase = base2; + for (let j = 0; force.forceReduce() && j < 10; j++) { + if (verbose) + console.log(forceBase + this.stackID(force) + " (via force-reduce)"); + let done = this.advanceFully(force, newStacks); + if (done) + break; + if (verbose) + forceBase = this.stackID(force) + " -> "; } - if (currentSlide) { - currentSlide.children.forEach((f2) => { - if (!execState.newState[f2.node.ref]) { - execState.newState[f2.node.ref] = { props: {}, styles: {}, actions: {} }; - } - if (f2.node.ref == treeNode.id) { - execState.state[f2.node.ref].props = { ...execState.state[f2.node.ref].props, ...execState.state[f2.node.id].props }; - execState.state[f2.node.ref].styles = { ...execState.state[f2.node.ref].styles, ...execState.state[f2.node.id].styles }; - execState.state[f2.node.ref].actions = { ...execState.state[f2.node.ref].actions, ...execState.state[f2.node.id].actions }; - } else { - execState.newState[f2.node.ref].props = { ...execState.newState[f2.node.ref].props, ...execState.state[f2.node.id].props }; - execState.newState[f2.node.ref].styles = { ...execState.newState[f2.node.ref].styles, ...execState.state[f2.node.id].styles }; - execState.newState[f2.node.ref].actions = { ...execState.newState[f2.node.ref].actions, ...execState.state[f2.node.id].actions }; - } - }); + for (let insert2 of stack.recoverByInsert(token)) { + if (verbose) + console.log(base2 + this.stackID(insert2) + " (via recover-insert)"); + this.advanceFully(insert2, newStacks); + } + if (this.stream.end > stack.pos) { + if (tokenEnd == stack.pos) { + tokenEnd++; + token = 0; + } + stack.recoverByDelete(token, tokenEnd); + if (verbose) + console.log(base2 + this.stackID(stack) + ` (via recover-delete ${this.parser.getName(token)})`); + pushStackDedup(stack, newStacks); + } else if (!finished || finished.score < stack.score) { + finished = stack; } } + return finished; + } + stackToTree(stack) { + stack.close(); + return Tree.build({ + buffer: StackBufferCursor.create(stack), + nodeSet: this.parser.nodeSet, + topID: this.topTerm, + maxBufferLength: this.parser.bufferLength, + reused: this.reused, + start: this.ranges[0].from, + length: stack.pos - this.ranges[0].from, + minRepeatType: this.parser.minRepeatTerm + }); + } + stackID(stack) { + let id3 = (stackIDs || (stackIDs = /* @__PURE__ */ new WeakMap())).get(stack); + if (!id3) + stackIDs.set(stack, id3 = String.fromCodePoint(this.nextStackID++)); + return id3 + stack; } - return { id: executionContext.runID, root: executionContext.root, exec: treeNode, state: execState.state, slides: execState.slides, newState: execState.newState, prevState: execState.prevState }; }; -var executeNode = async (executable, results, contexts, api) => { - const propResults = await executePropsCodeBlocks(executable, results, contexts, api); - const stylesResults = executeCodeBlocks(executable.node, "styles", executable.execStyles, propResults); - const actions = executeCodeBlocks(executable.node, "actions", executable.execActions, stylesResults); - return actions; +function pushStackDedup(stack, newStacks) { + for (let i4 = 0; i4 < newStacks.length; i4++) { + let other = newStacks[i4]; + if (other.pos == stack.pos && other.sameState(stack)) { + if (newStacks[i4].score < stack.score) + newStacks[i4] = stack; + return; + } + } + newStacks.push(stack); +} +var Dialect = class { + constructor(source, flags, disabled) { + this.source = source; + this.flags = flags; + this.disabled = disabled; + } + allows(term) { + return !this.disabled || this.disabled[term] == 0; + } }; -var executeCode = (code, environment) => { - const isMultiLine = typeof code === "string" || code instanceof String ? code.includes("\n") : false; - const func = isMultiLine ? new Function(`with(this) { ${code} }`) : new Function(`with(this) { return ${code}; }`); - return func.call(environment); +var id = (x2) => x2; +var ContextTracker = class { + constructor(spec) { + this.start = spec.start; + this.shift = spec.shift || id; + this.reduce = spec.reduce || id; + this.reuse = spec.reuse || id; + this.hash = spec.hash || (() => 0); + this.strict = spec.strict !== false; + } }; -var executePropsCodeBlocks = async (executable, results, contexts, api) => { - const { id: id3 } = executable.node; - const codeBlockStore = executable.execProps ?? {}; - const environment = results.state; - environment[id3] = { - props: results.state[id3]?.props ?? {}, - actions: results.state[id3]?.actions ?? {}, - styles: results.state[id3]?.styles ?? {} - }; - environment.$contexts = contexts, environment.$api = api; - for (const { name: key2, isConst } of executable.execPropsOptions.props) { - try { - let result; - if (key2 in (results.newState?.[id3]?.["props"] || {}) && isConst) { - result = results.newState[id3]["props"][key2]; - } else { - result = codeBlockStore[key2]?.call(environment); - } - if (result !== null) { - environment[id3]["props"][key2] = result; - results.state[id3]["props"][key2] = result; - if (results.newState) { - results.newState[id3] = results.newState[id3] ?? { props: {}, styles: {}, actions: {} }; - results.newState[id3]["props"][key2] = result; +var LRParser = class extends Parser4 { + constructor(spec) { + super(); + this.wrappers = []; + if (spec.version != 14) + throw new RangeError(`Parser version (${spec.version}) doesn't match runtime version (${14})`); + let nodeNames = spec.nodeNames.split(" "); + this.minRepeatTerm = nodeNames.length; + for (let i4 = 0; i4 < spec.repeatNodeCount; i4++) + nodeNames.push(""); + let topTerms = Object.keys(spec.topRules).map((r2) => spec.topRules[r2][1]); + let nodeProps = []; + for (let i4 = 0; i4 < nodeNames.length; i4++) + nodeProps.push([]); + function setProp(nodeID, prop2, value) { + nodeProps[nodeID].push([prop2, prop2.deserialize(String(value))]); + } + if (spec.nodeProps) + for (let propSpec of spec.nodeProps) { + let prop2 = propSpec[0]; + if (typeof prop2 == "string") + prop2 = NodeProp[prop2]; + for (let i4 = 1; i4 < propSpec.length; ) { + let next = propSpec[i4++]; + if (next >= 0) { + setProp(next, prop2, propSpec[i4++]); + } else { + let value = propSpec[i4 + -next]; + for (let j = -next; j > 0; j--) + setProp(propSpec[i4++], prop2, value); + i4++; + } } - } else { - delete environment[id3]["props"][key2]; - delete results.state[id3]["props"][key2]; - if (results.newState?.[id3]) { - delete results.newState[id3]["props"][key2]; + } + this.nodeSet = new NodeSet(nodeNames.map((name317, i4) => NodeType.define({ + name: i4 >= this.minRepeatTerm ? void 0 : name317, + id: i4, + props: nodeProps[i4], + top: topTerms.indexOf(i4) > -1, + error: i4 == 0, + skipped: spec.skippedNodes && spec.skippedNodes.indexOf(i4) > -1 + }))); + if (spec.propSources) + this.nodeSet = this.nodeSet.extend(...spec.propSources); + this.strict = false; + this.bufferLength = DefaultBufferLength; + let tokenArray = decodeArray(spec.tokenData); + this.context = spec.context; + this.specialized = new Uint16Array(spec.specialized ? spec.specialized.length : 0); + this.specializers = []; + if (spec.specialized) + for (let i4 = 0; i4 < spec.specialized.length; i4++) { + this.specialized[i4] = spec.specialized[i4].term; + this.specializers[i4] = spec.specialized[i4].get; + } + this.states = decodeArray(spec.states, Uint32Array); + this.data = decodeArray(spec.stateData); + this.goto = decodeArray(spec.goto); + this.maxTerm = spec.maxTerm; + this.tokenizers = spec.tokenizers.map((value) => typeof value == "number" ? new TokenGroup(tokenArray, value) : value); + this.topRules = spec.topRules; + this.dialects = spec.dialects || {}; + this.dynamicPrecedences = spec.dynamicPrecedences || null; + this.tokenPrecTable = spec.tokenPrec; + this.termNames = spec.termNames || null; + this.maxNode = this.nodeSet.types.length - 1; + this.dialect = this.parseDialect(); + this.top = this.topRules[Object.keys(this.topRules)[0]]; + } + createParse(input, fragments, ranges) { + let parse7 = new Parse(this, input, fragments, ranges); + for (let w2 of this.wrappers) + parse7 = w2(parse7, input, fragments, ranges); + return parse7; + } + getGoto(state, term, loose = false) { + let table = this.goto; + if (term >= table[0]) + return -1; + for (let pos = table[term + 1]; ; ) { + let groupTag = table[pos++], last = groupTag & 1; + let target = table[pos++]; + if (last && loose) + return target; + for (let end = pos + (groupTag >> 1); pos < end; pos++) + if (table[pos] == state) + return target; + if (last) + return -1; + } + } + hasAction(state, terminal) { + let data2 = this.data; + for (let set = 0; set < 2; set++) { + for (let i4 = this.stateSlot(state, set ? 2 : 1), next; ; i4 += 3) { + if ((next = data2[i4]) == 65535) { + if (data2[i4 + 1] == 1) + next = data2[i4 = pair(data2, i4 + 2)]; + else if (data2[i4 + 1] == 2) + return pair(data2, i4 + 2); + else + break; } + if (next == terminal || next == 0) + return pair(data2, i4 + 1); } - } catch (error) { - console.log(key2, error, codeBlockStore[key2]); } + return 0; } - return results; -}; -function executeCodeBlocks(node, type, codeBlockStore, results) { - const { id: id3 } = node; - for (const key2 of Object.keys(codeBlockStore)) { - let result; - try { - if (key2 in (results.newState?.[id3]?.[type] || {})) { - result = results.newState[id3][type][key2]; - } else { - result = codeBlockStore[key2]?.call(results.state); + stateSlot(state, slot) { + return this.states[state * 6 + slot]; + } + stateFlag(state, flag) { + return (this.stateSlot(state, 0) & flag) > 0; + } + validAction(state, action) { + if (action == this.stateSlot(state, 4)) + return true; + for (let i4 = this.stateSlot(state, 1); ; i4 += 3) { + if (this.data[i4] == 65535) { + if (this.data[i4 + 1] == 1) + i4 = pair(this.data, i4 + 2); + else + return false; } - if (result !== null) { - results.state[node.id][type][key2] = result; - } else { - delete results.state[node.id][type][key2]; + if (action == pair(this.data, i4 + 1)) + return true; + } + } + nextStates(state) { + let result = []; + for (let i4 = this.stateSlot(state, 1); ; i4 += 3) { + if (this.data[i4] == 65535) { + if (this.data[i4 + 1] == 1) + i4 = pair(this.data, i4 + 2); + else + break; + } + if ((this.data[i4 + 2] & 65536 >> 16) == 0) { + let value = this.data[i4 + 1]; + if (!result.some((v2, i5) => i5 & 1 && v2 == value)) + result.push(this.data[i4], value); } - } catch (error) { - console.log(error, key2); } + return result; } - return results; -} - -// src/core/superstate/commands.ts -var SpacesCommandsAdapter = class { - constructor(manager, superstate) { - this.superstate = superstate; - this.scheme = "spaces"; - this.apiCommands = { - path: { - open: { - schema: { - id: "path.open", - name: "Open Path", - type: "api" - }, - fields: [{ - name: "path", - type: "link" - }] - }, - create: { - schema: { - id: "path.create", - name: "Create Item", - type: "api" - }, - fields: [{ - name: "name", - type: "text" - }, { - name: "space", - type: "space" - }, { - name: "content", - type: "text" - }] - }, - setProperty: { - schema: { - id: "path.setProperty", - name: "Save Property", - type: "api" - }, - fields: [ - { - name: "path", - type: "link" - }, - { - name: "property", - type: "option", - value: JSON.stringify({ - source: "$properties" - }) - }, - { - name: "value", - type: "text" - } - ] - } - }, - table: { - select: { - schema: { - id: "table.select", - name: "Get All List Items from Table", - type: "api" - }, - fields: [{ - name: "path", - type: "link" - }, { - name: "table", - type: "text" - }] - }, - update: { - schema: { - id: "table.update", - name: "Update List Item in Table", - type: "api" - }, - fields: [ - { - name: "path", - type: "link" - }, - { - name: "table", - type: "text" - }, - { - name: "index", - type: "number" - }, - { - name: "row", - type: "object" - } - ] - }, - insert: { - schema: { - id: "table.insert", - name: "Insert List Item into Table", - type: "api" - }, - fields: [{ - name: "path", - type: "link" - }, { - name: "schema", - type: "text" - }, { - name: "row", - type: "object" - }] - } - }, - context: { - select: { - schema: { - id: "context.select", - name: "Select Items from Context", - type: "api" - }, - fields: [{ - name: "path", - type: "link" - }, { - name: "table", - type: "text" - }] - }, - update: { - schema: { - id: "context.update", - name: "Update Item in Context", - type: "api" - }, - fields: [{ - name: "path", - type: "space" - }, { - name: "file", - type: "link" - }, { - name: "field", - type: "text" - }, { - name: "value", - type: "text" - }] - }, - insert: { - schema: { - id: "context.insert", - name: "Insert Item into Context", - type: "api" - }, - fields: [ - { - name: "path", - type: "link" - }, - { - name: "schema", - type: "text" - }, - { - name: "name", - type: "text" - }, - { - name: "row", - type: "object" - } - ] - } - } - }; - this.manager = manager; + overrides(token, prev) { + let iPrev = findOffset(this.data, this.tokenPrecTable, prev); + return iPrev < 0 || findOffset(this.data, this.tokenPrecTable, token) < iPrev; } - commandForAction(action) { - if (!action) - return null; - const uri = parseURI(action); - if (uri.authority == "$api") { - return this.apiCommands[uri.path]?.[uri.ref]; - } else if (uri.authority == "$actions") { - return this.superstate.actions.get(uri.path)?.find((f2) => f2.schema.id == uri.ref); - } else { - return this.superstate.actionsIndex.get(uri.path)?.find((f2) => f2.schema.id == uri.ref); + configure(config4) { + let copy = Object.assign(Object.create(LRParser.prototype), this); + if (config4.props) + copy.nodeSet = this.nodeSet.extend(...config4.props); + if (config4.top) { + let info = this.topRules[config4.top]; + if (!info) + throw new RangeError(`Invalid top rule name ${config4.top}`); + copy.top = info; } + if (config4.tokenizers) + copy.tokenizers = this.tokenizers.map((t5) => { + let found = config4.tokenizers.find((r2) => r2.from == t5); + return found ? found.to : t5; + }); + if (config4.contextTracker) + copy.context = config4.contextTracker; + if (config4.dialect) + copy.dialect = this.parseDialect(config4.dialect); + if (config4.strict != null) + copy.strict = config4.strict; + if (config4.wrap) + copy.wrappers = copy.wrappers.concat(config4.wrap); + if (config4.bufferLength != null) + copy.bufferLength = config4.bufferLength; + return copy; } - runCommand(action, instance) { - const command = this.commandForAction(action); - let result; - let error; - try { - if (command.schema.type == "api") { - const [namespace, method] = command.schema.id.split("."); - result = this.superstate.api[namespace]?.[method]?.(...command.fields.map((f2) => instance.instanceProps[f2.name])); - } - if (command.schema.type == "actions") - result = runActionString(this.superstate, command.code, instance); - if (command.schema.type == "script") - result = executeCode(command.code, instance.instanceProps); - if (command.schema.type == "formula") - result = runFormulaWithContext(this.superstate.formulaContext, this.superstate.pathsIndex, command.code, command.fields.reduce((p, c3) => ({ ...p, [c3.name]: c3 }), {}), instance.instanceProps); - } catch (e5) { - error = e5; - } - console.log(result, error); - return result; + hasWrappers() { + return this.wrappers.length > 0; } - allCommands() { - const apiCommands = Object.keys(this.apiCommands).flatMap((f2) => Object.keys(this.apiCommands[f2]).map((g) => ({ scheme: "spaces", path: `spaces://$api/${f2}/#;${g}`, ...this.apiCommands[f2][g] }))); - const actionCommands = [...this.superstate.actions.entries()].flatMap((f2) => f2[1].map((g) => ({ scheme: "spaces", path: `spaces://$api/${f2[0]}/#;${g.schema.id}`, ...g }))); - return [...apiCommands, ...actionCommands]; + getName(term) { + return this.termNames ? this.termNames[term] : String(term <= this.maxNode && this.nodeSet.types[term].name || term); } -}; - -// src/core/utils/contexts/linkContextRow.ts -var propertyDependencies = (fields) => { - const graph = /* @__PURE__ */ new Map(); - fields.filter((f2) => f2.type == "fileprop" || f2.name.startsWith("tags")).forEach((f2) => { - const { value } = parseFieldValue(f2.value, f2.type); - const localDependencies = []; - try { - const deps = parse4(value).filter((f3) => f3.type == "FunctionNode").filter((f3) => f3.fn.name == "prop" && f3.args[0].type == "ConstantNode").map((f3) => f3.args[0]?.value); - localDependencies.push(...deps); - } catch (e5) { - } - const key2 = f2.name; - if (!graph.has(key2)) { - graph.set(key2, /* @__PURE__ */ new Set()); - } - for (const dep of localDependencies) { - const depStr = dep; - if (depStr === key2) - continue; - graph.get(key2).add(depStr); - } - }); - const visited = /* @__PURE__ */ new Set(); - const result = []; - const temp = /* @__PURE__ */ new Set(); - const visit = (key2) => { - if (temp.has(key2)) - throw new Error("Circular dependency detected"); - if (!visited.has(key2)) { - temp.add(key2); - const edges = graph.get(key2) || /* @__PURE__ */ new Set(); - for (const dep of edges) { - visit(dep); - } - visited.add(key2); - temp.delete(key2); - result.push(key2); - } - }; - for (const key2 of fields) { - if (!visited.has(key2.name)) { - visit(key2.name); - } + get eofTerm() { + return this.maxNode + 1; } - return result; -}; -var linkContextRow = (runContext, paths, row2, fields, path2, dependencies314) => { - if (!row2) - return {}; - const result = dependencies314 ?? propertyDependencies(fields); - const frontmatter = paths.get(row2[PathPropertyName])?.metadata?.property ?? {}; - const filteredFrontmatter = Object.keys(frontmatter).filter((f2) => fields.some((g) => g.name == f2)).reduce((p, c3) => ({ ...p, [c3]: parseProperty(c3, frontmatter[c3]) }), {}); - const fieldsSorted = result.map((f2) => fields.find((g) => g.name == f2)).filter((f2) => f2 && (f2.type == "fileprop" || f2.name == "tags")); - const properties3 = fields.reduce((p, c3) => ({ ...p, [c3.name]: c3 }), {}); - return { - ...row2, - ...filteredFrontmatter, - ...fieldsSorted.reduce((p, c3) => { - const { value } = parseFieldValue(c3.value, c3.type); - return { ...p, [c3.name]: runFormulaWithContext(runContext, paths, value, properties3, { ...row2, ...p }, path2) }; - }, {}) - }; -}; - -// src/core/types/metadata.ts -var labelProperties = [ - { - id: "label.sticker", - label: i18n_default.metadataTypes.sticker, - field: "sticker", - vType: "text", - defaultFilter: "isEmpty", - type: "label", - description: "Sticker label for the item" - }, - { - id: "label.color", - label: i18n_default.metadataTypes.color, - field: "color", - vType: "color", - defaultFilter: "equals", - type: "label", - description: "Color label for the item" + get topNode() { + return this.nodeSet.types[this.top[1]]; } -]; -var fileProperties = [ - { - id: "file.name", - label: i18n_default.metadataTypes.fileName, - field: "name", - vType: "text", - defaultFilter: "contains", - type: "file", - description: "Name for a space or note" - }, - { - id: "file.path", - label: i18n_default.metadataTypes.path, - field: "path", - vType: "link", - defaultFilter: "contains", - type: "file", - description: "Path for a space or note" - }, - { - id: "file.parent", - label: i18n_default.metadataTypes.folder, - field: "parent", - vType: "space", - defaultFilter: "contains", - type: "file", - description: "Folder the note or space is in" - }, - { - id: "file.ctime", - label: i18n_default.metadataTypes.created, - field: "ctime", - vType: "date", - defaultFilter: "isSameDate", - type: "file", - description: "Creation date for the note or space" - }, - { - id: "file.mtime", - label: i18n_default.metadataTypes.lastModified, - field: "mtime", - vType: "date", - defaultFilter: "isSameDate", - type: "file", - description: "Last modified date for the note or space" - }, - { - id: "file.extension", - label: i18n_default.metadataTypes.extension, - field: "extension", - vType: "text", - defaultFilter: "is", - type: "file", - description: "File extension" - }, - { - id: "file.size", - label: i18n_default.metadataTypes.size, - field: "size", - vType: "number", - defaultFilter: "lessThan", - type: "file", - description: "File size" + dynamicPrecedence(term) { + let prec = this.dynamicPrecedences; + return prec == null ? 0 : prec[term] || 0; } -]; -var pathCacheMetadata = [ - { - id: "path.tags", - label: i18n_default.metadataTypes.tags, - field: "tags", - vType: "tags-multi", - defaultFilter: "contains", - type: "path", - description: "Tags for the note or space" - }, - { - id: "path.inlinks", - label: i18n_default.metadataTypes.inlinks, - field: "inlinks", - vType: "link-multi", - defaultFilter: "contains", - type: "path", - description: "Links to the note or space" - }, - { - id: "path.outlinks", - label: i18n_default.metadataTypes.outlinks, - field: "outlinks", - vType: "link-multi", - defaultFilter: "contains", - type: "path", - description: "Links from the note or space" + parseDialect(dialect) { + let values2 = Object.keys(this.dialects), flags = values2.map(() => false); + if (dialect) + for (let part of dialect.split(" ")) { + let id3 = values2.indexOf(part); + if (id3 >= 0) + flags[id3] = true; + } + let disabled = null; + for (let i4 = 0; i4 < values2.length; i4++) + if (!flags[i4]) { + for (let j = this.dialects[values2[i4]], id3; (id3 = this.data[j++]) != 65535; ) + (disabled || (disabled = new Uint8Array(this.maxTerm + 1)))[id3] = 1; + } + return new Dialect(dialect, flags, disabled); } -]; - -// src/core/utils/metadata.ts -var allMetadata = (superstate) => ({ - label: { - name: i18n_default.metadataTypes.label, - properties: labelProperties - }, - file: { - name: i18n_default.metadataTypes.fileMetadata, - properties: fileProperties - }, - path: { - name: i18n_default.metadataTypes.outlinks, - properties: pathCacheMetadata - }, - frontmatter: { - name: i18n_default.metadataTypes.frontmatter, - properties: superstate.spaceManager.keysForCacheType("frontmatter").map((f2) => ({ - id: "frontmatter." + f2, - label: f2, - field: f2, - vType: "any", - defaultFilter: "contains", - type: "frontmatter", - description: "Frontmatter property" - })) - }, - context: { - name: i18n_default.metadataTypes.contexts, - properties: [...superstate.contextsIndex.values()].flatMap((f2) => f2.cols.filter((f3) => f3.primary != "true").map((g) => ({ - id: "contexts." + f2.path + "." + g.name, - label: g.name, - field: f2.path + "." + g.name, - vType: fieldTypeForField(g), - defaultFilter: "contains", - type: "context", - description: f2.path + " context property" - }))) + static deserialize(spec) { + return new LRParser(spec); } -}); - -// inline-worker:__inline-worker -function inlineWorker(scriptText, name317) { - let blob = new Blob([scriptText], { type: "text/javascript" }); - let url = URL.createObjectURL(blob); - let worker = new Worker(url, name317); - URL.revokeObjectURL(url); - return worker; +}; +function pair(data2, off) { + return data2[off] | data2[off + 1] << 16; } - -// src/core/superstate/workers/indexer/indexer.worker.ts -function Worker2() { - return inlineWorker(`"use strict";var Dk=Object.create;var bb=Object.defineProperty;var Sk=Object.getOwnPropertyDescriptor;var Nk=Object.getOwnPropertyNames;var Ak=Object.getPrototypeOf,Mk=Object.prototype.hasOwnProperty;var vn=(e,r)=>()=>(r||e((r={exports:{}}).exports,r),r.exports),Ck=(e,r)=>{for(var t in r)bb(e,t,{get:r[t],enumerable:!0})},Ek=(e,r,t,n)=>{if(r&&typeof r=="object"||typeof r=="function")for(let a of Nk(r))!Mk.call(e,a)&&a!==t&&bb(e,a,{get:()=>r[a],enumerable:!(n=Sk(r,a))||n.enumerable});return e};var ca=(e,r,t)=>(t=e!=null?Dk(Ak(e)):{},Ek(r||!e||!e.__esModule?bb(t,"default",{value:e,enumerable:!0}):t,e));var fm=vn((gu,Sc)=>{(function(){var e,r="4.17.21",t=200,n="Unsupported core-js use. Try https://npms.io/search?q=ponyfill.",a="Expected a function",i="Invalid \`variable\` option passed into \`_.template\`",u="__lodash_hash_undefined__",l=500,c="__lodash_placeholder__",o=1,s=2,m=4,d=1,h=2,x=1,v=2,y=4,w=8,C=16,b=32,M=64,A=128,S=256,O=512,_=30,E="...",T=800,R=16,q=1,W=2,G=3,H=1/0,L=9007199254740991,k=17976931348623157e292,K=0/0,z=4294967295,oe=z-1,pe=z>>>1,ae=[["ary",A],["bind",x],["bindKey",v],["curry",w],["curryRight",C],["flip",O],["partial",b],["partialRight",M],["rearg",S]],$="[object Arguments]",le="[object Array]",Ee="[object AsyncFunction]",me="[object Boolean]",ge="[object Date]",Se="[object DOMException]",xe="[object Error]",be="[object Function]",De="[object GeneratorFunction]",Ae="[object Map]",We="[object Number]",Je="[object Null]",J="[object Object]",re="[object Promise]",ye="[object Proxy]",j="[object RegExp]",ne="[object Set]",ue="[object String]",Me="[object Symbol]",Ce="[object Undefined]",Le="[object WeakMap]",Ie="[object WeakSet]",fr="[object ArrayBuffer]",or="[object DataView]",Ke="[object Float32Array]",Pr="[object Float64Array]",ee="[object Int8Array]",ce="[object Int16Array]",we="[object Int32Array]",Be="[object Uint8Array]",ke="[object Uint8ClampedArray]",Te="[object Uint16Array]",Re="[object Uint32Array]",Ye=/\\b__p \\+= '';/g,B=/\\b(__p \\+=) '' \\+/g,Q=/(__e\\(.*?\\)|\\b__t\\)) \\+\\n'';/g,ve=/&(?:amp|lt|gt|quot|#39);/g,Pe=/[&<>"']/g,tr=RegExp(ve.source),cr=RegExp(Pe.source),Xr=/<%-([\\s\\S]+?)%>/g,Pt=/<%([\\s\\S]+?)%>/g,Xt=/<%=([\\s\\S]+?)%>/g,li=/\\.|\\[(?:[^[\\]]*|(["'])(?:(?!\\1)[^\\\\]|\\\\.)*?\\1)\\]/,Wa=/^\\w*$/,Ef=/[^.[\\]]+|\\[(?:(-?\\d+(?:\\.\\d+)?)|(["'])((?:(?!\\2)[^\\\\]|\\\\.)*?)\\2)\\]|(?=(?:\\.|\\[\\])(?:\\.|\\[\\]|$))/g,Ya=/[\\\\^$.*+?()[\\]{}|]/g,oo=RegExp(Ya.source),nr=/^\\s+/,Tf=/\\s/,Ff=/\\{(?:\\n\\/\\* \\[wrapped with .+\\] \\*\\/)?\\n?/,mn=/\\{\\n\\/\\* \\[wrapped with (.+)\\] \\*/,Jo=/,? & /,ot=/[^\\x00-\\x2f\\x3a-\\x40\\x5b-\\x60\\x7b-\\x7f]+/g,Pi=/[()=,{}\\[\\]\\/\\s]/,_f=/\\\\(\\\\)?/g,Gt=/\\$\\{([^\\\\}]*(?:\\\\.[^\\\\}]*)*)\\}/g,zn=/\\w*$/,Un=/^[-+]0x[0-9a-f]+$/i,Tt=/^0b[01]+$/i,On=/^\\[object .+?Constructor\\]$/,ta=/^0o[0-7]+$/i,Ha=/^(?:0|[1-9]\\d*)$/,Of=/[\\xc0-\\xd6\\xd8-\\xf6\\xf8-\\xff\\u0100-\\u017f]/g,so=/($^)/,Bf=/['\\n\\r\\u2028\\u2029\\\\]/g,vt="\\\\ud800-\\\\udfff",uo="\\\\u0300-\\\\u036f",Pf="\\\\ufe20-\\\\ufe2f",Ls="\\\\u20d0-\\\\u20ff",Ko=uo+Pf+Ls,zs="\\\\u2700-\\\\u27bf",Us="a-z\\\\xdf-\\\\xf6\\\\xf8-\\\\xff",Ii="\\\\xac\\\\xb1\\\\xd7\\\\xf7",et="\\\\x00-\\\\x2f\\\\x3a-\\\\x40\\\\x5b-\\\\x60\\\\x7b-\\\\xbf",on="\\\\u2000-\\\\u206f",If=" \\\\t\\\\x0b\\\\f\\\\xa0\\\\ufeff\\\\n\\\\r\\\\u2028\\\\u2029\\\\u1680\\\\u180e\\\\u2000\\\\u2001\\\\u2002\\\\u2003\\\\u2004\\\\u2005\\\\u2006\\\\u2007\\\\u2008\\\\u2009\\\\u200a\\\\u202f\\\\u205f\\\\u3000",mi="A-Z\\\\xc0-\\\\xd6\\\\xd8-\\\\xde",$a="\\\\ufe0e\\\\ufe0f",Ws=Ii+et+on+If,Rf="['\\u2019]",gy="["+vt+"]",kf="["+Ws+"]",pi="["+Ko+"]",qf="\\\\d+",xy="["+zs+"]",Vc="["+Us+"]",fo="[^"+vt+Ws+qf+zs+Us+mi+"]",co="\\\\ud83c[\\\\udffb-\\\\udfff]",Zc="(?:"+pi+"|"+co+")",lo="[^"+vt+"]",na="(?:\\\\ud83c[\\\\udde6-\\\\uddff]){2}",Lf="[\\\\ud800-\\\\udbff][\\\\udc00-\\\\udfff]",mo="["+mi+"]",Qc="\\\\u200d",Xc="(?:"+Vc+"|"+fo+")",yy="(?:"+mo+"|"+fo+")",Jc="(?:"+Rf+"(?:d|ll|m|re|s|t|ve))?",Kc="(?:"+Rf+"(?:D|LL|M|RE|S|T|VE))?",jc=Zc+"?",Ys="["+$a+"]?",by="(?:"+Qc+"(?:"+[lo,na,Lf].join("|")+")"+Ys+jc+")*",el="\\\\d*(?:1st|2nd|3rd|(?![123])\\\\dth)(?=\\\\b|[A-Z_])",wy="\\\\d*(?:1ST|2ND|3RD|(?![123])\\\\dTH)(?=\\\\b|[a-z_])",rl=Ys+jc+by,Dy="(?:"+[xy,na,Lf].join("|")+")"+rl,Sy="(?:"+[lo+pi+"?",pi,na,Lf,gy].join("|")+")",Ny=RegExp(Rf,"g"),Ay=RegExp(pi,"g"),zf=RegExp(co+"(?="+co+")|"+Sy+rl,"g"),My=RegExp([mo+"?"+Vc+"+"+Jc+"(?="+[kf,mo,"$"].join("|")+")",yy+"+"+Kc+"(?="+[kf,mo+Xc,"$"].join("|")+")",mo+"?"+Xc+"+"+Jc,mo+"+"+Kc,wy,el,qf,Dy].join("|"),"g"),Cy=RegExp("["+Qc+vt+Ko+$a+"]"),Ey=/[a-z][A-Z]|[A-Z]{2}[a-z]|[0-9][a-zA-Z]|[a-zA-Z][0-9]|[^a-zA-Z0-9 ]/,Ty=["Array","Buffer","DataView","Date","Error","Float32Array","Float64Array","Function","Int8Array","Int16Array","Int32Array","Map","Math","Object","Promise","RegExp","Set","String","Symbol","TypeError","Uint8Array","Uint8ClampedArray","Uint16Array","Uint32Array","WeakMap","_","clearTimeout","isFinite","parseInt","setTimeout"],Fy=-1,yt={};yt[Ke]=yt[Pr]=yt[ee]=yt[ce]=yt[we]=yt[Be]=yt[ke]=yt[Te]=yt[Re]=!0,yt[$]=yt[le]=yt[fr]=yt[me]=yt[or]=yt[ge]=yt[xe]=yt[be]=yt[Ae]=yt[We]=yt[J]=yt[j]=yt[ne]=yt[ue]=yt[Le]=!1;var gt={};gt[$]=gt[le]=gt[fr]=gt[or]=gt[me]=gt[ge]=gt[Ke]=gt[Pr]=gt[ee]=gt[ce]=gt[we]=gt[Ae]=gt[We]=gt[J]=gt[j]=gt[ne]=gt[ue]=gt[Me]=gt[Be]=gt[ke]=gt[Te]=gt[Re]=!0,gt[xe]=gt[be]=gt[Le]=!1;var _y={\\u00C0:"A",\\u00C1:"A",\\u00C2:"A",\\u00C3:"A",\\u00C4:"A",\\u00C5:"A",\\u00E0:"a",\\u00E1:"a",\\u00E2:"a",\\u00E3:"a",\\u00E4:"a",\\u00E5:"a",\\u00C7:"C",\\u00E7:"c",\\u00D0:"D",\\u00F0:"d",\\u00C8:"E",\\u00C9:"E",\\u00CA:"E",\\u00CB:"E",\\u00E8:"e",\\u00E9:"e",\\u00EA:"e",\\u00EB:"e",\\u00CC:"I",\\u00CD:"I",\\u00CE:"I",\\u00CF:"I",\\u00EC:"i",\\u00ED:"i",\\u00EE:"i",\\u00EF:"i",\\u00D1:"N",\\u00F1:"n",\\u00D2:"O",\\u00D3:"O",\\u00D4:"O",\\u00D5:"O",\\u00D6:"O",\\u00D8:"O",\\u00F2:"o",\\u00F3:"o",\\u00F4:"o",\\u00F5:"o",\\u00F6:"o",\\u00F8:"o",\\u00D9:"U",\\u00DA:"U",\\u00DB:"U",\\u00DC:"U",\\u00F9:"u",\\u00FA:"u",\\u00FB:"u",\\u00FC:"u",\\u00DD:"Y",\\u00FD:"y",\\u00FF:"y",\\u00C6:"Ae",\\u00E6:"ae",\\u00DE:"Th",\\u00FE:"th",\\u00DF:"ss",\\u0100:"A",\\u0102:"A",\\u0104:"A",\\u0101:"a",\\u0103:"a",\\u0105:"a",\\u0106:"C",\\u0108:"C",\\u010A:"C",\\u010C:"C",\\u0107:"c",\\u0109:"c",\\u010B:"c",\\u010D:"c",\\u010E:"D",\\u0110:"D",\\u010F:"d",\\u0111:"d",\\u0112:"E",\\u0114:"E",\\u0116:"E",\\u0118:"E",\\u011A:"E",\\u0113:"e",\\u0115:"e",\\u0117:"e",\\u0119:"e",\\u011B:"e",\\u011C:"G",\\u011E:"G",\\u0120:"G",\\u0122:"G",\\u011D:"g",\\u011F:"g",\\u0121:"g",\\u0123:"g",\\u0124:"H",\\u0126:"H",\\u0125:"h",\\u0127:"h",\\u0128:"I",\\u012A:"I",\\u012C:"I",\\u012E:"I",\\u0130:"I",\\u0129:"i",\\u012B:"i",\\u012D:"i",\\u012F:"i",\\u0131:"i",\\u0134:"J",\\u0135:"j",\\u0136:"K",\\u0137:"k",\\u0138:"k",\\u0139:"L",\\u013B:"L",\\u013D:"L",\\u013F:"L",\\u0141:"L",\\u013A:"l",\\u013C:"l",\\u013E:"l",\\u0140:"l",\\u0142:"l",\\u0143:"N",\\u0145:"N",\\u0147:"N",\\u014A:"N",\\u0144:"n",\\u0146:"n",\\u0148:"n",\\u014B:"n",\\u014C:"O",\\u014E:"O",\\u0150:"O",\\u014D:"o",\\u014F:"o",\\u0151:"o",\\u0154:"R",\\u0156:"R",\\u0158:"R",\\u0155:"r",\\u0157:"r",\\u0159:"r",\\u015A:"S",\\u015C:"S",\\u015E:"S",\\u0160:"S",\\u015B:"s",\\u015D:"s",\\u015F:"s",\\u0161:"s",\\u0162:"T",\\u0164:"T",\\u0166:"T",\\u0163:"t",\\u0165:"t",\\u0167:"t",\\u0168:"U",\\u016A:"U",\\u016C:"U",\\u016E:"U",\\u0170:"U",\\u0172:"U",\\u0169:"u",\\u016B:"u",\\u016D:"u",\\u016F:"u",\\u0171:"u",\\u0173:"u",\\u0174:"W",\\u0175:"w",\\u0176:"Y",\\u0177:"y",\\u0178:"Y",\\u0179:"Z",\\u017B:"Z",\\u017D:"Z",\\u017A:"z",\\u017C:"z",\\u017E:"z",\\u0132:"IJ",\\u0133:"ij",\\u0152:"Oe",\\u0153:"oe",\\u0149:"'n",\\u017F:"s"},Uf={"&":"&","<":"<",">":">",'"':""","'":"'"},Wf={"&":"&","<":"<",">":">",""":'"',"'":"'"},Oy={"\\\\":"\\\\","'":"'","\\n":"n","\\r":"r","\\u2028":"u2028","\\u2029":"u2029"},tl=parseFloat,nl=parseInt,al=typeof global=="object"&&global&&global.Object===Object&&global,By=typeof self=="object"&&self&&self.Object===Object&&self,Vt=al||By||Function("return this")(),Yf=typeof gu=="object"&&gu&&!gu.nodeType&&gu,di=Yf&&typeof Sc=="object"&&Sc&&!Sc.nodeType&&Sc,bt=di&&di.exports===Yf,Ri=bt&&al.process,sn=function(){try{var de=di&&di.require&&di.require("util").types;return de||Ri&&Ri.binding&&Ri.binding("util")}catch{}}(),il=sn&&sn.isArrayBuffer,Hf=sn&&sn.isDate,ol=sn&&sn.isMap,sl=sn&&sn.isRegExp,jo=sn&&sn.isSet,Ga=sn&&sn.isTypedArray;function pn(de,_e,Ne){switch(Ne.length){case 0:return de.call(_e);case 1:return de.call(_e,Ne[0]);case 2:return de.call(_e,Ne[0],Ne[1]);case 3:return de.call(_e,Ne[0],Ne[1],Ne[2])}return de.apply(_e,Ne)}function Py(de,_e,Ne,ir){for(var Ar=-1,rt=de==null?0:de.length;++Ar-1}function $f(de,_e,Ne){for(var ir=-1,Ar=de==null?0:de.length;++ir-1;);return Ne}function dl(de,_e){for(var Ne=de.length;Ne--&&po(_e,de[Ne],0)>-1;);return Ne}function zy(de,_e){for(var Ne=de.length,ir=0;Ne--;)de[Ne]===_e&&++ir;return ir}var hl=es(_y),Uy=es(Uf);function Wy(de){return"\\\\"+Oy[de]}function Yy(de,_e){return de==null?e:de[_e]}function wa(de){return Cy.test(de)}function Hy(de){return Ey.test(de)}function $y(de){for(var _e,Ne=[];!(_e=de.next()).done;)Ne.push(_e.value);return Ne}function jf(de){var _e=-1,Ne=Array(de.size);return de.forEach(function(ir,Ar){Ne[++_e]=[Ar,ir]}),Ne}function rs(de,_e){return function(Ne){return de(_e(Ne))}}function aa(de,_e){for(var Ne=-1,ir=de.length,Ar=0,rt=[];++Ne-1}function Fl(f,p){var D=this.__data__,P=Hn(D,f);return P<0?(++this.size,D.push([f,p])):D[P][1]=p,this}Qa.prototype.clear=y1,Qa.prototype.delete=Tl,Qa.prototype.get=b1,Qa.prototype.has=w1,Qa.prototype.set=Fl;function Xa(f){var p=-1,D=f==null?0:f.length;for(this.clear();++p=p?f:p)),f}function Pn(f,p,D,P,Y,X){var ie,fe=p&o,he=p&s,qe=p&m;if(D&&(ie=Y?D(f,P,Y,X):D(f)),ie!==e)return ie;if(!_t(f))return f;var ze=Br(f);if(ze){if(ie=J5(f),!fe)return $n(f,ie)}else{var He=wn(f),er=He==be||He==De;if(Ao(f))return XS(f,fe);if(He==J||He==$||er&&!Y){if(ie=he||er?{}:hN(f),!fe)return he?z5(f,F1(ie,f)):L5(f,nc(ie,f))}else{if(!gt[He])return Y?f:{};ie=K5(f,He,fe)}}X||(X=new ia);var mr=X.get(f);if(mr)return mr;X.set(f,ie),HN(f)?f.forEach(function(Sr){ie.add(Pn(Sr,p,D,Sr,f,X))}):WN(f)&&f.forEach(function(Sr,Yr){ie.set(Yr,Pn(Sr,p,D,Yr,f,X))});var Dr=qe?he?J1:X1:he?Vn:un,qr=ze?e:Dr(f);return It(qr||f,function(Sr,Yr){qr&&(Yr=Sr,Sr=f[Yr]),ls(ie,Yr,Pn(Sr,p,D,Yr,f,X))}),ie}function ac(f){var p=un(f);return function(D){return Il(D,f,p)}}function Il(f,p,D){var P=D.length;if(f==null)return!P;for(f=zr(f);P--;){var Y=D[P],X=p[Y],ie=f[Y];if(ie===e&&!(Y in f)||!X(ie))return!1}return!0}function Rl(f,p,D){if(typeof f!="function")throw new Wn(a);return pc(function(){f.apply(e,D)},p)}function In(f,p,D,P){var Y=-1,X=$s,ie=!0,fe=f.length,he=[],qe=p.length;if(!fe)return he;D&&(p=dt(p,bn(D))),P?(X=$f,ie=!1):p.length>=t&&(X=ho,ie=!1,p=new zi(p));e:for(;++YY?0:Y+D),P=P===e||P>Y?Y:Rr(P),P<0&&(P+=Y),P=D>P?0:GN(P);D0&&D(fe)?p>1?Jt(fe,p-1,D,P,Y):ba(Y,fe):P||(Y[Y.length]=fe)}return Y}var ic=tN(),Ll=tN(!0);function Da(f,p){return f&&ic(f,p,un)}function oc(f,p){return f&&Ll(f,p,un)}function Sa(f,p){return hi(p,function(D){return Gi(f[D])})}function Wi(f,p){p=So(p,f);for(var D=0,P=p.length;f!=null&&Dp}function B1(f,p){return f!=null&&ut.call(f,p)}function P1(f,p){return f!=null&&p in zr(f)}function I1(f,p,D){return f>=Ft(p,D)&&f=120&&ze.length>=120)?new zi(ie&&ze):e}ze=f[0];var He=-1,er=fe[0];e:for(;++He-1;)fe!==f&&qi.call(fe,he,1),qi.call(f,he,1);return f}function WS(f,p){for(var D=f?p.length:0,P=D-1;D--;){var Y=p[D];if(D==P||Y!==X){var X=Y;$i(Y)?qi.call(f,Y,1):Y1(f,Y)}}return f}function z1(f,p){return f+is(Cl()*(p-f+1))}function E5(f,p,D,P){for(var Y=-1,X=Rt(eu((p-f)/(D||1)),0),ie=Ne(X);X--;)ie[P?X:++Y]=f,f+=D;return ie}function U1(f,p){var D="";if(!f||p<1||p>L)return D;do p%2&&(D+=f),p=is(p/2),p&&(f+=f);while(p);return D}function Ur(f,p){return ab(xN(f,p,Zn),f+"")}function T5(f){return Pl(hu(f))}function F5(f,p){var D=hu(f);return Jl(D,Ui(p,0,D.length))}function cc(f,p,D,P){if(!_t(f))return f;p=So(p,f);for(var Y=-1,X=p.length,ie=X-1,fe=f;fe!=null&&++YY?0:Y+p),D=D>Y?Y:D,D<0&&(D+=Y),Y=p>D?0:D-p>>>0,p>>>=0;for(var X=Ne(Y);++P>>1,ie=f[X];ie!==null&&!sa(ie)&&(D?ie<=p:ie=t){var qe=p?null:H5(f);if(qe)return vo(qe);ie=!1,Y=ho,he=new zi}else he=p?[]:fe;e:for(;++P=P?f:Ma(f,p,D)}var QS=n1||function(f){return Vt.clearTimeout(f)};function XS(f,p){if(p)return f.slice();var D=f.length,P=bl?bl(D):new f.constructor(D);return f.copy(P),P}function V1(f){var p=new f.constructor(f.byteLength);return new Js(p).set(new Js(f)),p}function I5(f,p){var D=p?V1(f.buffer):f.buffer;return new f.constructor(D,f.byteOffset,f.byteLength)}function R5(f){var p=new f.constructor(f.source,zn.exec(f));return p.lastIndex=f.lastIndex,p}function k5(f){return cs?zr(cs.call(f)):{}}function JS(f,p){var D=p?V1(f.buffer):f.buffer;return new f.constructor(D,f.byteOffset,f.length)}function KS(f,p){if(f!==p){var D=f!==e,P=f===null,Y=f===f,X=sa(f),ie=p!==e,fe=p===null,he=p===p,qe=sa(p);if(!fe&&!qe&&!X&&f>p||X&&ie&&he&&!fe&&!qe||P&&ie&&he||!D&&he||!Y)return 1;if(!P&&!X&&!qe&&f=fe)return he;var qe=D[P];return he*(qe=="desc"?-1:1)}}return f.index-p.index}function jS(f,p,D,P){for(var Y=-1,X=f.length,ie=D.length,fe=-1,he=p.length,qe=Rt(X-ie,0),ze=Ne(he+qe),He=!P;++fe1?D[Y-1]:e,ie=Y>2?D[2]:e;for(X=f.length>3&&typeof X=="function"?(Y--,X):e,ie&&Rn(D[0],D[1],ie)&&(X=Y<3?e:X,Y=1),p=zr(p);++P-1?Y[X?p[ie]:ie]:e}}function iN(f){return Hi(function(p){var D=p.length,P=D,Y=Yn.prototype.thru;for(f&&p.reverse();P--;){var X=p[P];if(typeof X!="function")throw new Wn(a);if(Y&&!ie&&Ql(X)=="wrapper")var ie=new Yn([],!0)}for(P=ie?P:D;++P1&&Zr.reverse(),ze&&hefe))return!1;var qe=X.get(f),ze=X.get(p);if(qe&&ze)return qe==p&&ze==f;var He=-1,er=!0,mr=D&h?new zi:e;for(X.set(f,p),X.set(p,f);++He1?"& ":"")+p[P],p=p.join(D>2?", ":" "),f.replace(Ff,\`{ -/* [wrapped with \`+p+\`] */ -\`)}function e8(f){return Br(f)||vs(f)||!!(Sl&&f&&f[Sl])}function $i(f,p){var D=typeof f;return p=p??L,!!p&&(D=="number"||D!="symbol"&&Ha.test(f))&&f>-1&&f%1==0&&f0){if(++p>=T)return arguments[0]}else p=0;return f.apply(e,arguments)}}function Jl(f,p){var D=-1,P=f.length,Y=P-1;for(p=p===e?P:p;++D1?f[p-1]:e;return D=typeof D=="function"?(f.pop(),D):e,FN(f,D)});function _N(f){var p=Z(f);return p.__chain__=!0,p}function l6(f,p){return p(f),f}function Kl(f,p){return p(f)}var m6=Hi(function(f){var p=f.length,D=p?f[0]:0,P=this.__wrapped__,Y=function(X){return fu(X,f)};return p>1||this.__actions__.length||!(P instanceof kr)||!$i(D)?this.thru(Y):(P=P.slice(D,+D+(p?1:0)),P.__actions__.push({func:Kl,args:[Y],thisArg:e}),new Yn(P,this.__chain__).thru(function(X){return p&&!X.length&&X.push(e),X}))});function p6(){return _N(this)}function d6(){return new Yn(this.value(),this.__chain__)}function h6(){this.__values__===e&&(this.__values__=$N(this.value()));var f=this.__index__>=this.__values__.length,p=f?e:this.__values__[this.__index__++];return{done:f,value:p}}function v6(){return this}function g6(f){for(var p,D=this;D instanceof iu;){var P=NN(D);P.__index__=0,P.__values__=e,p?Y.__wrapped__=P:p=P;var Y=P;D=D.__wrapped__}return Y.__wrapped__=f,p}function x6(){var f=this.__wrapped__;if(f instanceof kr){var p=f;return this.__actions__.length&&(p=new kr(this)),p=p.reverse(),p.__actions__.push({func:Kl,args:[ib],thisArg:e}),new Yn(p,this.__chain__)}return this.thru(ib)}function y6(){return VS(this.__wrapped__,this.__actions__)}var b6=Hl(function(f,p,D){ut.call(f,D)?++f[D]:Ja(f,D,1)});function w6(f,p,D){var P=Br(f)?Hs:_1;return D&&Rn(f,p,D)&&(p=e),P(f,xr(p,3))}function D6(f,p){var D=Br(f)?hi:ql;return D(f,xr(p,3))}var S6=aN(AN),N6=aN(MN);function A6(f,p){return Jt(jl(f,p),1)}function M6(f,p){return Jt(jl(f,p),H)}function C6(f,p,D){return D=D===e?1:Rr(D),Jt(jl(f,p),D)}function ON(f,p){var D=Br(f)?It:bi;return D(f,xr(p,3))}function BN(f,p){var D=Br(f)?Iy:kl;return D(f,xr(p,3))}var E6=Hl(function(f,p,D){ut.call(f,D)?f[D].push(p):Ja(f,D,[p])});function T6(f,p,D,P){f=Gn(f)?f:hu(f),D=D&&!P?Rr(D):0;var Y=f.length;return D<0&&(D=Rt(Y+D,0)),am(f)?D<=Y&&f.indexOf(p,D)>-1:!!Y&&po(f,p,D)>-1}var F6=Ur(function(f,p,D){var P=-1,Y=typeof p=="function",X=Gn(f)?Ne(f.length):[];return bi(f,function(ie){X[++P]=Y?pn(p,ie,D):Na(ie,p,D)}),X}),_6=Hl(function(f,p,D){Ja(f,D,p)});function jl(f,p){var D=Br(f)?dt:Fe;return D(f,xr(p,3))}function O6(f,p,D,P){return f==null?[]:(Br(p)||(p=p==null?[]:[p]),D=P?e:D,Br(D)||(D=D==null?[]:[D]),ja(f,p,D))}var B6=Hl(function(f,p,D){f[D?0:1].push(p)},function(){return[[],[]]});function P6(f,p,D){var P=Br(f)?Gf:ml,Y=arguments.length<3;return P(f,xr(p,4),D,Y,bi)}function I6(f,p,D){var P=Br(f)?Ry:ml,Y=arguments.length<3;return P(f,xr(p,4),D,Y,kl)}function R6(f,p){var D=Br(f)?hi:ql;return D(f,tm(xr(p,3)))}function k6(f){var p=Br(f)?Pl:T5;return p(f)}function q6(f,p,D){(D?Rn(f,p,D):p===e)?p=1:p=Rr(p);var P=Br(f)?C1:F5;return P(f,p)}function L6(f){var p=Br(f)?E1:O5;return p(f)}function z6(f){if(f==null)return 0;if(Gn(f))return am(f)?vi(f):f.length;var p=wn(f);return p==Ae||p==ne?f.size:U(f).length}function U6(f,p,D){var P=Br(f)?Vf:B5;return D&&Rn(f,p,D)&&(p=e),P(f,xr(p,3))}var W6=Ur(function(f,p){if(f==null)return[];var D=p.length;return D>1&&Rn(f,p[0],p[1])?p=[]:D>2&&Rn(p[0],p[1],p[2])&&(p=[p[0]]),ja(f,Jt(p,1),[])}),em=a1||function(){return Vt.Date.now()};function Y6(f,p){if(typeof p!="function")throw new Wn(a);return f=Rr(f),function(){if(--f<1)return p.apply(this,arguments)}}function PN(f,p,D){return p=D?e:p,p=f&&p==null?f.length:p,Yi(f,A,e,e,e,e,p)}function IN(f,p){var D;if(typeof p!="function")throw new Wn(a);return f=Rr(f),function(){return--f>0&&(D=p.apply(this,arguments)),f<=1&&(p=e),D}}var sb=Ur(function(f,p,D){var P=x;if(D.length){var Y=aa(D,pu(sb));P|=b}return Yi(f,P,p,D,Y)}),RN=Ur(function(f,p,D){var P=x|v;if(D.length){var Y=aa(D,pu(RN));P|=b}return Yi(p,P,f,D,Y)});function kN(f,p,D){p=D?e:p;var P=Yi(f,w,e,e,e,e,e,p);return P.placeholder=kN.placeholder,P}function qN(f,p,D){p=D?e:p;var P=Yi(f,C,e,e,e,e,e,p);return P.placeholder=qN.placeholder,P}function LN(f,p,D){var P,Y,X,ie,fe,he,qe=0,ze=!1,He=!1,er=!0;if(typeof f!="function")throw new Wn(a);p=Ea(p)||0,_t(D)&&(ze=!!D.leading,He="maxWait"in D,X=He?Rt(Ea(D.maxWait)||0,p):X,er="trailing"in D?!!D.trailing:er);function mr(Wt){var ri=P,Zi=Y;return P=Y=e,qe=Wt,ie=f.apply(Zi,ri),ie}function Dr(Wt){return qe=Wt,fe=pc(Yr,p),ze?mr(Wt):ie}function qr(Wt){var ri=Wt-he,Zi=Wt-qe,aA=p-ri;return He?Ft(aA,X-Zi):aA}function Sr(Wt){var ri=Wt-he,Zi=Wt-qe;return he===e||ri>=p||ri<0||He&&Zi>=X}function Yr(){var Wt=em();if(Sr(Wt))return Zr(Wt);fe=pc(Yr,qr(Wt))}function Zr(Wt){return fe=e,er&&P?mr(Wt):(P=Y=e,ie)}function ua(){fe!==e&&QS(fe),qe=0,P=he=Y=fe=e}function kn(){return fe===e?ie:Zr(em())}function fa(){var Wt=em(),ri=Sr(Wt);if(P=arguments,Y=this,he=Wt,ri){if(fe===e)return Dr(he);if(He)return QS(fe),fe=pc(Yr,p),mr(he)}return fe===e&&(fe=pc(Yr,p)),ie}return fa.cancel=ua,fa.flush=kn,fa}var H6=Ur(function(f,p){return Rl(f,1,p)}),$6=Ur(function(f,p,D){return Rl(f,Ea(p)||0,D)});function G6(f){return Yi(f,O)}function rm(f,p){if(typeof f!="function"||p!=null&&typeof p!="function")throw new Wn(a);var D=function(){var P=arguments,Y=p?p.apply(this,P):P[0],X=D.cache;if(X.has(Y))return X.get(Y);var ie=f.apply(this,P);return D.cache=X.set(Y,ie)||X,ie};return D.cache=new(rm.Cache||Xa),D}rm.Cache=Xa;function tm(f){if(typeof f!="function")throw new Wn(a);return function(){var p=arguments;switch(p.length){case 0:return!f.call(this);case 1:return!f.call(this,p[0]);case 2:return!f.call(this,p[0],p[1]);case 3:return!f.call(this,p[0],p[1],p[2])}return!f.apply(this,p)}}function V6(f){return IN(2,f)}var Z6=P5(function(f,p){p=p.length==1&&Br(p[0])?dt(p[0],bn(xr())):dt(Jt(p,1),bn(xr()));var D=p.length;return Ur(function(P){for(var Y=-1,X=Ft(P.length,D);++Y=p}),vs=Ul(function(){return arguments}())?Ul:function(f){return kt(f)&&ut.call(f,"callee")&&!Dl.call(f,"callee")},Br=Ne.isArray,f7=il?bn(il):R1;function Gn(f){return f!=null&&nm(f.length)&&!Gi(f)}function Ut(f){return kt(f)&&Gn(f)}function c7(f){return f===!0||f===!1||kt(f)&&dn(f)==me}var Ao=Nl||yb,l7=Hf?bn(Hf):k1;function m7(f){return kt(f)&&f.nodeType===1&&!dc(f)}function p7(f){if(f==null)return!0;if(Gn(f)&&(Br(f)||typeof f=="string"||typeof f.splice=="function"||Ao(f)||du(f)||vs(f)))return!f.length;var p=wn(f);if(p==Ae||p==ne)return!f.size;if(mc(f))return!U(f).length;for(var D in f)if(ut.call(f,D))return!1;return!0}function d7(f,p){return ms(f,p)}function h7(f,p,D){D=typeof D=="function"?D:e;var P=D?D(f,p):e;return P===e?ms(f,p,e,D):!!P}function fb(f){if(!kt(f))return!1;var p=dn(f);return p==xe||p==Se||typeof f.message=="string"&&typeof f.name=="string"&&!dc(f)}function v7(f){return typeof f=="number"&&os(f)}function Gi(f){if(!_t(f))return!1;var p=dn(f);return p==be||p==De||p==Ee||p==ye}function UN(f){return typeof f=="number"&&f==Rr(f)}function nm(f){return typeof f=="number"&&f>-1&&f%1==0&&f<=L}function _t(f){var p=typeof f;return f!=null&&(p=="object"||p=="function")}function kt(f){return f!=null&&typeof f=="object"}var WN=ol?bn(ol):fc;function g7(f,p){return f===p||wi(f,p,j1(p))}function x7(f,p,D){return D=typeof D=="function"?D:e,wi(f,p,j1(p),D)}function y7(f){return YN(f)&&f!=+f}function b7(f){if(n8(f))throw new Ar(n);return ps(f)}function w7(f){return f===null}function D7(f){return f==null}function YN(f){return typeof f=="number"||kt(f)&&dn(f)==We}function dc(f){if(!kt(f)||dn(f)!=J)return!1;var p=Ks(f);if(p===null)return!0;var D=ut.call(p,"constructor")&&p.constructor;return typeof D=="function"&&D instanceof D&&ns.call(D)==e1}var cb=sl?bn(sl):Vr;function S7(f){return UN(f)&&f>=-L&&f<=L}var HN=jo?bn(jo):g;function am(f){return typeof f=="string"||!Br(f)&&kt(f)&&dn(f)==ue}function sa(f){return typeof f=="symbol"||kt(f)&&dn(f)==Me}var du=Ga?bn(Ga):N;function N7(f){return f===e}function A7(f){return kt(f)&&wn(f)==Le}function M7(f){return kt(f)&&dn(f)==Ie}var C7=Zl(se),E7=Zl(function(f,p){return f<=p});function $N(f){if(!f)return[];if(Gn(f))return am(f)?Bn(f):$n(f);if(as&&f[as])return $y(f[as]());var p=wn(f),D=p==Ae?jf:p==ne?vo:hu;return D(f)}function Vi(f){if(!f)return f===0?f:0;if(f=Ea(f),f===H||f===-H){var p=f<0?-1:1;return p*k}return f===f?f:0}function Rr(f){var p=Vi(f),D=p%1;return p===p?D?p-D:p:0}function GN(f){return f?Ui(Rr(f),0,z):0}function Ea(f){if(typeof f=="number")return f;if(sa(f))return K;if(_t(f)){var p=typeof f.valueOf=="function"?f.valueOf():f;f=_t(p)?p+"":p}if(typeof f!="string")return f===0?f:+f;f=pl(f);var D=Tt.test(f);return D||ta.test(f)?nl(f.slice(2),D?2:8):Un.test(f)?K:+f}function VN(f){return Di(f,Vn(f))}function T7(f){return f?Ui(Rr(f),-L,L):f===0?f:0}function ft(f){return f==null?"":oa(f)}var F7=lu(function(f,p){if(mc(p)||Gn(p)){Di(p,un(p),f);return}for(var D in p)ut.call(p,D)&&ls(f,D,p[D])}),ZN=lu(function(f,p){Di(p,Vn(p),f)}),im=lu(function(f,p,D,P){Di(p,Vn(p),f,P)}),_7=lu(function(f,p,D,P){Di(p,un(p),f,P)}),O7=Hi(fu);function B7(f,p){var D=wo(f);return p==null?D:nc(D,p)}var P7=Ur(function(f,p){f=zr(f);var D=-1,P=p.length,Y=P>2?p[2]:e;for(Y&&Rn(p[0],p[1],Y)&&(P=1);++D1),X}),Di(f,J1(f),D),P&&(D=Pn(D,o|s|m,$5));for(var Y=p.length;Y--;)Y1(D,p[Y]);return D});function K7(f,p){return XN(f,tm(xr(p)))}var j7=Hi(function(f,p){return f==null?{}:M5(f,p)});function XN(f,p){if(f==null)return{};var D=dt(J1(f),function(P){return[P]});return p=xr(p),US(f,D,function(P,Y){return p(P,Y[0])})}function e9(f,p,D){p=So(p,f);var P=-1,Y=p.length;for(Y||(Y=1,f=e);++Pp){var P=f;f=p,p=P}if(D||f%1||p%1){var Y=Cl();return Ft(f+Y*(p-f+tl("1e-"+((Y+"").length-1))),p)}return z1(f,p)}var l9=mu(function(f,p,D){return p=p.toLowerCase(),f+(D?jN(p):p)});function jN(f){return pb(ft(f).toLowerCase())}function eA(f){return f=ft(f),f&&f.replace(Of,hl).replace(Ay,"")}function m9(f,p,D){f=ft(f),p=oa(p);var P=f.length;D=D===e?P:Ui(Rr(D),0,P);var Y=D;return D-=p.length,D>=0&&f.slice(D,Y)==p}function p9(f){return f=ft(f),f&&cr.test(f)?f.replace(Pe,Uy):f}function d9(f){return f=ft(f),f&&oo.test(f)?f.replace(Ya,"\\\\$&"):f}var h9=mu(function(f,p,D){return f+(D?"-":"")+p.toLowerCase()}),v9=mu(function(f,p,D){return f+(D?" ":"")+p.toLowerCase()}),g9=nN("toLowerCase");function x9(f,p,D){f=ft(f),p=Rr(p);var P=p?vi(f):0;if(!p||P>=p)return f;var Y=(p-P)/2;return Vl(is(Y),D)+f+Vl(eu(Y),D)}function y9(f,p,D){f=ft(f),p=Rr(p);var P=p?vi(f):0;return p&&P>>0,D?(f=ft(f),f&&(typeof p=="string"||p!=null&&!cb(p))&&(p=oa(p),!p&&wa(f))?No(Bn(f),0,D):f.split(p,D)):[]}var M9=mu(function(f,p,D){return f+(D?" ":"")+pb(p)});function C9(f,p,D){return f=ft(f),D=D==null?0:Ui(Rr(D),0,f.length),p=oa(p),f.slice(D,D+p.length)==p}function E9(f,p,D){var P=Z.templateSettings;D&&Rn(f,p,D)&&(p=e),f=ft(f),p=im({},p,P,cN);var Y=im({},p.imports,P.imports,cN),X=un(Y),ie=Kf(Y,X),fe,he,qe=0,ze=p.interpolate||so,He="__p += '",er=Va((p.escape||so).source+"|"+ze.source+"|"+(ze===Xt?Gt:so).source+"|"+(p.evaluate||so).source+"|$","g"),mr="//# sourceURL="+(ut.call(p,"sourceURL")?(p.sourceURL+"").replace(/\\s/g," "):"lodash.templateSources["+ ++Fy+"]")+\` -\`;f.replace(er,function(Sr,Yr,Zr,ua,kn,fa){return Zr||(Zr=ua),He+=f.slice(qe,fa).replace(Bf,Wy),Yr&&(fe=!0,He+=\`' + -__e(\`+Yr+\`) + -'\`),kn&&(he=!0,He+=\`'; -\`+kn+\`; -__p += '\`),Zr&&(He+=\`' + -((__t = (\`+Zr+\`)) == null ? '' : __t) + -'\`),qe=fa+Sr.length,Sr}),He+=\`'; -\`;var Dr=ut.call(p,"variable")&&p.variable;if(!Dr)He=\`with (obj) { -\`+He+\` +function findOffset(data2, start, term) { + for (let i4 = start, next; (next = data2[i4]) != 65535; i4++) + if (next == term) + return i4 - start; + return -1; } -\`;else if(Pi.test(Dr))throw new Ar(i);He=(he?He.replace(Ye,""):He).replace(B,"$1").replace(Q,"$1;"),He="function("+(Dr||"obj")+\`) { -\`+(Dr?"":\`obj || (obj = {}); -\`)+"var __t, __p = ''"+(fe?", __e = _.escape":"")+(he?\`, __j = Array.prototype.join; -function print() { __p += __j.call(arguments, '') } -\`:\`; -\`)+He+\`return __p -}\`;var qr=tA(function(){return rt(X,mr+"return "+He).apply(e,ie)});if(qr.source=He,fb(qr))throw qr;return qr}function T9(f){return ft(f).toLowerCase()}function F9(f){return ft(f).toUpperCase()}function _9(f,p,D){if(f=ft(f),f&&(D||p===e))return pl(f);if(!f||!(p=oa(p)))return f;var P=Bn(f),Y=Bn(p),X=xt(P,Y),ie=dl(P,Y)+1;return No(P,X,ie).join("")}function O9(f,p,D){if(f=ft(f),f&&(D||p===e))return f.slice(0,Vs(f)+1);if(!f||!(p=oa(p)))return f;var P=Bn(f),Y=dl(P,Bn(p))+1;return No(P,0,Y).join("")}function B9(f,p,D){if(f=ft(f),f&&(D||p===e))return f.replace(nr,"");if(!f||!(p=oa(p)))return f;var P=Bn(f),Y=xt(P,Bn(p));return No(P,Y).join("")}function P9(f,p){var D=_,P=E;if(_t(p)){var Y="separator"in p?p.separator:Y;D="length"in p?Rr(p.length):D,P="omission"in p?oa(p.omission):P}f=ft(f);var X=f.length;if(wa(f)){var ie=Bn(f);X=ie.length}if(D>=X)return f;var fe=D-vi(P);if(fe<1)return P;var he=ie?No(ie,0,fe).join(""):f.slice(0,fe);if(Y===e)return he+P;if(ie&&(fe+=he.length-fe),cb(Y)){if(f.slice(fe).search(Y)){var qe,ze=he;for(Y.global||(Y=Va(Y.source,ft(zn.exec(Y))+"g")),Y.lastIndex=0;qe=Y.exec(ze);)var He=qe.index;he=he.slice(0,He===e?fe:He)}}else if(f.indexOf(oa(Y),fe)!=fe){var er=he.lastIndexOf(Y);er>-1&&(he=he.slice(0,er))}return he+P}function I9(f){return f=ft(f),f&&tr.test(f)?f.replace(ve,Zy):f}var R9=mu(function(f,p,D){return f+(D?" ":"")+p.toUpperCase()}),pb=nN("toUpperCase");function rA(f,p,D){return f=ft(f),p=D?e:p,p===e?Hy(f)?Jy(f):qy(f):f.match(p)||[]}var tA=Ur(function(f,p){try{return pn(f,e,p)}catch(D){return fb(D)?D:new Ar(D)}}),k9=Hi(function(f,p){return It(p,function(D){D=Si(D),Ja(f,D,sb(f[D],f))}),f});function q9(f){var p=f==null?0:f.length,D=xr();return f=p?dt(f,function(P){if(typeof P[1]!="function")throw new Wn(a);return[D(P[0]),P[1]]}):[],Ur(function(P){for(var Y=-1;++YL)return[];var D=z,P=Ft(f,z);p=xr(p),f-=z;for(var Y=Jf(P,p);++D0||p<0)?new kr(D):(f<0?D=D.takeRight(-f):f&&(D=D.drop(f)),p!==e&&(p=Rr(p),D=p<0?D.dropRight(-p):D.take(p-f)),D)},kr.prototype.takeRightWhile=function(f){return this.reverse().takeWhile(f).reverse()},kr.prototype.toArray=function(){return this.take(z)},Da(kr.prototype,function(f,p){var D=/^(?:filter|find|map|reject)|While$/.test(p),P=/^(?:head|last)$/.test(p),Y=Z[P?"take"+(p=="last"?"Right":""):p],X=P||/^find/.test(p);!Y||(Z.prototype[p]=function(){var ie=this.__wrapped__,fe=P?[1]:arguments,he=ie instanceof kr,qe=fe[0],ze=he||Br(ie),He=function(Yr){var Zr=Y.apply(Z,ba([Yr],fe));return P&&er?Zr[0]:Zr};ze&&D&&typeof qe=="function"&&qe.length!=1&&(he=ze=!1);var er=this.__chain__,mr=!!this.__actions__.length,Dr=X&&!er,qr=he&&!mr;if(!X&&ze){ie=qr?ie:new kr(this);var Sr=f.apply(ie,fe);return Sr.__actions__.push({func:Kl,args:[He],thisArg:e}),new Yn(Sr,er)}return Dr&&qr?f.apply(this,fe):(Sr=this.thru(He),Dr?P?Sr.value()[0]:Sr.value():Sr)})}),It(["pop","push","shift","sort","splice","unshift"],function(f){var p=ts[f],D=/^(?:push|sort|unshift)$/.test(f)?"tap":"thru",P=/^(?:pop|shift)$/.test(f);Z.prototype[f]=function(){var Y=arguments;if(P&&!this.__chain__){var X=this.value();return p.apply(Br(X)?X:[],Y)}return this[D](function(ie){return p.apply(Br(ie)?ie:[],Y)})}}),Da(kr.prototype,function(f,p){var D=Z[p];if(D){var P=D.name+"";ut.call(bo,P)||(bo[P]=[]),bo[P].push({name:p,func:D})}}),bo[$l(e,v).name]=[{name:"wrapper",func:e}],kr.prototype.clone=m1,kr.prototype.reverse=p1,kr.prototype.value=d1,Z.prototype.at=m6,Z.prototype.chain=p6,Z.prototype.commit=d6,Z.prototype.next=h6,Z.prototype.plant=g6,Z.prototype.reverse=x6,Z.prototype.toJSON=Z.prototype.valueOf=Z.prototype.value=y6,Z.prototype.first=Z.prototype.head,as&&(Z.prototype[as]=v6),Z},gi=Ky();typeof define=="function"&&typeof define.amd=="object"&&define.amd?(Vt._=gi,define(function(){return gi})):di?((di.exports=gi)._=gi,Yf._=gi):Vt._=gi}).call(gu)});var Am=vn((Wb,Yb)=>{(function(e,r){typeof Wb=="object"&&typeof Yb<"u"?Yb.exports=r():typeof define=="function"&&define.amd?define(r):(e=typeof globalThis<"u"?globalThis:e||self,e["'typed'"]=r())})(Wb,function(){"use strict";function e(){return!0}function r(){return!1}function t(){}let n="Argument is not a typed-function.";function a(){function u(ee){return typeof ee=="object"&&ee!==null&&ee.constructor===Object}let l=[{name:"number",test:function(ee){return typeof ee=="number"}},{name:"string",test:function(ee){return typeof ee=="string"}},{name:"boolean",test:function(ee){return typeof ee=="boolean"}},{name:"Function",test:function(ee){return typeof ee=="function"}},{name:"Array",test:Array.isArray},{name:"Date",test:function(ee){return ee instanceof Date}},{name:"RegExp",test:function(ee){return ee instanceof RegExp}},{name:"Object",test:u},{name:"null",test:function(ee){return ee===null}},{name:"undefined",test:function(ee){return ee===void 0}}],c={name:"any",test:e,isAny:!0},o,s,m=0,d={createCount:0};function h(ee){let ce=o.get(ee);if(ce)return ce;let we='Unknown type "'+ee+'"',Be=ee.toLowerCase(),ke;for(ke of s)if(ke.toLowerCase()===Be){we+='. Did you mean "'+ke+'" ?';break}throw new TypeError(we)}function x(ee){let ce=arguments.length>1&&arguments[1]!==void 0?arguments[1]:"any",we=ce?h(ce).index:s.length,Be=[];for(let Te=0;Te{let Be=o.get(we);return!Be.isAny&&Be.test(ee)});return ce.length?ce:["any"]}function C(ee){return ee&&typeof ee=="function"&&"_typedFunctionData"in ee}function b(ee,ce,we){if(!C(ee))throw new TypeError(n);let Be=we&&we.exact,ke=Array.isArray(ce)?ce.join(","):ce,Te=T(ke),Re=S(Te);if(!Be||Re in ee.signatures){let ve=ee._typedFunctionData.signatureMap.get(Re);if(ve)return ve}let Ye=Te.length,B;if(Be){B=[];let ve;for(ve in ee.signatures)B.push(ee._typedFunctionData.signatureMap.get(ve))}else B=ee._typedFunctionData.signatures;for(let ve=0;ve!Pt.has(Xt.name)))continue}tr.push(cr)}}if(B=tr,B.length===0)break}let Q;for(Q of B)if(Q.params.length<=Ye)return Q;throw new TypeError("Signature not found (signature: "+(ee.name||"unnamed")+"("+S(Te,", ")+"))")}function M(ee,ce,we){return b(ee,ce,we).implementation}function A(ee,ce){let we=h(ce);if(we.test(ee))return ee;let Be=we.conversionsTo;if(Be.length===0)throw new Error("There are no conversions to "+ce+" defined.");for(let ke=0;ke1&&arguments[1]!==void 0?arguments[1]:",";return ee.map(we=>we.name).join(ce)}function O(ee){let ce=ee.indexOf("...")===0,Be=(ce?ee.length>3?ee.slice(3):"any":ee).split("|").map(Ye=>h(Ye.trim())),ke=!1,Te=ce?"...":"";return{types:Be.map(function(Ye){return ke=Ye.isAny||ke,Te+=Ye.name+"|",{name:Ye.name,typeIndex:Ye.index,test:Ye.test,isAny:Ye.isAny,conversion:null,conversionIndex:-1}}),name:Te.slice(0,-1),hasAny:ke,hasConversion:!1,restParam:ce}}function _(ee){let ce=ee.types.map(Re=>Re.name),we=$(ce),Be=ee.hasAny,ke=ee.name,Te=we.map(function(Re){let Ye=h(Re.from);return Be=Ye.isAny||Be,ke+="|"+Re.from,{name:Re.from,typeIndex:Ye.index,test:Ye.test,isAny:Ye.isAny,conversion:Re,conversionIndex:Re.index}});return{types:ee.types.concat(Te),name:ke,hasAny:Be,hasConversion:Te.length>0,restParam:ee.restParam}}function E(ee){return ee.typeSet||(ee.typeSet=new Set,ee.types.forEach(ce=>ee.typeSet.add(ce.name))),ee.typeSet}function T(ee){let ce=[];if(typeof ee!="string")throw new TypeError("Signatures must be strings");let we=ee.trim();if(we==="")return ce;let Be=we.split(",");for(let ke=0;ke=ke+1}}else return ee.length===0?function(Te){return Te.length===0}:ee.length===1?(we=q(ee[0]),function(Te){return we(Te[0])&&Te.length===1}):ee.length===2?(we=q(ee[0]),Be=q(ee[1]),function(Te){return we(Te[0])&&Be(Te[1])&&Te.length===2}):(ce=ee.map(q),function(Te){for(let Re=0;Re{let ke=H(Be.params,ce),Te;for(Te of ke)we.add(Te)}),we.has("any")?["any"]:Array.from(we)}function K(ee,ce,we){let Be,ke,Te=ee||"unnamed",Re=we,Ye;for(Ye=0;Ye{let cr=G(tr.params,Ye),Xr=q(cr);(Ye0){let tr=w(ce[Ye]);return Be=new TypeError("Unexpected type of argument in function "+Te+" (expected: "+ke.join(" or ")+", actual: "+tr.join(" | ")+", index: "+Ye+")"),Be.data={category:"wrongType",fn:Te,index:Ye,actual:tr,expected:ke},Be}}else Re=Pe}let B=Re.map(function(Pe){return R(Pe.params)?1/0:Pe.params.length});if(ce.lengthQ)return Be=new TypeError("Too many arguments in function "+Te+" (expected: "+Q+", actual: "+ce.length+")"),Be.data={category:"tooManyArgs",fn:Te,index:ce.length,expectedLength:Q},Be;let ve=[];for(let Pe=0;Pe0)return 1;let Be=oe(ee)-oe(ce);return Be<0?-1:Be>0?1:0}function ae(ee,ce){let we=ee.params,Be=ce.params,ke=J(we),Te=J(Be),Re=R(we),Ye=R(Be);if(Re&&ke.hasAny){if(!Ye||!Te.hasAny)return 1}else if(Ye&&Te.hasAny)return-1;let B=0,Q=0,ve;for(ve of we)ve.hasAny&&++B,ve.hasConversion&&++Q;let Pe=0,tr=0;for(ve of Be)ve.hasAny&&++Pe,ve.hasConversion&&++tr;if(B!==Pe)return B-Pe;if(Re&&ke.hasConversion){if(!Ye||!Te.hasConversion)return 1}else if(Ye&&Te.hasConversion)return-1;if(Q!==tr)return Q-tr;if(Re){if(!Ye)return 1}else if(Ye)return-1;let cr=(we.length-Be.length)*(Re?-1:1);if(cr!==0)return cr;let Xr=[],Pt=0;for(let li=0;li1&&ce.sort((ke,Te)=>ke.index-Te.index);let we=ce[0].conversionsTo;if(ee.length===1)return we;we=we.concat([]);let Be=new Set(ee);for(let ke=1;keke.hasConversion)){let ke=R(ee),Te=ee.map(Ee);we=function(){let Ye=[],B=ke?arguments.length-1:arguments.length;for(let Q=0;QB.name).join("|"),hasAny:Ye.some(B=>B.isAny),hasConversion:!1,restParam:!0}),Re.push(Te)}else Re=Te.types.map(function(Ye){return{types:[Ye],name:Ye.name,hasAny:Ye.isAny,hasConversion:Ye.conversion,restParam:!1}});return j(Re,function(Ye){return ce(we,Be+1,ke.concat([Ye]))})}else return[ke]}return ce(ee,0,[])}function ge(ee,ce){let we=Math.max(ee.length,ce.length);for(let Ye=0;Ye=Be:Re?Be>=ke:Be===ke}function Se(ee){return ee.map(ce=>Le(ce)?Me(ce.referToSelf.callback):Ce(ce)?ue(ce.referTo.references,ce.referTo.callback):ce)}function xe(ee,ce,we){let Be=[],ke;for(ke of ee){let Te=we[ke];if(typeof Te!="number")throw new TypeError('No definition for referenced signature "'+ke+'"');if(Te=ce[Te],typeof Te!="function")return!1;Be.push(Te)}return Be}function be(ee,ce,we){let Be=Se(ee),ke=new Array(Be.length).fill(!1),Te=!0;for(;Te;){Te=!1;let Re=!0;for(let Ye=0;Ye{let Be=ee[we];if(ce.test(Be.toString()))throw new SyntaxError("Using \`this\` to self-reference a function is deprecated since typed-function@3. Use typed.referTo and typed.referToSelf instead.")})}function Ae(ee,ce){if(d.createCount++,Object.keys(ce).length===0)throw new SyntaxError("No signatures provided");d.warnAgainstDeprecatedThis&&De(ce);let we=[],Be=[],ke={},Te=[],Re;for(Re in ce){if(!Object.prototype.hasOwnProperty.call(ce,Re))continue;let et=T(Re);if(!et)continue;we.forEach(function($a){if(ge($a,et))throw new TypeError('Conflicting signatures "'+S($a)+'" and "'+S(et)+'".')}),we.push(et);let on=Be.length;Be.push(ce[Re]);let If=et.map(_),mi;for(mi of me(If)){let $a=S(mi);Te.push({params:mi,name:$a,fn:on}),mi.every(Ws=>!Ws.hasConversion)&&(ke[$a]=on)}}Te.sort(ae);let Ye=be(Be,ke,Ii),B;for(B in ke)Object.prototype.hasOwnProperty.call(ke,B)&&(ke[B]=Ye[ke[B]]);let Q=[],ve=new Map;for(B of Te)ve.has(B.name)||(B.fn=Ye[B.fn],Q.push(B),ve.set(B.name,B));let Pe=Q[0]&&Q[0].params.length<=2&&!R(Q[0].params),tr=Q[1]&&Q[1].params.length<=2&&!R(Q[1].params),cr=Q[2]&&Q[2].params.length<=2&&!R(Q[2].params),Xr=Q[3]&&Q[3].params.length<=2&&!R(Q[3].params),Pt=Q[4]&&Q[4].params.length<=2&&!R(Q[4].params),Xt=Q[5]&&Q[5].params.length<=2&&!R(Q[5].params),li=Pe&&tr&&cr&&Xr&&Pt&&Xt;for(let et=0;etet.test),zs=Q.map(et=>et.implementation),Us=function(){for(let on=Pf;onS(T(we))),ce=J(arguments);if(typeof ce!="function")throw new TypeError("Callback function expected as last argument");return ue(ee,ce)}function ue(ee,ce){return{referTo:{references:ee,callback:ce}}}function Me(ee){if(typeof ee!="function")throw new TypeError("Callback function expected as first argument");return{referToSelf:{callback:ee}}}function Ce(ee){return ee&&typeof ee.referTo=="object"&&Array.isArray(ee.referTo.references)&&typeof ee.referTo.callback=="function"}function Le(ee){return ee&&typeof ee.referToSelf=="object"&&typeof ee.referToSelf.callback=="function"}function Ie(ee,ce){if(!ee)return ce;if(ce&&ce!==ee){let we=new Error("Function names do not match (expected: "+ee+", actual: "+ce+")");throw we.data={actual:ce,expected:ee},we}return ee}function fr(ee){let ce;for(let we in ee)Object.prototype.hasOwnProperty.call(ee,we)&&(C(ee[we])||typeof ee[we].signature=="string")&&(ce=Ie(ce,ee[we].name));return ce}function or(ee,ce){let we;for(we in ce)if(Object.prototype.hasOwnProperty.call(ce,we)){if(we in ee&&ce[we]!==ee[we]){let Be=new Error('Signature "'+we+'" is defined twice');throw Be.data={signature:we,sourceFunction:ce[we],destFunction:ee[we]},Be}ee[we]=ce[we]}}let Ke=d;d=function(ee){let ce=typeof ee=="string",we=ce?1:0,Be=ce?ee:"",ke={};for(let Te=we;Teke.from===ee.from);if(!we)throw new Error("Attempt to remove nonexistent conversion from "+ee.from+" to "+ee.to);if(we.convert!==ee.convert)throw new Error("Conversion to remove does not match existing conversion");let Be=ce.conversionsTo.indexOf(we);ce.conversionsTo.splice(Be,1)},d.resolve=function(ee,ce){if(!C(ee))throw new TypeError(n);let we=ee._typedFunctionData.signatures;for(let Be=0;Be{(function(e){"use strict";var r=Math.cosh||function(o){return Math.abs(o)<1e-9?1-o:(Math.exp(o)+Math.exp(-o))*.5},t=Math.sinh||function(o){return Math.abs(o)<1e-9?o:(Math.exp(o)-Math.exp(-o))*.5},n=function(o){var s=Math.PI/4;if(-s>o||o>s)return Math.cos(o)-1;var m=o*o;return m*(m*(m*(m*(m*(m*(m*(m/20922789888e3-1/87178291200)+1/479001600)-1/3628800)+1/40320)-1/720)+1/24)-1/2)},a=function(o,s){var m=Math.abs(o),d=Math.abs(s);return m<3e3&&d<3e3?Math.sqrt(m*m+d*d):(m0&&i();break;case"number":m.im=0,m.re=o;break;default:i()}return isNaN(m.re)||isNaN(m.im),m};function c(o,s){if(!(this instanceof c))return new c(o,s);var m=l(o,s);this.re=m.re,this.im=m.im}c.prototype={re:0,im:0,sign:function(){var o=this.abs();return new c(this.re/o,this.im/o)},add:function(o,s){var m=new c(o,s);return this.isInfinite()&&m.isInfinite()?c.NAN:this.isInfinite()||m.isInfinite()?c.INFINITY:new c(this.re+m.re,this.im+m.im)},sub:function(o,s){var m=new c(o,s);return this.isInfinite()&&m.isInfinite()?c.NAN:this.isInfinite()||m.isInfinite()?c.INFINITY:new c(this.re-m.re,this.im-m.im)},mul:function(o,s){var m=new c(o,s);return this.isInfinite()&&m.isZero()||this.isZero()&&m.isInfinite()?c.NAN:this.isInfinite()||m.isInfinite()?c.INFINITY:m.im===0&&this.im===0?new c(this.re*m.re,0):new c(this.re*m.re-this.im*m.im,this.re*m.im+this.im*m.re)},div:function(o,s){var m=new c(o,s);if(this.isZero()&&m.isZero()||this.isInfinite()&&m.isInfinite())return c.NAN;if(this.isInfinite()||m.isZero())return c.INFINITY;if(this.isZero()||m.isInfinite())return c.ZERO;o=this.re,s=this.im;var d=m.re,h=m.im,x,v;return h===0?new c(o/d,s/d):Math.abs(d)0)return new c(Math.pow(o,m.re),0);if(o===0)switch((m.re%4+4)%4){case 0:return new c(Math.pow(s,m.re),0);case 1:return new c(0,Math.pow(s,m.re));case 2:return new c(-Math.pow(s,m.re),0);case 3:return new c(0,-Math.pow(s,m.re))}}if(o===0&&s===0&&m.re>0&&m.im>=0)return c.ZERO;var d=Math.atan2(s,o),h=u(o,s);return o=Math.exp(m.re*h-m.im*d),s=m.im*h+m.re*d,new c(o*Math.cos(s),o*Math.sin(s))},sqrt:function(){var o=this.re,s=this.im,m=this.abs(),d,h;if(o>=0){if(s===0)return new c(Math.sqrt(o),0);d=.5*Math.sqrt(2*(m+o))}else d=Math.abs(s)/Math.sqrt(2*(m-o));return o<=0?h=.5*Math.sqrt(2*(m-o)):h=Math.abs(s)/Math.sqrt(2*(m+o)),new c(d,s<0?-h:h)},exp:function(){var o=Math.exp(this.re);return this.im,new c(o*Math.cos(this.im),o*Math.sin(this.im))},expm1:function(){var o=this.re,s=this.im;return new c(Math.expm1(o)*Math.cos(s)+n(s),Math.exp(o)*Math.sin(s))},log:function(){var o=this.re,s=this.im;return s===0&&o>0,new c(u(o,s),Math.atan2(s,o))},abs:function(){return a(this.re,this.im)},arg:function(){return Math.atan2(this.im,this.re)},sin:function(){var o=this.re,s=this.im;return new c(Math.sin(o)*r(s),Math.cos(o)*t(s))},cos:function(){var o=this.re,s=this.im;return new c(Math.cos(o)*r(s),-Math.sin(o)*t(s))},tan:function(){var o=2*this.re,s=2*this.im,m=Math.cos(o)+r(s);return new c(Math.sin(o)/m,t(s)/m)},cot:function(){var o=2*this.re,s=2*this.im,m=Math.cos(o)-r(s);return new c(-Math.sin(o)/m,t(s)/m)},sec:function(){var o=this.re,s=this.im,m=.5*r(2*s)+.5*Math.cos(2*o);return new c(Math.cos(o)*r(s)/m,Math.sin(o)*t(s)/m)},csc:function(){var o=this.re,s=this.im,m=.5*r(2*s)-.5*Math.cos(2*o);return new c(Math.sin(o)*r(s)/m,-Math.cos(o)*t(s)/m)},asin:function(){var o=this.re,s=this.im,m=new c(s*s-o*o+1,-2*o*s).sqrt(),d=new c(m.re-s,m.im+o).log();return new c(d.im,-d.re)},acos:function(){var o=this.re,s=this.im,m=new c(s*s-o*o+1,-2*o*s).sqrt(),d=new c(m.re-s,m.im+o).log();return new c(Math.PI/2-d.im,d.re)},atan:function(){var o=this.re,s=this.im;if(o===0){if(s===1)return new c(0,1/0);if(s===-1)return new c(0,-1/0)}var m=o*o+(1-s)*(1-s),d=new c((1-s*s-o*o)/m,-2*o/m).log();return new c(-.5*d.im,.5*d.re)},acot:function(){var o=this.re,s=this.im;if(s===0)return new c(Math.atan2(1,o),0);var m=o*o+s*s;return m!==0?new c(o/m,-s/m).atan():new c(o!==0?o/0:0,s!==0?-s/0:0).atan()},asec:function(){var o=this.re,s=this.im;if(o===0&&s===0)return new c(0,1/0);var m=o*o+s*s;return m!==0?new c(o/m,-s/m).acos():new c(o!==0?o/0:0,s!==0?-s/0:0).acos()},acsc:function(){var o=this.re,s=this.im;if(o===0&&s===0)return new c(Math.PI/2,1/0);var m=o*o+s*s;return m!==0?new c(o/m,-s/m).asin():new c(o!==0?o/0:0,s!==0?-s/0:0).asin()},sinh:function(){var o=this.re,s=this.im;return new c(t(o)*Math.cos(s),r(o)*Math.sin(s))},cosh:function(){var o=this.re,s=this.im;return new c(r(o)*Math.cos(s),t(o)*Math.sin(s))},tanh:function(){var o=2*this.re,s=2*this.im,m=r(o)+Math.cos(s);return new c(t(o)/m,Math.sin(s)/m)},coth:function(){var o=2*this.re,s=2*this.im,m=r(o)-Math.cos(s);return new c(t(o)/m,-Math.sin(s)/m)},csch:function(){var o=this.re,s=this.im,m=Math.cos(2*s)-r(2*o);return new c(-2*t(o)*Math.cos(s)/m,2*r(o)*Math.sin(s)/m)},sech:function(){var o=this.re,s=this.im,m=Math.cos(2*s)+r(2*o);return new c(2*r(o)*Math.cos(s)/m,-2*t(o)*Math.sin(s)/m)},asinh:function(){var o=this.im;this.im=-this.re,this.re=o;var s=this.asin();return this.re=-this.im,this.im=o,o=s.re,s.re=-s.im,s.im=o,s},acosh:function(){var o=this.acos();if(o.im<=0){var s=o.re;o.re=-o.im,o.im=s}else{var s=o.im;o.im=-o.re,o.re=s}return o},atanh:function(){var o=this.re,s=this.im,m=o>1&&s===0,d=1-o,h=1+o,x=d*d+s*s,v=x!==0?new c((h*d-s*s)/x,(s*d+h*s)/x):new c(o!==-1?o/0:0,s!==0?s/0:0),y=v.re;return v.re=u(v.re,v.im)/2,v.im=Math.atan2(v.im,y)/2,m&&(v.im=-v.im),v},acoth:function(){var o=this.re,s=this.im;if(o===0&&s===0)return new c(0,Math.PI/2);var m=o*o+s*s;return m!==0?new c(o/m,-s/m).atanh():new c(o!==0?o/0:0,s!==0?-s/0:0).atanh()},acsch:function(){var o=this.re,s=this.im;if(s===0)return new c(o!==0?Math.log(o+Math.sqrt(o*o+1)):1/0,0);var m=o*o+s*s;return m!==0?new c(o/m,-s/m).asinh():new c(o!==0?o/0:0,s!==0?-s/0:0).asinh()},asech:function(){var o=this.re,s=this.im;if(this.isZero())return c.INFINITY;var m=o*o+s*s;return m!==0?new c(o/m,-s/m).acosh():new c(o!==0?o/0:0,s!==0?-s/0:0).acosh()},inverse:function(){if(this.isZero())return c.INFINITY;if(this.isInfinite())return c.ZERO;var o=this.re,s=this.im,m=o*o+s*s;return new c(o/m,-s/m)},conjugate:function(){return new c(this.re,-this.im)},neg:function(){return new c(-this.re,-this.im)},ceil:function(o){return o=Math.pow(10,o||0),new c(Math.ceil(this.re*o)/o,Math.ceil(this.im*o)/o)},floor:function(o){return o=Math.pow(10,o||0),new c(Math.floor(this.re*o)/o,Math.floor(this.im*o)/o)},round:function(o){return o=Math.pow(10,o||0),new c(Math.round(this.re*o)/o,Math.round(this.im*o)/o)},equals:function(o,s){var m=new c(o,s);return Math.abs(m.re-this.re)<=c.EPSILON&&Math.abs(m.im-this.im)<=c.EPSILON},clone:function(){return new c(this.re,this.im)},toString:function(){var o=this.re,s=this.im,m="";return this.isNaN()?"NaN":this.isInfinite()?"Infinity":(Math.abs(o){(function(e){"use strict";var r=2e3,t={s:1,n:0,d:1};function n(v,y){if(isNaN(v=parseInt(v,10)))throw h();return v*y}function a(v,y){if(y===0)throw d();var w=Object.create(m.prototype);w.s=v<0?-1:1,v=v<0?-v:v;var C=s(v,y);return w.n=v/C,w.d=y/C,w}function i(v){for(var y={},w=v,C=2,b=4;b<=w;){for(;w%C===0;)w/=C,y[C]=(y[C]||0)+1;b+=1+2*C++}return w!==v?w>1&&(y[w]=(y[w]||0)+1):y[v]=(y[v]||0)+1,y}var u=function(v,y){var w=0,C=1,b=1,M=0,A=0,S=0,O=1,_=1,E=0,T=1,R=1,q=1,W=1e7,G;if(v!=null)if(y!==void 0){if(w=v,C=y,b=w*C,w%1!==0||C%1!==0)throw x()}else switch(typeof v){case"object":{if("d"in v&&"n"in v)w=v.n,C=v.d,"s"in v&&(w*=v.s);else if(0 in v)w=v[0],1 in v&&(C=v[1]);else throw h();b=w*C;break}case"number":{if(v<0&&(b=v,v=-v),v%1===0)w=v;else if(v>0){for(v>=1&&(_=Math.pow(10,Math.floor(1+Math.log(v)/Math.LN10)),v/=_);T<=W&&q<=W;)if(G=(E+R)/(T+q),v===G){T+q<=W?(w=E+R,C=T+q):q>T?(w=R,C=q):(w=E,C=T);break}else v>G?(E+=R,T+=q):(R+=E,q+=T),T>W?(w=R,C=q):(w=E,C=T);w*=_}else(isNaN(v)||isNaN(y))&&(C=w=NaN);break}case"string":{if(T=v.match(/\\d+|./g),T===null)throw h();if(T[E]==="-"?(b=-1,E++):T[E]==="+"&&E++,T.length===E+1?A=n(T[E++],b):T[E+1]==="."||T[E]==="."?(T[E]!=="."&&(M=n(T[E++],b)),E++,(E+1===T.length||T[E+1]==="("&&T[E+3]===")"||T[E+1]==="'"&&T[E+3]==="'")&&(A=n(T[E],b),O=Math.pow(10,T[E].length),E++),(T[E]==="("&&T[E+2]===")"||T[E]==="'"&&T[E+2]==="'")&&(S=n(T[E+1],b),_=Math.pow(10,T[E+1].length)-1,E+=3)):T[E+1]==="/"||T[E+1]===":"?(A=n(T[E],b),O=n(T[E+2],1),E+=3):T[E+3]==="/"&&T[E+1]===" "&&(M=n(T[E],b),A=n(T[E+2],b),O=n(T[E+4],1),E+=5),T.length<=E){C=O*_,b=w=S+C*M+_*A;break}}default:throw h()}if(C===0)throw d();t.s=b<0?-1:1,t.n=Math.abs(w),t.d=Math.abs(C)};function l(v,y,w){for(var C=1;y>0;v=v*v%w,y>>=1)y&1&&(C=C*v%w);return C}function c(v,y){for(;y%2===0;y/=2);for(;y%5===0;y/=5);if(y===1)return 0;for(var w=10%y,C=1;w!==1;C++)if(w=w*10%y,C>r)return 0;return C}function o(v,y,w){for(var C=1,b=l(10,w,y),M=0;M<300;M++){if(C===b)return M;C=C*10%y,b=b*10%y}return 0}function s(v,y){if(!v)return y;if(!y)return v;for(;;){if(v%=y,!v)return y;if(y%=v,!y)return v}}function m(v,y){if(u(v,y),this instanceof m)v=s(t.d,t.n),this.s=t.s,this.n=t.n/v,this.d=t.d/v;else return a(t.s*t.n,t.d)}var d=function(){return new Error("Division by Zero")},h=function(){return new Error("Invalid argument")},x=function(){return new Error("Parameters must be integer")};m.prototype={s:1,n:0,d:1,abs:function(){return a(this.n,this.d)},neg:function(){return a(-this.s*this.n,this.d)},add:function(v,y){return u(v,y),a(this.s*this.n*t.d+t.s*this.d*t.n,this.d*t.d)},sub:function(v,y){return u(v,y),a(this.s*this.n*t.d-t.s*this.d*t.n,this.d*t.d)},mul:function(v,y){return u(v,y),a(this.s*t.s*this.n*t.n,this.d*t.d)},div:function(v,y){return u(v,y),a(this.s*t.s*this.n*t.d,this.d*t.n)},clone:function(){return a(this.s*this.n,this.d)},mod:function(v,y){if(isNaN(this.n)||isNaN(this.d))return new m(NaN);if(v===void 0)return a(this.s*this.n%this.d,1);if(u(v,y),t.n===0&&this.d===0)throw d();return a(this.s*(t.d*this.n)%(t.n*this.d),t.d*this.d)},gcd:function(v,y){return u(v,y),a(s(t.n,this.n)*s(t.d,this.d),t.d*this.d)},lcm:function(v,y){return u(v,y),t.n===0&&this.n===0?a(0,1):a(t.n*this.n,s(t.n,this.n)*s(t.d,this.d))},ceil:function(v){return v=Math.pow(10,v||0),isNaN(this.n)||isNaN(this.d)?new m(NaN):a(Math.ceil(v*this.s*this.n/this.d),v)},floor:function(v){return v=Math.pow(10,v||0),isNaN(this.n)||isNaN(this.d)?new m(NaN):a(Math.floor(v*this.s*this.n/this.d),v)},round:function(v){return v=Math.pow(10,v||0),isNaN(this.n)||isNaN(this.d)?new m(NaN):a(Math.round(v*this.s*this.n/this.d),v)},inverse:function(){return a(this.s*this.d,this.n)},pow:function(v,y){if(u(v,y),t.d===1)return t.s<0?a(Math.pow(this.s*this.d,t.n),Math.pow(this.n,t.n)):a(Math.pow(this.s*this.n,t.n),Math.pow(this.d,t.n));if(this.s<0)return null;var w=i(this.n),C=i(this.d),b=1,M=1;for(var A in w)if(A!=="1"){if(A==="0"){b=0;break}if(w[A]*=t.n,w[A]%t.d===0)w[A]/=t.d;else return null;b*=Math.pow(A,w[A])}for(var A in C)if(A!=="1"){if(C[A]*=t.n,C[A]%t.d===0)C[A]/=t.d;else return null;M*=Math.pow(A,C[A])}return t.s<0?a(M,b):a(b,M)},equals:function(v,y){return u(v,y),this.s*this.n*t.d===t.s*t.n*this.d},compare:function(v,y){u(v,y);var w=this.s*this.n*t.d-t.s*t.n*this.d;return(0=0;M--)b=b.inverse().add(w[M]);if(Math.abs(b.sub(y).valueOf())0&&(w+=y,w+=" ",C%=b),w+=C,w+="/",w+=b),w},toLatex:function(v){var y,w="",C=this.n,b=this.d;return this.s<0&&(w+="-"),b===1?w+=C:(v&&(y=Math.floor(C/b))>0&&(w+=y,C%=b),w+="\\\\frac{",w+=C,w+="}{",w+=b,w+="}"),w},toContinued:function(){var v,y=this.n,w=this.d,C=[];if(isNaN(y)||isNaN(w))return C;do C.push(Math.floor(y/w)),v=y%w,y=w,w=v;while(y!==1);return C},toString:function(v){var y=this.n,w=this.d;if(isNaN(y)||isNaN(w))return"NaN";v=v||15;var C=c(y,w),b=o(y,w,C),M=this.s<0?"-":"";if(M+=y/w|0,y%=w,y*=10,y&&(M+="."),C){for(var A=b;A--;)M+=y/w|0,y%=w,y*=10;M+="(";for(var A=C;A--;)M+=y/w|0,y%=w,y*=10;M+=")"}else for(var A=v;y&&A--;)M+=y/w|0,y%=w,y*=10;return M}},typeof mw=="object"?(Object.defineProperty(m,"__esModule",{value:!0}),m.default=m,m.Fraction=m,qM.exports=m):e.Fraction=m})(mw)});var eE=vn((Tce,jC)=>{jC.exports=function e(r,t){"use strict";var n=/(^([+\\-]?(?:0|[1-9]\\d*)(?:\\.\\d*)?(?:[eE][+\\-]?\\d+)?)?$|^0x[0-9a-f]+$|\\d+)/gi,a=/(^[ ]*|[ ]*$)/g,i=/(^([\\w ]+,?[\\w ]+)?[\\w ]+,?[\\w ]+\\d+:\\d+(:\\d+)?[\\w ]?|^\\d{1,4}[\\/\\-]\\d{1,4}[\\/\\-]\\d{1,4}|^\\w+, \\w+ \\d+, \\d{4})/,u=/^0x[0-9a-f]+$/i,l=/^0/,c=function(b){return e.insensitive&&(""+b).toLowerCase()||""+b},o=c(r).replace(a,"")||"",s=c(t).replace(a,"")||"",m=o.replace(n,"\\0$1\\0").replace(/\\0$/,"").replace(/^\\0/,"").split("\\0"),d=s.replace(n,"\\0$1\\0").replace(/\\0$/,"").replace(/^\\0/,"").split("\\0"),h=parseInt(o.match(u),16)||m.length!==1&&o.match(i)&&Date.parse(o),x=parseInt(s.match(u),16)||h&&s.match(i)&&Date.parse(s)||null,v,y;if(x){if(hx)return 1}for(var w=0,C=Math.max(m.length,d.length);wy)return 1}return 0}});var nT=vn((Ghe,tT)=>{"use strict";var gD=Object.assign||function(e){for(var r=1;r1&&arguments[1]!==void 0?arguments[1]:{},t=r.preserveFormatting,n=t===void 0?!1:t,a=r.escapeMapFn,i=a===void 0?I$:a,u=String(e),l="",c=i(gD({},B$),n?gD({},P$):{}),o=Object.keys(c),s=function(){var d=!1;o.forEach(function(h,x){d||u.length>=h.length&&u.slice(0,h.length)===h&&(l+=c[o[x]],u=u.slice(h.length,u.length),d=!0)}),d||(l+=u.slice(0,1),u=u.slice(1,u.length))};u;)s();return l}});var BB=vn((OB,AD)=>{(function(e,r,t){function n(l){var c=this,o=u();c.next=function(){var s=2091639*c.s0+c.c*23283064365386963e-26;return c.s0=c.s1,c.s1=c.s2,c.s2=s-(c.c=s|0)},c.c=1,c.s0=o(" "),c.s1=o(" "),c.s2=o(" "),c.s0-=o(l),c.s0<0&&(c.s0+=1),c.s1-=o(l),c.s1<0&&(c.s1+=1),c.s2-=o(l),c.s2<0&&(c.s2+=1),o=null}function a(l,c){return c.c=l.c,c.s0=l.s0,c.s1=l.s1,c.s2=l.s2,c}function i(l,c){var o=new n(l),s=c&&c.state,m=o.next;return m.int32=function(){return o.next()*4294967296|0},m.double=function(){return m()+(m()*2097152|0)*11102230246251565e-32},m.quick=m,s&&(typeof s=="object"&&a(s,o),m.state=function(){return a(o,{})}),m}function u(){var l=4022871197,c=function(o){o=String(o);for(var s=0;s>>0,m-=l,m*=l,l=m>>>0,m-=l,l+=m*4294967296}return(l>>>0)*23283064365386963e-26};return c}r&&r.exports?r.exports=i:t&&t.amd?t(function(){return i}):this.alea=i})(OB,typeof AD=="object"&&AD,typeof define=="function"&&define)});var IB=vn((PB,MD)=>{(function(e,r,t){function n(u){var l=this,c="";l.x=0,l.y=0,l.z=0,l.w=0,l.next=function(){var s=l.x^l.x<<11;return l.x=l.y,l.y=l.z,l.z=l.w,l.w^=l.w>>>19^s^s>>>8},u===(u|0)?l.x=u:c+=u;for(var o=0;o>>0)/4294967296};return s.double=function(){do var m=c.next()>>>11,d=(c.next()>>>0)/4294967296,h=(m+d)/(1<<21);while(h===0);return h},s.int32=c.next,s.quick=s,o&&(typeof o=="object"&&a(o,c),s.state=function(){return a(c,{})}),s}r&&r.exports?r.exports=i:t&&t.amd?t(function(){return i}):this.xor128=i})(PB,typeof MD=="object"&&MD,typeof define=="function"&&define)});var kB=vn((RB,CD)=>{(function(e,r,t){function n(u){var l=this,c="";l.next=function(){var s=l.x^l.x>>>2;return l.x=l.y,l.y=l.z,l.z=l.w,l.w=l.v,(l.d=l.d+362437|0)+(l.v=l.v^l.v<<4^(s^s<<1))|0},l.x=0,l.y=0,l.z=0,l.w=0,l.v=0,u===(u|0)?l.x=u:c+=u;for(var o=0;o>>4),l.next()}function a(u,l){return l.x=u.x,l.y=u.y,l.z=u.z,l.w=u.w,l.v=u.v,l.d=u.d,l}function i(u,l){var c=new n(u),o=l&&l.state,s=function(){return(c.next()>>>0)/4294967296};return s.double=function(){do var m=c.next()>>>11,d=(c.next()>>>0)/4294967296,h=(m+d)/(1<<21);while(h===0);return h},s.int32=c.next,s.quick=s,o&&(typeof o=="object"&&a(o,c),s.state=function(){return a(c,{})}),s}r&&r.exports?r.exports=i:t&&t.amd?t(function(){return i}):this.xorwow=i})(RB,typeof CD=="object"&&CD,typeof define=="function"&&define)});var LB=vn((qB,ED)=>{(function(e,r,t){function n(u){var l=this;l.next=function(){var o=l.x,s=l.i,m,d,h;return m=o[s],m^=m>>>7,d=m^m<<24,m=o[s+1&7],d^=m^m>>>10,m=o[s+3&7],d^=m^m>>>3,m=o[s+4&7],d^=m^m<<7,m=o[s+7&7],m=m^m<<13,d^=m^m<<9,o[s]=d,l.i=s+1&7,d};function c(o,s){var m,d,h=[];if(s===(s|0))d=h[0]=s;else for(s=""+s,m=0;m0;--m)o.next()}c(l,u)}function a(u,l){return l.x=u.x.slice(),l.i=u.i,l}function i(u,l){u==null&&(u=+new Date);var c=new n(u),o=l&&l.state,s=function(){return(c.next()>>>0)/4294967296};return s.double=function(){do var m=c.next()>>>11,d=(c.next()>>>0)/4294967296,h=(m+d)/(1<<21);while(h===0);return h},s.int32=c.next,s.quick=s,o&&(o.x&&a(o,c),s.state=function(){return a(c,{})}),s}r&&r.exports?r.exports=i:t&&t.amd?t(function(){return i}):this.xorshift7=i})(qB,typeof ED=="object"&&ED,typeof define=="function"&&define)});var UB=vn((zB,TD)=>{(function(e,r,t){function n(u){var l=this;l.next=function(){var o=l.w,s=l.X,m=l.i,d,h;return l.w=o=o+1640531527|0,h=s[m+34&127],d=s[m=m+1&127],h^=h<<13,d^=d<<17,h^=h>>>15,d^=d>>>12,h=s[m]=h^d,l.i=m,h+(o^o>>>16)|0};function c(o,s){var m,d,h,x,v,y=[],w=128;for(s===(s|0)?(d=s,s=null):(s=s+"\\0",d=0,w=Math.max(w,s.length)),h=0,x=-32;x>>15,d^=d<<4,d^=d>>>13,x>=0&&(v=v+1640531527|0,m=y[x&127]^=d+v,h=m==0?h+1:0);for(h>=128&&(y[(s&&s.length||0)&127]=-1),h=127,x=4*128;x>0;--x)d=y[h+34&127],m=y[h=h+1&127],d^=d<<13,m^=m<<17,d^=d>>>15,m^=m>>>12,y[h]=d^m;o.w=v,o.X=y,o.i=h}c(l,u)}function a(u,l){return l.i=u.i,l.w=u.w,l.X=u.X.slice(),l}function i(u,l){u==null&&(u=+new Date);var c=new n(u),o=l&&l.state,s=function(){return(c.next()>>>0)/4294967296};return s.double=function(){do var m=c.next()>>>11,d=(c.next()>>>0)/4294967296,h=(m+d)/(1<<21);while(h===0);return h},s.int32=c.next,s.quick=s,o&&(o.X&&a(o,c),s.state=function(){return a(c,{})}),s}r&&r.exports?r.exports=i:t&&t.amd?t(function(){return i}):this.xor4096=i})(zB,typeof TD=="object"&&TD,typeof define=="function"&&define)});var YB=vn((WB,FD)=>{(function(e,r,t){function n(u){var l=this,c="";l.next=function(){var s=l.b,m=l.c,d=l.d,h=l.a;return s=s<<25^s>>>7^m,m=m-d|0,d=d<<24^d>>>8^h,h=h-s|0,l.b=s=s<<20^s>>>12^m,l.c=m=m-d|0,l.d=d<<16^m>>>16^h,l.a=h-s|0},l.a=0,l.b=0,l.c=-1640531527,l.d=1367130551,u===Math.floor(u)?(l.a=u/4294967296|0,l.b=u|0):c+=u;for(var o=0;o>>0)/4294967296};return s.double=function(){do var m=c.next()>>>11,d=(c.next()>>>0)/4294967296,h=(m+d)/(1<<21);while(h===0);return h},s.int32=c.next,s.quick=s,o&&(typeof o=="object"&&a(o,c),s.state=function(){return a(c,{})}),s}r&&r.exports?r.exports=i:t&&t.amd?t(function(){return i}):this.tychei=i})(WB,typeof FD=="object"&&FD,typeof define=="function"&&define)});var HB=vn(()=>{});var GB=vn(($B,Ug)=>{(function(e,r,t){var n=256,a=6,i=52,u="random",l=t.pow(n,a),c=t.pow(2,i),o=c*2,s=n-1,m;function d(b,M,A){var S=[];M=M==!0?{entropy:!0}:M||{};var O=y(v(M.entropy?[b,C(r)]:b??w(),3),S),_=new h(S),E=function(){for(var T=_.g(a),R=l,q=0;T=o;)T/=2,R/=2,q>>>=1;return(T+q)/R};return E.int32=function(){return _.g(4)|0},E.quick=function(){return _.g(4)/4294967296},E.double=E,y(C(_.S),r),(M.pass||A||function(T,R,q,W){return W&&(W.S&&x(W,_),T.state=function(){return x(_,{})}),q?(t[u]=T,R):T})(E,O,"global"in M?M.global:this==t,M.state)}function h(b){var M,A=b.length,S=this,O=0,_=S.i=S.j=0,E=S.S=[];for(A||(b=[A++]);O{var KG=BB(),jG=IB(),eV=kB(),rV=LB(),tV=UB(),nV=YB(),Os=GB();Os.alea=KG;Os.xor128=jG;Os.xorwow=eV;Os.xorshift7=rV;Os.xor4096=tV;Os.tychei=nV;VB.exports=Os});var QR=vn((OIe,CS)=>{function MS(){}MS.prototype={on:function(e,r,t){var n=this.e||(this.e={});return(n[e]||(n[e]=[])).push({fn:r,ctx:t}),this},once:function(e,r,t){var n=this;function a(){n.off(e,a),r.apply(t,arguments)}return a._=r,this.on(e,a,t)},emit:function(e){var r=[].slice.call(arguments,1),t=((this.e||(this.e={}))[e]||[]).slice(),n=0,a=t.length;for(n;n{(function(e,r){typeof ES=="object"&&typeof Nf<"u"?Nf.exports=r():typeof define=="function"&&define.amd?define(r):e.moment=r()})(ES,function(){"use strict";var e;function r(){return e.apply(null,arguments)}function t(g){e=g}function n(g){return g instanceof Array||Object.prototype.toString.call(g)==="[object Array]"}function a(g){return g!=null&&Object.prototype.toString.call(g)==="[object Object]"}function i(g,N){return Object.prototype.hasOwnProperty.call(g,N)}function u(g){if(Object.getOwnPropertyNames)return Object.getOwnPropertyNames(g).length===0;var N;for(N in g)if(i(g,N))return!1;return!0}function l(g){return g===void 0}function c(g){return typeof g=="number"||Object.prototype.toString.call(g)==="[object Number]"}function o(g){return g instanceof Date||Object.prototype.toString.call(g)==="[object Date]"}function s(g,N){var I=[],U,V=g.length;for(U=0;U>>0,U;for(U=0;U0)for(I=0;I=0;return(se?I?"+":"":"-")+Math.pow(10,Math.max(0,V)).toString().substr(1)+U}var z=/(\\[[^\\[]*\\])|(\\\\)?([Hh]mm(ss)?|Mo|MM?M?M?|Do|DDDo|DD?D?D?|ddd?d?|do?|w[o|w]?|W[o|W]?|Qo?|N{1,5}|YYYYYY|YYYYY|YYYY|YY|y{2,4}|yo?|gg(ggg?)?|GG(GGG?)?|e|E|a|A|hh?|HH?|kk?|mm?|ss?|S{1,9}|x|X|zz?|ZZ?|.)/g,oe=/(\\[[^\\[]*\\])|(\\\\)?(LTS|LT|LL?L?L?|l{1,4})/g,pe={},ae={};function $(g,N,I,U){var V=U;typeof U=="string"&&(V=function(){return this[U]()}),g&&(ae[g]=V),N&&(ae[N[0]]=function(){return K(V.apply(this,arguments),N[1],N[2])}),I&&(ae[I]=function(){return this.localeData().ordinal(V.apply(this,arguments),g)})}function le(g){return g.match(/\\[[\\s\\S]/)?g.replace(/^\\[|\\]$/g,""):g.replace(/\\\\/g,"")}function Ee(g){var N=g.match(z),I,U;for(I=0,U=N.length;I=0&&oe.test(g);)g=g.replace(oe,U),oe.lastIndex=0,I-=1;return g}var Se={LTS:"h:mm:ss A",LT:"h:mm A",L:"MM/DD/YYYY",LL:"MMMM D, YYYY",LLL:"MMMM D, YYYY h:mm A",LLLL:"dddd, MMMM D, YYYY h:mm A"};function xe(g){var N=this._longDateFormat[g],I=this._longDateFormat[g.toUpperCase()];return N||!I?N:(this._longDateFormat[g]=I.match(z).map(function(U){return U==="MMMM"||U==="MM"||U==="DD"||U==="dddd"?U.slice(1):U}).join(""),this._longDateFormat[g])}var be="Invalid date";function De(){return this._invalidDate}var Ae="%d",We=/\\d{1,2}/;function Je(g){return this._ordinal.replace("%d",g)}var J={future:"in %s",past:"%s ago",s:"a few seconds",ss:"%d seconds",m:"a minute",mm:"%d minutes",h:"an hour",hh:"%d hours",d:"a day",dd:"%d days",w:"a week",ww:"%d weeks",M:"a month",MM:"%d months",y:"a year",yy:"%d years"};function re(g,N,I,U){var V=this._relativeTime[I];return R(V)?V(g,N,I,U):V.replace(/%d/i,g)}function ye(g,N){var I=this._relativeTime[g>0?"future":"past"];return R(I)?I(N):I.replace(/%s/i,N)}var j={};function ne(g,N){var I=g.toLowerCase();j[I]=j[I+"s"]=j[N]=g}function ue(g){return typeof g=="string"?j[g]||j[g.toLowerCase()]:void 0}function Me(g){var N={},I,U;for(U in g)i(g,U)&&(I=ue(U),I&&(N[I]=g[U]));return N}var Ce={};function Le(g,N){Ce[g]=N}function Ie(g){var N=[],I;for(I in g)i(g,I)&&N.push({unit:I,priority:Ce[I]});return N.sort(function(U,V){return U.priority-V.priority}),N}function fr(g){return g%4===0&&g%100!==0||g%400===0}function or(g){return g<0?Math.ceil(g)||0:Math.floor(g)}function Ke(g){var N=+g,I=0;return N!==0&&isFinite(N)&&(I=or(N)),I}function Pr(g,N){return function(I){return I!=null?(ce(this,g,I),r.updateOffset(this,N),this):ee(this,g)}}function ee(g,N){return g.isValid()?g._d["get"+(g._isUTC?"UTC":"")+N]():NaN}function ce(g,N,I){g.isValid()&&!isNaN(I)&&(N==="FullYear"&&fr(g.year())&&g.month()===1&&g.date()===29?(I=Ke(I),g._d["set"+(g._isUTC?"UTC":"")+N](I,g.month(),uo(I,g.month()))):g._d["set"+(g._isUTC?"UTC":"")+N](I))}function we(g){return g=ue(g),R(this[g])?this[g]():this}function Be(g,N){if(typeof g=="object"){g=Me(g);var I=Ie(g),U,V=I.length;for(U=0;U68?1900:2e3)};var qf=Pr("FullYear",!0);function xy(){return fr(this.year())}function Vc(g,N,I,U,V,se,Fe){var dr;return g<100&&g>=0?(dr=new Date(g+400,N,I,U,V,se,Fe),isFinite(dr.getFullYear())&&dr.setFullYear(g)):dr=new Date(g,N,I,U,V,se,Fe),dr}function fo(g){var N,I;return g<100&&g>=0?(I=Array.prototype.slice.call(arguments),I[0]=g+400,N=new Date(Date.UTC.apply(null,I)),isFinite(N.getUTCFullYear())&&N.setUTCFullYear(g)):N=new Date(Date.UTC.apply(null,arguments)),N}function co(g,N,I){var U=7+N-I,V=(7+fo(g,0,U).getUTCDay()-N)%7;return-V+U-1}function Zc(g,N,I,U,V){var se=(7+I-U)%7,Fe=co(g,U,V),dr=1+7*(N-1)+se+Fe,Or,tt;return dr<=0?(Or=g-1,tt=pi(Or)+dr):dr>pi(g)?(Or=g+1,tt=dr-pi(g)):(Or=g,tt=dr),{year:Or,dayOfYear:tt}}function lo(g,N,I){var U=co(g.year(),N,I),V=Math.floor((g.dayOfYear()-U-1)/7)+1,se,Fe;return V<1?(Fe=g.year()-1,se=V+na(Fe,N,I)):V>na(g.year(),N,I)?(se=V-na(g.year(),N,I),Fe=g.year()+1):(Fe=g.year(),se=V),{week:se,year:Fe}}function na(g,N,I){var U=co(g,N,I),V=co(g+1,N,I);return(pi(g)-U+V)/7}$("w",["ww",2],"wo","week"),$("W",["WW",2],"Wo","isoWeek"),ne("week","w"),ne("isoWeek","W"),Le("week",5),Le("isoWeek",5),nr("w",Q),nr("ww",Q,Te),nr("W",Q),nr("WW",Q,Te),Pi(["w","ww","W","WW"],function(g,N,I,U){N[U.substr(0,1)]=Ke(g)});function Lf(g){return lo(g,this._week.dow,this._week.doy).week}var mo={dow:0,doy:6};function Qc(){return this._week.dow}function Xc(){return this._week.doy}function yy(g){var N=this.localeData().week(this);return g==null?N:this.add((g-N)*7,"d")}function Jc(g){var N=lo(this,1,4).week;return g==null?N:this.add((g-N)*7,"d")}$("d",0,"do","day"),$("dd",0,0,function(g){return this.localeData().weekdaysMin(this,g)}),$("ddd",0,0,function(g){return this.localeData().weekdaysShort(this,g)}),$("dddd",0,0,function(g){return this.localeData().weekdays(this,g)}),$("e",0,0,"weekday"),$("E",0,0,"isoWeekday"),ne("day","d"),ne("weekday","e"),ne("isoWeekday","E"),Le("day",11),Le("weekday",11),Le("isoWeekday",11),nr("d",Q),nr("e",Q),nr("E",Q),nr("dd",function(g,N){return N.weekdaysMinRegex(g)}),nr("ddd",function(g,N){return N.weekdaysShortRegex(g)}),nr("dddd",function(g,N){return N.weekdaysRegex(g)}),Pi(["dd","ddd","dddd"],function(g,N,I,U){var V=I._locale.weekdaysParse(g,U,I._strict);V!=null?N.d=V:x(I).invalidWeekday=g}),Pi(["d","e","E"],function(g,N,I,U){N[U]=Ke(g)});function Kc(g,N){return typeof g!="string"?g:isNaN(g)?(g=N.weekdaysParse(g),typeof g=="number"?g:null):parseInt(g,10)}function jc(g,N){return typeof g=="string"?N.weekdaysParse(g)%7||7:isNaN(g)?null:g}function Ys(g,N){return g.slice(N,7).concat(g.slice(0,N))}var by="Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday".split("_"),el="Sun_Mon_Tue_Wed_Thu_Fri_Sat".split("_"),wy="Su_Mo_Tu_We_Th_Fr_Sa".split("_"),rl=Ya,Dy=Ya,Sy=Ya;function Ny(g,N){var I=n(this._weekdays)?this._weekdays:this._weekdays[g&&g!==!0&&this._weekdays.isFormat.test(N)?"format":"standalone"];return g===!0?Ys(I,this._week.dow):g?I[g.day()]:I}function Ay(g){return g===!0?Ys(this._weekdaysShort,this._week.dow):g?this._weekdaysShort[g.day()]:this._weekdaysShort}function zf(g){return g===!0?Ys(this._weekdaysMin,this._week.dow):g?this._weekdaysMin[g.day()]:this._weekdaysMin}function My(g,N,I){var U,V,se,Fe=g.toLocaleLowerCase();if(!this._weekdaysParse)for(this._weekdaysParse=[],this._shortWeekdaysParse=[],this._minWeekdaysParse=[],U=0;U<7;++U)se=d([2e3,1]).day(U),this._minWeekdaysParse[U]=this.weekdaysMin(se,"").toLocaleLowerCase(),this._shortWeekdaysParse[U]=this.weekdaysShort(se,"").toLocaleLowerCase(),this._weekdaysParse[U]=this.weekdays(se,"").toLocaleLowerCase();return I?N==="dddd"?(V=vt.call(this._weekdaysParse,Fe),V!==-1?V:null):N==="ddd"?(V=vt.call(this._shortWeekdaysParse,Fe),V!==-1?V:null):(V=vt.call(this._minWeekdaysParse,Fe),V!==-1?V:null):N==="dddd"?(V=vt.call(this._weekdaysParse,Fe),V!==-1||(V=vt.call(this._shortWeekdaysParse,Fe),V!==-1)?V:(V=vt.call(this._minWeekdaysParse,Fe),V!==-1?V:null)):N==="ddd"?(V=vt.call(this._shortWeekdaysParse,Fe),V!==-1||(V=vt.call(this._weekdaysParse,Fe),V!==-1)?V:(V=vt.call(this._minWeekdaysParse,Fe),V!==-1?V:null)):(V=vt.call(this._minWeekdaysParse,Fe),V!==-1||(V=vt.call(this._weekdaysParse,Fe),V!==-1)?V:(V=vt.call(this._shortWeekdaysParse,Fe),V!==-1?V:null))}function Cy(g,N,I){var U,V,se;if(this._weekdaysParseExact)return My.call(this,g,N,I);for(this._weekdaysParse||(this._weekdaysParse=[],this._minWeekdaysParse=[],this._shortWeekdaysParse=[],this._fullWeekdaysParse=[]),U=0;U<7;U++){if(V=d([2e3,1]).day(U),I&&!this._fullWeekdaysParse[U]&&(this._fullWeekdaysParse[U]=new RegExp("^"+this.weekdays(V,"").replace(".","\\\\.?")+"$","i"),this._shortWeekdaysParse[U]=new RegExp("^"+this.weekdaysShort(V,"").replace(".","\\\\.?")+"$","i"),this._minWeekdaysParse[U]=new RegExp("^"+this.weekdaysMin(V,"").replace(".","\\\\.?")+"$","i")),this._weekdaysParse[U]||(se="^"+this.weekdays(V,"")+"|^"+this.weekdaysShort(V,"")+"|^"+this.weekdaysMin(V,""),this._weekdaysParse[U]=new RegExp(se.replace(".",""),"i")),I&&N==="dddd"&&this._fullWeekdaysParse[U].test(g))return U;if(I&&N==="ddd"&&this._shortWeekdaysParse[U].test(g))return U;if(I&&N==="dd"&&this._minWeekdaysParse[U].test(g))return U;if(!I&&this._weekdaysParse[U].test(g))return U}}function Ey(g){if(!this.isValid())return g!=null?this:NaN;var N=this._isUTC?this._d.getUTCDay():this._d.getDay();return g!=null?(g=Kc(g,this.localeData()),this.add(g-N,"d")):N}function Ty(g){if(!this.isValid())return g!=null?this:NaN;var N=(this.day()+7-this.localeData()._week.dow)%7;return g==null?N:this.add(g-N,"d")}function Fy(g){if(!this.isValid())return g!=null?this:NaN;if(g!=null){var N=jc(g,this.localeData());return this.day(this.day()%7?N:N-7)}else return this.day()||7}function yt(g){return this._weekdaysParseExact?(i(this,"_weekdaysRegex")||Uf.call(this),g?this._weekdaysStrictRegex:this._weekdaysRegex):(i(this,"_weekdaysRegex")||(this._weekdaysRegex=rl),this._weekdaysStrictRegex&&g?this._weekdaysStrictRegex:this._weekdaysRegex)}function gt(g){return this._weekdaysParseExact?(i(this,"_weekdaysRegex")||Uf.call(this),g?this._weekdaysShortStrictRegex:this._weekdaysShortRegex):(i(this,"_weekdaysShortRegex")||(this._weekdaysShortRegex=Dy),this._weekdaysShortStrictRegex&&g?this._weekdaysShortStrictRegex:this._weekdaysShortRegex)}function _y(g){return this._weekdaysParseExact?(i(this,"_weekdaysRegex")||Uf.call(this),g?this._weekdaysMinStrictRegex:this._weekdaysMinRegex):(i(this,"_weekdaysMinRegex")||(this._weekdaysMinRegex=Sy),this._weekdaysMinStrictRegex&&g?this._weekdaysMinStrictRegex:this._weekdaysMinRegex)}function Uf(){function g(hn,Aa){return Aa.length-hn.length}var N=[],I=[],U=[],V=[],se,Fe,dr,Or,tt;for(se=0;se<7;se++)Fe=d([2e3,1]).day(se),dr=mn(this.weekdaysMin(Fe,"")),Or=mn(this.weekdaysShort(Fe,"")),tt=mn(this.weekdays(Fe,"")),N.push(dr),I.push(Or),U.push(tt),V.push(dr),V.push(Or),V.push(tt);N.sort(g),I.sort(g),U.sort(g),V.sort(g),this._weekdaysRegex=new RegExp("^("+V.join("|")+")","i"),this._weekdaysShortRegex=this._weekdaysRegex,this._weekdaysMinRegex=this._weekdaysRegex,this._weekdaysStrictRegex=new RegExp("^("+U.join("|")+")","i"),this._weekdaysShortStrictRegex=new RegExp("^("+I.join("|")+")","i"),this._weekdaysMinStrictRegex=new RegExp("^("+N.join("|")+")","i")}function Wf(){return this.hours()%12||12}function Oy(){return this.hours()||24}$("H",["HH",2],0,"hour"),$("h",["hh",2],0,Wf),$("k",["kk",2],0,Oy),$("hmm",0,0,function(){return""+Wf.apply(this)+K(this.minutes(),2)}),$("hmmss",0,0,function(){return""+Wf.apply(this)+K(this.minutes(),2)+K(this.seconds(),2)}),$("Hmm",0,0,function(){return""+this.hours()+K(this.minutes(),2)}),$("Hmmss",0,0,function(){return""+this.hours()+K(this.minutes(),2)+K(this.seconds(),2)});function tl(g,N){$(g,0,0,function(){return this.localeData().meridiem(this.hours(),this.minutes(),N)})}tl("a",!0),tl("A",!1),ne("hour","h"),Le("hour",13);function nl(g,N){return N._meridiemParse}nr("a",nl),nr("A",nl),nr("H",Q),nr("h",Q),nr("k",Q),nr("HH",Q,Te),nr("hh",Q,Te),nr("kk",Q,Te),nr("hmm",ve),nr("hmmss",Pe),nr("Hmm",ve),nr("Hmmss",Pe),ot(["H","HH"],Tt),ot(["k","kk"],function(g,N,I){var U=Ke(g);N[Tt]=U===24?0:U}),ot(["a","A"],function(g,N,I){I._isPm=I._locale.isPM(g),I._meridiem=g}),ot(["h","hh"],function(g,N,I){N[Tt]=Ke(g),x(I).bigHour=!0}),ot("hmm",function(g,N,I){var U=g.length-2;N[Tt]=Ke(g.substr(0,U)),N[On]=Ke(g.substr(U)),x(I).bigHour=!0}),ot("hmmss",function(g,N,I){var U=g.length-4,V=g.length-2;N[Tt]=Ke(g.substr(0,U)),N[On]=Ke(g.substr(U,2)),N[ta]=Ke(g.substr(V)),x(I).bigHour=!0}),ot("Hmm",function(g,N,I){var U=g.length-2;N[Tt]=Ke(g.substr(0,U)),N[On]=Ke(g.substr(U))}),ot("Hmmss",function(g,N,I){var U=g.length-4,V=g.length-2;N[Tt]=Ke(g.substr(0,U)),N[On]=Ke(g.substr(U,2)),N[ta]=Ke(g.substr(V))});function al(g){return(g+"").toLowerCase().charAt(0)==="p"}var By=/[ap]\\.?m?\\.?/i,Vt=Pr("Hours",!0);function Yf(g,N,I){return g>11?I?"pm":"PM":I?"am":"AM"}var di={calendar:L,longDateFormat:Se,invalidDate:be,ordinal:Ae,dayOfMonthOrdinalParse:We,relativeTime:J,months:Pf,monthsShort:Ls,week:mo,weekdays:by,weekdaysMin:wy,weekdaysShort:el,meridiemParse:By},bt={},Ri={},sn;function il(g,N){var I,U=Math.min(g.length,N.length);for(I=0;I0;){if(V=jo(se.slice(0,I).join("-")),V)return V;if(U&&U.length>=I&&il(se,U)>=I-1)break;I--}N++}return sn}function sl(g){return g.match("^[^/\\\\\\\\]*$")!=null}function jo(g){var N=null,I;if(bt[g]===void 0&&typeof Nf<"u"&&Nf&&Nf.exports&&sl(g))try{N=sn._abbr,I=require,I("./locale/"+g),Ga(N)}catch{bt[g]=null}return bt[g]}function Ga(g,N){var I;return g&&(l(N)?I=It(g):I=pn(g,N),I?sn=I:typeof console<"u"&&console.warn&&console.warn("Locale "+g+" not found. Did you forget to load it?")),sn._abbr}function pn(g,N){if(N!==null){var I,U=di;if(N.abbr=g,bt[g]!=null)T("defineLocaleOverride","use moment.updateLocale(localeName, config) to change an existing locale. moment.defineLocale(localeName, config) should only be used for creating a new locale See http://momentjs.com/guides/#/warnings/define-locale/ for more info."),U=bt[g]._config;else if(N.parentLocale!=null)if(bt[N.parentLocale]!=null)U=bt[N.parentLocale]._config;else if(I=jo(N.parentLocale),I!=null)U=I._config;else return Ri[N.parentLocale]||(Ri[N.parentLocale]=[]),Ri[N.parentLocale].push({name:g,config:N}),null;return bt[g]=new G(W(U,N)),Ri[g]&&Ri[g].forEach(function(V){pn(V.name,V.config)}),Ga(g),bt[g]}else return delete bt[g],null}function Py(g,N){if(N!=null){var I,U,V=di;bt[g]!=null&&bt[g].parentLocale!=null?bt[g].set(W(bt[g]._config,N)):(U=jo(g),U!=null&&(V=U._config),N=W(V,N),U==null&&(N.abbr=g),I=new G(N),I.parentLocale=bt[g],bt[g]=I),Ga(g)}else bt[g]!=null&&(bt[g].parentLocale!=null?(bt[g]=bt[g].parentLocale,g===Ga()&&Ga(g)):bt[g]!=null&&delete bt[g]);return bt[g]}function It(g){var N;if(g&&g._locale&&g._locale._abbr&&(g=g._locale._abbr),!g)return sn;if(!n(g)){if(N=jo(g),N)return N;g=[g]}return ol(g)}function Iy(){return H(bt)}function Hs(g){var N,I=g._a;return I&&x(g).overflow===-2&&(N=I[zn]<0||I[zn]>11?zn:I[Un]<1||I[Un]>uo(I[Gt],I[zn])?Un:I[Tt]<0||I[Tt]>24||I[Tt]===24&&(I[On]!==0||I[ta]!==0||I[Ha]!==0)?Tt:I[On]<0||I[On]>59?On:I[ta]<0||I[ta]>59?ta:I[Ha]<0||I[Ha]>999?Ha:-1,x(g)._overflowDayOfYear&&(NUn)&&(N=Un),x(g)._overflowWeeks&&N===-1&&(N=Of),x(g)._overflowWeekday&&N===-1&&(N=so),x(g).overflow=N),g}var hi=/^\\s*((?:[+-]\\d{6}|\\d{4})-(?:\\d\\d-\\d\\d|W\\d\\d-\\d|W\\d\\d|\\d\\d\\d|\\d\\d))(?:(T| )(\\d\\d(?::\\d\\d(?::\\d\\d(?:[.,]\\d+)?)?)?)([+-]\\d\\d(?::?\\d\\d)?|\\s*Z)?)?$/,$s=/^\\s*((?:[+-]\\d{6}|\\d{4})(?:\\d\\d\\d\\d|W\\d\\d\\d|W\\d\\d|\\d\\d\\d|\\d\\d|))(?:(T| )(\\d\\d(?:\\d\\d(?:\\d\\d(?:[.,]\\d+)?)?)?)([+-]\\d\\d(?::?\\d\\d)?|\\s*Z)?)?$/,$f=/Z|[+-]\\d\\d(?::?\\d\\d)?/,dt=[["YYYYYY-MM-DD",/[+-]\\d{6}-\\d\\d-\\d\\d/],["YYYY-MM-DD",/\\d{4}-\\d\\d-\\d\\d/],["GGGG-[W]WW-E",/\\d{4}-W\\d\\d-\\d/],["GGGG-[W]WW",/\\d{4}-W\\d\\d/,!1],["YYYY-DDD",/\\d{4}-\\d{3}/],["YYYY-MM",/\\d{4}-\\d\\d/,!1],["YYYYYYMMDD",/[+-]\\d{10}/],["YYYYMMDD",/\\d{8}/],["GGGG[W]WWE",/\\d{4}W\\d{3}/],["GGGG[W]WW",/\\d{4}W\\d{2}/,!1],["YYYYDDD",/\\d{7}/],["YYYYMM",/\\d{6}/,!1],["YYYY",/\\d{4}/,!1]],ba=[["HH:mm:ss.SSSS",/\\d\\d:\\d\\d:\\d\\d\\.\\d+/],["HH:mm:ss,SSSS",/\\d\\d:\\d\\d:\\d\\d,\\d+/],["HH:mm:ss",/\\d\\d:\\d\\d:\\d\\d/],["HH:mm",/\\d\\d:\\d\\d/],["HHmmss.SSSS",/\\d\\d\\d\\d\\d\\d\\.\\d+/],["HHmmss,SSSS",/\\d\\d\\d\\d\\d\\d,\\d+/],["HHmmss",/\\d\\d\\d\\d\\d\\d/],["HHmm",/\\d\\d\\d\\d/],["HH",/\\d\\d/]],Gf=/^\\/?Date\\((-?\\d+)/i,Ry=/^(?:(Mon|Tue|Wed|Thu|Fri|Sat|Sun),?\\s)?(\\d{1,2})\\s(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\\s(\\d{2,4})\\s(\\d\\d):(\\d\\d)(?::(\\d\\d))?\\s(?:(UT|GMT|[ECMP][SD]T)|([Zz])|([+-]\\d{4}))$/,Vf={UT:0,GMT:0,EDT:-4*60,EST:-5*60,CDT:-5*60,CST:-6*60,MDT:-6*60,MST:-7*60,PDT:-7*60,PST:-8*60};function ul(g){var N,I,U=g._i,V=hi.exec(U)||$s.exec(U),se,Fe,dr,Or,tt=dt.length,hn=ba.length;if(V){for(x(g).iso=!0,N=0,I=tt;Npi(Fe)||g._dayOfYear===0)&&(x(g)._overflowDayOfYear=!0),I=fo(Fe,0,g._dayOfYear),g._a[zn]=I.getUTCMonth(),g._a[Un]=I.getUTCDate()),N=0;N<3&&g._a[N]==null;++N)g._a[N]=U[N]=V[N];for(;N<7;N++)g._a[N]=U[N]=g._a[N]==null?N===2?1:0:g._a[N];g._a[Tt]===24&&g._a[On]===0&&g._a[ta]===0&&g._a[Ha]===0&&(g._nextDay=!0,g._a[Tt]=0),g._d=(g._useUTC?fo:Vc).apply(null,U),se=g._useUTC?g._d.getUTCDay():g._d.getDay(),g._tzm!=null&&g._d.setUTCMinutes(g._d.getUTCMinutes()-g._tzm),g._nextDay&&(g._a[Tt]=24),g._w&&typeof g._w.d<"u"&&g._w.d!==se&&(x(g).weekdayMismatch=!0)}}function ml(g){var N,I,U,V,se,Fe,dr,Or,tt;N=g._w,N.GG!=null||N.W!=null||N.E!=null?(se=1,Fe=4,I=ki(N.GG,g._a[Gt],lo(xt(),1,4).year),U=ki(N.W,1),V=ki(N.E,1),(V<1||V>7)&&(Or=!0)):(se=g._locale._week.dow,Fe=g._locale._week.doy,tt=lo(xt(),se,Fe),I=ki(N.gg,g._a[Gt],tt.year),U=ki(N.w,tt.week),N.d!=null?(V=N.d,(V<0||V>6)&&(Or=!0)):N.e!=null?(V=N.e+se,(N.e<0||N.e>6)&&(Or=!0)):V=se),U<1||U>na(I,se,Fe)?x(g)._overflowWeeks=!0:Or!=null?x(g)._overflowWeekday=!0:(dr=Zc(I,U,V,se,Fe),g._a[Gt]=dr.year,g._dayOfYear=dr.dayOfYear)}r.ISO_8601=function(){},r.RFC_2822=function(){};function Qf(g){if(g._f===r.ISO_8601){ul(g);return}if(g._f===r.RFC_2822){cl(g);return}g._a=[],x(g).empty=!0;var N=""+g._i,I,U,V,se,Fe,dr=N.length,Or=0,tt,hn;for(V=ge(g._f,g._locale).match(z)||[],hn=V.length,I=0;I0&&x(g).unusedInput.push(Fe),N=N.slice(N.indexOf(U)+U.length),Or+=U.length),ae[se]?(U?x(g).empty=!1:x(g).unusedTokens.push(se),_f(se,U,g)):g._strict&&!U&&x(g).unusedTokens.push(se);x(g).charsLeftOver=dr-Or,N.length>0&&x(g).unusedInput.push(N),g._a[Tt]<=12&&x(g).bigHour===!0&&g._a[Tt]>0&&(x(g).bigHour=void 0),x(g).parsedDateParts=g._a.slice(0),x(g).meridiem=g._meridiem,g._a[Tt]=Xf(g._locale,g._a[Tt],g._meridiem),tt=x(g).era,tt!==null&&(g._a[Gt]=g._locale.erasConvertYear(tt,g._a[Gt])),es(g),Hs(g)}function Xf(g,N,I){var U;return I==null?N:g.meridiemHour!=null?g.meridiemHour(N,I):(g.isPM!=null&&(U=g.isPM(I),U&&N<12&&(N+=12),!U&&N===12&&(N=0)),N)}function Jf(g){var N,I,U,V,se,Fe,dr=!1,Or=g._f.length;if(Or===0){x(g).invalidFormat=!0,g._d=new Date(NaN);return}for(V=0;Vthis?this:g:w()});function hl(g,N){var I,U;if(N.length===1&&n(N[0])&&(N=N[0]),!N.length)return xt();for(I=N[0],U=1;Uthis.clone().month(0).utcOffset()||this.utcOffset()>this.clone().month(5).utcOffset()}function _e(){if(!l(this._isDSTShifted))return this._isDSTShifted;var g={},N;return M(g,this),g=bn(g),g._a?(N=g._isUTC?d(g._a):xt(g._a),this._isDSTShifted=this.isValid()&&Gy(g._a,N.toArray())>0):this._isDSTShifted=!1,this._isDSTShifted}function Ne(){return this.isValid()?!this._isUTC:!1}function ir(){return this.isValid()?this._isUTC:!1}function Ar(){return this.isValid()?this._isUTC&&this._offset===0:!1}var rt=/^(-|\\+)?(?:(\\d*)[. ])?(\\d+):(\\d+)(?::(\\d+)(\\.\\d*)?)?$/,zt=/^(-|\\+)?P(?:([-+]?[0-9,.]*)Y)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)W)?(?:([-+]?[0-9,.]*)D)?(?:T(?:([-+]?[0-9,.]*)H)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)S)?)?$/;function zr(g,N){var I=g,U=null,V,se,Fe;return aa(g)?I={ms:g._milliseconds,d:g._days,M:g._months}:c(g)||!isNaN(+g)?(I={},N?I[N]=+g:I.milliseconds=+g):(U=rt.exec(g))?(V=U[1]==="-"?-1:1,I={y:0,d:Ke(U[Un])*V,h:Ke(U[Tt])*V,m:Ke(U[On])*V,s:Ke(U[ta])*V,ms:Ke(vo(U[Ha]*1e3))*V}):(U=zt.exec(g))?(V=U[1]==="-"?-1:1,I={y:Va(U[2],V),M:Va(U[3],V),w:Va(U[4],V),d:Va(U[5],V),h:Va(U[6],V),m:Va(U[7],V),s:Va(U[8],V)}):I==null?I={}:typeof I=="object"&&("from"in I||"to"in I)&&(Fe=Wn(xt(I.from),xt(I.to)),I={},I.ms=Fe.milliseconds,I.M=Fe.months),se=new rs(I),aa(g)&&i(g,"_locale")&&(se._locale=g._locale),aa(g)&&i(g,"_isValid")&&(se._isValid=g._isValid),se}zr.fn=rs.prototype,zr.invalid=jf;function Va(g,N){var I=g&&parseFloat(g.replace(",","."));return(isNaN(I)?0:I)*N}function gl(g,N){var I={};return I.months=N.month()-g.month()+(N.year()-g.year())*12,g.clone().add(I.months,"M").isAfter(N)&&--I.months,I.milliseconds=+N-+g.clone().add(I.months,"M"),I}function Wn(g,N){var I;return g.isValid()&&N.isValid()?(N=Bn(N,g),g.isBefore(N)?I=gl(g,N):(I=gl(N,g),I.milliseconds=-I.milliseconds,I.months=-I.months),I):{milliseconds:0,months:0}}function ts(g,N){return function(I,U){var V,se;return U!==null&&!isNaN(+U)&&(T(N,"moment()."+N+"(period, number) is deprecated. Please use moment()."+N+"(number, period). See http://momentjs.com/guides/#/warnings/add-inverted-param/ for more info."),se=I,I=U,U=se),V=zr(I,U),xl(this,V,g),this}}function xl(g,N,I,U){var V=N._milliseconds,se=vo(N._days),Fe=vo(N._months);!g.isValid()||(U=U??!0,Fe&&mi(g,ee(g,"Month")+Fe*I),se&&ce(g,"Date",ee(g,"Date")+se*I),V&&g._d.setTime(g._d.valueOf()+V*I),U&&r.updateOffset(g,se||Fe))}var go=ts(1,"add"),Zs=ts(-1,"subtract");function ns(g){return typeof g=="string"||g instanceof String}function ut(g){return S(g)||o(g)||ns(g)||c(g)||yl(g)||jy(g)||g===null||g===void 0}function jy(g){var N=a(g)&&!u(g),I=!1,U=["years","year","y","months","month","M","days","day","d","dates","date","D","hours","hour","h","minutes","minute","m","seconds","second","s","milliseconds","millisecond","ms"],V,se,Fe=U.length;for(V=0;VI.valueOf():I.valueOf()9999?me(I,N?"YYYYYY-MM-DD[T]HH:mm:ss.SSS[Z]":"YYYYYY-MM-DD[T]HH:mm:ss.SSSZ"):R(Date.prototype.toISOString)?N?this.toDate().toISOString():new Date(this.valueOf()+this.utcOffset()*60*1e3).toISOString().replace("Z",me(I,"Z")):me(I,N?"YYYY-MM-DD[T]HH:mm:ss.SSS[Z]":"YYYY-MM-DD[T]HH:mm:ss.SSSZ")}function Li(){if(!this.isValid())return"moment.invalid(/* "+this._i+" */)";var g="moment",N="",I,U,V,se;return this.isLocal()||(g=this.utcOffset()===0?"moment.utc":"moment.parseZone",N="Z"),I="["+g+'("]',U=0<=this.year()&&this.year()<=9999?"YYYY":"YYYYYY",V="-MM-DD[T]HH:mm:ss.SSS",se=N+'[")]',this.format(I+U+V+se)}function js(g){g||(g=this.isUtc()?r.defaultFormatUtc:r.defaultFormat);var N=me(this,g);return this.localeData().postformat(N)}function n1(g,N){return this.isValid()&&(S(g)&&g.isValid()||xt(g).isValid())?zr({to:this,from:g}).locale(this.locale()).humanize(!N):this.localeData().invalidDate()}function a1(g){return this.from(xt(),g)}function i1(g,N){return this.isValid()&&(S(g)&&g.isValid()||xt(g).isValid())?zr({from:this,to:g}).locale(this.locale()).humanize(!N):this.localeData().invalidDate()}function eu(g){return this.to(xt(),g)}function is(g){var N;return g===void 0?this._locale._abbr:(N=It(g),N!=null&&(this._locale=N),this)}var ru=_("moment().lang() is deprecated. Instead, use moment().localeData() to get the language configuration. Use moment().locale() to change languages.",function(g){return g===void 0?this.localeData():this.locale(g)});function Nl(){return this._locale}var os=1e3,xo=60*os,tu=60*xo,Rt=(365*400+97)*24*tu;function Ft(g,N){return(g%N+N)%N}function Al(g,N,I){return g<100&&g>=0?new Date(g+400,N,I)-Rt:new Date(g,N,I).valueOf()}function Ml(g,N,I){return g<100&&g>=0?Date.UTC(g+400,N,I)-Rt:Date.UTC(g,N,I)}function Cl(g){var N,I;if(g=ue(g),g===void 0||g==="millisecond"||!this.isValid())return this;switch(I=this._isUTC?Ml:Al,g){case"year":N=I(this.year(),0,1);break;case"quarter":N=I(this.year(),this.month()-this.month()%3,1);break;case"month":N=I(this.year(),this.month(),1);break;case"week":N=I(this.year(),this.month(),this.date()-this.weekday());break;case"isoWeek":N=I(this.year(),this.month(),this.date()-(this.isoWeekday()-1));break;case"day":case"date":N=I(this.year(),this.month(),this.date());break;case"hour":N=this._d.valueOf(),N-=Ft(N+(this._isUTC?0:this.utcOffset()*xo),tu);break;case"minute":N=this._d.valueOf(),N-=Ft(N,xo);break;case"second":N=this._d.valueOf(),N-=Ft(N,os);break}return this._d.setTime(N),r.updateOffset(this,!0),this}function o1(g){var N,I;if(g=ue(g),g===void 0||g==="millisecond"||!this.isValid())return this;switch(I=this._isUTC?Ml:Al,g){case"year":N=I(this.year()+1,0,1)-1;break;case"quarter":N=I(this.year(),this.month()-this.month()%3+3,1)-1;break;case"month":N=I(this.year(),this.month()+1,1)-1;break;case"week":N=I(this.year(),this.month(),this.date()-this.weekday()+7)-1;break;case"isoWeek":N=I(this.year(),this.month(),this.date()-(this.isoWeekday()-1)+7)-1;break;case"day":case"date":N=I(this.year(),this.month(),this.date()+1)-1;break;case"hour":N=this._d.valueOf(),N+=tu-Ft(N+(this._isUTC?0:this.utcOffset()*xo),tu)-1;break;case"minute":N=this._d.valueOf(),N+=xo-Ft(N,xo)-1;break;case"second":N=this._d.valueOf(),N+=os-Ft(N,os)-1;break}return this._d.setTime(N),r.updateOffset(this,!0),this}function ec(){return this._d.valueOf()-(this._offset||0)*6e4}function ss(){return Math.floor(this.valueOf()/1e3)}function rc(){return new Date(this.valueOf())}function yo(){var g=this;return[g.year(),g.month(),g.date(),g.hour(),g.minute(),g.second(),g.millisecond()]}function us(){var g=this;return{years:g.year(),months:g.month(),date:g.date(),hours:g.hours(),minutes:g.minutes(),seconds:g.seconds(),milliseconds:g.milliseconds()}}function fs(){return this.isValid()?this.toISOString():null}function nu(){return y(this)}function bo(){return m({},x(this))}function s1(){return x(this).overflow}function u1(){return{input:this._i,format:this._f,locale:this._locale,isUTC:this._isUTC,strict:this._strict}}$("N",0,0,"eraAbbr"),$("NN",0,0,"eraAbbr"),$("NNN",0,0,"eraAbbr"),$("NNNN",0,0,"eraName"),$("NNNNN",0,0,"eraNarrow"),$("y",["y",1],"yo","eraYear"),$("y",["yy",2],0,"eraYear"),$("y",["yyy",3],0,"eraYear"),$("y",["yyyy",4],0,"eraYear"),nr("N",kr),nr("NN",kr),nr("NNN",kr),nr("NNNN",m1),nr("NNNNN",p1),ot(["N","NN","NNN","NNNN","NNNNN"],function(g,N,I,U){var V=I._locale.erasParse(g,U,I._strict);V?x(I).era=V:x(I).invalidEra=g}),nr("y",Pt),nr("yy",Pt),nr("yyy",Pt),nr("yyyy",Pt),nr("yo",d1),ot(["y","yy","yyy","yyyy"],Gt),ot(["yo"],function(g,N,I,U){var V;I._locale._eraYearOrdinalRegex&&(V=g.match(I._locale._eraYearOrdinalRegex)),I._locale.eraYearOrdinalParse?N[Gt]=I._locale.eraYearOrdinalParse(g,V):N[Gt]=parseInt(g,10)});function f1(g,N){var I,U,V,se=this._eras||It("en")._eras;for(I=0,U=se.length;I=0)return se[U]}function l1(g,N){var I=g.since<=g.until?1:-1;return N===void 0?r(g.since).year():r(g.since).year()+(N-g.offset)*I}function au(){var g,N,I,U=this.localeData().eras();for(g=0,N=U.length;gse&&(N=se),b1.call(this,g,N,I,U,V))}function b1(g,N,I,U,V){var se=Zc(g,N,I,U,V),Fe=fo(se.year,0,se.dayOfYear);return this.year(Fe.getUTCFullYear()),this.month(Fe.getUTCMonth()),this.date(Fe.getUTCDate()),this}$("Q",0,"Qo","quarter"),ne("quarter","Q"),Le("quarter",7),nr("Q",ke),ot("Q",function(g,N){N[zn]=(Ke(g)-1)*3});function w1(g){return g==null?Math.ceil((this.month()+1)/3):this.month((g-1)*3+this.month()%3)}$("D",["DD",2],"Do","date"),ne("date","D"),Le("date",9),nr("D",Q),nr("DD",Q,Te),nr("Do",function(g,N){return g?N._dayOfMonthOrdinalParse||N._ordinalParse:N._dayOfMonthOrdinalParseLenient}),ot(["D","DD"],Un),ot("Do",function(g,N){N[Un]=Ke(g.match(Q)[0])});var Fl=Pr("Date",!0);$("DDD",["DDDD",3],"DDDo","dayOfYear"),ne("dayOfYear","DDD"),Le("dayOfYear",4),nr("DDD",tr),nr("DDDD",Re),ot(["DDD","DDDD"],function(g,N,I){I._dayOfYear=Ke(g)});function Xa(g){var N=Math.round((this.clone().startOf("day")-this.clone().startOf("year"))/864e5)+1;return g==null?N:this.add(g-N,"d")}$("m",["mm",2],0,"minute"),ne("minute","m"),Le("minute",14),nr("m",Q),nr("mm",Q,Te),ot(["m","mm"],On);var D1=Pr("Minutes",!1);$("s",["ss",2],0,"second"),ne("second","s"),Le("second",15),nr("s",Q),nr("ss",Q,Te),ot(["s","ss"],ta);var S1=Pr("Seconds",!1);$("S",0,0,function(){return~~(this.millisecond()/100)}),$(0,["SS",2],0,function(){return~~(this.millisecond()/10)}),$(0,["SSS",3],0,"millisecond"),$(0,["SSSS",4],0,function(){return this.millisecond()*10}),$(0,["SSSSS",5],0,function(){return this.millisecond()*100}),$(0,["SSSSSS",6],0,function(){return this.millisecond()*1e3}),$(0,["SSSSSSS",7],0,function(){return this.millisecond()*1e4}),$(0,["SSSSSSSS",8],0,function(){return this.millisecond()*1e5}),$(0,["SSSSSSSSS",9],0,function(){return this.millisecond()*1e6}),ne("millisecond","ms"),Le("millisecond",16),nr("S",tr,ke),nr("SS",tr,Te),nr("SSS",tr,Re);var yi,_l;for(yi="SSSS";yi.length<=9;yi+="S")nr(yi,Pt);function N1(g,N){N[Ha]=Ke(("0."+g)*1e3)}for(yi="S";yi.length<=9;yi+="S")ot(yi,N1);_l=Pr("Milliseconds",!1),$("z",0,0,"zoneAbbr"),$("zz",0,0,"zoneName");function zi(){return this._isUTC?"UTC":""}function A1(){return this._isUTC?"Coordinated Universal Time":""}var Ve=A.prototype;Ve.add=go,Ve.calendar=r1,Ve.clone=t1,Ve.diff=Dl,Ve.endOf=o1,Ve.format=js,Ve.from=n1,Ve.fromNow=a1,Ve.to=i1,Ve.toNow=eu,Ve.get=we,Ve.invalidAt=s1,Ve.isAfter=Xs,Ve.isBefore=xi,Ve.isBetween=Js,Ve.isSame=bl,Ve.isSameOrAfter=Ks,Ve.isSameOrBefore=wl,Ve.isValid=nu,Ve.lang=ru,Ve.locale=is,Ve.localeData=Nl,Ve.max=zy,Ve.min=dl,Ve.parsingFlags=bo,Ve.set=Be,Ve.startOf=Cl,Ve.subtract=Zs,Ve.toArray=yo,Ve.toObject=us,Ve.toDate=rc,Ve.toISOString=as,Ve.inspect=Li,typeof Symbol<"u"&&Symbol.for!=null&&(Ve[Symbol.for("nodejs.util.inspect.custom")]=function(){return"Moment<"+this.format()+">"}),Ve.toJSON=fs,Ve.toString=Sl,Ve.unix=ss,Ve.valueOf=ec,Ve.creationData=u1,Ve.eraName=au,Ve.eraNarrow=cs,Ve.eraAbbr=El,Ve.eraYear=Z,Ve.year=qf,Ve.isLeapYear=xy,Ve.weekYear=h1,Ve.isoWeekYear=v1,Ve.quarter=Ve.quarters=w1,Ve.month=$a,Ve.daysInMonth=Ws,Ve.week=Ve.weeks=yy,Ve.isoWeek=Ve.isoWeeks=Jc,Ve.weeksInYear=Qa,Ve.weeksInWeekYear=y1,Ve.isoWeeksInYear=g1,Ve.isoWeeksInISOWeekYear=x1,Ve.date=Fl,Ve.day=Ve.days=Ey,Ve.weekday=Ty,Ve.isoWeekday=Fy,Ve.dayOfYear=Xa,Ve.hour=Ve.hours=Vt,Ve.minute=Ve.minutes=D1,Ve.second=Ve.seconds=S1,Ve.millisecond=Ve.milliseconds=_l,Ve.utcOffset=Zy,Ve.utc=Xy,Ve.local=Jy,Ve.parseZone=Ky,Ve.hasAlignedHourOffset=gi,Ve.isDST=de,Ve.isLocal=Ne,Ve.isUtcOffset=ir,Ve.isUtc=Ar,Ve.isUTC=Ar,Ve.zoneAbbr=zi,Ve.zoneName=A1,Ve.dates=_("dates accessor is deprecated. Use date instead.",Fl),Ve.months=_("months accessor is deprecated. Use month instead",$a),Ve.years=_("years accessor is deprecated. Use year instead",qf),Ve.zone=_("moment().zone is deprecated, use moment().utcOffset instead. http://momentjs.com/guides/#/warnings/zone/",Qy),Ve.isDSTShifted=_("isDSTShifted is deprecated. See http://momentjs.com/guides/#/warnings/dst-shifted/ for more information",_e);function ia(g){return xt(g*1e3)}function M1(){return xt.apply(null,arguments).parseZone()}function Ol(g){return g}var Jr=G.prototype;Jr.calendar=k,Jr.longDateFormat=xe,Jr.invalidDate=De,Jr.ordinal=Je,Jr.preparse=Ol,Jr.postformat=Ol,Jr.relativeTime=re,Jr.pastFuture=ye,Jr.set=q,Jr.eras=f1,Jr.erasParse=c1,Jr.erasConvertYear=l1,Jr.erasAbbrRegex=iu,Jr.erasNameRegex=wo,Jr.erasNarrowRegex=Yn,Jr.months=Ii,Jr.monthsShort=et,Jr.monthsParse=If,Jr.monthsRegex=gy,Jr.monthsShortRegex=Rf,Jr.week=Lf,Jr.firstDayOfYear=Xc,Jr.firstDayOfWeek=Qc,Jr.weekdays=Ny,Jr.weekdaysMin=zf,Jr.weekdaysShort=Ay,Jr.weekdaysParse=Cy,Jr.weekdaysRegex=yt,Jr.weekdaysShortRegex=gt,Jr.weekdaysMinRegex=_y,Jr.isPM=al,Jr.meridiem=Yf;function su(g,N,I,U){var V=It(),se=d().set(U,N);return V[I](se,g)}function Bl(g,N,I){if(c(g)&&(N=g,g=void 0),g=g||"",N!=null)return su(g,N,I,"month");var U,V=[];for(U=0;U<12;U++)V[U]=su(g,U,I,"month");return V}function uu(g,N,I,U){typeof g=="boolean"?(c(N)&&(I=N,N=void 0),N=N||""):(N=g,I=N,g=!1,c(N)&&(I=N,N=void 0),N=N||"");var V=It(),se=g?V._week.dow:0,Fe,dr=[];if(I!=null)return su(N,(I+se)%7,U,"day");for(Fe=0;Fe<7;Fe++)dr[Fe]=su(N,(Fe+se)%7,U,"day");return dr}function Pl(g,N){return Bl(g,N,"months")}function C1(g,N){return Bl(g,N,"monthsShort")}function E1(g,N,I){return uu(g,N,I,"weekdays")}function tc(g,N,I){return uu(g,N,I,"weekdaysShort")}function ls(g,N,I){return uu(g,N,I,"weekdaysMin")}Ga("en",{eras:[{since:"0001-01-01",until:1/0,offset:1,name:"Anno Domini",narrow:"AD",abbr:"AD"},{since:"0000-12-31",until:-1/0,offset:1,name:"Before Christ",narrow:"BC",abbr:"BC"}],dayOfMonthOrdinalParse:/\\d{1,2}(th|st|nd|rd)/,ordinal:function(g){var N=g%10,I=Ke(g%100/10)===1?"th":N===1?"st":N===2?"nd":N===3?"rd":"th";return g+I}}),r.lang=_("moment.lang is deprecated. Use moment.locale instead.",Ga),r.langData=_("moment.langData is deprecated. Use moment.localeData instead.",It);var Hn=Math.abs;function T1(){var g=this._data;return this._milliseconds=Hn(this._milliseconds),this._days=Hn(this._days),this._months=Hn(this._months),g.milliseconds=Hn(g.milliseconds),g.seconds=Hn(g.seconds),g.minutes=Hn(g.minutes),g.hours=Hn(g.hours),g.months=Hn(g.months),g.years=Hn(g.years),this}function nc(g,N,I,U){var V=zr(N,I);return g._milliseconds+=U*V._milliseconds,g._days+=U*V._days,g._months+=U*V._months,g._bubble()}function F1(g,N){return nc(this,g,N,1)}function Ja(g,N){return nc(this,g,N,-1)}function fu(g){return g<0?Math.floor(g):Math.ceil(g)}function Ui(){var g=this._milliseconds,N=this._days,I=this._months,U=this._data,V,se,Fe,dr,Or;return g>=0&&N>=0&&I>=0||g<=0&&N<=0&&I<=0||(g+=fu(ac(I)+N)*864e5,N=0,I=0),U.milliseconds=g%1e3,V=or(g/1e3),U.seconds=V%60,se=or(V/60),U.minutes=se%60,Fe=or(se/60),U.hours=Fe%24,N+=or(Fe/24),Or=or(Pn(N)),I+=Or,N-=fu(ac(Or)),dr=or(I/12),I%=12,U.days=N,U.months=I,U.years=dr,this}function Pn(g){return g*4800/146097}function ac(g){return g*146097/4800}function Il(g){if(!this.isValid())return NaN;var N,I,U=this._milliseconds;if(g=ue(g),g==="month"||g==="quarter"||g==="year")switch(N=this._days+U/864e5,I=this._months+Pn(N),g){case"month":return I;case"quarter":return I/3;case"year":return I/12}else switch(N=this._days+Math.round(ac(this._months)),g){case"week":return N/7+U/6048e5;case"day":return N+U/864e5;case"hour":return N*24+U/36e5;case"minute":return N*1440+U/6e4;case"second":return N*86400+U/1e3;case"millisecond":return Math.floor(N*864e5)+U;default:throw new Error("Unknown unit "+g)}}function Rl(){return this.isValid()?this._milliseconds+this._days*864e5+this._months%12*2592e6+Ke(this._months/12)*31536e6:NaN}function In(g){return function(){return this.as(g)}}var bi=In("ms"),kl=In("s"),_1=In("m"),cu=In("h"),O1=In("d"),ql=In("w"),Jt=In("M"),ic=In("Q"),Ll=In("y");function Da(){return zr(this)}function oc(g){return g=ue(g),this.isValid()?this[g+"s"]():NaN}function Sa(g){return function(){return this.isValid()?this._data[g]:NaN}}var Wi=Sa("milliseconds"),zl=Sa("seconds"),dn=Sa("minutes"),sc=Sa("hours"),B1=Sa("days"),P1=Sa("months"),I1=Sa("years");function uc(){return or(this.days()/7)}var Ka=Math.round,Na={ss:44,s:45,m:45,h:22,d:26,w:null,M:11};function Ul(g,N,I,U,V){return V.relativeTime(N||1,!!I,g,U)}function R1(g,N,I,U){var V=zr(g).abs(),se=Ka(V.as("s")),Fe=Ka(V.as("m")),dr=Ka(V.as("h")),Or=Ka(V.as("d")),tt=Ka(V.as("M")),hn=Ka(V.as("w")),Aa=Ka(V.as("y")),ja=se<=I.ss&&["s",se]||se0,ja[4]=U,Ul.apply(null,ja)}function k1(g){return g===void 0?Ka:typeof g=="function"?(Ka=g,!0):!1}function ms(g,N){return Na[g]===void 0?!1:N===void 0?Na[g]:(Na[g]=N,g==="s"&&(Na.ss=N-1),!0)}function q1(g,N){if(!this.isValid())return this.localeData().invalidDate();var I=!1,U=Na,V,se;return typeof g=="object"&&(N=g,g=!1),typeof g=="boolean"&&(I=g),typeof N=="object"&&(U=Object.assign({},Na,N),N.s!=null&&N.ss==null&&(U.ss=N.s-1)),V=this.localeData(),se=R1(this,!I,U,V),I&&(se=V.pastFuture(+this,se)),V.postformat(se)}var fc=Math.abs;function wi(g){return(g>0)-(g<0)||+g}function ps(){if(!this.isValid())return this.localeData().invalidDate();var g=fc(this._milliseconds)/1e3,N=fc(this._days),I=fc(this._months),U,V,se,Fe,dr=this.asSeconds(),Or,tt,hn,Aa;return dr?(U=or(g/60),V=or(U/60),g%=60,U%=60,se=or(I/12),I%=12,Fe=g?g.toFixed(3).replace(/\\.?0+$/,""):"",Or=dr<0?"-":"",tt=wi(this._months)!==wi(dr)?"-":"",hn=wi(this._days)!==wi(dr)?"-":"",Aa=wi(this._milliseconds)!==wi(dr)?"-":"",Or+"P"+(se?tt+se+"Y":"")+(I?tt+I+"M":"")+(N?hn+N+"D":"")+(V||U||g?"T":"")+(V?Aa+V+"H":"")+(U?Aa+U+"M":"")+(g?Aa+Fe+"S":"")):"P0D"}var Vr=rs.prototype;Vr.isValid=$y,Vr.abs=T1,Vr.add=F1,Vr.subtract=Ja,Vr.as=Il,Vr.asMilliseconds=bi,Vr.asSeconds=kl,Vr.asMinutes=_1,Vr.asHours=cu,Vr.asDays=O1,Vr.asWeeks=ql,Vr.asMonths=Jt,Vr.asQuarters=ic,Vr.asYears=Ll,Vr.valueOf=Rl,Vr._bubble=Ui,Vr.clone=Da,Vr.get=oc,Vr.milliseconds=Wi,Vr.seconds=zl,Vr.minutes=dn,Vr.hours=sc,Vr.days=B1,Vr.weeks=uc,Vr.months=P1,Vr.years=I1,Vr.humanize=q1,Vr.toISOString=ps,Vr.toString=ps,Vr.toJSON=ps,Vr.locale=is,Vr.localeData=Nl,Vr.toIsoString=_("toIsoString() is deprecated. Please use toISOString() instead (notice the capitals)",ps),Vr.lang=ru,$("X",0,0,"unix"),$("x",0,0,"valueOf"),nr("x",Xt),nr("X",Ef),ot("X",function(g,N,I){I._d=new Date(parseFloat(g)*1e3)}),ot("x",function(g,N,I){I._d=new Date(Ke(g))});return r.version="2.29.4",t(xt),r.fn=Ve,r.min=Uy,r.max=Wy,r.now=Yy,r.utc=d,r.unix=ia,r.months=Pl,r.isDate=o,r.locale=Ga,r.invalid=w,r.duration=zr,r.isMoment=S,r.weekdays=E1,r.parseZone=M1,r.localeData=It,r.isDuration=aa,r.monthsShort=C1,r.weekdaysMin=ls,r.defineLocale=pn,r.updateLocale=Py,r.locales=Iy,r.weekdaysShort=tc,r.normalizeUnits=ue,r.relativeTimeRounding=k1,r.relativeTimeThreshold=ms,r.calendarFormat=e1,r.prototype=Ve,r.HTML5_FMT={DATETIME_LOCAL:"YYYY-MM-DDTHH:mm",DATETIME_LOCAL_SECONDS:"YYYY-MM-DDTHH:mm:ss",DATETIME_LOCAL_MS:"YYYY-MM-DDTHH:mm:ss.SSS",DATE:"YYYY-MM-DD",TIME:"HH:mm",TIME_SECONDS:"HH:mm:ss",TIME_MS:"HH:mm:ss.SSS",WEEK:"GGGG-[W]WW",MONTH:"YYYY-MM"},r})});function Ta(e){return Ta=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(r){return typeof r}:function(r){return r&&typeof Symbol=="function"&&r.constructor===Symbol&&r!==Symbol.prototype?"symbol":typeof r},Ta(e)}function Dn(e){if(e===null||e===!0||e===!1)return NaN;var r=Number(e);return isNaN(r)?r:r<0?Math.ceil(r):Math.floor(r)}function nt(e,r){if(r.length1?"s":"")+" required, but only "+r.length+" present")}function Yt(e){nt(1,arguments);var r=Object.prototype.toString.call(e);return e instanceof Date||Ta(e)==="object"&&r==="[object Date]"?new Date(e.getTime()):typeof e=="number"||r==="[object Number]"?new Date(e):((typeof e=="string"||r==="[object String]")&&typeof console<"u"&&(console.warn("Starting with v2.0.0-beta.1 date-fns doesn't accept strings as date arguments. Please use \`parseISO\` to parse strings. See: https://github.com/date-fns/date-fns/blob/master/docs/upgradeGuide.md#string-arguments"),console.warn(new Error().stack)),new Date(NaN))}function wb(e,r){nt(2,arguments);var t=Yt(e).getTime(),n=Dn(r);return new Date(t+n)}var Tk={};function Mo(){return Tk}function Db(e){var r=new Date(Date.UTC(e.getFullYear(),e.getMonth(),e.getDate(),e.getHours(),e.getMinutes(),e.getSeconds(),e.getMilliseconds()));return r.setUTCFullYear(e.getFullYear()),e.getTime()-r.getTime()}var Fk=365.2425,_k=Math.pow(10,8)*24*60*60*1e3,Sb=6e4,Nb=36e5;var rQ=-_k;var Ok=3600;var iA=Ok*24,tQ=iA*7,Bk=iA*Fk,Pk=Bk/12,nQ=Pk*3;function Ab(e){return nt(1,arguments),e instanceof Date||Ta(e)==="object"&&Object.prototype.toString.call(e)==="[object Date]"}function Mb(e){if(nt(1,arguments),!Ab(e)&&typeof e!="number")return!1;var r=Yt(e);return!isNaN(Number(r))}function Cb(e,r){nt(2,arguments);var t=Dn(r);return wb(e,-t)}var Ik=864e5;function Eb(e){nt(1,arguments);var r=Yt(e),t=r.getTime();r.setUTCMonth(0,1),r.setUTCHours(0,0,0,0);var n=r.getTime(),a=t-n;return Math.floor(a/Ik)+1}function Co(e){nt(1,arguments);var r=1,t=Yt(e),n=t.getUTCDay(),a=(n=a.getTime()?t+1:r.getTime()>=u.getTime()?t:t-1}function Tb(e){nt(1,arguments);var r=hc(e),t=new Date(0);t.setUTCFullYear(r,0,4),t.setUTCHours(0,0,0,0);var n=Co(t);return n}var Rk=6048e5;function Fb(e){nt(1,arguments);var r=Yt(e),t=Co(r).getTime()-Tb(r).getTime();return Math.round(t/Rk)+1}function Eo(e,r){var t,n,a,i,u,l,c,o;nt(1,arguments);var s=Mo(),m=Dn((t=(n=(a=(i=r?.weekStartsOn)!==null&&i!==void 0?i:r==null||(u=r.locale)===null||u===void 0||(l=u.options)===null||l===void 0?void 0:l.weekStartsOn)!==null&&a!==void 0?a:s.weekStartsOn)!==null&&n!==void 0?n:(c=s.locale)===null||c===void 0||(o=c.options)===null||o===void 0?void 0:o.weekStartsOn)!==null&&t!==void 0?t:0);if(!(m>=0&&m<=6))throw new RangeError("weekStartsOn must be between 0 and 6 inclusively");var d=Yt(e),h=d.getUTCDay(),x=(h=1&&h<=7))throw new RangeError("firstWeekContainsDate must be between 1 and 7 inclusively");var x=new Date(0);x.setUTCFullYear(m+1,0,h),x.setUTCHours(0,0,0,0);var v=Eo(x,r),y=new Date(0);y.setUTCFullYear(m,0,h),y.setUTCHours(0,0,0,0);var w=Eo(y,r);return s.getTime()>=v.getTime()?m+1:s.getTime()>=w.getTime()?m:m-1}function _b(e,r){var t,n,a,i,u,l,c,o;nt(1,arguments);var s=Mo(),m=Dn((t=(n=(a=(i=r?.firstWeekContainsDate)!==null&&i!==void 0?i:r==null||(u=r.locale)===null||u===void 0||(l=u.options)===null||l===void 0?void 0:l.firstWeekContainsDate)!==null&&a!==void 0?a:s.firstWeekContainsDate)!==null&&n!==void 0?n:(c=s.locale)===null||c===void 0||(o=c.options)===null||o===void 0?void 0:o.firstWeekContainsDate)!==null&&t!==void 0?t:1),d=vc(e,r),h=new Date(0);h.setUTCFullYear(d,0,m),h.setUTCHours(0,0,0,0);var x=Eo(h,r);return x}var kk=6048e5;function Ob(e,r){nt(1,arguments);var t=Yt(e),n=Eo(t,r).getTime()-_b(t,r).getTime();return Math.round(n/kk)+1}function st(e,r){for(var t=e<0?"-":"",n=Math.abs(e).toString();n.length0?n:1-n;return st(t==="yy"?a%100:a,t.length)},M:function(r,t){var n=r.getUTCMonth();return t==="M"?String(n+1):st(n+1,2)},d:function(r,t){return st(r.getUTCDate(),t.length)},a:function(r,t){var n=r.getUTCHours()/12>=1?"pm":"am";switch(t){case"a":case"aa":return n.toUpperCase();case"aaa":return n;case"aaaaa":return n[0];case"aaaa":default:return n==="am"?"a.m.":"p.m."}},h:function(r,t){return st(r.getUTCHours()%12||12,t.length)},H:function(r,t){return st(r.getUTCHours(),t.length)},m:function(r,t){return st(r.getUTCMinutes(),t.length)},s:function(r,t){return st(r.getUTCSeconds(),t.length)},S:function(r,t){var n=t.length,a=r.getUTCMilliseconds(),i=Math.floor(a*Math.pow(10,n-3));return st(i,t.length)}},Qi=qk;var vu={am:"am",pm:"pm",midnight:"midnight",noon:"noon",morning:"morning",afternoon:"afternoon",evening:"evening",night:"night"},Lk={G:function(r,t,n){var a=r.getUTCFullYear()>0?1:0;switch(t){case"G":case"GG":case"GGG":return n.era(a,{width:"abbreviated"});case"GGGGG":return n.era(a,{width:"narrow"});case"GGGG":default:return n.era(a,{width:"wide"})}},y:function(r,t,n){if(t==="yo"){var a=r.getUTCFullYear(),i=a>0?a:1-a;return n.ordinalNumber(i,{unit:"year"})}return Qi.y(r,t)},Y:function(r,t,n,a){var i=vc(r,a),u=i>0?i:1-i;if(t==="YY"){var l=u%100;return st(l,2)}return t==="Yo"?n.ordinalNumber(u,{unit:"year"}):st(u,t.length)},R:function(r,t){var n=hc(r);return st(n,t.length)},u:function(r,t){var n=r.getUTCFullYear();return st(n,t.length)},Q:function(r,t,n){var a=Math.ceil((r.getUTCMonth()+1)/3);switch(t){case"Q":return String(a);case"QQ":return st(a,2);case"Qo":return n.ordinalNumber(a,{unit:"quarter"});case"QQQ":return n.quarter(a,{width:"abbreviated",context:"formatting"});case"QQQQQ":return n.quarter(a,{width:"narrow",context:"formatting"});case"QQQQ":default:return n.quarter(a,{width:"wide",context:"formatting"})}},q:function(r,t,n){var a=Math.ceil((r.getUTCMonth()+1)/3);switch(t){case"q":return String(a);case"qq":return st(a,2);case"qo":return n.ordinalNumber(a,{unit:"quarter"});case"qqq":return n.quarter(a,{width:"abbreviated",context:"standalone"});case"qqqqq":return n.quarter(a,{width:"narrow",context:"standalone"});case"qqqq":default:return n.quarter(a,{width:"wide",context:"standalone"})}},M:function(r,t,n){var a=r.getUTCMonth();switch(t){case"M":case"MM":return Qi.M(r,t);case"Mo":return n.ordinalNumber(a+1,{unit:"month"});case"MMM":return n.month(a,{width:"abbreviated",context:"formatting"});case"MMMMM":return n.month(a,{width:"narrow",context:"formatting"});case"MMMM":default:return n.month(a,{width:"wide",context:"formatting"})}},L:function(r,t,n){var a=r.getUTCMonth();switch(t){case"L":return String(a+1);case"LL":return st(a+1,2);case"Lo":return n.ordinalNumber(a+1,{unit:"month"});case"LLL":return n.month(a,{width:"abbreviated",context:"standalone"});case"LLLLL":return n.month(a,{width:"narrow",context:"standalone"});case"LLLL":default:return n.month(a,{width:"wide",context:"standalone"})}},w:function(r,t,n,a){var i=Ob(r,a);return t==="wo"?n.ordinalNumber(i,{unit:"week"}):st(i,t.length)},I:function(r,t,n){var a=Fb(r);return t==="Io"?n.ordinalNumber(a,{unit:"week"}):st(a,t.length)},d:function(r,t,n){return t==="do"?n.ordinalNumber(r.getUTCDate(),{unit:"date"}):Qi.d(r,t)},D:function(r,t,n){var a=Eb(r);return t==="Do"?n.ordinalNumber(a,{unit:"dayOfYear"}):st(a,t.length)},E:function(r,t,n){var a=r.getUTCDay();switch(t){case"E":case"EE":case"EEE":return n.day(a,{width:"abbreviated",context:"formatting"});case"EEEEE":return n.day(a,{width:"narrow",context:"formatting"});case"EEEEEE":return n.day(a,{width:"short",context:"formatting"});case"EEEE":default:return n.day(a,{width:"wide",context:"formatting"})}},e:function(r,t,n,a){var i=r.getUTCDay(),u=(i-a.weekStartsOn+8)%7||7;switch(t){case"e":return String(u);case"ee":return st(u,2);case"eo":return n.ordinalNumber(u,{unit:"day"});case"eee":return n.day(i,{width:"abbreviated",context:"formatting"});case"eeeee":return n.day(i,{width:"narrow",context:"formatting"});case"eeeeee":return n.day(i,{width:"short",context:"formatting"});case"eeee":default:return n.day(i,{width:"wide",context:"formatting"})}},c:function(r,t,n,a){var i=r.getUTCDay(),u=(i-a.weekStartsOn+8)%7||7;switch(t){case"c":return String(u);case"cc":return st(u,t.length);case"co":return n.ordinalNumber(u,{unit:"day"});case"ccc":return n.day(i,{width:"abbreviated",context:"standalone"});case"ccccc":return n.day(i,{width:"narrow",context:"standalone"});case"cccccc":return n.day(i,{width:"short",context:"standalone"});case"cccc":default:return n.day(i,{width:"wide",context:"standalone"})}},i:function(r,t,n){var a=r.getUTCDay(),i=a===0?7:a;switch(t){case"i":return String(i);case"ii":return st(i,t.length);case"io":return n.ordinalNumber(i,{unit:"day"});case"iii":return n.day(a,{width:"abbreviated",context:"formatting"});case"iiiii":return n.day(a,{width:"narrow",context:"formatting"});case"iiiiii":return n.day(a,{width:"short",context:"formatting"});case"iiii":default:return n.day(a,{width:"wide",context:"formatting"})}},a:function(r,t,n){var a=r.getUTCHours(),i=a/12>=1?"pm":"am";switch(t){case"a":case"aa":return n.dayPeriod(i,{width:"abbreviated",context:"formatting"});case"aaa":return n.dayPeriod(i,{width:"abbreviated",context:"formatting"}).toLowerCase();case"aaaaa":return n.dayPeriod(i,{width:"narrow",context:"formatting"});case"aaaa":default:return n.dayPeriod(i,{width:"wide",context:"formatting"})}},b:function(r,t,n){var a=r.getUTCHours(),i;switch(a===12?i=vu.noon:a===0?i=vu.midnight:i=a/12>=1?"pm":"am",t){case"b":case"bb":return n.dayPeriod(i,{width:"abbreviated",context:"formatting"});case"bbb":return n.dayPeriod(i,{width:"abbreviated",context:"formatting"}).toLowerCase();case"bbbbb":return n.dayPeriod(i,{width:"narrow",context:"formatting"});case"bbbb":default:return n.dayPeriod(i,{width:"wide",context:"formatting"})}},B:function(r,t,n){var a=r.getUTCHours(),i;switch(a>=17?i=vu.evening:a>=12?i=vu.afternoon:a>=4?i=vu.morning:i=vu.night,t){case"B":case"BB":case"BBB":return n.dayPeriod(i,{width:"abbreviated",context:"formatting"});case"BBBBB":return n.dayPeriod(i,{width:"narrow",context:"formatting"});case"BBBB":default:return n.dayPeriod(i,{width:"wide",context:"formatting"})}},h:function(r,t,n){if(t==="ho"){var a=r.getUTCHours()%12;return a===0&&(a=12),n.ordinalNumber(a,{unit:"hour"})}return Qi.h(r,t)},H:function(r,t,n){return t==="Ho"?n.ordinalNumber(r.getUTCHours(),{unit:"hour"}):Qi.H(r,t)},K:function(r,t,n){var a=r.getUTCHours()%12;return t==="Ko"?n.ordinalNumber(a,{unit:"hour"}):st(a,t.length)},k:function(r,t,n){var a=r.getUTCHours();return a===0&&(a=24),t==="ko"?n.ordinalNumber(a,{unit:"hour"}):st(a,t.length)},m:function(r,t,n){return t==="mo"?n.ordinalNumber(r.getUTCMinutes(),{unit:"minute"}):Qi.m(r,t)},s:function(r,t,n){return t==="so"?n.ordinalNumber(r.getUTCSeconds(),{unit:"second"}):Qi.s(r,t)},S:function(r,t){return Qi.S(r,t)},X:function(r,t,n,a){var i=a._originalDate||r,u=i.getTimezoneOffset();if(u===0)return"Z";switch(t){case"X":return sA(u);case"XXXX":case"XX":return gs(u);case"XXXXX":case"XXX":default:return gs(u,":")}},x:function(r,t,n,a){var i=a._originalDate||r,u=i.getTimezoneOffset();switch(t){case"x":return sA(u);case"xxxx":case"xx":return gs(u);case"xxxxx":case"xxx":default:return gs(u,":")}},O:function(r,t,n,a){var i=a._originalDate||r,u=i.getTimezoneOffset();switch(t){case"O":case"OO":case"OOO":return"GMT"+oA(u,":");case"OOOO":default:return"GMT"+gs(u,":")}},z:function(r,t,n,a){var i=a._originalDate||r,u=i.getTimezoneOffset();switch(t){case"z":case"zz":case"zzz":return"GMT"+oA(u,":");case"zzzz":default:return"GMT"+gs(u,":")}},t:function(r,t,n,a){var i=a._originalDate||r,u=Math.floor(i.getTime()/1e3);return st(u,t.length)},T:function(r,t,n,a){var i=a._originalDate||r,u=i.getTime();return st(u,t.length)}};function oA(e,r){var t=e>0?"-":"+",n=Math.abs(e),a=Math.floor(n/60),i=n%60;if(i===0)return t+String(a);var u=r||"";return t+String(a)+u+st(i,2)}function sA(e,r){if(e%60===0){var t=e>0?"-":"+";return t+st(Math.abs(e)/60,2)}return gs(e,r)}function gs(e,r){var t=r||"",n=e>0?"-":"+",a=Math.abs(e),i=st(Math.floor(a/60),2),u=st(a%60,2);return n+i+t+u}var uA=Lk;var fA=function(r,t){switch(r){case"P":return t.date({width:"short"});case"PP":return t.date({width:"medium"});case"PPP":return t.date({width:"long"});case"PPPP":default:return t.date({width:"full"})}},cA=function(r,t){switch(r){case"p":return t.time({width:"short"});case"pp":return t.time({width:"medium"});case"ppp":return t.time({width:"long"});case"pppp":default:return t.time({width:"full"})}},zk=function(r,t){var n=r.match(/(P+)(p+)?/)||[],a=n[1],i=n[2];if(!i)return fA(r,t);var u;switch(a){case"P":u=t.dateTime({width:"short"});break;case"PP":u=t.dateTime({width:"medium"});break;case"PPP":u=t.dateTime({width:"long"});break;case"PPPP":default:u=t.dateTime({width:"full"});break}return u.replace("{{date}}",fA(a,t)).replace("{{time}}",cA(i,t))},Uk={p:cA,P:zk},lA=Uk;var Wk=["D","DD"],Yk=["YY","YYYY"];function mA(e){return Wk.indexOf(e)!==-1}function pA(e){return Yk.indexOf(e)!==-1}function Bb(e,r,t){if(e==="YYYY")throw new RangeError("Use \`yyyy\` instead of \`YYYY\` (in \`".concat(r,"\`) for formatting years to the input \`").concat(t,"\`; see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md"));if(e==="YY")throw new RangeError("Use \`yy\` instead of \`YY\` (in \`".concat(r,"\`) for formatting years to the input \`").concat(t,"\`; see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md"));if(e==="D")throw new RangeError("Use \`d\` instead of \`D\` (in \`".concat(r,"\`) for formatting days of the month to the input \`").concat(t,"\`; see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md"));if(e==="DD")throw new RangeError("Use \`dd\` instead of \`DD\` (in \`".concat(r,"\`) for formatting days of the month to the input \`").concat(t,"\`; see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md"))}var Hk={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"}},$k=function(r,t,n){var a,i=Hk[r];return typeof i=="string"?a=i:t===1?a=i.one:a=i.other.replace("{{count}}",t.toString()),n!=null&&n.addSuffix?n.comparison&&n.comparison>0?"in "+a:a+" ago":a},dA=$k;function gc(e){return function(){var r=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},t=r.width?String(r.width):e.defaultWidth,n=e.formats[t]||e.formats[e.defaultWidth];return n}}var Gk={full:"EEEE, MMMM do, y",long:"MMMM do, y",medium:"MMM d, y",short:"MM/dd/yyyy"},Vk={full:"h:mm:ss a zzzz",long:"h:mm:ss a z",medium:"h:mm:ss a",short:"h:mm a"},Zk={full:"{{date}} 'at' {{time}}",long:"{{date}} 'at' {{time}}",medium:"{{date}}, {{time}}",short:"{{date}}, {{time}}"},Qk={date:gc({formats:Gk,defaultWidth:"full"}),time:gc({formats:Vk,defaultWidth:"full"}),dateTime:gc({formats:Zk,defaultWidth:"full"})},hA=Qk;var Xk={lastWeek:"'last' eeee 'at' p",yesterday:"'yesterday at' p",today:"'today at' p",tomorrow:"'tomorrow at' p",nextWeek:"eeee 'at' p",other:"P"},Jk=function(r,t,n,a){return Xk[r]},vA=Jk;function xs(e){return function(r,t){var n=t!=null&&t.context?String(t.context):"standalone",a;if(n==="formatting"&&e.formattingValues){var i=e.defaultFormattingWidth||e.defaultWidth,u=t!=null&&t.width?String(t.width):i;a=e.formattingValues[u]||e.formattingValues[i]}else{var l=e.defaultWidth,c=t!=null&&t.width?String(t.width):e.defaultWidth;a=e.values[c]||e.values[l]}var o=e.argumentCallback?e.argumentCallback(r):r;return a[o]}}var Kk={narrow:["B","A"],abbreviated:["BC","AD"],wide:["Before Christ","Anno Domini"]},jk={narrow:["1","2","3","4"],abbreviated:["Q1","Q2","Q3","Q4"],wide:["1st quarter","2nd quarter","3rd quarter","4th quarter"]},eq={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"]},rq={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"]},tq={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"}},nq={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"}},aq=function(r,t){var n=Number(r),a=n%100;if(a>20||a<10)switch(a%10){case 1:return n+"st";case 2:return n+"nd";case 3:return n+"rd"}return n+"th"},iq={ordinalNumber:aq,era:xs({values:Kk,defaultWidth:"wide"}),quarter:xs({values:jk,defaultWidth:"wide",argumentCallback:function(r){return r-1}}),month:xs({values:eq,defaultWidth:"wide"}),day:xs({values:rq,defaultWidth:"wide"}),dayPeriod:xs({values:tq,defaultWidth:"wide",formattingValues:nq,defaultFormattingWidth:"wide"})},gA=iq;function ys(e){return function(r){var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},n=t.width,a=n&&e.matchPatterns[n]||e.matchPatterns[e.defaultMatchWidth],i=r.match(a);if(!i)return null;var u=i[0],l=n&&e.parsePatterns[n]||e.parsePatterns[e.defaultParseWidth],c=Array.isArray(l)?sq(l,function(m){return m.test(u)}):oq(l,function(m){return m.test(u)}),o;o=e.valueCallback?e.valueCallback(c):c,o=t.valueCallback?t.valueCallback(o):o;var s=r.slice(u.length);return{value:o,rest:s}}}function oq(e,r){for(var t in e)if(e.hasOwnProperty(t)&&r(e[t]))return t}function sq(e,r){for(var t=0;t1&&arguments[1]!==void 0?arguments[1]:{},n=r.match(e.matchPattern);if(!n)return null;var a=n[0],i=r.match(e.parsePattern);if(!i)return null;var u=e.valueCallback?e.valueCallback(i[0]):i[0];u=t.valueCallback?t.valueCallback(u):u;var l=r.slice(a.length);return{value:u,rest:l}}}var uq=/^(\\d+)(th|st|nd|rd)?/i,fq=/\\d+/i,cq={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},lq={any:[/^b/i,/^(a|c)/i]},mq={narrow:/^[1234]/i,abbreviated:/^q[1234]/i,wide:/^[1234](th|st|nd|rd)? quarter/i},pq={any:[/1/i,/2/i,/3/i,/4/i]},dq={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},hq={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]},vq={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},gq={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]},xq={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},yq={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}},bq={ordinalNumber:Pb({matchPattern:uq,parsePattern:fq,valueCallback:function(r){return parseInt(r,10)}}),era:ys({matchPatterns:cq,defaultMatchWidth:"wide",parsePatterns:lq,defaultParseWidth:"any"}),quarter:ys({matchPatterns:mq,defaultMatchWidth:"wide",parsePatterns:pq,defaultParseWidth:"any",valueCallback:function(r){return r+1}}),month:ys({matchPatterns:dq,defaultMatchWidth:"wide",parsePatterns:hq,defaultParseWidth:"any"}),day:ys({matchPatterns:vq,defaultMatchWidth:"wide",parsePatterns:gq,defaultParseWidth:"any"}),dayPeriod:ys({matchPatterns:xq,defaultMatchWidth:"any",parsePatterns:yq,defaultParseWidth:"any"})},xA=bq;var wq={code:"en-US",formatDistance:dA,formatLong:hA,formatRelative:vA,localize:gA,match:xA,options:{weekStartsOn:0,firstWeekContainsDate:1}},yA=wq;var bA=yA;var Dq=/[yYQqMLwIdDecihHKkms]o|(\\w)\\1*|''|'(''|[^'])+('|$)|./g,Sq=/P+p+|P+|p+|''|'(''|[^'])+('|$)|./g,Nq=/^'([^]*?)'?$/,Aq=/''/g,Mq=/[a-zA-Z]/;function Ni(e,r,t){var n,a,i,u,l,c,o,s,m,d,h,x,v,y,w,C,b,M;nt(2,arguments);var A=String(r),S=Mo(),O=(n=(a=t?.locale)!==null&&a!==void 0?a:S.locale)!==null&&n!==void 0?n:bA,_=Dn((i=(u=(l=(c=t?.firstWeekContainsDate)!==null&&c!==void 0?c:t==null||(o=t.locale)===null||o===void 0||(s=o.options)===null||s===void 0?void 0:s.firstWeekContainsDate)!==null&&l!==void 0?l:S.firstWeekContainsDate)!==null&&u!==void 0?u:(m=S.locale)===null||m===void 0||(d=m.options)===null||d===void 0?void 0:d.firstWeekContainsDate)!==null&&i!==void 0?i:1);if(!(_>=1&&_<=7))throw new RangeError("firstWeekContainsDate must be between 1 and 7 inclusively");var E=Dn((h=(x=(v=(y=t?.weekStartsOn)!==null&&y!==void 0?y:t==null||(w=t.locale)===null||w===void 0||(C=w.options)===null||C===void 0?void 0:C.weekStartsOn)!==null&&v!==void 0?v:S.weekStartsOn)!==null&&x!==void 0?x:(b=S.locale)===null||b===void 0||(M=b.options)===null||M===void 0?void 0:M.weekStartsOn)!==null&&h!==void 0?h:0);if(!(E>=0&&E<=6))throw new RangeError("weekStartsOn must be between 0 and 6 inclusively");if(!O.localize)throw new RangeError("locale must contain localize property");if(!O.formatLong)throw new RangeError("locale must contain formatLong property");var T=Yt(e);if(!Mb(T))throw new RangeError("Invalid time value");var R=Db(T),q=Cb(T,R),W={firstWeekContainsDate:_,weekStartsOn:E,locale:O,_originalDate:T},G=A.match(Sq).map(function(H){var L=H[0];if(L==="p"||L==="P"){var k=lA[L];return k(H,O.formatLong)}return H}).join("").match(Dq).map(function(H){if(H==="''")return"'";var L=H[0];if(L==="'")return Cq(H);var k=uA[L];if(k)return!(t!=null&&t.useAdditionalWeekYearTokens)&&pA(H)&&Bb(H,r,String(e)),!(t!=null&&t.useAdditionalDayOfYearTokens)&&mA(H)&&Bb(H,r,String(e)),k(q,H,O.localize,W);if(L.match(Mq))throw new RangeError("Format string contains an unescaped latin alphabet character \`"+L+"\`");return H}).join("");return G}function Cq(e){var r=e.match(Nq);return r?r[1].replace(Aq,"'"):e}function Ib(e,r){if(Ta(e)!="object"||!e)return e;var t=e[Symbol.toPrimitive];if(t!==void 0){var n=t.call(e,r||"default");if(Ta(n)!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return(r==="string"?String:Number)(e)}function Rb(e){var r=Ib(e,"string");return Ta(r)=="symbol"?r:r+""}function Hr(e,r,t){return r=Rb(r),r in e?Object.defineProperty(e,r,{value:t,enumerable:!0,configurable:!0,writable:!0}):e[r]=t,e}function sm(e,r){var t;nt(1,arguments);var n=Dn((t=r?.additionalDigits)!==null&&t!==void 0?t:2);if(n!==2&&n!==1&&n!==0)throw new RangeError("additionalDigits must be 0, 1 or 2");if(!(typeof e=="string"||Object.prototype.toString.call(e)==="[object String]"))return new Date(NaN);var a=_q(e),i;if(a.date){var u=Oq(a.date,n);i=Bq(u.restDateString,u.year)}if(!i||isNaN(i.getTime()))return new Date(NaN);var l=i.getTime(),c=0,o;if(a.time&&(c=Pq(a.time),isNaN(c)))return new Date(NaN);if(a.timezone){if(o=Iq(a.timezone),isNaN(o))return new Date(NaN)}else{var s=new Date(l+c),m=new Date(0);return m.setFullYear(s.getUTCFullYear(),s.getUTCMonth(),s.getUTCDate()),m.setHours(s.getUTCHours(),s.getUTCMinutes(),s.getUTCSeconds(),s.getUTCMilliseconds()),m}return new Date(l+c+o)}var om={dateTimeDelimiter:/[T ]/,timeZoneDelimiter:/[Z ]/i,timezone:/([Z+-].*)$/},Eq=/^-?(?:(\\d{3})|(\\d{2})(?:-?(\\d{2}))?|W(\\d{2})(?:-?(\\d{1}))?|)$/,Tq=/^(\\d{2}(?:[.,]\\d*)?)(?::?(\\d{2}(?:[.,]\\d*)?))?(?::?(\\d{2}(?:[.,]\\d*)?))?$/,Fq=/^([+-])(\\d{2})(?::?(\\d{2}))?$/;function _q(e){var r={},t=e.split(om.dateTimeDelimiter),n;if(t.length>2)return r;if(/:/.test(t[0])?n=t[0]:(r.date=t[0],n=t[1],om.timeZoneDelimiter.test(r.date)&&(r.date=e.split(om.timeZoneDelimiter)[0],n=e.substr(r.date.length,e.length))),n){var a=om.timezone.exec(n);a?(r.time=n.replace(a[1],""),r.timezone=a[1]):r.time=n}return r}function Oq(e,r){var t=new RegExp("^(?:(\\\\d{4}|[+-]\\\\d{"+(4+r)+"})|(\\\\d{2}|[+-]\\\\d{"+(2+r)+"})$)"),n=e.match(t);if(!n)return{year:NaN,restDateString:""};var a=n[1]?parseInt(n[1]):null,i=n[2]?parseInt(n[2]):null;return{year:i===null?a:i*100,restDateString:e.slice((n[1]||n[2]).length)}}function Bq(e,r){if(r===null)return new Date(NaN);var t=e.match(Eq);if(!t)return new Date(NaN);var n=!!t[4],a=xc(t[1]),i=xc(t[2])-1,u=xc(t[3]),l=xc(t[4]),c=xc(t[5])-1;if(n)return zq(r,l,c)?Rq(r,l,c):new Date(NaN);var o=new Date(0);return!qq(r,i,u)||!Lq(r,a)?new Date(NaN):(o.setUTCFullYear(r,i,Math.max(a,u)),o)}function xc(e){return e?parseInt(e):1}function Pq(e){var r=e.match(Tq);if(!r)return NaN;var t=kb(r[1]),n=kb(r[2]),a=kb(r[3]);return Uq(t,n,a)?t*Nb+n*Sb+a*1e3:NaN}function kb(e){return e&&parseFloat(e.replace(",","."))||0}function Iq(e){if(e==="Z")return 0;var r=e.match(Fq);if(!r)return 0;var t=r[1]==="+"?-1:1,n=parseInt(r[2]),a=r[3]&&parseInt(r[3])||0;return Wq(n,a)?t*(n*Nb+a*Sb):NaN}function Rq(e,r,t){var n=new Date(0);n.setUTCFullYear(e,0,4);var a=n.getUTCDay()||7,i=(r-1)*7+t+1-a;return n.setUTCDate(n.getUTCDate()+i),n}var kq=[31,null,31,30,31,30,31,31,30,31,30,31];function wA(e){return e%400===0||e%4===0&&e%100!==0}function qq(e,r,t){return r>=0&&r<=11&&t>=1&&t<=(kq[r]||(wA(e)?29:28))}function Lq(e,r){return r>=1&&r<=(wA(e)?366:365)}function zq(e,r,t){return r>=1&&r<=53&&t>=0&&t<=6}function Uq(e,r,t){return e===24?r===0&&t===0:t>=0&&t<60&&r>=0&&r<60&&e>=0&&e<25}function Wq(e,r){return r>=0&&r<=59}var Fa="File";var yc=e=>e.lastIndexOf("/")!=-1?e.lastIndexOf(".")!=-1?DA(e.substring(e.lastIndexOf("/")+1,e.lastIndexOf("."))):e.substring(e.lastIndexOf("/")+1):e.lastIndexOf(".")!=-1?e.substring(0,e.lastIndexOf(".")):e;function um(e){return Array.isArray(e)?e:typeof e=="string"?[e]:[]}var SA=(e,r)=>r.indexOf(e)>0?r.indexOf(e):r.length;var bc=e=>"spaces://"+e;var DA=e=>e.charAt(0)=="/"?e.substring(1):e;var ti=e=>[...new Set(e)];var NA=(e,r)=>e.sort(function(t,n){let a=r.indexOf(t),i=r.indexOf(n);return a>i?a!=-1&&i==-1?-1:1:i!=-1&&a==-1?1:-1});var qb=(e,r)=>{if(e instanceof Date)return"date";if(typeof e=="string"){if(/\\/\\/(\\S+?(?:jpe?g|png|gif|svg))/gi.test(e)||e.includes("unsplash"))return"image";if(/^\\d{4}-\\d{2}-\\d{2}$/.test(e))return"date";if(r=="tag"||r=="tags")return"tags-multi";if(/\\[\\[.*?\\]\\]/.test(e))return"link"}else{if(typeof e=="number")return"number";if(typeof e=="boolean")return"boolean";if(e)if(Array.isArray(e)||typeof e=="string"&&e.indexOf(",")>-1){let t=Array.isArray(e)?e:[];if(typeof e=="string"&&e.indexOf(",")>-1&&(t=Sn(e)),r=="tag"||r=="tags")return"tags-multi";if(t.length==1&&Array.isArray(t[0])&&t[0].length==1&&typeof t[0][0]=="string")return"link";let n=ti(t.map(a=>qb(a,r)));return n.length==1&&n[0]=="link"?"link-multi":n.some(a=>a=="object")?"object-multi":"option-multi"}else{if(e.isLuxonDateTime)return"date";if(e.isLuxonDuration)return"duration";if(e.type=="file")return"link";if(typeof e=="object"&&!Array.isArray(e)&&e!==null)return"object"}else return"unknown"}return"text"};var AA=e=>e.map(r=>r.replace(",","\\\\,")).join(", "),bs=e=>JSON.stringify(e);var Sn=e=>e?.startsWith("[")?um(wc(e)):Yq(e),Yq=e=>(e?.replace("\\\\,",",")?.match(/(\\\\.|[^,])+/g)??[]).map(r=>r.trim()),ws=(e,r)=>{switch(qb(r,e)){case"tags-multi":return r;case"object":case"object-multi":return JSON.stringify(r);case"number":return r.toString();case"boolean":return r?"true":"false";case"date":{if(r instanceof Date){let n=Ni(r,"yyyy-MM-dd");return typeof n=="string"?n:""}return typeof r!="string"?"":r}break;case"duration":return AA(Object.keys(r.values).reduce((n,a)=>[...n,...r.values[a]>0?[r.values[a]+" "+a]:[]],[]));case"option-multi":case"link-multi":return typeof r=="string"?Dc(r):bs(r.map(n=>n?typeof n=="string"?Dc(n):n.path?n.path:Array.isArray(r)&&n.length==1&&Array.isArray(n[0])&&n[0].length==1&&typeof n[0][0]=="string"?n[0][0]:JSON.stringify(n):""));case"link":return Array.isArray(r)&&r.length==1&&Array.isArray(r[0])&&r[0].length==1&&typeof r[0][0]=="string"?r[0][0]:typeof r=="string"?Dc(r):r.path;case"text":case"tag":case"image":return r}return""};var wc=e=>{let r;try{r=JSON.parse(e)}catch{}return r};var Dc=e=>{if(!e)return"";let r=/\\[\\[(.*?)\\]\\]/g.exec(e),t=r?.length>1?r[1].substring(0,SA("|",r[1])):e;return t||e};var xu=ca(fm());var MA=e=>(0,xu.isNumber)(e)?new Date(e):(0,xu.isString)(e)?sm(e):(0,xu.isDate)(e)?e:new Date;var CA=(e,r,t)=>{if(e.length!==1)return"";let n=e.map(function(i){return i.compile().evaluate(t)});return t.get("$paths").get(n[0])};CA.rawArgs=!0;var EA=(e,r,t)=>t?.get("$current");EA.rawArgs=!0;var TA=(e,r,t)=>{if(e.length!==2)return"";let n=e[0].compile().evaluate?e[0].compile().evaluate(t):e[0];return Array.isArray(n)?n.find(a=>{t.set("$current",a),r.evaluate("current = current()",t);let i=e[1].compile().evaluate?e[1].compile().evaluate(t):e[1];return a===i})??"":""};TA.rawArgs=!0;var FA=(e,r,t)=>{if(e.length!==2)return"";let n=e[0].compile().evaluate?e[0].compile().evaluate(t):e[0];return Array.isArray(n)?n.findIndex(a=>{t.set("$current",a),r.evaluate("current = current()",t);let i=e[1].compile().evaluate?e[1].compile().evaluate(t):e[1];return a===i}):""};FA.rawArgs=!0;var _A=(e,r,t)=>{if(e.length!==2)return"";let n=e[0].compile().evaluate?e[0].compile().evaluate(t):e[0];return Array.isArray(n)?n.filter(a=>(t.set("$current",a),r.evaluate("current = current()",t),e[1].compile().evaluate(t))):""};_A.rawArgs=!0;var OA=(e,r,t)=>{if(e.length!==2)return"";let n=e[0].compile().evaluate?e[0].compile().evaluate(t):e[0];return Array.isArray(n)?n.map(a=>(t.set("$current",a),r.evaluate("current = current()",t),e[1].compile().evaluate(t))):""};OA.rawArgs=!0;var BA=(e,r,t)=>{if(e.length!==2)return"";let n=e[0].compile().evaluate?e[0].compile().evaluate(t):e[0];return Array.isArray(n)?n.some(a=>(t.set("$current",a),r.evaluate("current = current()",t),e[1].compile().evaluate(t))):""};BA.rawArgs=!0;var PA=(e,r,t)=>{if(e.length!==2)return"";let n=e[0].compile().evaluate?e[0].compile().evaluate(t):e[0];return Array.isArray(n)?n.every(a=>(t.set("$current",a),r.evaluate("current = current()",t),e[1].compile().evaluate(t))):""};PA.rawArgs=!0;var IA=(e,r,t)=>{if(e.length!==1)return"";let n=e[0].compile().evaluate?e[0].compile().evaluate(t):e[0];return Array.isArray(n)?n.flat():""};IA.rawArgs=!0;var RA=(e,r,t)=>{if(e.length!==1)return"";let n=e.map(function(u){return u.compile().evaluate(t)}),a=t.get(n[0]),i=t.get("$properties")?.[n[0]]?.type;return(i=="file"||i=="link"||i=="context")&&(i.includes("multi")?a=Sn(a).map(u=>t.get("$paths").get(u)??u):a=t.get("$paths").get(a)??a),a??""};RA.rawArgs=!0;var kA=(e,r,t)=>{if((e.length-1)%2!==0)return"";for(let n=0;n{if(e.length<1||e.length>2)return"";let n=e[0].compile().evaluate(t);n instanceof Date||(n=new Date(n));let a=e[1]?.compile().evaluate(t);return a?.length>0?Ni(n,a):Ni(n,t.get("$settings")?.dateFormat??"yyyy-MM-dd")};qA.rawArgs=!0;var la=e=>typeof e=="string"||e instanceof String?e:e instanceof Date?Ni(e,"yyyy-MM-dd"):typeof e=="number"?e.toFixed(0):e.path?e.path:"",Lb={prop:RA,current:EA,slice:(e,r,t)=>(e=la(e),e.slice(r,t)),if:(e,r,t)=>e===!0?r:t,ifs:kA,empty:e=>e.length!==1?"":e[0]===""?"true":"false",length:e=>e.length,substring:(e,r,t)=>(e=la(e),t?e.substring(r,t):e.substring(r)),contains:(e,r)=>(e=la(e),r=la(r),e.includes(r)),test:(e,r)=>(e=la(e),new RegExp(r).test(e)),match:(e,r)=>(e=la(e),e.match(new RegExp(r))),replace:(e,r,t)=>(e=la(e),e.replace(new RegExp(r),t)),replaceAll:(e,r,t)=>(e=la(e),r=la(r),t=la(t),e.replace(new RegExp(r,"g"),t)),lower:e=>(e=la(e),e.toLowerCase()),upper:e=>(e=la(e),e.toUpperCase()),repeat:(e,r)=>e.repeat(r),format:la,toNumber:e=>e instanceof Date?e.getTime():typeof e=="string"?parseFloat(e):e,now:()=>new Date,minute:e=>e.getMinutes(),hour:e=>e.getHours(),day:e=>e.getDay(),date:e=>e.getDate(),week:e=>Ni(e,"w"),month:e=>e.getMonth()+1,year:e=>e.getFullYear(),pad:(e,r,t)=>e.padStart(r,t),dateAdd:(e,r,t)=>(t==="day"&&e.setDate(e.getDate()+r),t==="month"&&e.setMonth(e.getMonth()+r),t==="year"&&e.setFullYear(e.getFullYear()+r),t==="quarter"&&e.setMonth(e.getMonth()+r*3),t==="week"&&e.setDate(e.getDate()+r*7),t==="hour"&&e.setHours(e.getHours()+r),t==="minute"&&e.setMinutes(e.getMinutes()+r),t==="second"&&e.setSeconds(e.getSeconds()+r),e),dateSubtract:(e,r,t)=>(t==="day"&&e.setDate(e.getDate()-r),t==="month"&&e.setMonth(e.getMonth()-r),t==="year"&&e.setFullYear(e.getFullYear()-r),t==="quarter"&&e.setMonth(e.getMonth()-r*3),t==="week"&&e.setDate(e.getDate()-r*7),t==="hour"&&e.setHours(e.getHours()-r),t==="minute"&&e.setMinutes(e.getMinutes()-r),t==="second"&&e.setSeconds(e.getSeconds()-r),e),dateBetween:(e,r,t)=>{let u=Math.abs(r.getTime()-e.getTime());switch(t){case"days":return Math.round(u/864e5);case"months":return Math.round(u/2592e6);case"years":return Math.round(u/31536e6);case"hours":return Math.round(u/(60*60*1e3));case"minutes":return Math.round(u/(60*1e3));case"seconds":return Math.round(u/1e3);case"weeks":return Math.round(u/(864e5*7));case"quarters":return Math.round(u/(2592e6*3));default:return Math.round(u/864e5)}},style:(e,r)=>e,timeStamp:e=>e.getTime(),at:(e,r)=>e[r],first:e=>e[0],last:e=>e[e.length-1],concat:(e,r)=>e.concat(r),sort:e=>e.sort((r,t)=>t-r),reverse:e=>e.reverse(),join:(e,r)=>e.join(r),includes:(e,r)=>e.includes(r),split:(e,r)=>e.split(r),formatDate:qA,parseDate:e=>MA(e),find:TA,findIndex:FA,filter:_A,map:OA,some:BA,every:PA,flat:IA,path:CA};function ht(){return ht=Object.assign?Object.assign.bind():function(e){for(var r=1;re[r])}var Sm=["Matrix","Array"],Nm=["number","BigNumber","Fraction"];function HA(e,r){function t(n){if(n){var a=wu(e,ar);YA(n,"matrix",Sm),YA(n,"number",Nm),zb(e,n);var i=wu(e,ar),u=wu(n,ar);return r("config",i,a,u),i}else return wu(e,ar)}return t.MATRIX_OPTIONS=Sm,t.NUMBER_OPTIONS=Nm,Object.keys(Ds).forEach(n=>{Object.defineProperty(t,n,{get:()=>e[n],enumerable:!0,configurable:!0})}),t}function Hq(e,r){return e.indexOf(r)!==-1}function YA(e,r,t){e[r]!==void 0&&!Hq(t,e[r])&&console.warn('Warning: Unknown value "'+e[r]+'" for configuration option "'+r+'". Available options: '+t.map(n=>JSON.stringify(n)).join(", ")+".")}var Oe=function(r){if(r)throw new Error(\`The global config is readonly. -Please create a mathjs instance if you want to change the default configuration. -Example: - - import { create, all } from 'mathjs'; - const mathjs = create(all); - mathjs.config({ number: 'BigNumber' }); -\`);return Object.freeze(Ds)};ht(Oe,Ds,{MATRIX_OPTIONS:Sm,NUMBER_OPTIONS:Nm});var PD={};Ck(PD,{createAbs:()=>Ap,createAccessorNode:()=>Sv,createAcos:()=>Oh,createAcosh:()=>Bh,createAcot:()=>Ph,createAcoth:()=>Ih,createAcsc:()=>Rh,createAcsch:()=>kh,createAdd:()=>pv,createAddScalar:()=>Cp,createAnd:()=>ju,createAndTransform:()=>Ux,createApply:()=>qo,createApplyTransform:()=>wx,createArg:()=>jp,createArrayNode:()=>Av,createAsec:()=>qh,createAsech:()=>Lh,createAsin:()=>zh,createAsinh:()=>Uh,createAssignmentNode:()=>Tv,createAtan:()=>Wh,createAtan2:()=>Yh,createAtanh:()=>Hh,createAtomicMass:()=>j0,createAvogadro:()=>ex,createBellNumbers:()=>Gg,createBigNumberClass:()=>Hm,createBignumber:()=>hp,createBin:()=>Id,createBitAnd:()=>qu,createBitAndTransform:()=>Yx,createBitNot:()=>Jp,createBitOr:()=>Lu,createBitOrTransform:()=>Hx,createBitXor:()=>Kp,createBlockNode:()=>_v,createBohrMagneton:()=>B0,createBohrRadius:()=>L0,createBoltzmann:()=>rx,createBoolean:()=>dp,createCatalan:()=>Vg,createCbrt:()=>Tp,createCeil:()=>Fp,createChain:()=>vg,createChainClass:()=>dg,createClassicalElectronRadius:()=>z0,createClone:()=>Jm,createColumn:()=>Wu,createColumnTransform:()=>Dx,createCombinations:()=>Bg,createCombinationsWithRep:()=>Pg,createCompare:()=>ah,createCompareNatural:()=>ih,createCompareText:()=>oh,createCompile:()=>tg,createComplex:()=>vp,createComplexClass:()=>$m,createComposition:()=>Zg,createConcat:()=>Uu,createConcatTransform:()=>Bx,createConditionalNode:()=>Bv,createConductanceQuantum:()=>P0,createConj:()=>ed,createConstantNode:()=>kv,createCorr:()=>Og,createCos:()=>$h,createCosh:()=>Gh,createCot:()=>Vh,createCoth:()=>Zh,createCoulomb:()=>_0,createCount:()=>id,createCreateUnit:()=>_h,createCross:()=>od,createCsc:()=>Qh,createCsch:()=>Xh,createCtranspose:()=>Ad,createCube:()=>_p,createCumSum:()=>af,createCumSumTransform:()=>qx,createDeepEqual:()=>xh,createDenseMatrixClass:()=>Xm,createDerivative:()=>r0,createDet:()=>gg,createDeuteronMass:()=>G0,createDiag:()=>sd,createDiff:()=>Yu,createDiffTransform:()=>Px,createDistance:()=>Cg,createDivide:()=>Mg,createDivideScalar:()=>Wd,createDot:()=>vv,createDotDivide:()=>Qd,createDotMultiply:()=>Qp,createDotPow:()=>Zd,createE:()=>d0,createEfimovFactor:()=>K0,createEigs:()=>bg,createElectricConstant:()=>T0,createElectronMass:()=>U0,createElementaryCharge:()=>O0,createEqual:()=>uh,createEqualScalar:()=>cp,createEqualText:()=>fh,createErf:()=>Fd,createEvaluate:()=>ng,createExp:()=>Op,createExpm:()=>wg,createExpm1:()=>Bp,createFactorial:()=>kg,createFalse:()=>u0,createFaraday:()=>tx,createFermiCoupling:()=>W0,createFft:()=>Cd,createFibonacciHeapClass:()=>Ah,createFilter:()=>ud,createFilterTransform:()=>Sx,createFineStructure:()=>Y0,createFirstRadiation:()=>nx,createFix:()=>Pp,createFlatten:()=>fd,createFloor:()=>Pu,createForEach:()=>cd,createForEachTransform:()=>Nx,createFormat:()=>Pd,createFraction:()=>gp,createFractionClass:()=>Gm,createFreqz:()=>a0,createFunctionAssignmentNode:()=>Lv,createFunctionNode:()=>eg,createGamma:()=>Ig,createGasConstant:()=>ix,createGcd:()=>Ip,createGetMatrixDataType:()=>ld,createGravitationConstant:()=>A0,createGravity:()=>dx,createHartreeEnergy:()=>H0,createHasNumericValue:()=>ap,createHelp:()=>hg,createHelpClass:()=>pg,createHex:()=>kd,createHypot:()=>dv,createI:()=>D0,createIdentity:()=>md,createIfft:()=>Ed,createIm:()=>rd,createImmutableDenseMatrixClass:()=>Sh,createIndex:()=>xv,createIndexClass:()=>Nh,createIndexNode:()=>Uv,createIndexTransform:()=>Ax,createInfinity:()=>c0,createIntersect:()=>Eg,createInv:()=>xg,createInverseConductanceQuantum:()=>I0,createInvmod:()=>Vp,createIsInteger:()=>ep,createIsNaN:()=>sp,createIsNegative:()=>tp,createIsNumeric:()=>np,createIsPositive:()=>ip,createIsPrime:()=>zd,createIsZero:()=>op,createKldivergence:()=>qg,createKlitzing:()=>q0,createKron:()=>pd,createLN10:()=>g0,createLN2:()=>v0,createLOG10E:()=>y0,createLOG2E:()=>x0,createLarger:()=>hh,createLargerEq:()=>gh,createLcm:()=>Rp,createLeafCount:()=>Qg,createLeftShift:()=>eh,createLgamma:()=>Rg,createLog:()=>$d,createLog10:()=>kp,createLog1p:()=>Gd,createLog2:()=>qp,createLoschmidt:()=>ax,createLsolve:()=>Xd,createLsolveAll:()=>Kd,createLup:()=>og,createLusolve:()=>lg,createLyap:()=>Ag,createMad:()=>_g,createMagneticConstant:()=>E0,createMagneticFluxQuantum:()=>R0,createMap:()=>dd,createMapTransform:()=>Mx,createMatrix:()=>xp,createMatrixClass:()=>Zm,createMatrixFromColumns:()=>wp,createMatrixFromFunction:()=>yp,createMatrixFromRows:()=>bp,createMax:()=>ef,createMaxTransform:()=>Cx,createMean:()=>of,createMeanTransform:()=>Ex,createMedian:()=>Fg,createMin:()=>rf,createMinTransform:()=>Tx,createMod:()=>Iu,createMode:()=>Od,createMolarMass:()=>mx,createMolarMassC12:()=>px,createMolarPlanckConstant:()=>ox,createMolarVolume:()=>sx,createMultinomial:()=>Lg,createMultiply:()=>zp,createMultiplyScalar:()=>Lp,createNaN:()=>l0,createNeutronMass:()=>V0,createNode:()=>bv,createNorm:()=>hv,createNot:()=>nd,createNthRoot:()=>Up,createNthRoots:()=>Vd,createNuclearMagneton:()=>k0,createNull:()=>f0,createNumber:()=>mp,createNumeric:()=>Ud,createObjectNode:()=>Yv,createOct:()=>Rd,createOnes:()=>hd,createOperatorNode:()=>$v,createOr:()=>zu,createOrTransform:()=>Wx,createParenthesisNode:()=>Vv,createParse:()=>rg,createParser:()=>ig,createParserClass:()=>ag,createPartitionSelect:()=>wh,createPermutations:()=>zg,createPhi:()=>h0,createPi:()=>m0,createPickRandom:()=>Wg,createPinv:()=>yg,createPlanckCharge:()=>xx,createPlanckConstant:()=>M0,createPlanckLength:()=>hx,createPlanckMass:()=>vx,createPlanckTemperature:()=>yx,createPlanckTime:()=>gx,createPolynomialRoot:()=>mg,createPow:()=>Yd,createPrint:()=>Qu,createPrintTransform:()=>zx,createProd:()=>Bd,createProtonMass:()=>$0,createQr:()=>sg,createQuantileSeq:()=>uf,createQuantileSeqTransform:()=>kx,createQuantumOfCirculation:()=>Z0,createRandom:()=>Yg,createRandomInt:()=>Hg,createRange:()=>$u,createRangeClass:()=>Vm,createRangeNode:()=>Qv,createRangeTransform:()=>Fx,createRationalize:()=>t0,createRe:()=>td,createReducedPlanckConstant:()=>C0,createRelationalNode:()=>Jv,createReplacer:()=>o0,createReshape:()=>xd,createResize:()=>yd,createResolve:()=>jg,createResultSet:()=>Rm,createReviver:()=>i0,createRightArithShift:()=>rh,createRightLogShift:()=>th,createRotate:()=>bd,createRotationMatrix:()=>wd,createRound:()=>Hd,createRow:()=>Gu,createRowTransform:()=>_x,createRydberg:()=>Q0,createSQRT1_2:()=>b0,createSQRT2:()=>w0,createSackurTetrode:()=>ux,createSchur:()=>Ng,createSec:()=>Jh,createSech:()=>Kh,createSecondRadiation:()=>fx,createSetCartesian:()=>nv,createSetDifference:()=>av,createSetDistinct:()=>iv,createSetIntersect:()=>ov,createSetIsSubset:()=>sv,createSetMultiplicity:()=>uv,createSetPowerset:()=>fv,createSetSize:()=>cv,createSetSymDifference:()=>lv,createSetUnion:()=>mv,createSign:()=>Wp,createSimplify:()=>Xg,createSimplifyConstant:()=>Jg,createSimplifyCore:()=>Kg,createSin:()=>jh,createSinh:()=>ev,createSize:()=>Dd,createSlu:()=>cg,createSmaller:()=>lh,createSmallerEq:()=>ph,createSolveODE:()=>Td,createSort:()=>Dh,createSpaClass:()=>Mh,createSparse:()=>Fh,createSparseMatrixClass:()=>lp,createSpeedOfLight:()=>N0,createSplitUnit:()=>Dp,createSqrt:()=>Yp,createSqrtm:()=>Dg,createSquare:()=>Hp,createSqueeze:()=>Sd,createStd:()=>ff,createStdTransform:()=>Ix,createStefanBoltzmann:()=>cx,createStirlingS2:()=>$g,createString:()=>pp,createSubset:()=>Vu,createSubsetTransform:()=>Ox,createSubtract:()=>$p,createSubtractScalar:()=>Ep,createSum:()=>nf,createSumTransform:()=>Rx,createSylvester:()=>Sg,createSymbolNode:()=>Kv,createSymbolicEqual:()=>e0,createTan:()=>rv,createTanh:()=>tv,createTau:()=>p0,createThomsonCrossSection:()=>X0,createTo:()=>Ld,createTrace:()=>gv,createTranspose:()=>Nd,createTrue:()=>s0,createTypeOf:()=>up,createTyped:()=>Im,createUnaryMinus:()=>Sp,createUnaryPlus:()=>Np,createUnequal:()=>bh,createUnitClass:()=>Eh,createUnitFunction:()=>Th,createUppercaseE:()=>mP,createUppercasePi:()=>lP,createUsolve:()=>Jd,createUsolveAll:()=>jd,createVacuumImpedance:()=>F0,createVariance:()=>sf,createVarianceTransform:()=>Lx,createVersion:()=>S0,createWeakMixingAngle:()=>J0,createWienDisplacement:()=>lx,createXgcd:()=>Gp,createXor:()=>ad,createZeros:()=>Md,createZeta:()=>_d,createZpk2tf:()=>n0});var aw=ca(Am(),1);function Ze(e){return typeof e=="boolean"?!0:isFinite(e)?e===Math.round(e):!1}var Oa=Math.sign||function(e){return e>0?1:e<0?-1:0},VA=Math.log2||function(r){return Math.log(r)/Math.LN2},ZA=Math.log10||function(r){return Math.log(r)/Math.LN10},Mm=Math.log1p||function(e){return Math.log(e+1)},QA=Math.cbrt||function(r){if(r===0)return r;var t=r<0,n;return t&&(r=-r),isFinite(r)?(n=Math.exp(Math.log(r)/3),n=(r/(n*n)+2*n)/3):n=r,t?-n:n},XA=Math.expm1||function(r){return r>=2e-4||r<=-2e-4?Math.exp(r)-1:r+r*r/2+r*r*r/6};function Hb(e,r,t){var n={2:"0b",8:"0o",16:"0x"},a=n[r],i="";if(t){if(t<1)throw new Error("size must be in greater than 0");if(!Ze(t))throw new Error("size must be an integer");if(e>2**(t-1)-1||e<-(2**(t-1)))throw new Error("Value must be in range [-2^".concat(t-1,", 2^").concat(t-1,"-1]"));if(!Ze(e))throw new Error("Value must be an integer");e<0&&(e=e+2**t),i="i".concat(t)}var u="";return e<0&&(e=-e,u="-"),"".concat(u).concat(a).concat(e.toString(r)).concat(i)}function ai(e,r){if(typeof r=="function")return r(e);if(e===1/0)return"Infinity";if(e===-1/0)return"-Infinity";if(isNaN(e))return"NaN";var{notation:t,precision:n,wordSize:a}=$b(r);switch(t){case"fixed":return Gb(e,n);case"exponential":return JA(e,n);case"engineering":return $q(e,n);case"bin":return Hb(e,2,a);case"oct":return Hb(e,8,a);case"hex":return Hb(e,16,a);case"auto":return Gq(e,n,r).replace(/((\\.\\d*?)(0+))($|e)/,function(){var i=arguments[2],u=arguments[4];return i!=="."?i+u:u});default:throw new Error('Unknown notation "'+t+'". Choose "auto", "exponential", "fixed", "bin", "oct", or "hex.')}}function $b(e){var r="auto",t,n;if(e!==void 0)if(sr(e))t=e;else if(rr(e))t=e.toNumber();else if(Mi(e))e.precision!==void 0&&(t=$A(e.precision,()=>{throw new Error('Option "precision" must be a number or BigNumber')})),e.wordSize!==void 0&&(n=$A(e.wordSize,()=>{throw new Error('Option "wordSize" must be a number or BigNumber')})),e.notation&&(r=e.notation);else throw new Error("Unsupported type of options, number, BigNumber, or object expected");return{notation:r,precision:t,wordSize:n}}function Nu(e){var r=String(e).toLowerCase().match(/^(-?)(\\d+\\.?\\d*)(e([+-]?\\d+))?$/);if(!r)throw new SyntaxError("Invalid number "+e);var t=r[1],n=r[2],a=parseFloat(r[4]||"0"),i=n.indexOf(".");a+=i!==-1?i-1:n.length-1;var u=n.replace(".","").replace(/^0*/,function(l){return a-=l.length,""}).replace(/0*$/,"").split("").map(function(l){return parseInt(l)});return u.length===0&&(u.push(0),a++),{sign:t,coefficients:u,exponent:a}}function $q(e,r){if(isNaN(e)||!isFinite(e))return String(e);var t=Nu(e),n=Cm(t,r),a=n.exponent,i=n.coefficients,u=a%3===0?a:a<0?a-3-a%3:a-a%3;if(sr(r))for(;r>i.length||a-u+1>i.length;)i.push(0);else for(var l=Math.abs(a-u)-(i.length-1),c=0;c0;)s++,o--;var m=i.slice(s).join(""),d=sr(r)&&m.length||m.match(/[1-9]/)?"."+m:"",h=i.slice(0,s).join("")+d+"e"+(a>=0?"+":"")+u.toString();return n.sign+h}function Gb(e,r){if(isNaN(e)||!isFinite(e))return String(e);var t=Nu(e),n=typeof r=="number"?Cm(t,t.exponent+1+r):t,a=n.coefficients,i=n.exponent+1,u=i+(r||0);return a.length0?"."+a.join(""):"")+"e"+(i>=0?"+":"")+i}function Gq(e,r,t){if(isNaN(e)||!isFinite(e))return String(e);var n=GA(t?.lowerExp,-3),a=GA(t?.upperExp,5),i=Nu(e),u=r?Cm(i,r):i;if(u.exponent=a)return JA(e,r);var l=u.coefficients,c=u.exponent;l.length0?c:0;return or){var a=n.splice(r,n.length-r);if(a[0]>=5){var i=r-1;for(n[i]++;n[i]===10;)n.pop(),i===0&&(n.unshift(0),t.exponent++,i++),i--,n[i]++}}return t}function Su(e){for(var r=[],t=0;t0?!0:e<0?!1:1/e===1/0,n=r>0?!0:r<0?!1:1/r===1/0;return t^n?-e:e}function $A(e,r){if(sr(e))return e;if(rr(e))return e.toNumber();r()}function GA(e,r){return sr(e)?e:rr(e)?e.toNumber():r}function Vb(e,r,t){var n=e.constructor,a=new n(2),i="";if(t){if(t<1)throw new Error("size must be in greater than 0");if(!Ze(t))throw new Error("size must be an integer");if(e.greaterThan(a.pow(t-1).sub(1))||e.lessThan(a.pow(t-1).mul(-1)))throw new Error("Value must be in range [-2^".concat(t-1,", 2^").concat(t-1,"-1]"));if(!e.isInteger())throw new Error("Value must be an integer");e.lessThan(0)&&(e=e.add(a.pow(t))),i="i".concat(t)}switch(r){case 2:return"".concat(e.toBinary()).concat(i);case 8:return"".concat(e.toOctal()).concat(i);case 16:return"".concat(e.toHexadecimal()).concat(i);default:throw new Error("Base ".concat(r," not supported "))}}function oM(e,r){if(typeof r=="function")return r(e);if(!e.isFinite())return e.isNaN()?"NaN":e.gt(0)?"Infinity":"-Infinity";var{notation:t,precision:n,wordSize:a}=$b(r);switch(t){case"fixed":return Qq(e,n);case"exponential":return aM(e,n);case"engineering":return Zq(e,n);case"bin":return Vb(e,2,a);case"oct":return Vb(e,8,a);case"hex":return Vb(e,16,a);case"auto":{var i=iM(r?.lowerExp,-3),u=iM(r?.upperExp,5);if(e.isZero())return"0";var l,c=e.toSignificantDigits(n),o=c.e;return o>=i&&o=0?"+":"")+n.toString()}function aM(e,r){return r!==void 0?e.toExponential(r-1):e.toExponential()}function Qq(e,r){return e.toFixed(r)}function iM(e,r){return sr(e)?e:rr(e)?e.toNumber():r}function uM(e,r){var t=e.length-r.length,n=e.length;return e.substring(t,n)===r}function lr(e,r){var t=Xq(e,r);return r&&typeof r=="object"&&"truncate"in r&&t.length>r.truncate?t.substring(0,r.truncate-3)+"...":t}function Xq(e,r){if(typeof e=="number")return ai(e,r);if(rr(e))return oM(e,r);if(Jq(e))return!r||r.fraction!=="decimal"?e.s*e.n+"/"+e.d:e.toString();if(Array.isArray(e))return fM(e,r);if(St(e))return Ss(e);if(typeof e=="function")return e.syntax?String(e.syntax):"function";if(e&&typeof e=="object"){if(typeof e.format=="function")return e.format(r);if(e&&e.toString(r)!=={}.toString())return e.toString(r);var t=Object.keys(e).map(n=>Ss(n)+": "+lr(e[n],r));return"{"+t.join(", ")+"}"}return String(e)}function Ss(e){for(var r=String(e),t="",n=0;n/g,">"),r}function fM(e,r){if(Array.isArray(e)){for(var t="[",n=e.length,a=0;ar?1:-1}function pr(e,r,t){if(!(this instanceof pr))throw new SyntaxError("Constructor must be called with the new operator");this.actual=e,this.expected=r,this.relation=t,this.message="Dimension mismatch ("+(Array.isArray(e)?"["+e.join(", ")+"]":e)+" "+(this.relation||"!=")+" "+(Array.isArray(r)?"["+r.join(", ")+"]":r)+")",this.stack=new Error().stack}pr.prototype=new RangeError;pr.prototype.constructor=RangeError;pr.prototype.name="DimensionError";pr.prototype.isDimensionError=!0;function tn(e,r,t){if(!(this instanceof tn))throw new SyntaxError("Constructor must be called with the new operator");this.index=e,arguments.length<3?(this.min=0,this.max=r):(this.min=r,this.max=t),this.min!==void 0&&this.index=this.max?this.message="Index out of range ("+this.index+" > "+(this.max-1)+")":this.message="Index out of range ("+this.index+")",this.stack=new Error().stack}tn.prototype=new RangeError;tn.prototype.constructor=RangeError;tn.prototype.name="IndexError";tn.prototype.isIndexError=!0;function ur(e){for(var r=[];Array.isArray(e);)r.push(e.length),e=e[0];return r}function cM(e,r,t){var n,a=e.length;if(a!==r[t])throw new pr(a,r[t]);if(t")}function Qb(e,r){var t=r.length===0;if(t){if(Array.isArray(e))throw new pr(e.length,0)}else cM(e,r,0)}function Ac(e,r){var t=e.isMatrix?e._size:ur(e),n=r._sourceSize;n.forEach((a,i)=>{if(a!==null&&a!==t[i])throw new pr(a,t[i])})}function Kr(e,r){if(e!==void 0){if(!sr(e)||!Ze(e))throw new TypeError("Index must be an integer (value: "+e+")");if(e<0||typeof r=="number"&&e>=r)throw new tn(e,r)}}function Ns(e){for(var r=0;r=0,c=r%t===0;if(l)if(c)n[i]=-r/t;else throw new Error("Could not replace wildcard, since "+r+" is no multiple of "+-t);return n}function lM(e){return e.reduce((r,t)=>r*t,1)}function Kq(e,r){for(var t=e,n,a=r.length-1;a>0;a--){var i=r[a];n=[];for(var u=t.length/i,l=0;lr.test(t))}function Xb(e,r){return Array.prototype.join.call(e,r)}function Ji(e){if(!Array.isArray(e))throw new TypeError("Array input expected");if(e.length===0)return e;var r=[],t=0;r[0]={value:e[0],identifier:0};for(var n=1;n1)return e.slice(1).reduce(function(t,n){return dM(t,n,r,0)},e[0]);throw new Error("Wrong number of arguments in function concat")}function jq(){for(var e=arguments.length,r=new Array(e),t=0;td.length),a=Math.max(...n),i=new Array(a).fill(null),u=0;ui[s]&&(i[s]=l[o])}for(var m=0;m1||e[a]>r[i])throw new Error("shape missmatch: missmatch is found in arg with shape (".concat(e,") not possible to broadcast dimension ").concat(n," with size ").concat(e[a]," to size ").concat(r[i]))}}function jb(e,r){var t=ur(e);if(ni(t,r))return e;Ec(t,r);var n=jq(t,r),a=n.length,i=[...Array(a-t.length).fill(1),...t],u=rL(e);t.length!nL(i)).every(i=>t[i]!==void 0);if(!n){var a=r.filter(i=>t[i]===void 0);throw new Error('Cannot create function "'.concat(e,'", ')+"some dependencies are missing: ".concat(a.map(i=>'"'.concat(i,'"')).join(", "),"."))}}function nL(e){return e&&e[0]==="?"}function ew(e){return e&&e[0]==="?"?e.slice(1):e}function wt(e,r){if(xM(e)&&vM(e,r))return e[r];throw typeof e[r]=="function"&&Bm(e,r)?new Error('Cannot access method "'+r+'" as a property'):new Error('No access to property "'+r+'"')}function Ei(e,r,t){if(xM(e)&&vM(e,r))return e[r]=t,t;throw new Error('No access to property "'+r+'"')}function hM(e,r){return r in e}function vM(e,r){return!e||typeof e!="object"?!1:Xe(aL,r)?!0:!(r in Object.prototype||r in Function.prototype)}function gM(e,r){if(!Bm(e,r))throw new Error('No access to method "'+r+'"');return e[r]}function Bm(e,r){return e==null||typeof e[r]!="function"||Xe(e,r)&&Object.getPrototypeOf&&r in Object.getPrototypeOf(e)?!1:Xe(iL,r)?!0:!(r in Object.prototype||r in Function.prototype)}function xM(e){return typeof e=="object"&&e&&e.constructor===Object}var aL={length:!0,name:!0},iL={toString:!0,valueOf:!0,toLocaleString:!0};var Ms=class{constructor(r){this.wrappedObject=r,this[Symbol.iterator]=this.entries}keys(){return Object.keys(this.wrappedObject).values()}get(r){return wt(this.wrappedObject,r)}set(r,t){return Ei(this.wrappedObject,r,t),this}has(r){return hM(this.wrappedObject,r)}entries(){return yM(this.keys(),r=>[r,this.get(r)])}forEach(r){for(var t of this.keys())r(this.get(t),t,this)}delete(r){delete this.wrappedObject[r]}clear(){for(var r of this.keys())this.delete(r)}get size(){return Object.keys(this.wrappedObject).length}},Eu=class{constructor(r,t,n){this.a=r,this.b=t,this.bKeys=n,this[Symbol.iterator]=this.entries}get(r){return this.bKeys.has(r)?this.b.get(r):this.a.get(r)}set(r,t){return this.bKeys.has(r)?this.b.set(r,t):this.a.set(r,t),this}has(r){return this.b.has(r)||this.a.has(r)}keys(){return new Set([...this.a.keys(),...this.b.keys()])[Symbol.iterator]()}entries(){return yM(this.keys(),r=>[r,this.get(r)])}forEach(r){for(var t of this.keys())r(this.get(t),t,this)}delete(r){return this.bKeys.has(r)?this.b.delete(r):this.a.delete(r)}clear(){this.a.clear(),this.b.clear()}get size(){return[...this.keys()].length}};function yM(e,r){return{next:()=>{var t=e.next();return t.done?t:{value:r(t.value),done:!1}}}}function Oo(){return new Map}function Ki(e){if(!e)return Oo();if(rw(e))return e;if(Mi(e))return new Ms(e);throw new Error("createMap can create maps from objects or Maps")}function bM(e){if(e instanceof Ms)return e.wrappedObject;var r={};for(var t of e.keys()){var n=e.get(t);Ei(r,t,n)}return r}function rw(e){return e?e instanceof Map||e instanceof Ms||typeof e.set=="function"&&typeof e.get=="function"&&typeof e.keys=="function"&&typeof e.has=="function":!1}var wM=function(){return wM=aw.default.create,aw.default},oL=["?BigNumber","?Complex","?DenseMatrix","?Fraction"],Im=F("typed",oL,function(r){var{BigNumber:t,Complex:n,DenseMatrix:a,Fraction:i}=r,u=wM();return u.clear(),u.addTypes([{name:"number",test:sr},{name:"Complex",test:Kt},{name:"BigNumber",test:rr},{name:"Fraction",test:ma},{name:"Unit",test:Ht},{name:"identifier",test:l=>St&&/^(?:[A-Za-z\\xAA\\xB5\\xBA\\xC0-\\xD6\\xD8-\\xF6\\xF8-\\u02C1\\u02C6-\\u02D1\\u02E0-\\u02E4\\u02EC\\u02EE\\u0370-\\u0374\\u0376\\u0377\\u037A-\\u037D\\u037F\\u0386\\u0388-\\u038A\\u038C\\u038E-\\u03A1\\u03A3-\\u03F5\\u03F7-\\u0481\\u048A-\\u052F\\u0531-\\u0556\\u0559\\u0560-\\u0588\\u05D0-\\u05EA\\u05EF-\\u05F2\\u0620-\\u064A\\u066E\\u066F\\u0671-\\u06D3\\u06D5\\u06E5\\u06E6\\u06EE\\u06EF\\u06FA-\\u06FC\\u06FF\\u0710\\u0712-\\u072F\\u074D-\\u07A5\\u07B1\\u07CA-\\u07EA\\u07F4\\u07F5\\u07FA\\u0800-\\u0815\\u081A\\u0824\\u0828\\u0840-\\u0858\\u0860-\\u086A\\u0870-\\u0887\\u0889-\\u088E\\u08A0-\\u08C9\\u0904-\\u0939\\u093D\\u0950\\u0958-\\u0961\\u0971-\\u0980\\u0985-\\u098C\\u098F\\u0990\\u0993-\\u09A8\\u09AA-\\u09B0\\u09B2\\u09B6-\\u09B9\\u09BD\\u09CE\\u09DC\\u09DD\\u09DF-\\u09E1\\u09F0\\u09F1\\u09FC\\u0A05-\\u0A0A\\u0A0F\\u0A10\\u0A13-\\u0A28\\u0A2A-\\u0A30\\u0A32\\u0A33\\u0A35\\u0A36\\u0A38\\u0A39\\u0A59-\\u0A5C\\u0A5E\\u0A72-\\u0A74\\u0A85-\\u0A8D\\u0A8F-\\u0A91\\u0A93-\\u0AA8\\u0AAA-\\u0AB0\\u0AB2\\u0AB3\\u0AB5-\\u0AB9\\u0ABD\\u0AD0\\u0AE0\\u0AE1\\u0AF9\\u0B05-\\u0B0C\\u0B0F\\u0B10\\u0B13-\\u0B28\\u0B2A-\\u0B30\\u0B32\\u0B33\\u0B35-\\u0B39\\u0B3D\\u0B5C\\u0B5D\\u0B5F-\\u0B61\\u0B71\\u0B83\\u0B85-\\u0B8A\\u0B8E-\\u0B90\\u0B92-\\u0B95\\u0B99\\u0B9A\\u0B9C\\u0B9E\\u0B9F\\u0BA3\\u0BA4\\u0BA8-\\u0BAA\\u0BAE-\\u0BB9\\u0BD0\\u0C05-\\u0C0C\\u0C0E-\\u0C10\\u0C12-\\u0C28\\u0C2A-\\u0C39\\u0C3D\\u0C58-\\u0C5A\\u0C5D\\u0C60\\u0C61\\u0C80\\u0C85-\\u0C8C\\u0C8E-\\u0C90\\u0C92-\\u0CA8\\u0CAA-\\u0CB3\\u0CB5-\\u0CB9\\u0CBD\\u0CDD\\u0CDE\\u0CE0\\u0CE1\\u0CF1\\u0CF2\\u0D04-\\u0D0C\\u0D0E-\\u0D10\\u0D12-\\u0D3A\\u0D3D\\u0D4E\\u0D54-\\u0D56\\u0D5F-\\u0D61\\u0D7A-\\u0D7F\\u0D85-\\u0D96\\u0D9A-\\u0DB1\\u0DB3-\\u0DBB\\u0DBD\\u0DC0-\\u0DC6\\u0E01-\\u0E30\\u0E32\\u0E33\\u0E40-\\u0E46\\u0E81\\u0E82\\u0E84\\u0E86-\\u0E8A\\u0E8C-\\u0EA3\\u0EA5\\u0EA7-\\u0EB0\\u0EB2\\u0EB3\\u0EBD\\u0EC0-\\u0EC4\\u0EC6\\u0EDC-\\u0EDF\\u0F00\\u0F40-\\u0F47\\u0F49-\\u0F6C\\u0F88-\\u0F8C\\u1000-\\u102A\\u103F\\u1050-\\u1055\\u105A-\\u105D\\u1061\\u1065\\u1066\\u106E-\\u1070\\u1075-\\u1081\\u108E\\u10A0-\\u10C5\\u10C7\\u10CD\\u10D0-\\u10FA\\u10FC-\\u1248\\u124A-\\u124D\\u1250-\\u1256\\u1258\\u125A-\\u125D\\u1260-\\u1288\\u128A-\\u128D\\u1290-\\u12B0\\u12B2-\\u12B5\\u12B8-\\u12BE\\u12C0\\u12C2-\\u12C5\\u12C8-\\u12D6\\u12D8-\\u1310\\u1312-\\u1315\\u1318-\\u135A\\u1380-\\u138F\\u13A0-\\u13F5\\u13F8-\\u13FD\\u1401-\\u166C\\u166F-\\u167F\\u1681-\\u169A\\u16A0-\\u16EA\\u16F1-\\u16F8\\u1700-\\u1711\\u171F-\\u1731\\u1740-\\u1751\\u1760-\\u176C\\u176E-\\u1770\\u1780-\\u17B3\\u17D7\\u17DC\\u1820-\\u1878\\u1880-\\u1884\\u1887-\\u18A8\\u18AA\\u18B0-\\u18F5\\u1900-\\u191E\\u1950-\\u196D\\u1970-\\u1974\\u1980-\\u19AB\\u19B0-\\u19C9\\u1A00-\\u1A16\\u1A20-\\u1A54\\u1AA7\\u1B05-\\u1B33\\u1B45-\\u1B4C\\u1B83-\\u1BA0\\u1BAE\\u1BAF\\u1BBA-\\u1BE5\\u1C00-\\u1C23\\u1C4D-\\u1C4F\\u1C5A-\\u1C7D\\u1C80-\\u1C88\\u1C90-\\u1CBA\\u1CBD-\\u1CBF\\u1CE9-\\u1CEC\\u1CEE-\\u1CF3\\u1CF5\\u1CF6\\u1CFA\\u1D00-\\u1DBF\\u1E00-\\u1F15\\u1F18-\\u1F1D\\u1F20-\\u1F45\\u1F48-\\u1F4D\\u1F50-\\u1F57\\u1F59\\u1F5B\\u1F5D\\u1F5F-\\u1F7D\\u1F80-\\u1FB4\\u1FB6-\\u1FBC\\u1FBE\\u1FC2-\\u1FC4\\u1FC6-\\u1FCC\\u1FD0-\\u1FD3\\u1FD6-\\u1FDB\\u1FE0-\\u1FEC\\u1FF2-\\u1FF4\\u1FF6-\\u1FFC\\u2071\\u207F\\u2090-\\u209C\\u2102\\u2107\\u210A-\\u2113\\u2115\\u2119-\\u211D\\u2124\\u2126\\u2128\\u212A-\\u212D\\u212F-\\u2139\\u213C-\\u213F\\u2145-\\u2149\\u214E\\u2183\\u2184\\u2C00-\\u2CE4\\u2CEB-\\u2CEE\\u2CF2\\u2CF3\\u2D00-\\u2D25\\u2D27\\u2D2D\\u2D30-\\u2D67\\u2D6F\\u2D80-\\u2D96\\u2DA0-\\u2DA6\\u2DA8-\\u2DAE\\u2DB0-\\u2DB6\\u2DB8-\\u2DBE\\u2DC0-\\u2DC6\\u2DC8-\\u2DCE\\u2DD0-\\u2DD6\\u2DD8-\\u2DDE\\u2E2F\\u3005\\u3006\\u3031-\\u3035\\u303B\\u303C\\u3041-\\u3096\\u309D-\\u309F\\u30A1-\\u30FA\\u30FC-\\u30FF\\u3105-\\u312F\\u3131-\\u318E\\u31A0-\\u31BF\\u31F0-\\u31FF\\u3400-\\u4DBF\\u4E00-\\uA48C\\uA4D0-\\uA4FD\\uA500-\\uA60C\\uA610-\\uA61F\\uA62A\\uA62B\\uA640-\\uA66E\\uA67F-\\uA69D\\uA6A0-\\uA6E5\\uA717-\\uA71F\\uA722-\\uA788\\uA78B-\\uA7CA\\uA7D0\\uA7D1\\uA7D3\\uA7D5-\\uA7D9\\uA7F2-\\uA801\\uA803-\\uA805\\uA807-\\uA80A\\uA80C-\\uA822\\uA840-\\uA873\\uA882-\\uA8B3\\uA8F2-\\uA8F7\\uA8FB\\uA8FD\\uA8FE\\uA90A-\\uA925\\uA930-\\uA946\\uA960-\\uA97C\\uA984-\\uA9B2\\uA9CF\\uA9E0-\\uA9E4\\uA9E6-\\uA9EF\\uA9FA-\\uA9FE\\uAA00-\\uAA28\\uAA40-\\uAA42\\uAA44-\\uAA4B\\uAA60-\\uAA76\\uAA7A\\uAA7E-\\uAAAF\\uAAB1\\uAAB5\\uAAB6\\uAAB9-\\uAABD\\uAAC0\\uAAC2\\uAADB-\\uAADD\\uAAE0-\\uAAEA\\uAAF2-\\uAAF4\\uAB01-\\uAB06\\uAB09-\\uAB0E\\uAB11-\\uAB16\\uAB20-\\uAB26\\uAB28-\\uAB2E\\uAB30-\\uAB5A\\uAB5C-\\uAB69\\uAB70-\\uABE2\\uAC00-\\uD7A3\\uD7B0-\\uD7C6\\uD7CB-\\uD7FB\\uF900-\\uFA6D\\uFA70-\\uFAD9\\uFB00-\\uFB06\\uFB13-\\uFB17\\uFB1D\\uFB1F-\\uFB28\\uFB2A-\\uFB36\\uFB38-\\uFB3C\\uFB3E\\uFB40\\uFB41\\uFB43\\uFB44\\uFB46-\\uFBB1\\uFBD3-\\uFD3D\\uFD50-\\uFD8F\\uFD92-\\uFDC7\\uFDF0-\\uFDFB\\uFE70-\\uFE74\\uFE76-\\uFEFC\\uFF21-\\uFF3A\\uFF41-\\uFF5A\\uFF66-\\uFFBE\\uFFC2-\\uFFC7\\uFFCA-\\uFFCF\\uFFD2-\\uFFD7\\uFFDA-\\uFFDC]|\\uD800[\\uDC00-\\uDC0B\\uDC0D-\\uDC26\\uDC28-\\uDC3A\\uDC3C\\uDC3D\\uDC3F-\\uDC4D\\uDC50-\\uDC5D\\uDC80-\\uDCFA\\uDE80-\\uDE9C\\uDEA0-\\uDED0\\uDF00-\\uDF1F\\uDF2D-\\uDF40\\uDF42-\\uDF49\\uDF50-\\uDF75\\uDF80-\\uDF9D\\uDFA0-\\uDFC3\\uDFC8-\\uDFCF]|\\uD801[\\uDC00-\\uDC9D\\uDCB0-\\uDCD3\\uDCD8-\\uDCFB\\uDD00-\\uDD27\\uDD30-\\uDD63\\uDD70-\\uDD7A\\uDD7C-\\uDD8A\\uDD8C-\\uDD92\\uDD94\\uDD95\\uDD97-\\uDDA1\\uDDA3-\\uDDB1\\uDDB3-\\uDDB9\\uDDBB\\uDDBC\\uDE00-\\uDF36\\uDF40-\\uDF55\\uDF60-\\uDF67\\uDF80-\\uDF85\\uDF87-\\uDFB0\\uDFB2-\\uDFBA]|\\uD802[\\uDC00-\\uDC05\\uDC08\\uDC0A-\\uDC35\\uDC37\\uDC38\\uDC3C\\uDC3F-\\uDC55\\uDC60-\\uDC76\\uDC80-\\uDC9E\\uDCE0-\\uDCF2\\uDCF4\\uDCF5\\uDD00-\\uDD15\\uDD20-\\uDD39\\uDD80-\\uDDB7\\uDDBE\\uDDBF\\uDE00\\uDE10-\\uDE13\\uDE15-\\uDE17\\uDE19-\\uDE35\\uDE60-\\uDE7C\\uDE80-\\uDE9C\\uDEC0-\\uDEC7\\uDEC9-\\uDEE4\\uDF00-\\uDF35\\uDF40-\\uDF55\\uDF60-\\uDF72\\uDF80-\\uDF91]|\\uD803[\\uDC00-\\uDC48\\uDC80-\\uDCB2\\uDCC0-\\uDCF2\\uDD00-\\uDD23\\uDE80-\\uDEA9\\uDEB0\\uDEB1\\uDF00-\\uDF1C\\uDF27\\uDF30-\\uDF45\\uDF70-\\uDF81\\uDFB0-\\uDFC4\\uDFE0-\\uDFF6]|\\uD804[\\uDC03-\\uDC37\\uDC71\\uDC72\\uDC75\\uDC83-\\uDCAF\\uDCD0-\\uDCE8\\uDD03-\\uDD26\\uDD44\\uDD47\\uDD50-\\uDD72\\uDD76\\uDD83-\\uDDB2\\uDDC1-\\uDDC4\\uDDDA\\uDDDC\\uDE00-\\uDE11\\uDE13-\\uDE2B\\uDE3F\\uDE40\\uDE80-\\uDE86\\uDE88\\uDE8A-\\uDE8D\\uDE8F-\\uDE9D\\uDE9F-\\uDEA8\\uDEB0-\\uDEDE\\uDF05-\\uDF0C\\uDF0F\\uDF10\\uDF13-\\uDF28\\uDF2A-\\uDF30\\uDF32\\uDF33\\uDF35-\\uDF39\\uDF3D\\uDF50\\uDF5D-\\uDF61]|\\uD805[\\uDC00-\\uDC34\\uDC47-\\uDC4A\\uDC5F-\\uDC61\\uDC80-\\uDCAF\\uDCC4\\uDCC5\\uDCC7\\uDD80-\\uDDAE\\uDDD8-\\uDDDB\\uDE00-\\uDE2F\\uDE44\\uDE80-\\uDEAA\\uDEB8\\uDF00-\\uDF1A\\uDF40-\\uDF46]|\\uD806[\\uDC00-\\uDC2B\\uDCA0-\\uDCDF\\uDCFF-\\uDD06\\uDD09\\uDD0C-\\uDD13\\uDD15\\uDD16\\uDD18-\\uDD2F\\uDD3F\\uDD41\\uDDA0-\\uDDA7\\uDDAA-\\uDDD0\\uDDE1\\uDDE3\\uDE00\\uDE0B-\\uDE32\\uDE3A\\uDE50\\uDE5C-\\uDE89\\uDE9D\\uDEB0-\\uDEF8]|\\uD807[\\uDC00-\\uDC08\\uDC0A-\\uDC2E\\uDC40\\uDC72-\\uDC8F\\uDD00-\\uDD06\\uDD08\\uDD09\\uDD0B-\\uDD30\\uDD46\\uDD60-\\uDD65\\uDD67\\uDD68\\uDD6A-\\uDD89\\uDD98\\uDEE0-\\uDEF2\\uDF02\\uDF04-\\uDF10\\uDF12-\\uDF33\\uDFB0]|\\uD808[\\uDC00-\\uDF99]|\\uD809[\\uDC80-\\uDD43]|\\uD80B[\\uDF90-\\uDFF0]|[\\uD80C\\uD81C-\\uD820\\uD822\\uD840-\\uD868\\uD86A-\\uD86C\\uD86F-\\uD872\\uD874-\\uD879\\uD880-\\uD883\\uD885-\\uD887][\\uDC00-\\uDFFF]|\\uD80D[\\uDC00-\\uDC2F\\uDC41-\\uDC46]|\\uD811[\\uDC00-\\uDE46]|\\uD81A[\\uDC00-\\uDE38\\uDE40-\\uDE5E\\uDE70-\\uDEBE\\uDED0-\\uDEED\\uDF00-\\uDF2F\\uDF40-\\uDF43\\uDF63-\\uDF77\\uDF7D-\\uDF8F]|\\uD81B[\\uDE40-\\uDE7F\\uDF00-\\uDF4A\\uDF50\\uDF93-\\uDF9F\\uDFE0\\uDFE1\\uDFE3]|\\uD821[\\uDC00-\\uDFF7]|\\uD823[\\uDC00-\\uDCD5\\uDD00-\\uDD08]|\\uD82B[\\uDFF0-\\uDFF3\\uDFF5-\\uDFFB\\uDFFD\\uDFFE]|\\uD82C[\\uDC00-\\uDD22\\uDD32\\uDD50-\\uDD52\\uDD55\\uDD64-\\uDD67\\uDD70-\\uDEFB]|\\uD82F[\\uDC00-\\uDC6A\\uDC70-\\uDC7C\\uDC80-\\uDC88\\uDC90-\\uDC99]|\\uD835[\\uDC00-\\uDC54\\uDC56-\\uDC9C\\uDC9E\\uDC9F\\uDCA2\\uDCA5\\uDCA6\\uDCA9-\\uDCAC\\uDCAE-\\uDCB9\\uDCBB\\uDCBD-\\uDCC3\\uDCC5-\\uDD05\\uDD07-\\uDD0A\\uDD0D-\\uDD14\\uDD16-\\uDD1C\\uDD1E-\\uDD39\\uDD3B-\\uDD3E\\uDD40-\\uDD44\\uDD46\\uDD4A-\\uDD50\\uDD52-\\uDEA5\\uDEA8-\\uDEC0\\uDEC2-\\uDEDA\\uDEDC-\\uDEFA\\uDEFC-\\uDF14\\uDF16-\\uDF34\\uDF36-\\uDF4E\\uDF50-\\uDF6E\\uDF70-\\uDF88\\uDF8A-\\uDFA8\\uDFAA-\\uDFC2\\uDFC4-\\uDFCB]|\\uD837[\\uDF00-\\uDF1E\\uDF25-\\uDF2A]|\\uD838[\\uDC30-\\uDC6D\\uDD00-\\uDD2C\\uDD37-\\uDD3D\\uDD4E\\uDE90-\\uDEAD\\uDEC0-\\uDEEB]|\\uD839[\\uDCD0-\\uDCEB\\uDFE0-\\uDFE6\\uDFE8-\\uDFEB\\uDFED\\uDFEE\\uDFF0-\\uDFFE]|\\uD83A[\\uDC00-\\uDCC4\\uDD00-\\uDD43\\uDD4B]|\\uD83B[\\uDE00-\\uDE03\\uDE05-\\uDE1F\\uDE21\\uDE22\\uDE24\\uDE27\\uDE29-\\uDE32\\uDE34-\\uDE37\\uDE39\\uDE3B\\uDE42\\uDE47\\uDE49\\uDE4B\\uDE4D-\\uDE4F\\uDE51\\uDE52\\uDE54\\uDE57\\uDE59\\uDE5B\\uDE5D\\uDE5F\\uDE61\\uDE62\\uDE64\\uDE67-\\uDE6A\\uDE6C-\\uDE72\\uDE74-\\uDE77\\uDE79-\\uDE7C\\uDE7E\\uDE80-\\uDE89\\uDE8B-\\uDE9B\\uDEA1-\\uDEA3\\uDEA5-\\uDEA9\\uDEAB-\\uDEBB]|\\uD869[\\uDC00-\\uDEDF\\uDF00-\\uDFFF]|\\uD86D[\\uDC00-\\uDF39\\uDF40-\\uDFFF]|\\uD86E[\\uDC00-\\uDC1D\\uDC20-\\uDFFF]|\\uD873[\\uDC00-\\uDEA1\\uDEB0-\\uDFFF]|\\uD87A[\\uDC00-\\uDFE0]|\\uD87E[\\uDC00-\\uDE1D]|\\uD884[\\uDC00-\\uDF4A\\uDF50-\\uDFFF]|\\uD888[\\uDC00-\\uDFAF])(?:[0-9A-Za-z\\xAA\\xB5\\xBA\\xC0-\\xD6\\xD8-\\xF6\\xF8-\\u02C1\\u02C6-\\u02D1\\u02E0-\\u02E4\\u02EC\\u02EE\\u0370-\\u0374\\u0376\\u0377\\u037A-\\u037D\\u037F\\u0386\\u0388-\\u038A\\u038C\\u038E-\\u03A1\\u03A3-\\u03F5\\u03F7-\\u0481\\u048A-\\u052F\\u0531-\\u0556\\u0559\\u0560-\\u0588\\u05D0-\\u05EA\\u05EF-\\u05F2\\u0620-\\u064A\\u066E\\u066F\\u0671-\\u06D3\\u06D5\\u06E5\\u06E6\\u06EE\\u06EF\\u06FA-\\u06FC\\u06FF\\u0710\\u0712-\\u072F\\u074D-\\u07A5\\u07B1\\u07CA-\\u07EA\\u07F4\\u07F5\\u07FA\\u0800-\\u0815\\u081A\\u0824\\u0828\\u0840-\\u0858\\u0860-\\u086A\\u0870-\\u0887\\u0889-\\u088E\\u08A0-\\u08C9\\u0904-\\u0939\\u093D\\u0950\\u0958-\\u0961\\u0971-\\u0980\\u0985-\\u098C\\u098F\\u0990\\u0993-\\u09A8\\u09AA-\\u09B0\\u09B2\\u09B6-\\u09B9\\u09BD\\u09CE\\u09DC\\u09DD\\u09DF-\\u09E1\\u09F0\\u09F1\\u09FC\\u0A05-\\u0A0A\\u0A0F\\u0A10\\u0A13-\\u0A28\\u0A2A-\\u0A30\\u0A32\\u0A33\\u0A35\\u0A36\\u0A38\\u0A39\\u0A59-\\u0A5C\\u0A5E\\u0A72-\\u0A74\\u0A85-\\u0A8D\\u0A8F-\\u0A91\\u0A93-\\u0AA8\\u0AAA-\\u0AB0\\u0AB2\\u0AB3\\u0AB5-\\u0AB9\\u0ABD\\u0AD0\\u0AE0\\u0AE1\\u0AF9\\u0B05-\\u0B0C\\u0B0F\\u0B10\\u0B13-\\u0B28\\u0B2A-\\u0B30\\u0B32\\u0B33\\u0B35-\\u0B39\\u0B3D\\u0B5C\\u0B5D\\u0B5F-\\u0B61\\u0B71\\u0B83\\u0B85-\\u0B8A\\u0B8E-\\u0B90\\u0B92-\\u0B95\\u0B99\\u0B9A\\u0B9C\\u0B9E\\u0B9F\\u0BA3\\u0BA4\\u0BA8-\\u0BAA\\u0BAE-\\u0BB9\\u0BD0\\u0C05-\\u0C0C\\u0C0E-\\u0C10\\u0C12-\\u0C28\\u0C2A-\\u0C39\\u0C3D\\u0C58-\\u0C5A\\u0C5D\\u0C60\\u0C61\\u0C80\\u0C85-\\u0C8C\\u0C8E-\\u0C90\\u0C92-\\u0CA8\\u0CAA-\\u0CB3\\u0CB5-\\u0CB9\\u0CBD\\u0CDD\\u0CDE\\u0CE0\\u0CE1\\u0CF1\\u0CF2\\u0D04-\\u0D0C\\u0D0E-\\u0D10\\u0D12-\\u0D3A\\u0D3D\\u0D4E\\u0D54-\\u0D56\\u0D5F-\\u0D61\\u0D7A-\\u0D7F\\u0D85-\\u0D96\\u0D9A-\\u0DB1\\u0DB3-\\u0DBB\\u0DBD\\u0DC0-\\u0DC6\\u0E01-\\u0E30\\u0E32\\u0E33\\u0E40-\\u0E46\\u0E81\\u0E82\\u0E84\\u0E86-\\u0E8A\\u0E8C-\\u0EA3\\u0EA5\\u0EA7-\\u0EB0\\u0EB2\\u0EB3\\u0EBD\\u0EC0-\\u0EC4\\u0EC6\\u0EDC-\\u0EDF\\u0F00\\u0F40-\\u0F47\\u0F49-\\u0F6C\\u0F88-\\u0F8C\\u1000-\\u102A\\u103F\\u1050-\\u1055\\u105A-\\u105D\\u1061\\u1065\\u1066\\u106E-\\u1070\\u1075-\\u1081\\u108E\\u10A0-\\u10C5\\u10C7\\u10CD\\u10D0-\\u10FA\\u10FC-\\u1248\\u124A-\\u124D\\u1250-\\u1256\\u1258\\u125A-\\u125D\\u1260-\\u1288\\u128A-\\u128D\\u1290-\\u12B0\\u12B2-\\u12B5\\u12B8-\\u12BE\\u12C0\\u12C2-\\u12C5\\u12C8-\\u12D6\\u12D8-\\u1310\\u1312-\\u1315\\u1318-\\u135A\\u1380-\\u138F\\u13A0-\\u13F5\\u13F8-\\u13FD\\u1401-\\u166C\\u166F-\\u167F\\u1681-\\u169A\\u16A0-\\u16EA\\u16F1-\\u16F8\\u1700-\\u1711\\u171F-\\u1731\\u1740-\\u1751\\u1760-\\u176C\\u176E-\\u1770\\u1780-\\u17B3\\u17D7\\u17DC\\u1820-\\u1878\\u1880-\\u1884\\u1887-\\u18A8\\u18AA\\u18B0-\\u18F5\\u1900-\\u191E\\u1950-\\u196D\\u1970-\\u1974\\u1980-\\u19AB\\u19B0-\\u19C9\\u1A00-\\u1A16\\u1A20-\\u1A54\\u1AA7\\u1B05-\\u1B33\\u1B45-\\u1B4C\\u1B83-\\u1BA0\\u1BAE\\u1BAF\\u1BBA-\\u1BE5\\u1C00-\\u1C23\\u1C4D-\\u1C4F\\u1C5A-\\u1C7D\\u1C80-\\u1C88\\u1C90-\\u1CBA\\u1CBD-\\u1CBF\\u1CE9-\\u1CEC\\u1CEE-\\u1CF3\\u1CF5\\u1CF6\\u1CFA\\u1D00-\\u1DBF\\u1E00-\\u1F15\\u1F18-\\u1F1D\\u1F20-\\u1F45\\u1F48-\\u1F4D\\u1F50-\\u1F57\\u1F59\\u1F5B\\u1F5D\\u1F5F-\\u1F7D\\u1F80-\\u1FB4\\u1FB6-\\u1FBC\\u1FBE\\u1FC2-\\u1FC4\\u1FC6-\\u1FCC\\u1FD0-\\u1FD3\\u1FD6-\\u1FDB\\u1FE0-\\u1FEC\\u1FF2-\\u1FF4\\u1FF6-\\u1FFC\\u2071\\u207F\\u2090-\\u209C\\u2102\\u2107\\u210A-\\u2113\\u2115\\u2119-\\u211D\\u2124\\u2126\\u2128\\u212A-\\u212D\\u212F-\\u2139\\u213C-\\u213F\\u2145-\\u2149\\u214E\\u2183\\u2184\\u2C00-\\u2CE4\\u2CEB-\\u2CEE\\u2CF2\\u2CF3\\u2D00-\\u2D25\\u2D27\\u2D2D\\u2D30-\\u2D67\\u2D6F\\u2D80-\\u2D96\\u2DA0-\\u2DA6\\u2DA8-\\u2DAE\\u2DB0-\\u2DB6\\u2DB8-\\u2DBE\\u2DC0-\\u2DC6\\u2DC8-\\u2DCE\\u2DD0-\\u2DD6\\u2DD8-\\u2DDE\\u2E2F\\u3005\\u3006\\u3031-\\u3035\\u303B\\u303C\\u3041-\\u3096\\u309D-\\u309F\\u30A1-\\u30FA\\u30FC-\\u30FF\\u3105-\\u312F\\u3131-\\u318E\\u31A0-\\u31BF\\u31F0-\\u31FF\\u3400-\\u4DBF\\u4E00-\\uA48C\\uA4D0-\\uA4FD\\uA500-\\uA60C\\uA610-\\uA61F\\uA62A\\uA62B\\uA640-\\uA66E\\uA67F-\\uA69D\\uA6A0-\\uA6E5\\uA717-\\uA71F\\uA722-\\uA788\\uA78B-\\uA7CA\\uA7D0\\uA7D1\\uA7D3\\uA7D5-\\uA7D9\\uA7F2-\\uA801\\uA803-\\uA805\\uA807-\\uA80A\\uA80C-\\uA822\\uA840-\\uA873\\uA882-\\uA8B3\\uA8F2-\\uA8F7\\uA8FB\\uA8FD\\uA8FE\\uA90A-\\uA925\\uA930-\\uA946\\uA960-\\uA97C\\uA984-\\uA9B2\\uA9CF\\uA9E0-\\uA9E4\\uA9E6-\\uA9EF\\uA9FA-\\uA9FE\\uAA00-\\uAA28\\uAA40-\\uAA42\\uAA44-\\uAA4B\\uAA60-\\uAA76\\uAA7A\\uAA7E-\\uAAAF\\uAAB1\\uAAB5\\uAAB6\\uAAB9-\\uAABD\\uAAC0\\uAAC2\\uAADB-\\uAADD\\uAAE0-\\uAAEA\\uAAF2-\\uAAF4\\uAB01-\\uAB06\\uAB09-\\uAB0E\\uAB11-\\uAB16\\uAB20-\\uAB26\\uAB28-\\uAB2E\\uAB30-\\uAB5A\\uAB5C-\\uAB69\\uAB70-\\uABE2\\uAC00-\\uD7A3\\uD7B0-\\uD7C6\\uD7CB-\\uD7FB\\uF900-\\uFA6D\\uFA70-\\uFAD9\\uFB00-\\uFB06\\uFB13-\\uFB17\\uFB1D\\uFB1F-\\uFB28\\uFB2A-\\uFB36\\uFB38-\\uFB3C\\uFB3E\\uFB40\\uFB41\\uFB43\\uFB44\\uFB46-\\uFBB1\\uFBD3-\\uFD3D\\uFD50-\\uFD8F\\uFD92-\\uFDC7\\uFDF0-\\uFDFB\\uFE70-\\uFE74\\uFE76-\\uFEFC\\uFF21-\\uFF3A\\uFF41-\\uFF5A\\uFF66-\\uFFBE\\uFFC2-\\uFFC7\\uFFCA-\\uFFCF\\uFFD2-\\uFFD7\\uFFDA-\\uFFDC]|\\uD800[\\uDC00-\\uDC0B\\uDC0D-\\uDC26\\uDC28-\\uDC3A\\uDC3C\\uDC3D\\uDC3F-\\uDC4D\\uDC50-\\uDC5D\\uDC80-\\uDCFA\\uDE80-\\uDE9C\\uDEA0-\\uDED0\\uDF00-\\uDF1F\\uDF2D-\\uDF40\\uDF42-\\uDF49\\uDF50-\\uDF75\\uDF80-\\uDF9D\\uDFA0-\\uDFC3\\uDFC8-\\uDFCF]|\\uD801[\\uDC00-\\uDC9D\\uDCB0-\\uDCD3\\uDCD8-\\uDCFB\\uDD00-\\uDD27\\uDD30-\\uDD63\\uDD70-\\uDD7A\\uDD7C-\\uDD8A\\uDD8C-\\uDD92\\uDD94\\uDD95\\uDD97-\\uDDA1\\uDDA3-\\uDDB1\\uDDB3-\\uDDB9\\uDDBB\\uDDBC\\uDE00-\\uDF36\\uDF40-\\uDF55\\uDF60-\\uDF67\\uDF80-\\uDF85\\uDF87-\\uDFB0\\uDFB2-\\uDFBA]|\\uD802[\\uDC00-\\uDC05\\uDC08\\uDC0A-\\uDC35\\uDC37\\uDC38\\uDC3C\\uDC3F-\\uDC55\\uDC60-\\uDC76\\uDC80-\\uDC9E\\uDCE0-\\uDCF2\\uDCF4\\uDCF5\\uDD00-\\uDD15\\uDD20-\\uDD39\\uDD80-\\uDDB7\\uDDBE\\uDDBF\\uDE00\\uDE10-\\uDE13\\uDE15-\\uDE17\\uDE19-\\uDE35\\uDE60-\\uDE7C\\uDE80-\\uDE9C\\uDEC0-\\uDEC7\\uDEC9-\\uDEE4\\uDF00-\\uDF35\\uDF40-\\uDF55\\uDF60-\\uDF72\\uDF80-\\uDF91]|\\uD803[\\uDC00-\\uDC48\\uDC80-\\uDCB2\\uDCC0-\\uDCF2\\uDD00-\\uDD23\\uDE80-\\uDEA9\\uDEB0\\uDEB1\\uDF00-\\uDF1C\\uDF27\\uDF30-\\uDF45\\uDF70-\\uDF81\\uDFB0-\\uDFC4\\uDFE0-\\uDFF6]|\\uD804[\\uDC03-\\uDC37\\uDC71\\uDC72\\uDC75\\uDC83-\\uDCAF\\uDCD0-\\uDCE8\\uDD03-\\uDD26\\uDD44\\uDD47\\uDD50-\\uDD72\\uDD76\\uDD83-\\uDDB2\\uDDC1-\\uDDC4\\uDDDA\\uDDDC\\uDE00-\\uDE11\\uDE13-\\uDE2B\\uDE3F\\uDE40\\uDE80-\\uDE86\\uDE88\\uDE8A-\\uDE8D\\uDE8F-\\uDE9D\\uDE9F-\\uDEA8\\uDEB0-\\uDEDE\\uDF05-\\uDF0C\\uDF0F\\uDF10\\uDF13-\\uDF28\\uDF2A-\\uDF30\\uDF32\\uDF33\\uDF35-\\uDF39\\uDF3D\\uDF50\\uDF5D-\\uDF61]|\\uD805[\\uDC00-\\uDC34\\uDC47-\\uDC4A\\uDC5F-\\uDC61\\uDC80-\\uDCAF\\uDCC4\\uDCC5\\uDCC7\\uDD80-\\uDDAE\\uDDD8-\\uDDDB\\uDE00-\\uDE2F\\uDE44\\uDE80-\\uDEAA\\uDEB8\\uDF00-\\uDF1A\\uDF40-\\uDF46]|\\uD806[\\uDC00-\\uDC2B\\uDCA0-\\uDCDF\\uDCFF-\\uDD06\\uDD09\\uDD0C-\\uDD13\\uDD15\\uDD16\\uDD18-\\uDD2F\\uDD3F\\uDD41\\uDDA0-\\uDDA7\\uDDAA-\\uDDD0\\uDDE1\\uDDE3\\uDE00\\uDE0B-\\uDE32\\uDE3A\\uDE50\\uDE5C-\\uDE89\\uDE9D\\uDEB0-\\uDEF8]|\\uD807[\\uDC00-\\uDC08\\uDC0A-\\uDC2E\\uDC40\\uDC72-\\uDC8F\\uDD00-\\uDD06\\uDD08\\uDD09\\uDD0B-\\uDD30\\uDD46\\uDD60-\\uDD65\\uDD67\\uDD68\\uDD6A-\\uDD89\\uDD98\\uDEE0-\\uDEF2\\uDF02\\uDF04-\\uDF10\\uDF12-\\uDF33\\uDFB0]|\\uD808[\\uDC00-\\uDF99]|\\uD809[\\uDC80-\\uDD43]|\\uD80B[\\uDF90-\\uDFF0]|[\\uD80C\\uD81C-\\uD820\\uD822\\uD840-\\uD868\\uD86A-\\uD86C\\uD86F-\\uD872\\uD874-\\uD879\\uD880-\\uD883\\uD885-\\uD887][\\uDC00-\\uDFFF]|\\uD80D[\\uDC00-\\uDC2F\\uDC41-\\uDC46]|\\uD811[\\uDC00-\\uDE46]|\\uD81A[\\uDC00-\\uDE38\\uDE40-\\uDE5E\\uDE70-\\uDEBE\\uDED0-\\uDEED\\uDF00-\\uDF2F\\uDF40-\\uDF43\\uDF63-\\uDF77\\uDF7D-\\uDF8F]|\\uD81B[\\uDE40-\\uDE7F\\uDF00-\\uDF4A\\uDF50\\uDF93-\\uDF9F\\uDFE0\\uDFE1\\uDFE3]|\\uD821[\\uDC00-\\uDFF7]|\\uD823[\\uDC00-\\uDCD5\\uDD00-\\uDD08]|\\uD82B[\\uDFF0-\\uDFF3\\uDFF5-\\uDFFB\\uDFFD\\uDFFE]|\\uD82C[\\uDC00-\\uDD22\\uDD32\\uDD50-\\uDD52\\uDD55\\uDD64-\\uDD67\\uDD70-\\uDEFB]|\\uD82F[\\uDC00-\\uDC6A\\uDC70-\\uDC7C\\uDC80-\\uDC88\\uDC90-\\uDC99]|\\uD835[\\uDC00-\\uDC54\\uDC56-\\uDC9C\\uDC9E\\uDC9F\\uDCA2\\uDCA5\\uDCA6\\uDCA9-\\uDCAC\\uDCAE-\\uDCB9\\uDCBB\\uDCBD-\\uDCC3\\uDCC5-\\uDD05\\uDD07-\\uDD0A\\uDD0D-\\uDD14\\uDD16-\\uDD1C\\uDD1E-\\uDD39\\uDD3B-\\uDD3E\\uDD40-\\uDD44\\uDD46\\uDD4A-\\uDD50\\uDD52-\\uDEA5\\uDEA8-\\uDEC0\\uDEC2-\\uDEDA\\uDEDC-\\uDEFA\\uDEFC-\\uDF14\\uDF16-\\uDF34\\uDF36-\\uDF4E\\uDF50-\\uDF6E\\uDF70-\\uDF88\\uDF8A-\\uDFA8\\uDFAA-\\uDFC2\\uDFC4-\\uDFCB]|\\uD837[\\uDF00-\\uDF1E\\uDF25-\\uDF2A]|\\uD838[\\uDC30-\\uDC6D\\uDD00-\\uDD2C\\uDD37-\\uDD3D\\uDD4E\\uDE90-\\uDEAD\\uDEC0-\\uDEEB]|\\uD839[\\uDCD0-\\uDCEB\\uDFE0-\\uDFE6\\uDFE8-\\uDFEB\\uDFED\\uDFEE\\uDFF0-\\uDFFE]|\\uD83A[\\uDC00-\\uDCC4\\uDD00-\\uDD43\\uDD4B]|\\uD83B[\\uDE00-\\uDE03\\uDE05-\\uDE1F\\uDE21\\uDE22\\uDE24\\uDE27\\uDE29-\\uDE32\\uDE34-\\uDE37\\uDE39\\uDE3B\\uDE42\\uDE47\\uDE49\\uDE4B\\uDE4D-\\uDE4F\\uDE51\\uDE52\\uDE54\\uDE57\\uDE59\\uDE5B\\uDE5D\\uDE5F\\uDE61\\uDE62\\uDE64\\uDE67-\\uDE6A\\uDE6C-\\uDE72\\uDE74-\\uDE77\\uDE79-\\uDE7C\\uDE7E\\uDE80-\\uDE89\\uDE8B-\\uDE9B\\uDEA1-\\uDEA3\\uDEA5-\\uDEA9\\uDEAB-\\uDEBB]|\\uD869[\\uDC00-\\uDEDF\\uDF00-\\uDFFF]|\\uD86D[\\uDC00-\\uDF39\\uDF40-\\uDFFF]|\\uD86E[\\uDC00-\\uDC1D\\uDC20-\\uDFFF]|\\uD873[\\uDC00-\\uDEA1\\uDEB0-\\uDFFF]|\\uD87A[\\uDC00-\\uDFE0]|\\uD87E[\\uDC00-\\uDE1D]|\\uD884[\\uDC00-\\uDF4A\\uDF50-\\uDFFF]|\\uD888[\\uDC00-\\uDFAF])*$/.test(l)},{name:"string",test:St},{name:"Chain",test:bu},{name:"Array",test:Mr},{name:"Matrix",test:Qe},{name:"DenseMatrix",test:Xi},{name:"SparseMatrix",test:pa},{name:"Range",test:To},{name:"Index",test:Ai},{name:"boolean",test:cm},{name:"ResultSet",test:lm},{name:"Help",test:yu},{name:"function",test:mm},{name:"Date",test:pm},{name:"RegExp",test:dm},{name:"null",test:hm},{name:"undefined",test:vm},{name:"AccessorNode",test:qn},{name:"ArrayNode",test:jt},{name:"AssignmentNode",test:gm},{name:"BlockNode",test:xm},{name:"ConditionalNode",test:ym},{name:"ConstantNode",test:yr},{name:"FunctionNode",test:gn},{name:"FunctionAssignmentNode",test:_a},{name:"IndexNode",test:Qn},{name:"Node",test:Nr},{name:"ObjectNode",test:Ci},{name:"OperatorNode",test:ct},{name:"ParenthesisNode",test:en},{name:"RangeNode",test:bm},{name:"RelationalNode",test:wm},{name:"SymbolNode",test:at},{name:"Map",test:rw},{name:"Object",test:Mi}]),u.addConversions([{from:"number",to:"BigNumber",convert:function(c){if(t||tw(c),KA(c)>15)throw new TypeError("Cannot implicitly convert a number with >15 significant digits to BigNumber (value: "+c+"). Use function bignumber(x) to convert to BigNumber.");return new t(c)}},{from:"number",to:"Complex",convert:function(c){return n||Pm(c),new n(c,0)}},{from:"BigNumber",to:"Complex",convert:function(c){return n||Pm(c),new n(c.toNumber(),0)}},{from:"Fraction",to:"BigNumber",convert:function(c){throw new TypeError("Cannot implicitly convert a Fraction to BigNumber or vice versa. Use function bignumber(x) to convert to BigNumber or fraction(x) to convert to Fraction.")}},{from:"Fraction",to:"Complex",convert:function(c){return n||Pm(c),new n(c.valueOf(),0)}},{from:"number",to:"Fraction",convert:function(c){i||nw(c);var o=new i(c);if(o.valueOf()!==c)throw new TypeError("Cannot implicitly convert a number to a Fraction when there will be a loss of precision (value: "+c+"). Use function fraction(x) to convert to Fraction.");return o}},{from:"string",to:"number",convert:function(c){var o=Number(c);if(isNaN(o))throw new Error('Cannot convert "'+c+'" to a number');return o}},{from:"string",to:"BigNumber",convert:function(c){t||tw(c);try{return new t(c)}catch{throw new Error('Cannot convert "'+c+'" to BigNumber')}}},{from:"string",to:"Fraction",convert:function(c){i||nw(c);try{return new i(c)}catch{throw new Error('Cannot convert "'+c+'" to Fraction')}}},{from:"string",to:"Complex",convert:function(c){n||Pm(c);try{return new n(c)}catch{throw new Error('Cannot convert "'+c+'" to Complex')}}},{from:"boolean",to:"number",convert:function(c){return+c}},{from:"boolean",to:"BigNumber",convert:function(c){return t||tw(c),new t(+c)}},{from:"boolean",to:"Fraction",convert:function(c){return i||nw(c),new i(+c)}},{from:"boolean",to:"string",convert:function(c){return String(c)}},{from:"Array",to:"Matrix",convert:function(c){return a||sL(),new a(c)}},{from:"Matrix",to:"Array",convert:function(c){return c.valueOf()}}]),u.onMismatch=(l,c,o)=>{var s=u.createError(l,c,o);if(["wrongType","mismatch"].includes(s.data.category)&&c.length===1&&Nt(c[0])&&o.some(d=>!d.params.includes(","))){var m=new TypeError("Function '".concat(l,"' doesn't apply to matrices. To call it ")+"elementwise on a matrix 'M', try 'map(M, ".concat(l,")'."));throw m.data=s.data,m}throw s},u.onMismatch=(l,c,o)=>{var s=u.createError(l,c,o);if(["wrongType","mismatch"].includes(s.data.category)&&c.length===1&&Nt(c[0])&&o.some(d=>!d.params.includes(","))){var m=new TypeError("Function '".concat(l,"' doesn't apply to matrices. To call it ")+"elementwise on a matrix 'M', try 'map(M, ".concat(l,")'."));throw m.data=s.data,m}throw s},u});function tw(e){throw new Error("Cannot convert value ".concat(e," into a BigNumber: no class 'BigNumber' provided"))}function Pm(e){throw new Error("Cannot convert value ".concat(e," into a Complex number: no class 'Complex' provided"))}function sL(){throw new Error("Cannot convert array into a Matrix: no class 'DenseMatrix' provided")}function nw(e){throw new Error("Cannot convert value ".concat(e," into a Fraction, no class 'Fraction' provided."))}var uL="ResultSet",fL=[],Rm=F(uL,fL,()=>{function e(r){if(!(this instanceof e))throw new SyntaxError("Constructor must be called with the new operator");this.entries=r||[]}return e.prototype.type="ResultSet",e.prototype.isResultSet=!0,e.prototype.valueOf=function(){return this.entries},e.prototype.toString=function(){return"["+this.entries.join(", ")+"]"},e.prototype.toJSON=function(){return{mathjs:"ResultSet",entries:this.entries}},e.fromJSON=function(r){return new e(r.entries)},e},{isClass:!0});var Tu=9e15,Ro=1e9,iw="0123456789abcdef",qm="2.3025850929940456840179914546843642076011014886287729760333279009675726096773524802359972050895982983419677840422862486334095254650828067566662873690987816894829072083255546808437998948262331985283935053089653777326288461633662222876982198867465436674744042432743651550489343149393914796194044002221051017141748003688084012647080685567743216228355220114804663715659121373450747856947683463616792101806445070648000277502684916746550586856935673420670581136429224554405758925724208241314695689016758940256776311356919292033376587141660230105703089634572075440370847469940168269282808481184289314848524948644871927809676271275775397027668605952496716674183485704422507197965004714951050492214776567636938662976979522110718264549734772662425709429322582798502585509785265383207606726317164309505995087807523710333101197857547331541421808427543863591778117054309827482385045648019095610299291824318237525357709750539565187697510374970888692180205189339507238539205144634197265287286965110862571492198849978748873771345686209167058",Lm="3.1415926535897932384626433832795028841971693993751058209749445923078164062862089986280348253421170679821480865132823066470938446095505822317253594081284811174502841027019385211055596446229489549303819644288109756659334461284756482337867831652712019091456485669234603486104543266482133936072602491412737245870066063155881748815209209628292540917153643678925903600113305305488204665213841469519415116094330572703657595919530921861173819326117931051185480744623799627495673518857527248912279381830119491298336733624406566430860213949463952247371907021798609437027705392171762931767523846748184676694051320005681271452635608277857713427577896091736371787214684409012249534301465495853710507922796892589235420199561121290219608640344181598136297747713099605187072113499999983729780499510597317328160963185950244594553469083026425223082533446850352619311881710100031378387528865875332083814206171776691473035982534904287554687311595628638823537875937519577818577805321712268066130019278766111959092164201989380952572010654858632789",ow={precision:20,rounding:4,modulo:1,toExpNeg:-7,toExpPos:21,minE:-Tu,maxE:Tu,crypto:!1},AM,ji,Cr=!0,Um="[DecimalError] ",Io=Um+"Invalid argument: ",MM=Um+"Precision limit exceeded",CM=Um+"crypto unavailable",EM="[object Decimal]",Nn=Math.floor,nn=Math.pow,cL=/^0b([01]+(\\.[01]*)?|\\.[01]+)(p[+-]?\\d+)?$/i,lL=/^0x([0-9a-f]+(\\.[0-9a-f]*)?|\\.[0-9a-f]+)(p[+-]?\\d+)?$/i,mL=/^0o([0-7]+(\\.[0-7]*)?|\\.[0-7]+)(p[+-]?\\d+)?$/i,TM=/^(\\d+(\\.\\d*)?|\\.\\d+)(e[+-]?\\d+)?$/i,si=1e7,br=7,pL=9007199254740991,dL=qm.length-1,sw=Lm.length-1,Ue={toStringTag:EM};Ue.absoluteValue=Ue.abs=function(){var e=new this.constructor(this);return e.s<0&&(e.s=1),hr(e)};Ue.ceil=function(){return hr(new this.constructor(this),this.e+1,2)};Ue.clampedTo=Ue.clamp=function(e,r){var t,n=this,a=n.constructor;if(e=new a(e),r=new a(r),!e.s||!r.s)return new a(NaN);if(e.gt(r))throw Error(Io+r);return t=n.cmp(e),t<0?e:n.cmp(r)>0?r:new a(n)};Ue.comparedTo=Ue.cmp=function(e){var r,t,n,a,i=this,u=i.d,l=(e=new i.constructor(e)).d,c=i.s,o=e.s;if(!u||!l)return!c||!o?NaN:c!==o?c:u===l?0:!u^c<0?1:-1;if(!u[0]||!l[0])return u[0]?c:l[0]?-o:0;if(c!==o)return c;if(i.e!==e.e)return i.e>e.e^c<0?1:-1;for(n=u.length,a=l.length,r=0,t=nl[r]^c<0?1:-1;return n===a?0:n>a^c<0?1:-1};Ue.cosine=Ue.cos=function(){var e,r,t=this,n=t.constructor;return t.d?t.d[0]?(e=n.precision,r=n.rounding,n.precision=e+Math.max(t.e,t.sd())+br,n.rounding=1,t=hL(n,PM(n,t)),n.precision=e,n.rounding=r,hr(ji==2||ji==3?t.neg():t,e,r,!0)):new n(1):new n(NaN)};Ue.cubeRoot=Ue.cbrt=function(){var e,r,t,n,a,i,u,l,c,o,s=this,m=s.constructor;if(!s.isFinite()||s.isZero())return new m(s);for(Cr=!1,i=s.s*nn(s.s*s,1/3),!i||Math.abs(i)==1/0?(t=xn(s.d),e=s.e,(i=(e-t.length+1)%3)&&(t+=i==1||i==-2?"0":"00"),i=nn(t,1/3),e=Nn((e+1)/3)-(e%3==(e<0?-1:2)),i==1/0?t="5e"+e:(t=i.toExponential(),t=t.slice(0,t.indexOf("e")+1)+e),n=new m(t),n.s=s.s):n=new m(i.toString()),u=(e=m.precision)+3;;)if(l=n,c=l.times(l).times(l),o=c.plus(s),n=Dt(o.plus(s).times(l),o.plus(c),u+2,1),xn(l.d).slice(0,u)===(t=xn(n.d)).slice(0,u))if(t=t.slice(u-3,u+1),t=="9999"||!a&&t=="4999"){if(!a&&(hr(l,e+1,0),l.times(l).times(l).eq(s))){n=l;break}u+=4,a=1}else{(!+t||!+t.slice(1)&&t.charAt(0)=="5")&&(hr(n,e+1,1),r=!n.times(n).times(n).eq(s));break}return Cr=!0,hr(n,e,m.rounding,r)};Ue.decimalPlaces=Ue.dp=function(){var e,r=this.d,t=NaN;if(r){if(e=r.length-1,t=(e-Nn(this.e/br))*br,e=r[e],e)for(;e%10==0;e/=10)t--;t<0&&(t=0)}return t};Ue.dividedBy=Ue.div=function(e){return Dt(this,new this.constructor(e))};Ue.dividedToIntegerBy=Ue.divToInt=function(e){var r=this,t=r.constructor;return hr(Dt(r,new t(e),0,1,1),t.precision,t.rounding)};Ue.equals=Ue.eq=function(e){return this.cmp(e)===0};Ue.floor=function(){return hr(new this.constructor(this),this.e+1,3)};Ue.greaterThan=Ue.gt=function(e){return this.cmp(e)>0};Ue.greaterThanOrEqualTo=Ue.gte=function(e){var r=this.cmp(e);return r==1||r===0};Ue.hyperbolicCosine=Ue.cosh=function(){var e,r,t,n,a,i=this,u=i.constructor,l=new u(1);if(!i.isFinite())return new u(i.s?1/0:NaN);if(i.isZero())return l;t=u.precision,n=u.rounding,u.precision=t+Math.max(i.e,i.sd())+4,u.rounding=1,a=i.d.length,a<32?(e=Math.ceil(a/3),r=(1/Ym(4,e)).toString()):(e=16,r="2.3283064365386962890625e-10"),i=Fu(u,1,i.times(r),new u(1),!0);for(var c,o=e,s=new u(8);o--;)c=i.times(i),i=l.minus(c.times(s.minus(c.times(s))));return hr(i,u.precision=t,u.rounding=n,!0)};Ue.hyperbolicSine=Ue.sinh=function(){var e,r,t,n,a=this,i=a.constructor;if(!a.isFinite()||a.isZero())return new i(a);if(r=i.precision,t=i.rounding,i.precision=r+Math.max(a.e,a.sd())+4,i.rounding=1,n=a.d.length,n<3)a=Fu(i,2,a,a,!0);else{e=1.4*Math.sqrt(n),e=e>16?16:e|0,a=a.times(1/Ym(5,e)),a=Fu(i,2,a,a,!0);for(var u,l=new i(5),c=new i(16),o=new i(20);e--;)u=a.times(a),a=a.times(l.plus(u.times(c.times(u).plus(o))))}return i.precision=r,i.rounding=t,hr(a,r,t,!0)};Ue.hyperbolicTangent=Ue.tanh=function(){var e,r,t=this,n=t.constructor;return t.isFinite()?t.isZero()?new n(t):(e=n.precision,r=n.rounding,n.precision=e+7,n.rounding=1,Dt(t.sinh(),t.cosh(),n.precision=e,n.rounding=r)):new n(t.s)};Ue.inverseCosine=Ue.acos=function(){var e,r=this,t=r.constructor,n=r.abs().cmp(1),a=t.precision,i=t.rounding;return n!==-1?n===0?r.isNeg()?oi(t,a,i):new t(0):new t(NaN):r.isZero()?oi(t,a+4,i).times(.5):(t.precision=a+6,t.rounding=1,r=r.asin(),e=oi(t,a+4,i).times(.5),t.precision=a,t.rounding=i,e.minus(r))};Ue.inverseHyperbolicCosine=Ue.acosh=function(){var e,r,t=this,n=t.constructor;return t.lte(1)?new n(t.eq(1)?0:NaN):t.isFinite()?(e=n.precision,r=n.rounding,n.precision=e+Math.max(Math.abs(t.e),t.sd())+4,n.rounding=1,Cr=!1,t=t.times(t).minus(1).sqrt().plus(t),Cr=!0,n.precision=e,n.rounding=r,t.ln()):new n(t)};Ue.inverseHyperbolicSine=Ue.asinh=function(){var e,r,t=this,n=t.constructor;return!t.isFinite()||t.isZero()?new n(t):(e=n.precision,r=n.rounding,n.precision=e+2*Math.max(Math.abs(t.e),t.sd())+6,n.rounding=1,Cr=!1,t=t.times(t).plus(1).sqrt().plus(t),Cr=!0,n.precision=e,n.rounding=r,t.ln())};Ue.inverseHyperbolicTangent=Ue.atanh=function(){var e,r,t,n,a=this,i=a.constructor;return a.isFinite()?a.e>=0?new i(a.abs().eq(1)?a.s/0:a.isZero()?a:NaN):(e=i.precision,r=i.rounding,n=a.sd(),Math.max(n,e)<2*-a.e-1?hr(new i(a),e,r,!0):(i.precision=t=n-a.e,a=Dt(a.plus(1),new i(1).minus(a),t+e,1),i.precision=e+4,i.rounding=1,a=a.ln(),i.precision=e,i.rounding=r,a.times(.5))):new i(NaN)};Ue.inverseSine=Ue.asin=function(){var e,r,t,n,a=this,i=a.constructor;return a.isZero()?new i(a):(r=a.abs().cmp(1),t=i.precision,n=i.rounding,r!==-1?r===0?(e=oi(i,t+4,n).times(.5),e.s=a.s,e):new i(NaN):(i.precision=t+6,i.rounding=1,a=a.div(new i(1).minus(a.times(a)).sqrt().plus(1)).atan(),i.precision=t,i.rounding=n,a.times(2)))};Ue.inverseTangent=Ue.atan=function(){var e,r,t,n,a,i,u,l,c,o=this,s=o.constructor,m=s.precision,d=s.rounding;if(o.isFinite()){if(o.isZero())return new s(o);if(o.abs().eq(1)&&m+4<=sw)return u=oi(s,m+4,d).times(.25),u.s=o.s,u}else{if(!o.s)return new s(NaN);if(m+4<=sw)return u=oi(s,m+4,d).times(.5),u.s=o.s,u}for(s.precision=l=m+10,s.rounding=1,t=Math.min(28,l/br+2|0),e=t;e;--e)o=o.div(o.times(o).plus(1).sqrt().plus(1));for(Cr=!1,r=Math.ceil(l/br),n=1,c=o.times(o),u=new s(o),a=o;e!==-1;)if(a=a.times(c),i=u.minus(a.div(n+=2)),a=a.times(c),u=i.plus(a.div(n+=2)),u.d[r]!==void 0)for(e=r;u.d[e]===i.d[e]&&e--;);return t&&(u=u.times(2<this.d.length-2};Ue.isNaN=function(){return!this.s};Ue.isNegative=Ue.isNeg=function(){return this.s<0};Ue.isPositive=Ue.isPos=function(){return this.s>0};Ue.isZero=function(){return!!this.d&&this.d[0]===0};Ue.lessThan=Ue.lt=function(e){return this.cmp(e)<0};Ue.lessThanOrEqualTo=Ue.lte=function(e){return this.cmp(e)<1};Ue.logarithm=Ue.log=function(e){var r,t,n,a,i,u,l,c,o=this,s=o.constructor,m=s.precision,d=s.rounding,h=5;if(e==null)e=new s(10),r=!0;else{if(e=new s(e),t=e.d,e.s<0||!t||!t[0]||e.eq(1))return new s(NaN);r=e.eq(10)}if(t=o.d,o.s<0||!t||!t[0]||o.eq(1))return new s(t&&!t[0]?-1/0:o.s!=1?NaN:t?0:1/0);if(r)if(t.length>1)i=!0;else{for(a=t[0];a%10===0;)a/=10;i=a!==1}if(Cr=!1,l=m+h,u=Po(o,l),n=r?zm(s,l+10):Po(e,l),c=Dt(u,n,l,1),Tc(c.d,a=m,d))do if(l+=10,u=Po(o,l),n=r?zm(s,l+10):Po(e,l),c=Dt(u,n,l,1),!i){+xn(c.d).slice(a+1,a+15)+1==1e14&&(c=hr(c,m+1,0));break}while(Tc(c.d,a+=10,d));return Cr=!0,hr(c,m,d)};Ue.minus=Ue.sub=function(e){var r,t,n,a,i,u,l,c,o,s,m,d,h=this,x=h.constructor;if(e=new x(e),!h.d||!e.d)return!h.s||!e.s?e=new x(NaN):h.d?e.s=-e.s:e=new x(e.d||h.s!==e.s?h:NaN),e;if(h.s!=e.s)return e.s=-e.s,h.plus(e);if(o=h.d,d=e.d,l=x.precision,c=x.rounding,!o[0]||!d[0]){if(d[0])e.s=-e.s;else if(o[0])e=new x(h);else return new x(c===3?-0:0);return Cr?hr(e,l,c):e}if(t=Nn(e.e/br),s=Nn(h.e/br),o=o.slice(),i=s-t,i){for(m=i<0,m?(r=o,i=-i,u=d.length):(r=d,t=s,u=o.length),n=Math.max(Math.ceil(l/br),u)+2,i>n&&(i=n,r.length=1),r.reverse(),n=i;n--;)r.push(0);r.reverse()}else{for(n=o.length,u=d.length,m=n0;--n)o[u++]=0;for(n=d.length;n>i;){if(o[--n]u?i+1:u+1,a>u&&(a=u,t.length=1),t.reverse();a--;)t.push(0);t.reverse()}for(u=o.length,a=s.length,u-a<0&&(a=u,t=s,s=o,o=t),r=0;a;)r=(o[--a]=o[a]+s[a]+r)/si|0,o[a]%=si;for(r&&(o.unshift(r),++n),u=o.length;o[--u]==0;)o.pop();return e.d=o,e.e=Wm(o,n),Cr?hr(e,l,c):e};Ue.precision=Ue.sd=function(e){var r,t=this;if(e!==void 0&&e!==!!e&&e!==1&&e!==0)throw Error(Io+e);return t.d?(r=FM(t.d),e&&t.e+1>r&&(r=t.e+1)):r=NaN,r};Ue.round=function(){var e=this,r=e.constructor;return hr(new r(e),e.e+1,r.rounding)};Ue.sine=Ue.sin=function(){var e,r,t=this,n=t.constructor;return t.isFinite()?t.isZero()?new n(t):(e=n.precision,r=n.rounding,n.precision=e+Math.max(t.e,t.sd())+br,n.rounding=1,t=gL(n,PM(n,t)),n.precision=e,n.rounding=r,hr(ji>2?t.neg():t,e,r,!0)):new n(NaN)};Ue.squareRoot=Ue.sqrt=function(){var e,r,t,n,a,i,u=this,l=u.d,c=u.e,o=u.s,s=u.constructor;if(o!==1||!l||!l[0])return new s(!o||o<0&&(!l||l[0])?NaN:l?u:1/0);for(Cr=!1,o=Math.sqrt(+u),o==0||o==1/0?(r=xn(l),(r.length+c)%2==0&&(r+="0"),o=Math.sqrt(r),c=Nn((c+1)/2)-(c<0||c%2),o==1/0?r="5e"+c:(r=o.toExponential(),r=r.slice(0,r.indexOf("e")+1)+c),n=new s(r)):n=new s(o.toString()),t=(c=s.precision)+3;;)if(i=n,n=i.plus(Dt(u,i,t+2,1)).times(.5),xn(i.d).slice(0,t)===(r=xn(n.d)).slice(0,t))if(r=r.slice(t-3,t+1),r=="9999"||!a&&r=="4999"){if(!a&&(hr(i,c+1,0),i.times(i).eq(u))){n=i;break}t+=4,a=1}else{(!+r||!+r.slice(1)&&r.charAt(0)=="5")&&(hr(n,c+1,1),e=!n.times(n).eq(u));break}return Cr=!0,hr(n,c,s.rounding,e)};Ue.tangent=Ue.tan=function(){var e,r,t=this,n=t.constructor;return t.isFinite()?t.isZero()?new n(t):(e=n.precision,r=n.rounding,n.precision=e+10,n.rounding=1,t=t.sin(),t.s=1,t=Dt(t,new n(1).minus(t.times(t)).sqrt(),e+10,0),n.precision=e,n.rounding=r,hr(ji==2||ji==4?t.neg():t,e,r,!0)):new n(NaN)};Ue.times=Ue.mul=function(e){var r,t,n,a,i,u,l,c,o,s=this,m=s.constructor,d=s.d,h=(e=new m(e)).d;if(e.s*=s.s,!d||!d[0]||!h||!h[0])return new m(!e.s||d&&!d[0]&&!h||h&&!h[0]&&!d?NaN:!d||!h?e.s/0:e.s*0);for(t=Nn(s.e/br)+Nn(e.e/br),c=d.length,o=h.length,c=0;){for(r=0,a=c+n;a>n;)l=i[a]+h[n]*d[a-n-1]+r,i[a--]=l%si|0,r=l/si|0;i[a]=(i[a]+r)%si|0}for(;!i[--u];)i.pop();return r?++t:i.shift(),e.d=i,e.e=Wm(i,t),Cr?hr(e,m.precision,m.rounding):e};Ue.toBinary=function(e,r){return cw(this,2,e,r)};Ue.toDecimalPlaces=Ue.toDP=function(e,r){var t=this,n=t.constructor;return t=new n(t),e===void 0?t:(Jn(e,0,Ro),r===void 0?r=n.rounding:Jn(r,0,8),hr(t,e+t.e+1,r))};Ue.toExponential=function(e,r){var t,n=this,a=n.constructor;return e===void 0?t=Ti(n,!0):(Jn(e,0,Ro),r===void 0?r=a.rounding:Jn(r,0,8),n=hr(new a(n),e+1,r),t=Ti(n,!0,e+1)),n.isNeg()&&!n.isZero()?"-"+t:t};Ue.toFixed=function(e,r){var t,n,a=this,i=a.constructor;return e===void 0?t=Ti(a):(Jn(e,0,Ro),r===void 0?r=i.rounding:Jn(r,0,8),n=hr(new i(a),e+a.e+1,r),t=Ti(n,!1,e+n.e+1)),a.isNeg()&&!a.isZero()?"-"+t:t};Ue.toFraction=function(e){var r,t,n,a,i,u,l,c,o,s,m,d,h=this,x=h.d,v=h.constructor;if(!x)return new v(h);if(o=t=new v(1),n=c=new v(0),r=new v(n),i=r.e=FM(x)-h.e-1,u=i%br,r.d[0]=nn(10,u<0?br+u:u),e==null)e=i>0?r:o;else{if(l=new v(e),!l.isInt()||l.lt(o))throw Error(Io+l);e=l.gt(r)?i>0?r:o:l}for(Cr=!1,l=new v(xn(x)),s=v.precision,v.precision=i=x.length*br*2;m=Dt(l,r,0,1,1),a=t.plus(m.times(n)),a.cmp(e)!=1;)t=n,n=a,a=o,o=c.plus(m.times(a)),c=a,a=r,r=l.minus(m.times(a)),l=a;return a=Dt(e.minus(t),n,0,1,1),c=c.plus(a.times(o)),t=t.plus(a.times(n)),c.s=o.s=h.s,d=Dt(o,n,i,1).minus(h).abs().cmp(Dt(c,t,i,1).minus(h).abs())<1?[o,n]:[c,t],v.precision=s,Cr=!0,d};Ue.toHexadecimal=Ue.toHex=function(e,r){return cw(this,16,e,r)};Ue.toNearest=function(e,r){var t=this,n=t.constructor;if(t=new n(t),e==null){if(!t.d)return t;e=new n(1),r=n.rounding}else{if(e=new n(e),r===void 0?r=n.rounding:Jn(r,0,8),!t.d)return e.s?t:e;if(!e.d)return e.s&&(e.s=t.s),e}return e.d[0]?(Cr=!1,t=Dt(t,e,0,r,1).times(e),Cr=!0,hr(t)):(e.s=t.s,t=e),t};Ue.toNumber=function(){return+this};Ue.toOctal=function(e,r){return cw(this,8,e,r)};Ue.toPower=Ue.pow=function(e){var r,t,n,a,i,u,l=this,c=l.constructor,o=+(e=new c(e));if(!l.d||!e.d||!l.d[0]||!e.d[0])return new c(nn(+l,o));if(l=new c(l),l.eq(1))return l;if(n=c.precision,i=c.rounding,e.eq(1))return hr(l,n,i);if(r=Nn(e.e/br),r>=e.d.length-1&&(t=o<0?-o:o)<=pL)return a=_M(c,l,t,n),e.s<0?new c(1).div(a):hr(a,n,i);if(u=l.s,u<0){if(rc.maxE+1||r0?u/0:0):(Cr=!1,c.rounding=l.s=1,t=Math.min(12,(r+"").length),a=uw(e.times(Po(l,n+t)),n),a.d&&(a=hr(a,n+5,1),Tc(a.d,n,i)&&(r=n+10,a=hr(uw(e.times(Po(l,r+t)),r),r+5,1),+xn(a.d).slice(n+1,n+15)+1==1e14&&(a=hr(a,n+1,0)))),a.s=u,Cr=!0,c.rounding=i,hr(a,n,i))};Ue.toPrecision=function(e,r){var t,n=this,a=n.constructor;return e===void 0?t=Ti(n,n.e<=a.toExpNeg||n.e>=a.toExpPos):(Jn(e,1,Ro),r===void 0?r=a.rounding:Jn(r,0,8),n=hr(new a(n),e,r),t=Ti(n,e<=n.e||n.e<=a.toExpNeg,e)),n.isNeg()&&!n.isZero()?"-"+t:t};Ue.toSignificantDigits=Ue.toSD=function(e,r){var t=this,n=t.constructor;return e===void 0?(e=n.precision,r=n.rounding):(Jn(e,1,Ro),r===void 0?r=n.rounding:Jn(r,0,8)),hr(new n(t),e,r)};Ue.toString=function(){var e=this,r=e.constructor,t=Ti(e,e.e<=r.toExpNeg||e.e>=r.toExpPos);return e.isNeg()&&!e.isZero()?"-"+t:t};Ue.truncated=Ue.trunc=function(){return hr(new this.constructor(this),this.e+1,1)};Ue.valueOf=Ue.toJSON=function(){var e=this,r=e.constructor,t=Ti(e,e.e<=r.toExpNeg||e.e>=r.toExpPos);return e.isNeg()?"-"+t:t};function xn(e){var r,t,n,a=e.length-1,i="",u=e[0];if(a>0){for(i+=u,r=1;rt)throw Error(Io+e)}function Tc(e,r,t,n){var a,i,u,l;for(i=e[0];i>=10;i/=10)--r;return--r<0?(r+=br,a=0):(a=Math.ceil((r+1)/br),r%=br),i=nn(10,br-r),l=e[a]%i|0,n==null?r<3?(r==0?l=l/100|0:r==1&&(l=l/10|0),u=t<4&&l==99999||t>3&&l==49999||l==5e4||l==0):u=(t<4&&l+1==i||t>3&&l+1==i/2)&&(e[a+1]/i/100|0)==nn(10,r-2)-1||(l==i/2||l==0)&&(e[a+1]/i/100|0)==0:r<4?(r==0?l=l/1e3|0:r==1?l=l/100|0:r==2&&(l=l/10|0),u=(n||t<4)&&l==9999||!n&&t>3&&l==4999):u=((n||t<4)&&l+1==i||!n&&t>3&&l+1==i/2)&&(e[a+1]/i/1e3|0)==nn(10,r-3)-1,u}function km(e,r,t){for(var n,a=[0],i,u=0,l=e.length;ut-1&&(a[n+1]===void 0&&(a[n+1]=0),a[n+1]+=a[n]/t|0,a[n]%=t)}return a.reverse()}function hL(e,r){var t,n,a;if(r.isZero())return r;n=r.d.length,n<32?(t=Math.ceil(n/3),a=(1/Ym(4,t)).toString()):(t=16,a="2.3283064365386962890625e-10"),e.precision+=t,r=Fu(e,1,r.times(a),new e(1));for(var i=t;i--;){var u=r.times(r);r=u.times(u).minus(u).times(8).plus(1)}return e.precision-=t,r}var Dt=function(){function e(n,a,i){var u,l=0,c=n.length;for(n=n.slice();c--;)u=n[c]*a+l,n[c]=u%i|0,l=u/i|0;return l&&n.unshift(l),n}function r(n,a,i,u){var l,c;if(i!=u)c=i>u?1:-1;else for(l=c=0;la[l]?1:-1;break}return c}function t(n,a,i,u){for(var l=0;i--;)n[i]-=l,l=n[i]1;)n.shift()}return function(n,a,i,u,l,c){var o,s,m,d,h,x,v,y,w,C,b,M,A,S,O,_,E,T,R,q,W=n.constructor,G=n.s==a.s?1:-1,H=n.d,L=a.d;if(!H||!H[0]||!L||!L[0])return new W(!n.s||!a.s||(H?L&&H[0]==L[0]:!L)?NaN:H&&H[0]==0||!L?G*0:G/0);for(c?(h=1,s=n.e-a.e):(c=si,h=br,s=Nn(n.e/h)-Nn(a.e/h)),R=L.length,E=H.length,w=new W(G),C=w.d=[],m=0;L[m]==(H[m]||0);m++);if(L[m]>(H[m]||0)&&s--,i==null?(S=i=W.precision,u=W.rounding):l?S=i+(n.e-a.e)+1:S=i,S<0)C.push(1),x=!0;else{if(S=S/h+2|0,m=0,R==1){for(d=0,L=L[0],S++;(m1&&(L=e(L,d,c),H=e(H,d,c),R=L.length,E=H.length),_=R,b=H.slice(0,R),M=b.length;M=c/2&&++T;do d=0,o=r(L,b,R,M),o<0?(A=b[0],R!=M&&(A=A*c+(b[1]||0)),d=A/T|0,d>1?(d>=c&&(d=c-1),v=e(L,d,c),y=v.length,M=b.length,o=r(v,b,y,M),o==1&&(d--,t(v,R=10;d/=10)m++;w.e=m+s*h-1,hr(w,l?i+w.e+1:i,u,x)}return w}}();function hr(e,r,t,n){var a,i,u,l,c,o,s,m,d,h=e.constructor;e:if(r!=null){if(m=e.d,!m)return e;for(a=1,l=m[0];l>=10;l/=10)a++;if(i=r-a,i<0)i+=br,u=r,s=m[d=0],c=s/nn(10,a-u-1)%10|0;else if(d=Math.ceil((i+1)/br),l=m.length,d>=l)if(n){for(;l++<=d;)m.push(0);s=c=0,a=1,i%=br,u=i-br+1}else break e;else{for(s=l=m[d],a=1;l>=10;l/=10)a++;i%=br,u=i-br+a,c=u<0?0:s/nn(10,a-u-1)%10|0}if(n=n||r<0||m[d+1]!==void 0||(u<0?s:s%nn(10,a-u-1)),o=t<4?(c||n)&&(t==0||t==(e.s<0?3:2)):c>5||c==5&&(t==4||n||t==6&&(i>0?u>0?s/nn(10,a-u):0:m[d-1])%10&1||t==(e.s<0?8:7)),r<1||!m[0])return m.length=0,o?(r-=e.e+1,m[0]=nn(10,(br-r%br)%br),e.e=-r||0):m[0]=e.e=0,e;if(i==0?(m.length=d,l=1,d--):(m.length=d+1,l=nn(10,br-i),m[d]=u>0?(s/nn(10,a-u)%nn(10,u)|0)*l:0),o)for(;;)if(d==0){for(i=1,u=m[0];u>=10;u/=10)i++;for(u=m[0]+=l,l=1;u>=10;u/=10)l++;i!=l&&(e.e++,m[0]==si&&(m[0]=1));break}else{if(m[d]+=l,m[d]!=si)break;m[d--]=0,l=1}for(i=m.length;m[--i]===0;)m.pop()}return Cr&&(e.e>h.maxE?(e.d=null,e.e=NaN):e.e0?i=i.charAt(0)+"."+i.slice(1)+Bo(n):u>1&&(i=i.charAt(0)+"."+i.slice(1)),i=i+(e.e<0?"e":"e+")+e.e):a<0?(i="0."+Bo(-a-1)+i,t&&(n=t-u)>0&&(i+=Bo(n))):a>=u?(i+=Bo(a+1-u),t&&(n=t-a-1)>0&&(i=i+"."+Bo(n))):((n=a+1)0&&(a+1===u&&(i+="."),i+=Bo(n))),i}function Wm(e,r){var t=e[0];for(r*=br;t>=10;t/=10)r++;return r}function zm(e,r,t){if(r>dL)throw Cr=!0,t&&(e.precision=t),Error(MM);return hr(new e(qm),r,1,!0)}function oi(e,r,t){if(r>sw)throw Error(MM);return hr(new e(Lm),r,t,!0)}function FM(e){var r=e.length-1,t=r*br+1;if(r=e[r],r){for(;r%10==0;r/=10)t--;for(r=e[0];r>=10;r/=10)t++}return t}function Bo(e){for(var r="";e--;)r+="0";return r}function _M(e,r,t,n){var a,i=new e(1),u=Math.ceil(n/br+4);for(Cr=!1;;){if(t%2&&(i=i.times(r),SM(i.d,u)&&(a=!0)),t=Nn(t/2),t===0){t=i.d.length-1,a&&i.d[t]===0&&++i.d[t];break}r=r.times(r),SM(r.d,u)}return Cr=!0,i}function DM(e){return e.d[e.d.length-1]&1}function OM(e,r,t){for(var n,a=new e(r[0]),i=0;++i17)return new d(e.d?e.d[0]?e.s<0?0:1/0:1:e.s?e.s<0?0:e:0/0);for(r==null?(Cr=!1,c=x):c=r,l=new d(.03125);e.e>-2;)e=e.times(l),m+=5;for(n=Math.log(nn(2,m))/Math.LN10*2+5|0,c+=n,t=i=u=new d(1),d.precision=c;;){if(i=hr(i.times(e),c,1),t=t.times(++s),l=u.plus(Dt(i,t,c,1)),xn(l.d).slice(0,c)===xn(u.d).slice(0,c)){for(a=m;a--;)u=hr(u.times(u),c,1);if(r==null)if(o<3&&Tc(u.d,c-n,h,o))d.precision=c+=10,t=i=l=new d(1),s=0,o++;else return hr(u,d.precision=x,h,Cr=!0);else return d.precision=x,u}u=l}}function Po(e,r){var t,n,a,i,u,l,c,o,s,m,d,h=1,x=10,v=e,y=v.d,w=v.constructor,C=w.rounding,b=w.precision;if(v.s<0||!y||!y[0]||!v.e&&y[0]==1&&y.length==1)return new w(y&&!y[0]?-1/0:v.s!=1?NaN:y?0:v);if(r==null?(Cr=!1,s=b):s=r,w.precision=s+=x,t=xn(y),n=t.charAt(0),Math.abs(i=v.e)<15e14){for(;n<7&&n!=1||n==1&&t.charAt(1)>3;)v=v.times(e),t=xn(v.d),n=t.charAt(0),h++;i=v.e,n>1?(v=new w("0."+t),i++):v=new w(n+"."+t.slice(1))}else return o=zm(w,s+2,b).times(i+""),v=Po(new w(n+"."+t.slice(1)),s-x).plus(o),w.precision=b,r==null?hr(v,b,C,Cr=!0):v;for(m=v,c=u=v=Dt(v.minus(1),v.plus(1),s,1),d=hr(v.times(v),s,1),a=3;;){if(u=hr(u.times(d),s,1),o=c.plus(Dt(u,new w(a),s,1)),xn(o.d).slice(0,s)===xn(c.d).slice(0,s))if(c=c.times(2),i!==0&&(c=c.plus(zm(w,s+2,b).times(i+""))),c=Dt(c,new w(h),s,1),r==null)if(Tc(c.d,s-x,C,l))w.precision=s+=x,o=u=v=Dt(m.minus(1),m.plus(1),s,1),d=hr(v.times(v),s,1),a=l=1;else return hr(c,w.precision=b,C,Cr=!0);else return w.precision=b,c;c=o,a+=2}}function BM(e){return String(e.s*e.s/0)}function fw(e,r){var t,n,a;for((t=r.indexOf("."))>-1&&(r=r.replace(".","")),(n=r.search(/e/i))>0?(t<0&&(t=n),t+=+r.slice(n+1),r=r.substring(0,n)):t<0&&(t=r.length),n=0;r.charCodeAt(n)===48;n++);for(a=r.length;r.charCodeAt(a-1)===48;--a);if(r=r.slice(n,a),r){if(a-=n,e.e=t=t-n-1,e.d=[],n=(t+1)%br,t<0&&(n+=br),ne.constructor.maxE?(e.d=null,e.e=NaN):e.e-1){if(r=r.replace(/(\\d)_(?=\\d)/g,"$1"),TM.test(r))return fw(e,r)}else if(r==="Infinity"||r==="NaN")return+r||(e.s=NaN),e.e=NaN,e.d=null,e;if(lL.test(r))t=16,r=r.toLowerCase();else if(cL.test(r))t=2;else if(mL.test(r))t=8;else throw Error(Io+r);for(i=r.search(/p/i),i>0?(c=+r.slice(i+1),r=r.substring(2,i)):r=r.slice(2),i=r.indexOf("."),u=i>=0,n=e.constructor,u&&(r=r.replace(".",""),l=r.length,i=l-i,a=_M(n,new n(t),i,i*2)),o=km(r,t,si),s=o.length-1,i=s;o[i]===0;--i)o.pop();return i<0?new n(e.s*0):(e.e=Wm(o,s),e.d=o,Cr=!1,u&&(e=Dt(e,a,l*4)),c&&(e=e.times(Math.abs(c)<54?nn(2,c):Fc.pow(2,c))),Cr=!0,e)}function gL(e,r){var t,n=r.d.length;if(n<3)return r.isZero()?r:Fu(e,2,r,r);t=1.4*Math.sqrt(n),t=t>16?16:t|0,r=r.times(1/Ym(5,t)),r=Fu(e,2,r,r);for(var a,i=new e(5),u=new e(16),l=new e(20);t--;)a=r.times(r),r=r.times(i.plus(a.times(u.times(a).minus(l))));return r}function Fu(e,r,t,n,a){var i,u,l,c,o=1,s=e.precision,m=Math.ceil(s/br);for(Cr=!1,c=t.times(t),l=new e(n);;){if(u=Dt(l.times(c),new e(r++*r++),s,1),l=a?n.plus(u):n.minus(u),n=Dt(u.times(c),new e(r++*r++),s,1),u=l.plus(n),u.d[m]!==void 0){for(i=m;u.d[i]===l.d[i]&&i--;);if(i==-1)break}i=l,l=n,n=u,u=i,o++}return Cr=!0,u.d.length=m+1,u}function Ym(e,r){for(var t=e;--r;)t*=e;return t}function PM(e,r){var t,n=r.s<0,a=oi(e,e.precision,1),i=a.times(.5);if(r=r.abs(),r.lte(i))return ji=n?4:1,r;if(t=r.divToInt(a),t.isZero())ji=n?3:2;else{if(r=r.minus(t.times(a)),r.lte(i))return ji=DM(t)?n?2:3:n?4:1,r;ji=DM(t)?n?1:4:n?3:2}return r.minus(a).abs()}function cw(e,r,t,n){var a,i,u,l,c,o,s,m,d,h=e.constructor,x=t!==void 0;if(x?(Jn(t,1,Ro),n===void 0?n=h.rounding:Jn(n,0,8)):(t=h.precision,n=h.rounding),!e.isFinite())s=BM(e);else{for(s=Ti(e),u=s.indexOf("."),x?(a=2,r==16?t=t*4-3:r==8&&(t=t*3-2)):a=r,u>=0&&(s=s.replace(".",""),d=new h(1),d.e=s.length-u,d.d=km(Ti(d),10,a),d.e=d.d.length),m=km(s,10,a),i=c=m.length;m[--c]==0;)m.pop();if(!m[0])s=x?"0p+0":"0";else{if(u<0?i--:(e=new h(e),e.d=m,e.e=i,e=Dt(e,d,t,n,0,a),m=e.d,i=e.e,o=AM),u=m[t],l=a/2,o=o||m[t+1]!==void 0,o=n<4?(u!==void 0||o)&&(n===0||n===(e.s<0?3:2)):u>l||u===l&&(n===4||o||n===6&&m[t-1]&1||n===(e.s<0?8:7)),m.length=t,o)for(;++m[--t]>a-1;)m[t]=0,t||(++i,m.unshift(1));for(c=m.length;!m[c-1];--c);for(u=0,s="";u1)if(r==16||r==8){for(u=r==16?4:3,--c;c%u;c++)s+="0";for(m=km(s,a,r),c=m.length;!m[c-1];--c);for(u=1,s="1.";uc)for(i-=c;i--;)s+="0";else ir)return e.length=r,!0}function xL(e){return new this(e).abs()}function yL(e){return new this(e).acos()}function bL(e){return new this(e).acosh()}function wL(e,r){return new this(e).plus(r)}function DL(e){return new this(e).asin()}function SL(e){return new this(e).asinh()}function NL(e){return new this(e).atan()}function AL(e){return new this(e).atanh()}function ML(e,r){e=new this(e),r=new this(r);var t,n=this.precision,a=this.rounding,i=n+4;return!e.s||!r.s?t=new this(NaN):!e.d&&!r.d?(t=oi(this,i,1).times(r.s>0?.25:.75),t.s=e.s):!r.d||e.isZero()?(t=r.s<0?oi(this,n,a):new this(0),t.s=e.s):!e.d||r.isZero()?(t=oi(this,i,1).times(.5),t.s=e.s):r.s<0?(this.precision=i,this.rounding=1,t=this.atan(Dt(e,r,i,1)),r=oi(this,i,1),this.precision=n,this.rounding=a,t=e.s<0?t.minus(r):t.plus(r)):t=this.atan(Dt(e,r,i,1)),t}function CL(e){return new this(e).cbrt()}function EL(e){return hr(e=new this(e),e.e+1,2)}function TL(e,r,t){return new this(e).clamp(r,t)}function FL(e){if(!e||typeof e!="object")throw Error(Um+"Object expected");var r,t,n,a=e.defaults===!0,i=["precision",1,Ro,"rounding",0,8,"toExpNeg",-Tu,0,"toExpPos",0,Tu,"maxE",0,Tu,"minE",-Tu,0,"modulo",0,9];for(r=0;r=i[r+1]&&n<=i[r+2])this[t]=n;else throw Error(Io+t+": "+n);if(t="crypto",a&&(this[t]=ow[t]),(n=e[t])!==void 0)if(n===!0||n===!1||n===0||n===1)if(n)if(typeof crypto<"u"&&crypto&&(crypto.getRandomValues||crypto.randomBytes))this[t]=!0;else throw Error(CM);else this[t]=!1;else throw Error(Io+t+": "+n);return this}function _L(e){return new this(e).cos()}function OL(e){return new this(e).cosh()}function IM(e){var r,t,n;function a(i){var u,l,c,o=this;if(!(o instanceof a))return new a(i);if(o.constructor=a,NM(i)){o.s=i.s,Cr?!i.d||i.e>a.maxE?(o.e=NaN,o.d=null):i.e=10;l/=10)u++;Cr?u>a.maxE?(o.e=NaN,o.d=null):u=429e7?r[i]=crypto.getRandomValues(new Uint32Array(1))[0]:l[i++]=a%1e7;else if(crypto.randomBytes){for(r=crypto.randomBytes(n*=4);i=214e7?crypto.randomBytes(4).copy(r,i):(l.push(a%1e7),i+=4);i=n/4}else throw Error(CM);else for(;i=10;a/=10)n++;n{var{on:r,config:t}=e,n=Cs.clone({precision:t.precision,modulo:Cs.EUCLID});return n.prototype=Object.create(n.prototype),n.prototype.type="BigNumber",n.prototype.isBigNumber=!0,n.prototype.toJSON=function(){return{mathjs:"BigNumber",value:this.toString()}},n.fromJSON=function(a){return new n(a.value)},r&&r("config",function(a,i){a.precision!==i.precision&&n.config({precision:a.precision})}),n},{isClass:!0});var fn=ca(kM(),1);var iz="Complex",oz=[],$m=F(iz,oz,()=>(Object.defineProperty(fn.default,"name",{value:"Complex"}),fn.default.prototype.constructor=fn.default,fn.default.prototype.type="Complex",fn.default.prototype.isComplex=!0,fn.default.prototype.toJSON=function(){return{mathjs:"Complex",re:this.re,im:this.im}},fn.default.prototype.toPolar=function(){return{r:this.abs(),phi:this.arg()}},fn.default.prototype.format=function(e){var r="",t=this.im,n=this.re,a=ai(this.re,e),i=ai(this.im,e),u=sr(e)?e:e?e.precision:null;if(u!==null){var l=Math.pow(10,-u);Math.abs(n/t)r.re?1:e.rer.im?1:e.im(Object.defineProperty(Fi.default,"name",{value:"Fraction"}),Fi.default.prototype.constructor=Fi.default,Fi.default.prototype.type="Fraction",Fi.default.prototype.isFraction=!0,Fi.default.prototype.toJSON=function(){return{mathjs:"Fraction",n:this.s*this.n,d:this.d}},Fi.default.fromJSON=function(e){return new Fi.default(e)},Fi.default),{isClass:!0});var fz="Range",cz=[],Vm=F(fz,cz,()=>{function e(r,t,n){if(!(this instanceof e))throw new SyntaxError("Constructor must be called with the new operator");var a=r!=null,i=t!=null,u=n!=null;if(a){if(rr(r))r=r.toNumber();else if(typeof r!="number")throw new TypeError("Parameter start must be a number")}if(i){if(rr(t))t=t.toNumber();else if(typeof t!="number")throw new TypeError("Parameter end must be a number")}if(u){if(rr(n))n=n.toNumber();else if(typeof n!="number")throw new TypeError("Parameter step must be a number")}this.start=a?parseFloat(r):0,this.end=i?parseFloat(t):0,this.step=u?parseFloat(n):1}return e.prototype.type="Range",e.prototype.isRange=!0,e.parse=function(r){if(typeof r!="string")return null;var t=r.split(":"),n=t.map(function(i){return parseFloat(i)}),a=n.some(function(i){return isNaN(i)});if(a)return null;switch(n.length){case 2:return new e(n[0],n[1]);case 3:return new e(n[0],n[2],n[1]);default:return null}},e.prototype.clone=function(){return new e(this.start,this.end,this.step)},e.prototype.size=function(){var r=0,t=this.start,n=this.step,a=this.end,i=a-t;return Oa(n)===Oa(i)?r=Math.ceil(i/n):i===0&&(r=0),isNaN(r)&&(r=0),[r]},e.prototype.min=function(){var r=this.size()[0];if(r>0)return this.step>0?this.start:this.start+(r-1)*this.step},e.prototype.max=function(){var r=this.size()[0];if(r>0)return this.step>0?this.start+(r-1)*this.step:this.start},e.prototype.forEach=function(r){var t=this.start,n=this.step,a=this.end,i=0;if(n>0)for(;ta;)r(t,[i],this),t+=n,i++},e.prototype.map=function(r){var t=[];return this.forEach(function(n,a,i){t[a[0]]=r(n,a,i)}),t},e.prototype.toArray=function(){var r=[];return this.forEach(function(t,n){r[n[0]]=t}),r},e.prototype.valueOf=function(){return this.toArray()},e.prototype.format=function(r){var t=ai(this.start,r);return this.step!==1&&(t+=":"+ai(this.step,r)),t+=":"+ai(this.end,r),t},e.prototype.toString=function(){return this.format()},e.prototype.toJSON=function(){return{mathjs:"Range",start:this.start,end:this.end,step:this.step}},e.fromJSON=function(r){return new e(r.start,r.end,r.step)},e},{isClass:!0});var lz="Matrix",mz=[],Zm=F(lz,mz,()=>{function e(){if(!(this instanceof e))throw new SyntaxError("Constructor must be called with the new operator")}return e.prototype.type="Matrix",e.prototype.isMatrix=!0,e.prototype.storage=function(){throw new Error("Cannot invoke storage on a Matrix interface")},e.prototype.datatype=function(){throw new Error("Cannot invoke datatype on a Matrix interface")},e.prototype.create=function(r,t){throw new Error("Cannot invoke create on a Matrix interface")},e.prototype.subset=function(r,t,n){throw new Error("Cannot invoke subset on a Matrix interface")},e.prototype.get=function(r){throw new Error("Cannot invoke get on a Matrix interface")},e.prototype.set=function(r,t,n){throw new Error("Cannot invoke set on a Matrix interface")},e.prototype.resize=function(r,t){throw new Error("Cannot invoke resize on a Matrix interface")},e.prototype.reshape=function(r,t){throw new Error("Cannot invoke reshape on a Matrix interface")},e.prototype.clone=function(){throw new Error("Cannot invoke clone on a Matrix interface")},e.prototype.size=function(){throw new Error("Cannot invoke size on a Matrix interface")},e.prototype.map=function(r,t){throw new Error("Cannot invoke map on a Matrix interface")},e.prototype.forEach=function(r){throw new Error("Cannot invoke forEach on a Matrix interface")},e.prototype[Symbol.iterator]=function(){throw new Error("Cannot iterate a Matrix interface")},e.prototype.toArray=function(){throw new Error("Cannot invoke toArray on a Matrix interface")},e.prototype.valueOf=function(){throw new Error("Cannot invoke valueOf on a Matrix interface")},e.prototype.format=function(r){throw new Error("Cannot invoke format on a Matrix interface")},e.prototype.toString=function(){throw new Error("Cannot invoke toString on a Matrix interface")},e},{isClass:!0});function zM(e){var r=0,t=1,n=Object.create(null),a=Object.create(null),i=0,u=function(c){var o=a[c];if(!!o&&(delete n[o],delete a[c],--r,t===o)){if(!r){i=0,t=1;return}for(;!Object.prototype.hasOwnProperty.call(n,++t););}};return e=Math.abs(e),{hit:function(c){var o=a[c],s=++i;if(n[s]=c,a[c]=s,!o)return++r,r<=e?void 0:(c=n[t],u(c),c);if(delete n[o],t===o)for(;!Object.prototype.hasOwnProperty.call(n,++t););},delete:u,clear:function(){r=i=0,t=1,n=Object.create(null),a=Object.create(null)}}}function Es(e){var{hasher:r,limit:t}=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};return t=t??Number.POSITIVE_INFINITY,r=r??JSON.stringify,function n(){typeof n.cache!="object"&&(n.cache={values:new Map,lru:zM(t||Number.POSITIVE_INFINITY)});for(var a=[],i=0;i{var{Matrix:r}=e;function t(s,m){if(!(this instanceof t))throw new SyntaxError("Constructor must be called with the new operator");if(m&&!St(m))throw new Error("Invalid datatype: "+m);if(Qe(s))s.type==="DenseMatrix"?(this._data=ar(s._data),this._size=ar(s._size),this._datatype=m||s._datatype):(this._data=s.toArray(),this._size=s.size(),this._datatype=m||s._datatype);else if(s&&Mr(s.data)&&Mr(s.size))this._data=s.data,this._size=s.size,Qb(this._data,this._size),this._datatype=m||s.datatype;else if(Mr(s))this._data=o(s),this._size=ur(this._data),Qb(this._data,this._size),this._datatype=m;else{if(s)throw new TypeError("Unsupported type of data ("+Fr(s)+")");this._data=[],this._size=[0],this._datatype=m}}t.prototype=new r,t.prototype.createDenseMatrix=function(s,m){return new t(s,m)},Object.defineProperty(t,"name",{value:"DenseMatrix"}),t.prototype.constructor=t,t.prototype.type="DenseMatrix",t.prototype.isDenseMatrix=!0,t.prototype.getDataType=function(){return _o(this._data,Fr)},t.prototype.storage=function(){return"dense"},t.prototype.datatype=function(){return this._datatype},t.prototype.create=function(s,m){return new t(s,m)},t.prototype.subset=function(s,m,d){switch(arguments.length){case 1:return n(this,s);case 2:case 3:return i(this,s,m,d);default:throw new SyntaxError("Wrong number of arguments")}},t.prototype.get=function(s){if(!Mr(s))throw new TypeError("Array expected");if(s.length!==this._size.length)throw new pr(s.length,this._size.length);for(var m=0;m");var b=m.max().map(function(S){return S+1});c(s,b,h);var M=x.length,A=0;u(s._data,m,d,M,A)}return s}function u(s,m,d,h,x){var v=x===h-1,y=m.dimension(x);v?y.forEach(function(w,C){Kr(w),s[w]=d[C[0]]}):y.forEach(function(w,C){Kr(w),u(s[w],m,d[C[0]],h,x+1)})}t.prototype.resize=function(s,m,d){if(!Nt(s))throw new TypeError("Array or Matrix expected");var h=s.valueOf().map(v=>Array.isArray(v)&&v.length===1?v[0]:v),x=d?this.clone():this;return l(x,h,m)};function l(s,m,d){if(m.length===0){for(var h=s._data;Mr(h);)h=h[0];return h}return s._size=m.slice(0),s._data=ii(s._data,s._size,d),s}t.prototype.reshape=function(s,m){var d=m?this.clone():this;d._data=Mc(d._data,s);var h=d._size.reduce((x,v)=>x*v);return d._size=Cc(s,h),d};function c(s,m,d){for(var h=s._size.slice(0),x=!1;h.lengthh[v]&&(h[v]=m[v],x=!0);x&&l(s,h,d)}t.prototype.clone=function(){var s=new t({data:ar(this._data),size:ar(this._size),datatype:this._datatype});return s},t.prototype.size=function(){return this._size.slice(0)},t.prototype.map=function(s){var m=this,d=Qm(s),h=function y(w,C){return Mr(w)?w.map(function(b,M){return y(b,C.concat(M))}):d===1?s(w):d===2?s(w,C):s(w,C,m)},x=h(this._data,[]),v=this._datatype!==void 0?_o(x,Fr):void 0;return new t(x,v)},t.prototype.forEach=function(s){var m=this,d=function h(x,v){Mr(x)?x.forEach(function(y,w){h(y,v.concat(w))}):s(x,v,m)};d(this._data,[])},t.prototype[Symbol.iterator]=function*(){var s=function*m(d,h){if(Mr(d))for(var x=0;x[b[w]]);m.push(new t(C,s._datatype))},v=0;v0?s:0,d=s<0?-s:0,h=this._size[0],x=this._size[1],v=Math.min(h-d,x-m),y=[],w=0;w0?d:0,v=d<0?-d:0,y=s[0],w=s[1],C=Math.min(y-v,w-x),b;if(Mr(m)){if(m.length!==C)throw new Error("Invalid value array length");b=function(_){return m[_]}}else if(Qe(m)){var M=m.size();if(M.length!==1||M[0]!==C)throw new Error("Invalid matrix length");b=function(_){return m.get([_])}}else b=function(){return m};h||(h=rr(b(0))?b(0).mul(0):0);var A=[];if(s.length>0){A=ii(A,s,h);for(var S=0;S{var{typed:r}=e;return r(UM,{any:ar})});function Km(e){var r=e.length,t=e[0].length,n,a,i=[];for(a=0;a=n.length)throw new tn(r,n.length);return Qe(e)?e.create(jm(e.valueOf(),r,t)):jm(e,r,t)}function jm(e,r,t){var n,a,i,u;if(r<=0)if(Array.isArray(e[0])){for(u=Km(e),a=[],n=0;n{var{typed:r}=e;return r(WM,{number:Ze,BigNumber:function(n){return n.isInt()},Fraction:function(n){return n.d===1&&isFinite(n.n)},"Array | Matrix":r.referToSelf(t=>n=>je(n,t))})});var Kn="number",eo="number, number";function dw(e){return Math.abs(e)}dw.signature=Kn;function hw(e,r){return e+r}hw.signature=eo;function vw(e,r){return e-r}vw.signature=eo;function gw(e,r){return e*r}gw.signature=eo;function gz(e,r){return e/r}gz.signature=eo;function xw(e){return-e}xw.signature=Kn;function yw(e){return e}yw.signature=Kn;function _u(e){return QA(e)}_u.signature=Kn;function bw(e){return e*e*e}bw.signature=Kn;function ww(e){return Math.exp(e)}ww.signature=Kn;function Dw(e){return XA(e)}Dw.signature=Kn;function xz(e,r){if(!Ze(e)||!Ze(r))throw new Error("Parameters in function gcd must be integer numbers");for(var t;r!==0;)t=e%r,e=r,r=t;return e<0?-e:e}xz.signature=eo;function Sw(e,r){if(!Ze(e)||!Ze(r))throw new Error("Parameters in function lcm must be integer numbers");if(e===0||r===0)return 0;for(var t,n=e*r;r!==0;)t=r,r=e%t,e=t;return Math.abs(n/e)}Sw.signature=eo;function YM(e,r){return r?Math.log(e)/Math.log(r):Math.log(e)}function Nw(e){return ZA(e)}Nw.signature=Kn;function Aw(e){return VA(e)}Aw.signature=Kn;function yz(e){return Mm(e)}yz.signature=Kn;function bz(e,r){return r===0?e:e-r*Math.floor(e/r)}bz.signature=eo;function Mw(e){var r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:2,t=r<0;if(t&&(r=-r),r===0)throw new Error("Root must be non-zero");if(e<0&&Math.abs(r)%2!==1)throw new Error("Root must be odd when a is negative.");if(e===0)return t?1/0:0;if(!isFinite(e))return t?0:e;var n=Math.pow(Math.abs(e),1/r);return n=e<0?-n:n,t?1/n:n}function rp(e){return Oa(e)}rp.signature=Kn;function wz(e){return Math.sqrt(e)}wz.signature=Kn;function Cw(e){return e*e}Cw.signature=Kn;function Ew(e,r){var t,n,a,i=0,u=1,l=1,c=0;if(!Ze(e)||!Ze(r))throw new Error("Parameters in function xgcd must be integer numbers");for(;r;)n=Math.floor(e/r),a=e-n*r,t=i,i=u-n*i,u=t,t=l,l=c-n*l,c=t,e=r,r=a;var o;return e<0?o=[-e,-u,-c]:o=[e,e?u:0,c],o}Ew.signature=eo;function Tw(e,r){return e*e<1&&r===1/0||e*e>1&&r===-1/0?0:Math.pow(e,r)}Tw.signature=eo;function Ou(e){var r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:0;if(!Ze(r)||r<0||r>15)throw new Error("Number of decimals in function round must be an integer from 0 to 15 inclusive");return parseFloat(Gb(e,r))}function Dz(e){return Math.abs(e)}Dz.signature=Kn;var Sz="number",Bu="number, number";function Fw(e,r){if(!Ze(e)||!Ze(r))throw new Error("Integers expected in function bitAnd");return e&r}Fw.signature=Bu;function _w(e){if(!Ze(e))throw new Error("Integer expected in function bitNot");return~e}_w.signature=Sz;function Ow(e,r){if(!Ze(e)||!Ze(r))throw new Error("Integers expected in function bitOr");return e|r}Ow.signature=Bu;function Bw(e,r){if(!Ze(e)||!Ze(r))throw new Error("Integers expected in function bitXor");return e^r}Bw.signature=Bu;function Pw(e,r){if(!Ze(e)||!Ze(r))throw new Error("Integers expected in function leftShift");return e<>r}Iw.signature=Bu;function Rw(e,r){if(!Ze(e)||!Ze(r))throw new Error("Integers expected in function rightLogShift");return e>>>r}Rw.signature=Bu;function da(e,r){if(r>1;return da(e,t)*da(t+1,r)}function kw(e,r){if(!Ze(e)||e<0)throw new TypeError("Positive integer value expected in function combinations");if(!Ze(r)||r<0)throw new TypeError("Positive integer value expected in function combinations");if(r>e)throw new TypeError("k must be less than or equal to n");for(var t=e-r,n=1,a=r171?1/0:da(1,e-1);if(e<.5)return Math.PI/(Math.sin(Math.PI*e)*_c(1-e));if(e>=171.35)return 1/0;if(e>85){var t=e*e,n=t*e,a=n*e,i=a*e;return Math.sqrt(2*Math.PI/e)*Math.pow(e/Math.E,e)*(1+1/(12*e)+1/(288*t)-139/(51840*n)-571/(2488320*a)+163879/(209018880*i)+5246819/(75246796800*i*e))}--e,r=Ts[0];for(var u=1;u=1;n--)t+=ZM[n]/(e+n);return Hw+(e+.5)*Math.log(r)-r+Math.log(t)}Oc.signature="number";var Ct="number",Cz="number, number";function Ez(e){return Math.acos(e)}Ez.signature=Ct;function $w(e){return jA(e)}$w.signature=Ct;function Gw(e){return Math.atan(1/e)}Gw.signature=Ct;function Vw(e){return isFinite(e)?(Math.log((e+1)/e)+Math.log(e/(e-1)))/2:0}Vw.signature=Ct;function Zw(e){return Math.asin(1/e)}Zw.signature=Ct;function Qw(e){var r=1/e;return Math.log(r+Math.sqrt(r*r+1))}Qw.signature=Ct;function Xw(e){return Math.acos(1/e)}Xw.signature=Ct;function Jw(e){var r=1/e,t=Math.sqrt(r*r-1);return Math.log(t+r)}Jw.signature=Ct;function Tz(e){return Math.asin(e)}Tz.signature=Ct;function Kw(e){return eM(e)}Kw.signature=Ct;function Fz(e){return Math.atan(e)}Fz.signature=Ct;function _z(e,r){return Math.atan2(e,r)}_z.signature=Cz;function jw(e){return rM(e)}jw.signature=Ct;function Oz(e){return Math.cos(e)}Oz.signature=Ct;function Bz(e){return Em(e)}Bz.signature=Ct;function eD(e){return 1/Math.tan(e)}eD.signature=Ct;function rD(e){var r=Math.exp(2*e);return(r+1)/(r-1)}rD.signature=Ct;function tD(e){return 1/Math.sin(e)}tD.signature=Ct;function nD(e){return e===0?Number.POSITIVE_INFINITY:Math.abs(2/(Math.exp(e)-Math.exp(-e)))*Oa(e)}nD.signature=Ct;function aD(e){return 1/Math.cos(e)}aD.signature=Ct;function iD(e){return 2/(Math.exp(e)+Math.exp(-e))}iD.signature=Ct;function Pz(e){return Math.sin(e)}Pz.signature=Ct;function oD(e){return tM(e)}oD.signature=Ct;function Iz(e){return Math.tan(e)}Iz.signature=Ct;function Rz(e){return Tm(e)}Rz.signature=Ct;var Bc="number";function kz(e){return Ze(e)}kz.signature=Bc;function sD(e){return e<0}sD.signature=Bc;function uD(e){return e>0}uD.signature=Bc;function fD(e){return e===0}fD.signature=Bc;function cD(e){return Number.isNaN(e)}cD.signature=Bc;var QM="isNegative",qz=["typed"],tp=F(QM,qz,e=>{var{typed:r}=e;return r(QM,{number:sD,BigNumber:function(n){return n.isNeg()&&!n.isZero()&&!n.isNaN()},Fraction:function(n){return n.s<0},Unit:r.referToSelf(t=>n=>r.find(t,n.valueType())(n.value)),"Array | Matrix":r.referToSelf(t=>n=>je(n,t))})});var XM="isNumeric",Lz=["typed"],np=F(XM,Lz,e=>{var{typed:r}=e;return r(XM,{"number | BigNumber | Fraction | boolean":()=>!0,"Complex | Unit | string | null | undefined | Node":()=>!1,"Array | Matrix":r.referToSelf(t=>n=>je(n,t))})});var JM="hasNumericValue",zz=["typed","isNumeric"],ap=F(JM,zz,e=>{var{typed:r,isNumeric:t}=e;return r(JM,{boolean:()=>!0,string:function(a){return a.trim().length>0&&!isNaN(Number(a))},any:function(a){return t(a)}})});var KM="isPositive",Uz=["typed"],ip=F(KM,Uz,e=>{var{typed:r}=e;return r(KM,{number:uD,BigNumber:function(n){return!n.isNeg()&&!n.isZero()&&!n.isNaN()},Fraction:function(n){return n.s>0&&n.n>0},Unit:r.referToSelf(t=>n=>r.find(t,n.valueType())(n.value)),"Array | Matrix":r.referToSelf(t=>n=>je(n,t))})});var jM="isZero",Wz=["typed"],op=F(jM,Wz,e=>{var{typed:r}=e;return r(jM,{number:fD,BigNumber:function(n){return n.isZero()},Complex:function(n){return n.re===0&&n.im===0},Fraction:function(n){return n.d===1&&n.n===0},Unit:r.referToSelf(t=>n=>r.find(t,n.valueType())(n.value)),"Array | Matrix":r.referToSelf(t=>n=>je(n,t))})});var e2="isNaN",Yz=["typed"],sp=F(e2,Yz,e=>{var{typed:r}=e;return r(e2,{number:cD,BigNumber:function(n){return n.isNaN()},Fraction:function(n){return!1},Complex:function(n){return n.isNaN()},Unit:function(n){return Number.isNaN(n.value)},"Array | Matrix":function(n){return je(n,Number.isNaN)}})});var r2="typeOf",Hz=["typed"],up=F(r2,Hz,e=>{var{typed:r}=e;return r(r2,{any:Fr})});function $t(e,r,t){if(t==null)return e.eq(r);if(e.eq(r))return!0;if(e.isNaN()||r.isNaN())return!1;if(e.isFinite()&&r.isFinite()){var n=e.minus(r).abs();if(n.isZero())return!0;var a=e.constructor.max(e.abs(),r.abs());return n.lte(a.times(t))}return!1}function t2(e,r,t){return At(e.re,r.re,t)&&At(e.im,r.im,t)}var Pa=F("compareUnits",["typed"],e=>{var{typed:r}=e;return{"Unit, Unit":r.referToSelf(t=>(n,a)=>{if(!n.equalBase(a))throw new Error("Cannot compare units with different base");return r.find(t,[n.valueType(),a.valueType()])(n.value,a.value)})}});var fp="equalScalar",$z=["typed","config"],cp=F(fp,$z,e=>{var{typed:r,config:t}=e,n=Pa({typed:r});return r(fp,{"boolean, boolean":function(i,u){return i===u},"number, number":function(i,u){return At(i,u,t.epsilon)},"BigNumber, BigNumber":function(i,u){return i.eq(u)||$t(i,u,t.epsilon)},"Fraction, Fraction":function(i,u){return i.equals(u)},"Complex, Complex":function(i,u){return t2(i,u,t.epsilon)}},n)}),fee=F(fp,["typed","config"],e=>{var{typed:r,config:t}=e;return r(fp,{"number, number":function(a,i){return At(a,i,t.epsilon)}})});var Gz="SparseMatrix",Vz=["typed","equalScalar","Matrix"],lp=F(Gz,Vz,e=>{var{typed:r,equalScalar:t,Matrix:n}=e;function a(v,y){if(!(this instanceof a))throw new SyntaxError("Constructor must be called with the new operator");if(y&&!St(y))throw new Error("Invalid datatype: "+y);if(Qe(v))i(this,v,y);else if(v&&Mr(v.index)&&Mr(v.ptr)&&Mr(v.size))this._values=v.values,this._index=v.index,this._ptr=v.ptr,this._size=v.size,this._datatype=y||v.datatype;else if(Mr(v))u(this,v,y);else{if(v)throw new TypeError("Unsupported type of data ("+Fr(v)+")");this._values=[],this._index=[],this._ptr=[0],this._size=[0,0],this._datatype=y}}function i(v,y,w){y.type==="SparseMatrix"?(v._values=y._values?ar(y._values):void 0,v._index=ar(y._index),v._ptr=ar(y._ptr),v._size=ar(y._size),v._datatype=w||y._datatype):u(v,y.valueOf(),w||y._datatype)}function u(v,y,w){v._values=[],v._index=[],v._ptr=[],v._datatype=w;var C=y.length,b=0,M=t,A=0;if(St(w)&&(M=r.find(t,[w,w])||t,A=r.convert(0,w)),C>0){var S=0;do{v._ptr.push(v._index.length);for(var O=0;O");if(b.length===1){var _=y.dimension(0);_.forEach(function(R,q){Kr(R),v.set([R,0],w[q[0]],C)})}else{var E=y.dimension(0),T=y.dimension(1);E.forEach(function(R,q){Kr(R),T.forEach(function(W,G){Kr(W),v.set([R,W],w[q[0]][G[0]],C)})})}}return v}a.prototype.get=function(v){if(!Mr(v))throw new TypeError("Array expected");if(v.length!==this._size.length)throw new pr(v.length,this._size.length);if(!this._values)throw new Error("Cannot invoke get on a Pattern only matrix");var y=v[0],w=v[1];Kr(y,this._size[0]),Kr(w,this._size[1]);var C=o(y,this._ptr[w],this._ptr[w+1],this._index);return CM-1||b>A-1)&&(d(this,Math.max(C+1,M),Math.max(b+1,A),w),M=this._size[0],A=this._size[1]),Kr(C,M),Kr(b,A);var _=o(C,this._ptr[b],this._ptr[b+1],this._index);return _Array.isArray(M)&&M.length===1?M[0]:M);if(C.length!==2)throw new Error("Only two dimensions matrix are supported");C.forEach(function(M){if(!sr(M)||!Ze(M)||M<0)throw new TypeError("Invalid size, must contain positive integers (size: "+lr(C)+")")});var b=w?this.clone():this;return d(b,C[0],C[1],y)};function d(v,y,w,C){var b=C||0,M=t,A=0;St(v._datatype)&&(M=r.find(t,[v._datatype,v._datatype])||t,A=r.convert(0,v._datatype),b=r.convert(b,v._datatype));var S=!M(b,A),O=v._size[0],_=v._size[1],E,T,R;if(w>_){for(T=_;TO){if(S){var q=0;for(T=0;T<_;T++){v._ptr[T]=v._ptr[T]+q,R=v._ptr[T+1]+q;var W=0;for(E=O;Ey-1&&(v._values.splice(R,1),v._index.splice(R,1),G++)}v._ptr[T]=v._values.length}return v._size[0]=y,v._size[1]=w,v}a.prototype.reshape=function(v,y){if(!Mr(v))throw new TypeError("Array expected");if(v.length!==2)throw new Error("Sparse matrices can only be reshaped in two dimensions");v.forEach(function(z){if(!sr(z)||!Ze(z)||z<=-2||z===0)throw new TypeError("Invalid size, must contain positive integers or -1 (size: "+lr(v)+")")});var w=this._size[0]*this._size[1];v=Cc(v,w);var C=v[0]*v[1];if(w!==C)throw new Error("Reshaping sparse matrix will result in the wrong number of elements");var b=y?this.clone():this;if(this._size[0]===v[0]&&this._size[1]===v[1])return b;for(var M=[],A=0;A=y&&L<=w&&R(v._values[H],L-y,q-C)}else{for(var k={},K=W;K "+(this._values?lr(this._values[O],v):"X")}return b},a.prototype.toString=function(){return lr(this.toArray())},a.prototype.toJSON=function(){return{mathjs:"SparseMatrix",values:this._values,index:this._index,ptr:this._ptr,size:this._size,datatype:this._datatype}},a.prototype.diagonal=function(v){if(v){if(rr(v)&&(v=v.toNumber()),!sr(v)||!Ze(v))throw new TypeError("The parameter k must be an integer number")}else v=0;var y=v>0?v:0,w=v<0?-v:0,C=this._size[0],b=this._size[1],M=Math.min(C-w,b-y),A=[],S=[],O=[];O[0]=0;for(var _=y;_0?w:0,O=w<0?-w:0,_=v[0],E=v[1],T=Math.min(_-O,E-S),R;if(Mr(y)){if(y.length!==T)throw new Error("Invalid value array length");R=function(oe){return y[oe]}}else if(Qe(y)){var q=y.size();if(q.length!==1||q[0]!==T)throw new Error("Invalid matrix length");R=function(oe){return y.get([oe])}}else R=function(){return y};for(var W=[],G=[],H=[],L=0;L=0&&k=O||b[E]!==y)){var R=C?C[_]:void 0;b.splice(E,0,y),C&&C.splice(E,0,R),b.splice(E<=_?_+1:_,1),C&&C.splice(E<=_?_+1:_,1);continue}if(E=O||b[_]!==v)){var q=C?C[E]:void 0;b.splice(_,0,v),C&&C.splice(_,0,q),b.splice(_<=E?E+1:E,1),C&&C.splice(_<=E?E+1:E,1)}}},a},{isClass:!0});var Zz="number",Qz=["typed"];function Xz(e){var r=e.match(/(0[box])([0-9a-fA-F]*)\\.([0-9a-fA-F]*)/);if(r){var t={"0b":2,"0o":8,"0x":16}[r[1]],n=r[2],a=r[3];return{input:e,radix:t,integerPart:n,fractionalPart:a}}else return null}function Jz(e){for(var r=parseInt(e.integerPart,e.radix),t=0,n=0;n{var{typed:r}=e,t=r("number",{"":function(){return 0},number:function(a){return a},string:function(a){if(a==="NaN")return NaN;var i=Xz(a);if(i)return Jz(i);var u=0,l=a.match(/(0[box][0-9a-fA-F]*)i([0-9]*)/);l&&(u=Number(l[2]),a=l[1]);var c=Number(a);if(isNaN(c))throw new SyntaxError('String "'+a+'" is not a valid number');if(l){if(c>2**u-1)throw new SyntaxError('String "'.concat(a,'" is out of range'));c>=2**(u-1)&&(c=c-2**u)}return c},BigNumber:function(a){return a.toNumber()},Fraction:function(a){return a.valueOf()},Unit:r.referToSelf(n=>a=>{var i=a.clone();return i.value=n(a.value),i}),null:function(a){return 0},"Unit, string | Unit":function(a,i){return a.toNumber(i)},"Array | Matrix":r.referToSelf(n=>a=>je(a,n))});return t.fromJSON=function(n){return parseFloat(n.value)},t});var n2="string",Kz=["typed"],pp=F(n2,Kz,e=>{var{typed:r}=e;return r(n2,{"":function(){return""},number:ai,null:function(n){return"null"},boolean:function(n){return n+""},string:function(n){return n},"Array | Matrix":r.referToSelf(t=>n=>je(n,t)),any:function(n){return String(n)}})});var a2="boolean",jz=["typed"],dp=F(a2,jz,e=>{var{typed:r}=e;return r(a2,{"":function(){return!1},boolean:function(n){return n},number:function(n){return!!n},null:function(n){return!1},BigNumber:function(n){return!n.isZero()},string:function(n){var a=n.toLowerCase();if(a==="true")return!0;if(a==="false")return!1;var i=Number(n);if(n!==""&&!isNaN(i))return!!i;throw new Error('Cannot convert "'+n+'" to a boolean')},"Array | Matrix":r.referToSelf(t=>n=>je(n,t))})});var eU="bignumber",rU=["typed","BigNumber"],hp=F(eU,rU,e=>{var{typed:r,BigNumber:t}=e;return r("bignumber",{"":function(){return new t(0)},number:function(a){return new t(a+"")},string:function(a){var i=a.match(/(0[box][0-9a-fA-F]*)i([0-9]*)/);if(i){var u=i[2],l=t(i[1]),c=new t(2).pow(Number(u));if(l.gt(c.sub(1)))throw new SyntaxError('String "'.concat(a,'" is out of range'));var o=new t(2).pow(Number(u)-1);return l.gte(o)?l.sub(c):l}return new t(a)},BigNumber:function(a){return a},Unit:r.referToSelf(n=>a=>{var i=a.clone();return i.value=n(a.value),i}),Fraction:function(a){return new t(a.n).div(a.d).times(a.s)},null:function(a){return new t(0)},"Array | Matrix":r.referToSelf(n=>a=>je(a,n))})});var tU="complex",nU=["typed","Complex"],vp=F(tU,nU,e=>{var{typed:r,Complex:t}=e;return r("complex",{"":function(){return t.ZERO},number:function(a){return new t(a,0)},"number, number":function(a,i){return new t(a,i)},"BigNumber, BigNumber":function(a,i){return new t(a.toNumber(),i.toNumber())},Fraction:function(a){return new t(a.valueOf(),0)},Complex:function(a){return a.clone()},string:function(a){return t(a)},null:function(a){return t(0)},Object:function(a){if("re"in a&&"im"in a)return new t(a.re,a.im);if("r"in a&&"phi"in a||"abs"in a&&"arg"in a)return new t(a);throw new Error("Expected object with properties (re and im) or (r and phi) or (abs and arg)")},"Array | Matrix":r.referToSelf(n=>a=>je(a,n))})});var aU="fraction",iU=["typed","Fraction"],gp=F(aU,iU,e=>{var{typed:r,Fraction:t}=e;return r("fraction",{number:function(a){if(!isFinite(a)||isNaN(a))throw new Error(a+" cannot be represented as a fraction");return new t(a)},string:function(a){return new t(a)},"number, number":function(a,i){return new t(a,i)},null:function(a){return new t(0)},BigNumber:function(a){return new t(a.toString())},Fraction:function(a){return a},Unit:r.referToSelf(n=>a=>{var i=a.clone();return i.value=n(a.value),i}),Object:function(a){return new t(a)},"Array | Matrix":r.referToSelf(n=>a=>je(a,n))})});var i2="matrix",oU=["typed","Matrix","DenseMatrix","SparseMatrix"],xp=F(i2,oU,e=>{var{typed:r,Matrix:t,DenseMatrix:n,SparseMatrix:a}=e;return r(i2,{"":function(){return i([])},string:function(l){return i([],l)},"string, string":function(l,c){return i([],l,c)},Array:function(l){return i(l)},Matrix:function(l){return i(l,l.storage())},"Array | Matrix, string":i,"Array | Matrix, string, string":i});function i(u,l,c){if(l==="dense"||l==="default"||l===void 0)return new n(u,c);if(l==="sparse")return new a(u,c);throw new TypeError("Unknown matrix type "+JSON.stringify(l)+".")}});var o2="matrixFromFunction",sU=["typed","matrix","isZero"],yp=F(o2,sU,e=>{var{typed:r,matrix:t,isZero:n}=e;return r(o2,{"Array | Matrix, function, string, string":function(u,l,c,o){return a(u,l,c,o)},"Array | Matrix, function, string":function(u,l,c){return a(u,l,c)},"Matrix, function":function(u,l){return a(u,l,"dense")},"Array, function":function(u,l){return a(u,l,"dense").toArray()},"Array | Matrix, string, function":function(u,l,c){return a(u,c,l)},"Array | Matrix, string, string, function":function(u,l,c,o){return a(u,o,l,c)}});function a(i,u,l,c){var o;return c!==void 0?o=t(l,c):o=t(l),o.resize(i),o.forEach(function(s,m){var d=u(m);n(d)||o.set(m,d)}),o}});var s2="matrixFromRows",uU=["typed","matrix","flatten","size"],bp=F(s2,uU,e=>{var{typed:r,matrix:t,flatten:n,size:a}=e;return r(s2,{"...Array":function(c){return i(c)},"...Matrix":function(c){return t(i(c.map(o=>o.toArray())))}});function i(l){if(l.length===0)throw new TypeError("At least one row is needed to construct a matrix.");var c=u(l[0]),o=[];for(var s of l){var m=u(s);if(m!==c)throw new TypeError("The vectors had different length: "+(c|0)+" \\u2260 "+(m|0));o.push(n(s))}return o}function u(l){var c=a(l);if(c.length===1)return c[0];if(c.length===2){if(c[0]===1)return c[1];if(c[1]===1)return c[0];throw new TypeError("At least one of the arguments is not a vector.")}else throw new TypeError("Only one- or two-dimensional vectors are supported.")}});var u2="matrixFromColumns",fU=["typed","matrix","flatten","size"],wp=F(u2,fU,e=>{var{typed:r,matrix:t,flatten:n,size:a}=e;return r(u2,{"...Array":function(c){return i(c)},"...Matrix":function(c){return t(i(c.map(o=>o.toArray())))}});function i(l){if(l.length===0)throw new TypeError("At least one column is needed to construct a matrix.");for(var c=u(l[0]),o=[],s=0;s{var{typed:r}=e;return r(f2,{"Unit, Array":function(n,a){return n.splitUnit(a)}})});var c2="unaryMinus",lU=["typed"],Sp=F(c2,lU,e=>{var{typed:r}=e;return r(c2,{number:xw,"Complex | BigNumber | Fraction":t=>t.neg(),Unit:r.referToSelf(t=>n=>{var a=n.clone();return a.value=r.find(t,a.valueType())(n.value),a}),"Array | Matrix":r.referToSelf(t=>n=>je(n,t,!0))})});var l2="unaryPlus",mU=["typed","config","BigNumber"],Np=F(l2,mU,e=>{var{typed:r,config:t,BigNumber:n}=e;return r(l2,{number:yw,Complex:function(i){return i},BigNumber:function(i){return i},Fraction:function(i){return i},Unit:function(i){return i.clone()},"Array | Matrix":r.referToSelf(a=>i=>je(i,a,!0)),"boolean | string":function(i){return t.number==="BigNumber"?new n(+i):+i}})});var m2="abs",pU=["typed"],Ap=F(m2,pU,e=>{var{typed:r}=e;return r(m2,{number:dw,"Complex | BigNumber | Fraction | Unit":t=>t.abs(),"Array | Matrix":r.referToSelf(t=>n=>je(n,t,!0))})});var p2="apply",dU=["typed","isInteger"],qo=F(p2,dU,e=>{var{typed:r,isInteger:t}=e;return r(p2,{"Array | Matrix, number | BigNumber, function":function(a,i,u){if(!t(i))throw new TypeError("Integer number expected for dimension");var l=Array.isArray(a)?ur(a):a.size();if(i<0||i>=l.length)throw new tn(i,l.length);return Qe(a)?a.create(Mp(a.valueOf(),i,u)):Mp(a,i,u)}})});function Mp(e,r,t){var n,a,i;if(r<=0)if(Array.isArray(e[0])){for(i=hU(e),a=[],n=0;n{var{typed:r}=e;return r(d2,{"number, number":hw,"Complex, Complex":function(n,a){return n.add(a)},"BigNumber, BigNumber":function(n,a){return n.plus(a)},"Fraction, Fraction":function(n,a){return n.add(a)},"Unit, Unit":r.referToSelf(t=>(n,a)=>{if(n.value===null||n.value===void 0)throw new Error("Parameter x contains a unit with undefined value");if(a.value===null||a.value===void 0)throw new Error("Parameter y contains a unit with undefined value");if(!n.equalBase(a))throw new Error("Units do not match");var i=n.clone();return i.value=r.find(t,[i.valueType(),a.valueType()])(i.value,a.value),i.fixPrefix=!1,i})})});var h2="subtractScalar",gU=["typed"],Ep=F(h2,gU,e=>{var{typed:r}=e;return r(h2,{"number, number":vw,"Complex, Complex":function(n,a){return n.sub(a)},"BigNumber, BigNumber":function(n,a){return n.minus(a)},"Fraction, Fraction":function(n,a){return n.sub(a)},"Unit, Unit":r.referToSelf(t=>(n,a)=>{if(n.value===null||n.value===void 0)throw new Error("Parameter x contains a unit with undefined value");if(a.value===null||a.value===void 0)throw new Error("Parameter y contains a unit with undefined value");if(!n.equalBase(a))throw new Error("Units do not match");var i=n.clone();return i.value=r.find(t,[i.valueType(),a.valueType()])(i.value,a.value),i.fixPrefix=!1,i})})});var v2="cbrt",xU=["config","typed","isNegative","unaryMinus","matrix","Complex","BigNumber","Fraction"],Tp=F(v2,xU,e=>{var{config:r,typed:t,isNegative:n,unaryMinus:a,matrix:i,Complex:u,BigNumber:l,Fraction:c}=e;return t(v2,{number:_u,Complex:o,"Complex, boolean":o,BigNumber:function(d){return d.cbrt()},Unit:s});function o(m,d){var h=m.arg()/3,x=m.abs(),v=new u(_u(x),0).mul(new u(0,h).exp());if(d){var y=[v,new u(_u(x),0).mul(new u(0,h+Math.PI*2/3).exp()),new u(_u(x),0).mul(new u(0,h-Math.PI*2/3).exp())];return r.matrix==="Array"?y:i(y)}else return v}function s(m){if(m.value&&Kt(m.value)){var d=m.clone();return d.value=1,d=d.pow(1/3),d.value=o(m.value),d}else{var h=n(m.value);h&&(m.value=a(m.value));var x;rr(m.value)?x=new l(1).div(3):ma(m.value)?x=new c(1,3):x=1/3;var v=m.pow(x);return h&&(v.value=a(v.value)),v}}});var yU="matAlgo11xS0s",bU=["typed","equalScalar"],jr=F(yU,bU,e=>{var{typed:r,equalScalar:t}=e;return function(a,i,u,l){var c=a._values,o=a._index,s=a._ptr,m=a._size,d=a._datatype;if(!c)throw new Error("Cannot perform operation on Pattern Sparse Matrix and Scalar value");var h=m[0],x=m[1],v,y=t,w=0,C=u;typeof d=="string"&&(v=d,y=r.find(t,[v,v]),w=r.convert(0,v),i=r.convert(i,v),C=r.find(u,[v,v]));for(var b=[],M=[],A=[],S=0;S{var{typed:r,DenseMatrix:t}=e;return function(a,i,u,l){var c=a._values,o=a._index,s=a._ptr,m=a._size,d=a._datatype;if(!c)throw new Error("Cannot perform operation on Pattern Sparse Matrix and Scalar value");var h=m[0],x=m[1],v,y=u;typeof d=="string"&&(v=d,i=r.convert(i,v),y=r.find(u,[v,v]));for(var w=[],C=[],b=[],M=0;M{var{typed:r}=e;return function(a,i,u,l){var c=a._data,o=a._size,s=a._datatype,m,d=u;typeof s=="string"&&(m=s,i=r.convert(i,m),d=r.find(u,[m,m]));var h=o.length>0?t(d,0,o,o[0],c,i,l):[];return a.createDenseMatrix({data:h,size:ar(o),datatype:m})};function t(n,a,i,u,l,c,o){var s=[];if(a===i.length-1)for(var m=0;m{var{typed:r,config:t,round:n}=e;return r(lD,{number:function(i){return At(i,n(i),t.epsilon)?n(i):Math.ceil(i)},"number, number":function(i,u){if(At(i,n(i,u),t.epsilon))return n(i,u);var[l,c]="".concat(i,"e").split("e"),o=Math.ceil(Number("".concat(l,"e").concat(Number(c)+u)));return[l,c]="".concat(o,"e").split("e"),Number("".concat(l,"e").concat(Number(c)-u))}})}),Fp=F(lD,AU,e=>{var{typed:r,config:t,round:n,matrix:a,equalScalar:i,zeros:u,DenseMatrix:l}=e,c=jr({typed:r,equalScalar:i}),o=Wr({typed:r,DenseMatrix:l}),s=qt({typed:r}),m=MU({typed:r,config:t,round:n});return r("ceil",{number:m.signatures.number,"number,number":m.signatures["number,number"],Complex:function(h){return h.ceil()},"Complex, number":function(h,x){return h.ceil(x)},"Complex, BigNumber":function(h,x){return h.ceil(x.toNumber())},BigNumber:function(h){return $t(h,n(h),t.epsilon)?n(h):h.ceil()},"BigNumber, BigNumber":function(h,x){return $t(h,n(h,x),t.epsilon)?n(h,x):h.toDecimalPlaces(x.toNumber(),Cs.ROUND_CEIL)},Fraction:function(h){return h.ceil()},"Fraction, number":function(h,x){return h.ceil(x)},"Fraction, BigNumber":function(h,x){return h.ceil(x.toNumber())},"Array | Matrix":r.referToSelf(d=>h=>je(h,d,!0)),"Array, number | BigNumber":r.referToSelf(d=>(h,x)=>je(h,v=>d(v,x),!0)),"SparseMatrix, number | BigNumber":r.referToSelf(d=>(h,x)=>c(h,x,d,!1)),"DenseMatrix, number | BigNumber":r.referToSelf(d=>(h,x)=>s(h,x,d,!1)),"number | Complex | Fraction | BigNumber, Array":r.referToSelf(d=>(h,x)=>s(a(x),h,d,!0).valueOf()),"number | Complex | Fraction | BigNumber, Matrix":r.referToSelf(d=>(h,x)=>i(h,0)?u(x.size(),x.storage()):x.storage()==="dense"?s(x,h,d,!0):o(x,h,d,!0))})});var g2="cube",CU=["typed"],_p=F(g2,CU,e=>{var{typed:r}=e;return r(g2,{number:bw,Complex:function(n){return n.mul(n).mul(n)},BigNumber:function(n){return n.times(n).times(n)},Fraction:function(n){return n.pow(3)},Unit:function(n){return n.pow(3)}})});var x2="exp",EU=["typed"],Op=F(x2,EU,e=>{var{typed:r}=e;return r(x2,{number:ww,Complex:function(n){return n.exp()},BigNumber:function(n){return n.exp()}})});var y2="expm1",TU=["typed","Complex"],Bp=F(y2,TU,e=>{var{typed:r,Complex:t}=e;return r(y2,{number:Dw,Complex:function(a){var i=Math.exp(a.re);return new t(i*Math.cos(a.im)-1,i*Math.sin(a.im))},BigNumber:function(a){return a.exp().minus(1)}})});var mD="fix",FU=["typed","Complex","matrix","ceil","floor","equalScalar","zeros","DenseMatrix"],_U=F(mD,["typed","ceil","floor"],e=>{var{typed:r,ceil:t,floor:n}=e;return r(mD,{number:function(i){return i>0?n(i):t(i)},"number, number":function(i,u){return i>0?n(i,u):t(i,u)}})}),Pp=F(mD,FU,e=>{var{typed:r,Complex:t,matrix:n,ceil:a,floor:i,equalScalar:u,zeros:l,DenseMatrix:c}=e,o=Wr({typed:r,DenseMatrix:c}),s=qt({typed:r}),m=_U({typed:r,ceil:a,floor:i});return r("fix",{number:m.signatures.number,"number, number | BigNumber":m.signatures["number,number"],Complex:function(h){return new t(h.re>0?Math.floor(h.re):Math.ceil(h.re),h.im>0?Math.floor(h.im):Math.ceil(h.im))},"Complex, number":function(h,x){return new t(h.re>0?i(h.re,x):a(h.re,x),h.im>0?i(h.im,x):a(h.im,x))},"Complex, BigNumber":function(h,x){var v=x.toNumber();return new t(h.re>0?i(h.re,v):a(h.re,v),h.im>0?i(h.im,v):a(h.im,v))},BigNumber:function(h){return h.isNegative()?a(h):i(h)},"BigNumber, number | BigNumber":function(h,x){return h.isNegative()?a(h,x):i(h,x)},Fraction:function(h){return h.s<0?h.ceil():h.floor()},"Fraction, number | BigNumber":function(h,x){return h.s<0?a(h,x):i(h,x)},"Array | Matrix":r.referToSelf(d=>h=>je(h,d,!0)),"Array | Matrix, number | BigNumber":r.referToSelf(d=>(h,x)=>je(h,v=>d(v,x),!0)),"number | Complex | Fraction | BigNumber, Array":r.referToSelf(d=>(h,x)=>s(n(x),h,d,!0).valueOf()),"number | Complex | Fraction | BigNumber, Matrix":r.referToSelf(d=>(h,x)=>u(h,0)?l(x.size(),x.storage()):x.storage()==="dense"?s(x,h,d,!0):o(x,h,d,!0))})});var pD="floor",OU=["typed","config","round","matrix","equalScalar","zeros","DenseMatrix"],BU=F(pD,["typed","config","round"],e=>{var{typed:r,config:t,round:n}=e;return r(pD,{number:function(i){return At(i,n(i),t.epsilon)?n(i):Math.floor(i)},"number, number":function(i,u){if(At(i,n(i,u),t.epsilon))return n(i,u);var[l,c]="".concat(i,"e").split("e"),o=Math.floor(Number("".concat(l,"e").concat(Number(c)+u)));return[l,c]="".concat(o,"e").split("e"),Number("".concat(l,"e").concat(Number(c)-u))}})}),Pu=F(pD,OU,e=>{var{typed:r,config:t,round:n,matrix:a,equalScalar:i,zeros:u,DenseMatrix:l}=e,c=jr({typed:r,equalScalar:i}),o=Wr({typed:r,DenseMatrix:l}),s=qt({typed:r}),m=BU({typed:r,config:t,round:n});return r("floor",{number:m.signatures.number,"number,number":m.signatures["number,number"],Complex:function(h){return h.floor()},"Complex, number":function(h,x){return h.floor(x)},"Complex, BigNumber":function(h,x){return h.floor(x.toNumber())},BigNumber:function(h){return $t(h,n(h),t.epsilon)?n(h):h.floor()},"BigNumber, BigNumber":function(h,x){return $t(h,n(h,x),t.epsilon)?n(h,x):h.toDecimalPlaces(x.toNumber(),Cs.ROUND_FLOOR)},Fraction:function(h){return h.floor()},"Fraction, number":function(h,x){return h.floor(x)},"Fraction, BigNumber":function(h,x){return h.floor(x.toNumber())},"Array | Matrix":r.referToSelf(d=>h=>je(h,d,!0)),"Array, number | BigNumber":r.referToSelf(d=>(h,x)=>je(h,v=>d(v,x),!0)),"SparseMatrix, number | BigNumber":r.referToSelf(d=>(h,x)=>c(h,x,d,!1)),"DenseMatrix, number | BigNumber":r.referToSelf(d=>(h,x)=>s(h,x,d,!1)),"number | Complex | Fraction | BigNumber, Array":r.referToSelf(d=>(h,x)=>s(a(x),h,d,!0).valueOf()),"number | Complex | Fraction | BigNumber, Matrix":r.referToSelf(d=>(h,x)=>i(h,0)?u(x.size(),x.storage()):x.storage()==="dense"?s(x,h,d,!0):o(x,h,d,!0))})});var PU="matAlgo02xDS0",IU=["typed","equalScalar"],Lt=F(PU,IU,e=>{var{typed:r,equalScalar:t}=e;return function(a,i,u,l){var c=a._data,o=a._size,s=a._datatype||a.getDataType(),m=i._values,d=i._index,h=i._ptr,x=i._size,v=i._datatype||i._data===void 0?i._datatype:i.getDataType();if(o.length!==x.length)throw new pr(o.length,x.length);if(o[0]!==x[0]||o[1]!==x[1])throw new RangeError("Dimension mismatch. Matrix A ("+o+") must match Matrix B ("+x+")");if(!m)throw new Error("Cannot perform operation on Dense Matrix and Pattern Sparse Matrix");var y=o[0],w=o[1],C,b=t,M=0,A=u;typeof s=="string"&&s===v&&s!=="mixed"&&(C=s,b=r.find(t,[C,C]),M=r.convert(0,C),A=r.find(u,[C,C]));for(var S=[],O=[],_=[],E=0;E{var{typed:r}=e;return function(n,a,i,u){var l=n._data,c=n._size,o=n._datatype||n.getDataType(),s=a._values,m=a._index,d=a._ptr,h=a._size,x=a._datatype||a._data===void 0?a._datatype:a.getDataType();if(c.length!==h.length)throw new pr(c.length,h.length);if(c[0]!==h[0]||c[1]!==h[1])throw new RangeError("Dimension mismatch. Matrix A ("+c+") must match Matrix B ("+h+")");if(!s)throw new Error("Cannot perform operation on Dense Matrix and Pattern Sparse Matrix");var v=c[0],y=c[1],w,C=0,b=i;typeof o=="string"&&o===x&&o!=="mixed"&&(w=o,C=r.convert(0,w),b=r.find(i,[w,w]));for(var M=[],A=0;A{var{typed:r,equalScalar:t}=e;return function(a,i,u){var l=a._values,c=a._index,o=a._ptr,s=a._size,m=a._datatype||a._data===void 0?a._datatype:a.getDataType(),d=i._values,h=i._index,x=i._ptr,v=i._size,y=i._datatype||i._data===void 0?i._datatype:i.getDataType();if(s.length!==v.length)throw new pr(s.length,v.length);if(s[0]!==v[0]||s[1]!==v[1])throw new RangeError("Dimension mismatch. Matrix A ("+s+") must match Matrix B ("+v+")");var w=s[0],C=s[1],b,M=t,A=0,S=u;typeof m=="string"&&m===y&&m!=="mixed"&&(b=m,M=r.find(t,[b,b]),A=r.convert(0,b),S=r.find(u,[b,b]));var O=l&&d?[]:void 0,_=[],E=[],T=O?[]:void 0,R=O?[]:void 0,q=[],W=[],G,H,L,k;for(H=0;H{var{typed:r}=e;return function(a,i,u){var l=a._data,c=a._size,o=a._datatype,s=i._data,m=i._size,d=i._datatype,h=[];if(c.length!==m.length)throw new pr(c.length,m.length);for(var x=0;x0?t(y,0,h,h[0],l,s):[];return a.createDenseMatrix({data:w,size:h,datatype:v})};function t(n,a,i,u,l,c){var o=[];if(a===i.length-1)for(var s=0;s{var{concat:r}=e;return function(a,i){var u=Math.max(a._size.length,i._size.length);if(a._size.length===i._size.length&&a._size.every((x,v)=>x===i._size[v]))return[a,i];for(var l=t(a._size,u,0),c=t(i._size,u,0),o=[],s=0;s{var{typed:r,matrix:t,concat:n}=e,a=b2({typed:r}),i=qt({typed:r}),u=w2({concat:n});return function(c){var o=c.elop,s=c.SD||c.DS,m;o?(m={"DenseMatrix, DenseMatrix":(v,y)=>a(...u(v,y),o),"Array, Array":(v,y)=>a(...u(t(v),t(y)),o).valueOf(),"Array, DenseMatrix":(v,y)=>a(...u(t(v),y),o),"DenseMatrix, Array":(v,y)=>a(...u(v,t(y)),o)},c.SS&&(m["SparseMatrix, SparseMatrix"]=(v,y)=>c.SS(...u(v,y),o,!1)),c.DS&&(m["DenseMatrix, SparseMatrix"]=(v,y)=>c.DS(...u(v,y),o,!1),m["Array, SparseMatrix"]=(v,y)=>c.DS(...u(t(v),y),o,!1)),s&&(m["SparseMatrix, DenseMatrix"]=(v,y)=>s(...u(y,v),o,!0),m["SparseMatrix, Array"]=(v,y)=>s(...u(t(y),v),o,!0))):(m={"DenseMatrix, DenseMatrix":r.referToSelf(v=>(y,w)=>a(...u(y,w),v)),"Array, Array":r.referToSelf(v=>(y,w)=>a(...u(t(y),t(w)),v).valueOf()),"Array, DenseMatrix":r.referToSelf(v=>(y,w)=>a(...u(t(y),w),v)),"DenseMatrix, Array":r.referToSelf(v=>(y,w)=>a(...u(y,t(w)),v))},c.SS&&(m["SparseMatrix, SparseMatrix"]=r.referToSelf(v=>(y,w)=>c.SS(...u(y,w),v,!1))),c.DS&&(m["DenseMatrix, SparseMatrix"]=r.referToSelf(v=>(y,w)=>c.DS(...u(y,w),v,!1)),m["Array, SparseMatrix"]=r.referToSelf(v=>(y,w)=>c.DS(...u(t(y),w),v,!1))),s&&(m["SparseMatrix, DenseMatrix"]=r.referToSelf(v=>(y,w)=>s(...u(w,y),v,!0)),m["SparseMatrix, Array"]=r.referToSelf(v=>(y,w)=>s(...u(t(w),y),v,!0))));var d=c.scalar||"any",h=c.Ds||c.Ss;h&&(o?(m["DenseMatrix,"+d]=(v,y)=>i(v,y,o,!1),m[d+", DenseMatrix"]=(v,y)=>i(y,v,o,!0),m["Array,"+d]=(v,y)=>i(t(v),y,o,!1).valueOf(),m[d+", Array"]=(v,y)=>i(t(y),v,o,!0).valueOf()):(m["DenseMatrix,"+d]=r.referToSelf(v=>(y,w)=>i(y,w,v,!1)),m[d+", DenseMatrix"]=r.referToSelf(v=>(y,w)=>i(w,y,v,!0)),m["Array,"+d]=r.referToSelf(v=>(y,w)=>i(t(y),w,v,!1).valueOf()),m[d+", Array"]=r.referToSelf(v=>(y,w)=>i(t(w),y,v,!0).valueOf())));var x=c.sS!==void 0?c.sS:c.Ss;return o?(c.Ss&&(m["SparseMatrix,"+d]=(v,y)=>c.Ss(v,y,o,!1)),x&&(m[d+", SparseMatrix"]=(v,y)=>x(y,v,o,!0))):(c.Ss&&(m["SparseMatrix,"+d]=r.referToSelf(v=>(y,w)=>c.Ss(y,w,v,!1))),x&&(m[d+", SparseMatrix"]=r.referToSelf(v=>(y,w)=>x(w,y,v,!0)))),o&&o.signatures&&Dm(m,o.signatures),m}});var D2="mod",GU=["typed","config","round","matrix","equalScalar","zeros","DenseMatrix","concat"],Iu=F(D2,GU,e=>{var{typed:r,config:t,round:n,matrix:a,equalScalar:i,zeros:u,DenseMatrix:l,concat:c}=e,o=Pu({typed:r,config:t,round:n,matrix:a,equalScalar:i,zeros:u,DenseMatrix:l}),s=Lt({typed:r,equalScalar:i}),m=lt({typed:r}),d=Lo({typed:r,equalScalar:i}),h=jr({typed:r,equalScalar:i}),x=Wr({typed:r,DenseMatrix:l}),v=vr({typed:r,matrix:a,concat:c});return r(D2,{"number, number":y,"BigNumber, BigNumber":function(C,b){return b.isZero()?C:C.sub(b.mul(o(C.div(b))))},"Fraction, Fraction":function(C,b){return b.equals(0)?C:C.sub(b.mul(o(C.div(b))))}},v({SS:d,DS:m,SD:s,Ss:h,sS:x}));function y(w,C){return C===0?w:w-C*o(w/C)}});var VU="matAlgo01xDSid",ZU=["typed"],Mn=F(VU,ZU,e=>{var{typed:r}=e;return function(n,a,i,u){var l=n._data,c=n._size,o=n._datatype||n.getDataType(),s=a._values,m=a._index,d=a._ptr,h=a._size,x=a._datatype||a._data===void 0?a._datatype:a.getDataType();if(c.length!==h.length)throw new pr(c.length,h.length);if(c[0]!==h[0]||c[1]!==h[1])throw new RangeError("Dimension mismatch. Matrix A ("+c+") must match Matrix B ("+h+")");if(!s)throw new Error("Cannot perform operation on Dense Matrix and Pattern Sparse Matrix");var v=c[0],y=c[1],w=typeof o=="string"&&o!=="mixed"&&o===x?o:void 0,C=w?r.find(i,[w,w]):i,b,M,A=[];for(b=0;b{var{typed:r,equalScalar:t}=e;return function(a,i,u){var l=a._values,c=a._index,o=a._ptr,s=a._size,m=a._datatype||a._data===void 0?a._datatype:a.getDataType(),d=i._values,h=i._index,x=i._ptr,v=i._size,y=i._datatype||i._data===void 0?i._datatype:i.getDataType();if(s.length!==v.length)throw new pr(s.length,v.length);if(s[0]!==v[0]||s[1]!==v[1])throw new RangeError("Dimension mismatch. Matrix A ("+s+") must match Matrix B ("+v+")");var w=s[0],C=s[1],b,M=t,A=0,S=u;typeof m=="string"&&m===y&&m!=="mixed"&&(b=m,M=r.find(t,[b,b]),A=r.convert(0,b),S=r.find(u,[b,b]));var O=l&&d?[]:void 0,_=[],E=[],T=l&&d?[]:void 0,R=l&&d?[]:void 0,q=[],W=[],G,H,L,k,K;for(H=0;H{var{typed:r,DenseMatrix:t}=e;return function(a,i,u,l){var c=a._values,o=a._index,s=a._ptr,m=a._size,d=a._datatype;if(!c)throw new Error("Cannot perform operation on Pattern Sparse Matrix and Scalar value");var h=m[0],x=m[1],v,y=u;typeof d=="string"&&(v=d,i=r.convert(i,v),y=r.find(u,[v,v]));for(var w=[],C=[],b=[],M=0;MArray.isArray(r))}var Ip=F(S2,jU,e=>{var{typed:r,matrix:t,config:n,round:a,equalScalar:i,zeros:u,BigNumber:l,DenseMatrix:c,concat:o}=e,s=Iu({typed:r,config:n,round:a,matrix:t,equalScalar:i,zeros:u,DenseMatrix:c,concat:o}),m=Mn({typed:r}),d=Ru({typed:r,equalScalar:i}),h=jn({typed:r,DenseMatrix:c}),x=vr({typed:r,matrix:t,concat:o});return r(S2,{"number, number":v,"BigNumber, BigNumber":y,"Fraction, Fraction":(w,C)=>w.gcd(C)},x({SS:d,DS:m,Ss:h}),{[eW]:r.referToSelf(w=>(C,b,M)=>{for(var A=w(C,b),S=0;SC=>{if(C.length===1&&Array.isArray(C[0])&&N2(C[0]))return w(...C[0]);if(N2(C))return w(...C);throw new ha("gcd() supports only 1d matrices!")}),Matrix:r.referToSelf(w=>C=>w(C.toArray()))});function v(w,C){if(!Ze(w)||!Ze(C))throw new Error("Parameters in function gcd must be integer numbers");for(var b;C!==0;)b=s(w,C),w=C,C=b;return w<0?-w:w}function y(w,C){if(!w.isInt()||!C.isInt())throw new Error("Parameters in function gcd must be integer numbers");for(var b=new l(0);!C.isZero();){var M=s(w,C);w=C,C=M}return w.lt(b)?w.neg():w}});var rW="matAlgo06xS0S0",tW=["typed","equalScalar"],zo=F(rW,tW,e=>{var{typed:r,equalScalar:t}=e;return function(a,i,u){var l=a._values,c=a._size,o=a._datatype||a._data===void 0?a._datatype:a.getDataType(),s=i._values,m=i._size,d=i._datatype||i._data===void 0?i._datatype:i.getDataType();if(c.length!==m.length)throw new pr(c.length,m.length);if(c[0]!==m[0]||c[1]!==m[1])throw new RangeError("Dimension mismatch. Matrix A ("+c+") must match Matrix B ("+m+")");var h=c[0],x=c[1],v,y=t,w=0,C=u;typeof o=="string"&&o===d&&o!=="mixed"&&(v=o,y=r.find(t,[v,v]),w=r.convert(0,v),C=r.find(u,[v,v]));for(var b=l&&s?[]:void 0,M=[],A=[],S=b?[]:void 0,O=[],_=[],E=0;E{var{typed:r,matrix:t,equalScalar:n,concat:a}=e,i=Lt({typed:r,equalScalar:n}),u=zo({typed:r,equalScalar:n}),l=jr({typed:r,equalScalar:n}),c=vr({typed:r,matrix:t,concat:a}),o="number | BigNumber | Fraction | Matrix | Array",s={};return s["".concat(o,", ").concat(o,", ...").concat(o)]=r.referToSelf(d=>(h,x,v)=>{for(var y=d(h,x),w=0;wd.lcm(h)},c({SS:u,DS:i,Ss:l}),s);function m(d,h){if(!d.isInt()||!h.isInt())throw new Error("Parameters in function lcm must be integer numbers");if(d.isZero())return d;if(h.isZero())return h;for(var x=d.times(h);!h.isZero();){var v=h;h=d.mod(v),d=v}return x.div(d).abs()}});var M2="log10",aW=["typed","config","Complex"],kp=F(M2,aW,e=>{var{typed:r,config:t,Complex:n}=e;return r(M2,{number:function(i){return i>=0||t.predictable?Nw(i):new n(i,0).log().div(Math.LN10)},Complex:function(i){return new n(i).log().div(Math.LN10)},BigNumber:function(i){return!i.isNegative()||t.predictable?i.log():new n(i.toNumber(),0).log().div(Math.LN10)},"Array | Matrix":r.referToSelf(a=>i=>je(i,a))})});var C2="log2",iW=["typed","config","Complex"],qp=F(C2,iW,e=>{var{typed:r,config:t,Complex:n}=e;return r(C2,{number:function(u){return u>=0||t.predictable?Aw(u):a(new n(u,0))},Complex:a,BigNumber:function(u){return!u.isNegative()||t.predictable?u.log(2):a(new n(u.toNumber(),0))},"Array | Matrix":r.referToSelf(i=>u=>je(u,i))});function a(i){var u=Math.sqrt(i.re*i.re+i.im*i.im);return new n(Math.log2?Math.log2(u):Math.log(u)/Math.LN2,Math.atan2(i.im,i.re)/Math.LN2)}});var oW="multiplyScalar",sW=["typed"],Lp=F(oW,sW,e=>{var{typed:r}=e;return r("multiplyScalar",{"number, number":gw,"Complex, Complex":function(n,a){return n.mul(a)},"BigNumber, BigNumber":function(n,a){return n.times(a)},"Fraction, Fraction":function(n,a){return n.mul(a)},"number | Fraction | BigNumber | Complex, Unit":(t,n)=>n.multiply(t),"Unit, number | Fraction | BigNumber | Complex | Unit":(t,n)=>t.multiply(n)})});var E2="multiply",uW=["typed","matrix","addScalar","multiplyScalar","equalScalar","dot"],zp=F(E2,uW,e=>{var{typed:r,matrix:t,addScalar:n,multiplyScalar:a,equalScalar:i,dot:u}=e,l=jr({typed:r,equalScalar:i}),c=qt({typed:r});function o(A,S){switch(A.length){case 1:switch(S.length){case 1:if(A[0]!==S[0])throw new RangeError("Dimension mismatch in multiplication. Vectors must have the same length");break;case 2:if(A[0]!==S[0])throw new RangeError("Dimension mismatch in multiplication. Vector length ("+A[0]+") must match Matrix rows ("+S[0]+")");break;default:throw new Error("Can only multiply a 1 or 2 dimensional matrix (Matrix B has "+S.length+" dimensions)")}break;case 2:switch(S.length){case 1:if(A[1]!==S[0])throw new RangeError("Dimension mismatch in multiplication. Matrix columns ("+A[1]+") must match Vector length ("+S[0]+")");break;case 2:if(A[1]!==S[0])throw new RangeError("Dimension mismatch in multiplication. Matrix A columns ("+A[1]+") must match Matrix B rows ("+S[0]+")");break;default:throw new Error("Can only multiply a 1 or 2 dimensional matrix (Matrix B has "+S.length+" dimensions)")}break;default:throw new Error("Can only multiply a 1 or 2 dimensional matrix (Matrix A has "+A.length+" dimensions)")}}function s(A,S,O){if(O===0)throw new Error("Cannot multiply two empty vectors");return u(A,S)}function m(A,S){if(S.storage()!=="dense")throw new Error("Support for SparseMatrix not implemented");return d(A,S)}function d(A,S){var O=A._data,_=A._size,E=A._datatype||A.getDataType(),T=S._data,R=S._size,q=S._datatype||S.getDataType(),W=_[0],G=R[1],H,L=n,k=a;E&&q&&E===q&&typeof E=="string"&&E!=="mixed"&&(H=E,L=r.find(n,[H,H]),k=r.find(a,[H,H]));for(var K=[],z=0;zge)for(var xe=0,be=0;be(S,O)=>{o(ur(S),ur(O));var _=A(t(S),t(O));return Qe(_)?_.valueOf():_}),"Matrix, Matrix":function(S,O){var _=S.size(),E=O.size();return o(_,E),_.length===1?E.length===1?s(S,O,_[0]):m(S,O):E.length===1?h(S,O):x(S,O)},"Matrix, Array":r.referTo("Matrix,Matrix",A=>(S,O)=>A(S,t(O))),"Array, Matrix":r.referToSelf(A=>(S,O)=>A(t(S,O.storage()),O)),"SparseMatrix, any":function(S,O){return l(S,O,a,!1)},"DenseMatrix, any":function(S,O){return c(S,O,a,!1)},"any, SparseMatrix":function(S,O){return l(O,S,a,!0)},"any, DenseMatrix":function(S,O){return c(O,S,a,!0)},"Array, any":function(S,O){return c(t(S),O,a,!1).valueOf()},"any, Array":function(S,O){return c(t(O),S,a,!0).valueOf()},"any, any":a,"any, any, ...any":r.referToSelf(A=>(S,O,_)=>{for(var E=A(S,O),T=0;T<_.length;T++)E=A(E,_[T]);return E})})});var T2="nthRoot",fW=["typed","matrix","equalScalar","BigNumber","concat"],Up=F(T2,fW,e=>{var{typed:r,matrix:t,equalScalar:n,BigNumber:a,concat:i}=e,u=Mn({typed:r}),l=Lt({typed:r,equalScalar:n}),c=zo({typed:r,equalScalar:n}),o=jr({typed:r,equalScalar:n}),s=vr({typed:r,matrix:t,concat:i});function m(){throw new Error("Complex number not supported in function nthRoot. Use nthRoots instead.")}return r(T2,{number:Mw,"number, number":Mw,BigNumber:h=>d(h,new a(2)),"BigNumber, BigNumber":d,Complex:m,"Complex, number":m,Array:r.referTo("DenseMatrix,number",h=>x=>h(t(x),2).valueOf()),DenseMatrix:r.referTo("DenseMatrix,number",h=>x=>h(x,2)),SparseMatrix:r.referTo("SparseMatrix,number",h=>x=>h(x,2)),"SparseMatrix, SparseMatrix":r.referToSelf(h=>(x,v)=>{if(v.density()===1)return c(x,v,h);throw new Error("Root must be non-zero")}),"DenseMatrix, SparseMatrix":r.referToSelf(h=>(x,v)=>{if(v.density()===1)return u(x,v,h,!1);throw new Error("Root must be non-zero")}),"Array, SparseMatrix":r.referTo("DenseMatrix,SparseMatrix",h=>(x,v)=>h(t(x),v)),"number | BigNumber, SparseMatrix":r.referToSelf(h=>(x,v)=>{if(v.density()===1)return o(v,x,h,!0);throw new Error("Root must be non-zero")})},s({scalar:"number | BigNumber",SD:l,Ss:o,sS:!1}));function d(h,x){var v=a.precision,y=a.clone({precision:v+2}),w=new a(0),C=new y(1),b=x.isNegative();if(b&&(x=x.neg()),x.isZero())throw new Error("Root must be non-zero");if(h.isNegative()&&!x.abs().mod(2).equals(1))throw new Error("Root must be odd when a is negative.");if(h.isZero())return b?new y(1/0):0;if(!h.isFinite())return b?w:h;var M=h.abs().pow(C.div(x));return M=h.isNeg()?M.neg():M,new a((b?C.div(M):M).toPrecision(v))}});var F2="sign",cW=["typed","BigNumber","Fraction","complex"],Wp=F(F2,cW,e=>{var{typed:r,BigNumber:t,complex:n,Fraction:a}=e;return r(F2,{number:rp,Complex:function(u){return u.im===0?n(rp(u.re)):u.sign()},BigNumber:function(u){return new t(u.cmp(0))},Fraction:function(u){return new a(u.s,1)},"Array | Matrix":r.referToSelf(i=>u=>je(u,i,!0)),Unit:r.referToSelf(i=>u=>{if(!u._isDerived()&&u.units[0].unit.offset!==0)throw new TypeError("sign is ambiguous for units with offset");return r.find(i,u.valueType())(u.value)})})});var lW="sqrt",mW=["config","typed","Complex"],Yp=F(lW,mW,e=>{var{config:r,typed:t,Complex:n}=e;return t("sqrt",{number:a,Complex:function(u){return u.sqrt()},BigNumber:function(u){return!u.isNegative()||r.predictable?u.sqrt():a(u.toNumber())},Unit:function(u){return u.pow(.5)}});function a(i){return isNaN(i)?NaN:i>=0||r.predictable?Math.sqrt(i):new n(i,0).sqrt()}});var _2="square",pW=["typed"],Hp=F(_2,pW,e=>{var{typed:r}=e;return r(_2,{number:Cw,Complex:function(n){return n.mul(n)},BigNumber:function(n){return n.times(n)},Fraction:function(n){return n.mul(n)},Unit:function(n){return n.pow(2)}})});var O2="subtract",dW=["typed","matrix","equalScalar","subtractScalar","unaryMinus","DenseMatrix","concat"],$p=F(O2,dW,e=>{var{typed:r,matrix:t,equalScalar:n,subtractScalar:a,unaryMinus:i,DenseMatrix:u,concat:l}=e,c=Mn({typed:r}),o=lt({typed:r}),s=Lo({typed:r,equalScalar:n}),m=jn({typed:r,DenseMatrix:u}),d=Wr({typed:r,DenseMatrix:u}),h=vr({typed:r,matrix:t,concat:l});return r(O2,{"any, any":a},h({elop:a,SS:s,DS:c,SD:o,Ss:d,sS:m}))});var B2="xgcd",hW=["typed","config","matrix","BigNumber"],Gp=F(B2,hW,e=>{var{typed:r,config:t,matrix:n,BigNumber:a}=e;return r(B2,{"number, number":function(l,c){var o=Ew(l,c);return t.matrix==="Array"?o:n(o)},"BigNumber, BigNumber":i});function i(u,l){var c,o,s,m=new a(0),d=new a(1),h=m,x=d,v=d,y=m;if(!u.isInt()||!l.isInt())throw new Error("Parameters in function xgcd must be integer numbers");for(;!l.isZero();)o=u.div(l).floor(),s=u.mod(l),c=h,h=x.minus(o.times(h)),x=c,c=v,v=y.minus(o.times(v)),y=c,u=l,l=s;var w;return u.lt(m)?w=[u.neg(),x.neg(),y.neg()]:w=[u,u.isZero()?0:x,y],t.matrix==="Array"?w:n(w)}});var P2="invmod",vW=["typed","config","BigNumber","xgcd","equal","smaller","mod","add","isInteger"],Vp=F(P2,vW,e=>{var{typed:r,config:t,BigNumber:n,xgcd:a,equal:i,smaller:u,mod:l,add:c,isInteger:o}=e;return r(P2,{"number, number":s,"BigNumber, BigNumber":s});function s(m,d){if(!o(m)||!o(d))throw new Error("Parameters in function invmod must be integer numbers");if(m=l(m,d),i(d,0))throw new Error("Divisor must be non zero");var h=a(m,d);h=h.valueOf();var[x,v]=h;return i(x,n(1))?(v=l(v,d),u(v,n(0))&&(v=c(v,d)),v):NaN}});var gW="matAlgo09xS0Sf",xW=["typed","equalScalar"],Zp=F(gW,xW,e=>{var{typed:r,equalScalar:t}=e;return function(a,i,u){var l=a._values,c=a._index,o=a._ptr,s=a._size,m=a._datatype||a._data===void 0?a._datatype:a.getDataType(),d=i._values,h=i._index,x=i._ptr,v=i._size,y=i._datatype||i._data===void 0?i._datatype:i.getDataType();if(s.length!==v.length)throw new pr(s.length,v.length);if(s[0]!==v[0]||s[1]!==v[1])throw new RangeError("Dimension mismatch. Matrix A ("+s+") must match Matrix B ("+v+")");var w=s[0],C=s[1],b,M=t,A=0,S=u;typeof m=="string"&&m===y&&m!=="mixed"&&(b=m,M=r.find(t,[b,b]),A=r.convert(0,b),S=r.find(u,[b,b]));var O=l&&d?[]:void 0,_=[],E=[],T=O?[]:void 0,R=[],q,W,G,H,L;for(W=0;W{var{typed:r,matrix:t,equalScalar:n,multiplyScalar:a,concat:i}=e,u=Lt({typed:r,equalScalar:n}),l=Zp({typed:r,equalScalar:n}),c=jr({typed:r,equalScalar:n}),o=vr({typed:r,matrix:t,concat:i});return r(I2,o({elop:a,SS:l,DS:u,Ss:c}))});function R2(e,r){if(e.isFinite()&&!e.isInteger()||r.isFinite()&&!r.isInteger())throw new Error("Integers expected in function bitAnd");var t=e.constructor;if(e.isNaN()||r.isNaN())return new t(NaN);if(e.isZero()||r.eq(-1)||e.eq(r))return e;if(r.isZero()||e.eq(-1))return r;if(!e.isFinite()||!r.isFinite()){if(!e.isFinite()&&!r.isFinite())return e.isNegative()===r.isNegative()?e:new t(0);if(!e.isFinite())return r.isNegative()?e:e.isNegative()?new t(0):r;if(!r.isFinite())return e.isNegative()?r:r.isNegative()?new t(0):e}return hD(e,r,function(n,a){return n&a})}function ku(e){if(e.isFinite()&&!e.isInteger())throw new Error("Integer expected in function bitNot");var r=e.constructor,t=r.precision;r.config({precision:1e9});var n=e.plus(new r(1));return n.s=-n.s||null,r.config({precision:t}),n}function k2(e,r){if(e.isFinite()&&!e.isInteger()||r.isFinite()&&!r.isInteger())throw new Error("Integers expected in function bitOr");var t=e.constructor;if(e.isNaN()||r.isNaN())return new t(NaN);var n=new t(-1);return e.isZero()||r.eq(n)||e.eq(r)?r:r.isZero()||e.eq(n)?e:!e.isFinite()||!r.isFinite()?!e.isFinite()&&!e.isNegative()&&r.isNegative()||e.isNegative()&&!r.isNegative()&&!r.isFinite()?n:e.isNegative()&&r.isNegative()?e.isFinite()?e:r:e.isFinite()?r:e:hD(e,r,function(a,i){return a|i})}function hD(e,r,t){var n=e.constructor,a,i,u=+(e.s<0),l=+(r.s<0);if(u){a=Xp(ku(e));for(var c=0;c0;)t(s[--h],m[--x])===v&&(y=y.plus(w)),w=w.times(C);for(;x>0;)t(d,m[--x])===v&&(y=y.plus(w)),w=w.times(C);return n.config({precision:b}),v===0&&(y.s=-y.s),y}function Xp(e){for(var r=e.d,t=r[0]+"",n=1;n0)if(++l>o)for(l-=o;l--;)c+="0";else l1&&((s[h+1]===null||s[h+1]===void 0)&&(s[h+1]=0),s[h+1]+=s[h]>>1,s[h]&=1)}return s.reverse()}function q2(e,r){if(e.isFinite()&&!e.isInteger()||r.isFinite()&&!r.isInteger())throw new Error("Integers expected in function bitXor");var t=e.constructor;if(e.isNaN()||r.isNaN())return new t(NaN);if(e.isZero())return r;if(r.isZero())return e;if(e.eq(r))return new t(0);var n=new t(-1);return e.eq(n)?ku(r):r.eq(n)?ku(e):!e.isFinite()||!r.isFinite()?!e.isFinite()&&!r.isFinite()?n:new t(e.isNegative()===r.isNegative()?1/0:-1/0):hD(e,r,function(a,i){return a^i})}function L2(e,r){if(e.isFinite()&&!e.isInteger()||r.isFinite()&&!r.isInteger())throw new Error("Integers expected in function leftShift");var t=e.constructor;return e.isNaN()||r.isNaN()||r.isNegative()&&!r.isZero()?new t(NaN):e.isZero()||r.isZero()?e:!e.isFinite()&&!r.isFinite()?new t(NaN):r.lt(55)?e.times(Math.pow(2,r.toNumber())+""):e.times(new t(2).pow(r))}function z2(e,r){if(e.isFinite()&&!e.isInteger()||r.isFinite()&&!r.isInteger())throw new Error("Integers expected in function rightArithShift");var t=e.constructor;return e.isNaN()||r.isNaN()||r.isNegative()&&!r.isZero()?new t(NaN):e.isZero()||r.isZero()?e:r.isFinite()?r.lt(55)?e.div(Math.pow(2,r.toNumber())+"").floor():e.div(new t(2).pow(r)).floor():e.isNegative()?new t(-1):e.isFinite()?new t(0):new t(NaN)}var U2="bitAnd",bW=["typed","matrix","equalScalar","concat"],qu=F(U2,bW,e=>{var{typed:r,matrix:t,equalScalar:n,concat:a}=e,i=Lt({typed:r,equalScalar:n}),u=zo({typed:r,equalScalar:n}),l=jr({typed:r,equalScalar:n}),c=vr({typed:r,matrix:t,concat:a});return r(U2,{"number, number":Fw,"BigNumber, BigNumber":R2},c({SS:u,DS:i,Ss:l}))});var W2="bitNot",wW=["typed"],Jp=F(W2,wW,e=>{var{typed:r}=e;return r(W2,{number:_w,BigNumber:ku,"Array | Matrix":r.referToSelf(t=>n=>je(n,t))})});var Y2="bitOr",DW=["typed","matrix","equalScalar","DenseMatrix","concat"],Lu=F(Y2,DW,e=>{var{typed:r,matrix:t,equalScalar:n,DenseMatrix:a,concat:i}=e,u=Mn({typed:r}),l=Ru({typed:r,equalScalar:n}),c=jn({typed:r,DenseMatrix:a}),o=vr({typed:r,matrix:t,concat:i});return r(Y2,{"number, number":Ow,"BigNumber, BigNumber":k2},o({SS:l,DS:u,Ss:c}))});var SW="matAlgo07xSSf",NW=["typed","DenseMatrix"],Zt=F(SW,NW,e=>{var{typed:r,DenseMatrix:t}=e;return function(i,u,l){var c=i._size,o=i._datatype||i._data===void 0?i._datatype:i.getDataType(),s=u._size,m=u._datatype||u._data===void 0?u._datatype:u.getDataType();if(c.length!==s.length)throw new pr(c.length,s.length);if(c[0]!==s[0]||c[1]!==s[1])throw new RangeError("Dimension mismatch. Matrix A ("+c+") must match Matrix B ("+s+")");var d=c[0],h=c[1],x,v=0,y=l;typeof o=="string"&&o===m&&o!=="mixed"&&(x=o,v=r.convert(0,x),y=r.find(l,[x,x]));var w,C,b=[];for(w=0;w{var{typed:r,matrix:t,DenseMatrix:n,concat:a}=e,i=lt({typed:r}),u=Zt({typed:r,DenseMatrix:n}),l=Wr({typed:r,DenseMatrix:n}),c=vr({typed:r,matrix:t,concat:a});return r(H2,{"number, number":Bw,"BigNumber, BigNumber":q2},c({SS:u,DS:i,Ss:l}))});var $2="arg",MW=["typed"],jp=F($2,MW,e=>{var{typed:r}=e;return r($2,{number:function(n){return Math.atan2(0,n)},BigNumber:function(n){return n.constructor.atan2(0,n)},Complex:function(n){return n.arg()},"Array | Matrix":r.referToSelf(t=>n=>je(n,t))})});var G2="conj",CW=["typed"],ed=F(G2,CW,e=>{var{typed:r}=e;return r(G2,{"number | BigNumber | Fraction":t=>t,Complex:t=>t.conjugate(),"Array | Matrix":r.referToSelf(t=>n=>je(n,t))})});var V2="im",EW=["typed"],rd=F(V2,EW,e=>{var{typed:r}=e;return r(V2,{number:()=>0,"BigNumber | Fraction":t=>t.mul(0),Complex:t=>t.im,"Array | Matrix":r.referToSelf(t=>n=>je(n,t))})});var Z2="re",TW=["typed"],td=F(Z2,TW,e=>{var{typed:r}=e;return r(Z2,{"number | BigNumber | Fraction":t=>t,Complex:t=>t.re,"Array | Matrix":r.referToSelf(t=>n=>je(n,t))})});var Q2="not",FW=["typed"],nd=F(Q2,FW,e=>{var{typed:r}=e;return r(Q2,{"null | undefined":()=>!0,number:Lw,Complex:function(n){return n.re===0&&n.im===0},BigNumber:function(n){return n.isZero()||n.isNaN()},Unit:r.referToSelf(t=>n=>r.find(t,n.valueType())(n.value)),"Array | Matrix":r.referToSelf(t=>n=>je(n,t))})});var X2="or",_W=["typed","matrix","equalScalar","DenseMatrix","concat"],zu=F(X2,_W,e=>{var{typed:r,matrix:t,equalScalar:n,DenseMatrix:a,concat:i}=e,u=lt({typed:r}),l=Lo({typed:r,equalScalar:n}),c=Wr({typed:r,DenseMatrix:a}),o=vr({typed:r,matrix:t,concat:i});return r(X2,{"number, number":zw,"Complex, Complex":function(m,d){return m.re!==0||m.im!==0||d.re!==0||d.im!==0},"BigNumber, BigNumber":function(m,d){return!m.isZero()&&!m.isNaN()||!d.isZero()&&!d.isNaN()},"Unit, Unit":r.referToSelf(s=>(m,d)=>s(m.value||0,d.value||0))},o({SS:l,DS:u,Ss:c}))});var J2="xor",OW=["typed","matrix","DenseMatrix","concat"],ad=F(J2,OW,e=>{var{typed:r,matrix:t,DenseMatrix:n,concat:a}=e,i=lt({typed:r}),u=Zt({typed:r,DenseMatrix:n}),l=Wr({typed:r,DenseMatrix:n}),c=vr({typed:r,matrix:t,concat:a});return r(J2,{"number, number":Uw,"Complex, Complex":function(s,m){return(s.re!==0||s.im!==0)!=(m.re!==0||m.im!==0)},"BigNumber, BigNumber":function(s,m){return(!s.isZero()&&!s.isNaN())!=(!m.isZero()&&!m.isNaN())},"Unit, Unit":r.referToSelf(o=>(s,m)=>o(s.value||0,m.value||0))},c({SS:u,DS:i,Ss:l}))});var K2="concat",BW=["typed","matrix","isInteger"],Uu=F(K2,BW,e=>{var{typed:r,matrix:t,isInteger:n}=e;return r(K2,{"...Array | Matrix | number | BigNumber":function(i){var u,l=i.length,c=-1,o,s=!1,m=[];for(u=0;u0&&c>o)throw new tn(c,o+1)}else{var h=ar(d).valueOf(),x=ur(h);if(m[u]=h,o=c,c=x.length-1,u>0&&c!==o)throw new pr(o+1,c+1)}}if(m.length===0)throw new SyntaxError("At least one matrix expected");for(var v=m.shift();m.length;)v=Kb(v,m.shift(),c);return s?t(v):v},"...string":function(i){return i.join("")}})});var j2="column",PW=["typed","Index","matrix","range"],Wu=F(j2,PW,e=>{var{typed:r,Index:t,matrix:n,range:a}=e;return r(j2,{"Matrix, number":i,"Array, number":function(l,c){return i(n(ar(l)),c).valueOf()}});function i(u,l){if(u.size().length!==2)throw new Error("Only two dimensional matrix is supported");Kr(l,u.size()[1]);var c=a(0,u.size()[0]),o=new t(c,l),s=u.subset(o);return Qe(s)?s:n([[s]])}});var eC="count",IW=["typed","size","prod"],id=F(eC,IW,e=>{var{typed:r,size:t,prod:n}=e;return r(eC,{string:function(i){return i.length},"Matrix | Array":function(i){return n(t(i))}})});var rC="cross",RW=["typed","matrix","subtract","multiply"],od=F(rC,RW,e=>{var{typed:r,matrix:t,subtract:n,multiply:a}=e;return r(rC,{"Matrix, Matrix":function(l,c){return t(i(l.toArray(),c.toArray()))},"Matrix, Array":function(l,c){return t(i(l.toArray(),c))},"Array, Matrix":function(l,c){return t(i(l,c.toArray()))},"Array, Array":i});function i(u,l){var c=Math.max(ur(u).length,ur(l).length);u=Au(u),l=Au(l);var o=ur(u),s=ur(l);if(o.length!==1||s.length!==1||o[0]!==3||s[0]!==3)throw new RangeError("Vectors with length 3 expected (Size A = ["+o.join(", ")+"], B = ["+s.join(", ")+"])");var m=[n(a(u[1],l[2]),a(u[2],l[1])),n(a(u[2],l[0]),a(u[0],l[2])),n(a(u[0],l[1]),a(u[1],l[0]))];return c>1?[m]:m}});var tC="diag",kW=["typed","matrix","DenseMatrix","SparseMatrix"],sd=F(tC,kW,e=>{var{typed:r,matrix:t,DenseMatrix:n,SparseMatrix:a}=e;return r(tC,{Array:function(o){return i(o,0,ur(o),null)},"Array, number":function(o,s){return i(o,s,ur(o),null)},"Array, BigNumber":function(o,s){return i(o,s.toNumber(),ur(o),null)},"Array, string":function(o,s){return i(o,0,ur(o),s)},"Array, number, string":function(o,s,m){return i(o,s,ur(o),m)},"Array, BigNumber, string":function(o,s,m){return i(o,s.toNumber(),ur(o),m)},Matrix:function(o){return i(o,0,o.size(),o.storage())},"Matrix, number":function(o,s){return i(o,s,o.size(),o.storage())},"Matrix, BigNumber":function(o,s){return i(o,s.toNumber(),o.size(),o.storage())},"Matrix, string":function(o,s){return i(o,0,o.size(),s)},"Matrix, number, string":function(o,s,m){return i(o,s,o.size(),m)},"Matrix, BigNumber, string":function(o,s,m){return i(o,s.toNumber(),o.size(),m)}});function i(c,o,s,m){if(!Ze(o))throw new TypeError("Second parameter in function diag must be an integer");var d=o>0?o:0,h=o<0?-o:0;switch(s.length){case 1:return u(c,o,m,s[0],h,d);case 2:return l(c,o,m,s,h,d)}throw new RangeError("Matrix for function diag must be 2 dimensional")}function u(c,o,s,m,d,h){var x=[m+d,m+h];if(s&&s!=="sparse"&&s!=="dense")throw new TypeError("Unknown matrix type ".concat(s,'"'));var v=s==="sparse"?a.diagonal(x,c,o):n.diagonal(x,c,o);return s!==null?v:v.valueOf()}function l(c,o,s,m,d,h){if(Qe(c)){var x=c.diagonal(o);return s!==null?s!==x.storage()?t(x,s):x:x.valueOf()}for(var v=Math.min(m[0]-d,m[1]-h),y=[],w=0;w=2&&v.push("index: ".concat(Fr(t))),h.length>=3&&v.push("array: ".concat(Fr(n))),new TypeError("Function ".concat(a," cannot apply callback arguments ")+"".concat(e.name,"(").concat(v.join(", "),") at index ").concat(JSON.stringify(t)))}else throw new TypeError("Function ".concat(a," cannot apply callback arguments ")+"to function ".concat(e.name,": ").concat(y.message))}}}var qW="filter",LW=["typed"],ud=F(qW,LW,e=>{var{typed:r}=e;return r("filter",{"Array, function":nC,"Matrix, function":function(n,a){return n.create(nC(n.toArray(),a))},"Array, RegExp":Mu,"Matrix, RegExp":function(n,a){return n.create(Mu(n.toArray(),a))}})});function nC(e,r){return Om(e,function(t,n,a){return Ia(r,t,[n],a,"filter")})}var aC="flatten",zW=["typed","matrix"],fd=F(aC,zW,e=>{var{typed:r,matrix:t}=e;return r(aC,{Array:function(a){return gr(a)},Matrix:function(a){var i=gr(a.toArray());return t(i)}})});var iC="forEach",UW=["typed"],cd=F(iC,UW,e=>{var{typed:r}=e;return r(iC,{"Array, function":WW,"Matrix, function":function(n,a){n.forEach(a)}})});function WW(e,r){var t=function n(a,i){if(Array.isArray(a))Fo(a,function(u,l){n(u,i.concat(l))});else return Ia(r,a,i,e,"forEach")};t(e,[])}var oC="getMatrixDataType",YW=["typed"],ld=F(oC,YW,e=>{var{typed:r}=e;return r(oC,{Array:function(n){return _o(n,Fr)},Matrix:function(n){return n.getDataType()}})});var sC="identity",HW=["typed","config","matrix","BigNumber","DenseMatrix","SparseMatrix"],md=F(sC,HW,e=>{var{typed:r,config:t,matrix:n,BigNumber:a,DenseMatrix:i,SparseMatrix:u}=e;return r(sC,{"":function(){return t.matrix==="Matrix"?n([]):[]},string:function(s){return n(s)},"number | BigNumber":function(s){return c(s,s,t.matrix==="Matrix"?"dense":void 0)},"number | BigNumber, string":function(s,m){return c(s,s,m)},"number | BigNumber, number | BigNumber":function(s,m){return c(s,m,t.matrix==="Matrix"?"dense":void 0)},"number | BigNumber, number | BigNumber, string":function(s,m,d){return c(s,m,d)},Array:function(s){return l(s)},"Array, string":function(s,m){return l(s,m)},Matrix:function(s){return l(s.valueOf(),s.storage())},"Matrix, string":function(s,m){return l(s.valueOf(),m)}});function l(o,s){switch(o.length){case 0:return s?n(s):[];case 1:return c(o[0],o[0],s);case 2:return c(o[0],o[1],s);default:throw new Error("Vector containing two values expected")}}function c(o,s,m){var d=rr(o)||rr(s)?a:null;if(rr(o)&&(o=o.toNumber()),rr(s)&&(s=s.toNumber()),!Ze(o)||o<1)throw new Error("Parameters in function identity must be positive integers");if(!Ze(s)||s<1)throw new Error("Parameters in function identity must be positive integers");var h=d?new a(1):1,x=d?new d(0):0,v=[o,s];if(m){if(m==="sparse")return u.diagonal(v,h,0,x);if(m==="dense")return i.diagonal(v,h,0,x);throw new TypeError('Unknown matrix type "'.concat(m,'"'))}for(var y=ii([],v,x),w=o{var{typed:r,matrix:t,multiplyScalar:n}=e;return r(uC,{"Matrix, Matrix":function(u,l){return t(a(u.toArray(),l.toArray()))},"Matrix, Array":function(u,l){return t(a(u.toArray(),l))},"Array, Matrix":function(u,l){return t(a(u,l.toArray()))},"Array, Array":a});function a(i,u){if(ur(i).length===1&&(i=[i]),ur(u).length===1&&(u=[u]),ur(i).length>2||ur(u).length>2)throw new RangeError("Vectors with dimensions greater then 2 are not supported expected (Size x = "+JSON.stringify(i.length)+", y = "+JSON.stringify(u.length)+")");var l=[],c=[];return i.map(function(o){return u.map(function(s){return c=[],l.push(c),o.map(function(m){return s.map(function(d){return c.push(n(m,d))})})})})&&l}});var fC="map",GW=["typed"],dd=F(fC,GW,e=>{var{typed:r}=e;return r(fC,{"Array, function":VW,"Matrix, function":function(n,a){return n.map(a)}})});function VW(e,r){var t=function n(a,i){return Array.isArray(a)?a.map(function(u,l){return n(u,i.concat(l))}):Ia(r,a,i,e,"map")};return t(e,[])}var cC="diff",ZW=["typed","matrix","subtract","number"],Yu=F(cC,ZW,e=>{var{typed:r,matrix:t,subtract:n,number:a}=e;return r(cC,{"Array | Matrix":function(s){return Qe(s)?t(u(s.toArray())):u(s)},"Array | Matrix, number":function(s,m){if(!Ze(m))throw new RangeError("Dimension must be a whole number");return Qe(s)?t(i(s.toArray(),m)):i(s,m)},"Array, BigNumber":r.referTo("Array,number",o=>(s,m)=>o(s,a(m))),"Matrix, BigNumber":r.referTo("Matrix,number",o=>(s,m)=>o(s,a(m)))});function i(o,s){if(Qe(o)&&(o=o.toArray()),!Array.isArray(o))throw RangeError("Array/Matrix does not have that many dimensions");if(s>0){var m=[];return o.forEach(d=>{m.push(i(d,s-1))}),m}else{if(s===0)return u(o);throw RangeError("Cannot have negative dimension")}}function u(o){for(var s=[],m=o.length,d=1;d{var{typed:r,config:t,matrix:n,BigNumber:a}=e;return r("ones",{"":function(){return t.matrix==="Array"?i([]):i([],"default")},"...number | BigNumber | string":function(o){var s=o[o.length-1];if(typeof s=="string"){var m=o.pop();return i(o,m)}else return t.matrix==="Array"?i(o):i(o,"default")},Array:i,Matrix:function(o){var s=o.storage();return i(o.valueOf(),s)},"Array | Matrix, string":function(o,s){return i(o.valueOf(),s)}});function i(c,o){var s=u(c),m=s?new a(1):1;if(l(c),o){var d=n(o);return c.length>0?d.resize(c,m):d}else{var h=[];return c.length>0?ii(h,c,m):h}}function u(c){var o=!1;return c.forEach(function(s,m,d){rr(s)&&(o=!0,d[m]=s.toNumber())}),o}function l(c){c.forEach(function(o){if(typeof o!="number"||!Ze(o)||o<0)throw new Error("Parameters in function ones must be positive integers")})}});function Hu(){throw new Error('No "bignumber" implementation available')}function vd(){throw new Error('No "fraction" implementation available')}function gd(){throw new Error('No "matrix" implementation available')}var lC="range",JW=["typed","config","?matrix","?bignumber","smaller","smallerEq","larger","largerEq","add","isPositive"],$u=F(lC,JW,e=>{var{typed:r,config:t,matrix:n,bignumber:a,smaller:i,smallerEq:u,larger:l,largerEq:c,add:o,isPositive:s}=e;return r(lC,{string:d,"string, boolean":d,"number, number":function(y,w){return m(h(y,w,1,!1))},"number, number, number":function(y,w,C){return m(h(y,w,C,!1))},"number, number, boolean":function(y,w,C){return m(h(y,w,1,C))},"number, number, number, boolean":function(y,w,C,b){return m(h(y,w,C,b))},"BigNumber, BigNumber":function(y,w){var C=y.constructor;return m(h(y,w,new C(1),!1))},"BigNumber, BigNumber, BigNumber":function(y,w,C){return m(h(y,w,C,!1))},"BigNumber, BigNumber, boolean":function(y,w,C){var b=y.constructor;return m(h(y,w,new b(1),C))},"BigNumber, BigNumber, BigNumber, boolean":function(y,w,C,b){return m(h(y,w,C,b))},"Unit, Unit, Unit":function(y,w,C){return m(h(y,w,C,!1))},"Unit, Unit, Unit, boolean":function(y,w,C,b){return m(h(y,w,C,b))}});function m(v){return t.matrix==="Matrix"?n?n(v):gd():v}function d(v,y){var w=x(v);if(!w)throw new SyntaxError('String "'+v+'" is no valid range');return t.number==="BigNumber"?(a===void 0&&Hu(),m(h(a(w.start),a(w.end),a(w.step)),y)):m(h(w.start,w.end,w.step,y))}function h(v,y,w,C){for(var b=[],M=s(w)?C?u:i:C?c:l,A=v;M(A,y);)b.push(A),A=o(A,w);return b}function x(v){var y=v.split(":"),w=y.map(function(b){return Number(b)}),C=w.some(function(b){return isNaN(b)});if(C)return null;switch(w.length){case 2:return{start:w[0],end:w[1],step:1};case 3:return{start:w[0],end:w[2],step:w[1]};default:return null}}});var mC="reshape",KW=["typed","isInteger","matrix"],xd=F(mC,KW,e=>{var{typed:r,isInteger:t}=e;return r(mC,{"Matrix, Array":function(a,i){return a.reshape(i,!0)},"Array, Array":function(a,i){return i.forEach(function(u){if(!t(u))throw new TypeError("Invalid size for dimension: "+u)}),Mc(a,i)}})});var jW="resize",eY=["config","matrix"],yd=F(jW,eY,e=>{var{config:r,matrix:t}=e;return function(i,u,l){if(arguments.length!==2&&arguments.length!==3)throw new ha("resize",arguments.length,2,3);if(Qe(u)&&(u=u.valueOf()),rr(u[0])&&(u=u.map(function(s){return rr(s)?s.toNumber():s})),Qe(i))return i.resize(u,l,!0);if(typeof i=="string")return n(i,u,l);var c=Array.isArray(i)?!1:r.matrix!=="Array";if(u.length===0){for(;Array.isArray(i);)i=i[0];return ar(i)}else{Array.isArray(i)||(i=[i]),i=ar(i);var o=ii(i,u,l);return c?t(o):o}};function n(a,i,u){if(u!==void 0){if(typeof u!="string"||u.length!==1)throw new TypeError("Single character expected as defaultValue")}else u=" ";if(i.length!==1)throw new pr(i.length,1);var l=i[0];if(typeof l!="number"||!Ze(l))throw new TypeError("Invalid size, must contain positive integers (size: "+lr(i)+")");if(a.length>l)return a.substring(0,l);if(a.length{var{typed:r,multiply:t,rotationMatrix:n}=e;return r(pC,{"Array , number | BigNumber | Complex | Unit":function(u,l){a(u,2);var c=t(n(l),u);return c.toArray()},"Matrix , number | BigNumber | Complex | Unit":function(u,l){return a(u,2),t(n(l),u)},"Array, number | BigNumber | Complex | Unit, Array | Matrix":function(u,l,c){a(u,3);var o=t(n(l,c),u);return o},"Matrix, number | BigNumber | Complex | Unit, Array | Matrix":function(u,l,c){return a(u,3),t(n(l,c),u)}});function a(i,u){var l=Array.isArray(i)?ur(i):i.size();if(l.length>2)throw new RangeError("Vector must be of dimensions 1x".concat(u));if(l.length===2&&l[1]!==1)throw new RangeError("Vector must be of dimensions 1x".concat(u));if(l[0]!==u)throw new RangeError("Vector must be of dimensions 1x".concat(u))}});var dC="rotationMatrix",tY=["typed","config","multiplyScalar","addScalar","unaryMinus","norm","matrix","BigNumber","DenseMatrix","SparseMatrix","cos","sin"],wd=F(dC,tY,e=>{var{typed:r,config:t,multiplyScalar:n,addScalar:a,unaryMinus:i,norm:u,BigNumber:l,matrix:c,DenseMatrix:o,SparseMatrix:s,cos:m,sin:d}=e;return r(dC,{"":function(){return t.matrix==="Matrix"?c([]):[]},string:function(b){return c(b)},"number | BigNumber | Complex | Unit":function(b){return h(b,t.matrix==="Matrix"?"dense":void 0)},"number | BigNumber | Complex | Unit, string":function(b,M){return h(b,M)},"number | BigNumber | Complex | Unit, Array":function(b,M){var A=c(M);return x(A),w(b,A,void 0)},"number | BigNumber | Complex | Unit, Matrix":function(b,M){x(M);var A=M.storage()||(t.matrix==="Matrix"?"dense":void 0);return w(b,M,A)},"number | BigNumber | Complex | Unit, Array, string":function(b,M,A){var S=c(M);return x(S),w(b,S,A)},"number | BigNumber | Complex | Unit, Matrix, string":function(b,M,A){return x(M),w(b,M,A)}});function h(C,b){var M=rr(C),A=M?new l(-1):-1,S=m(C),O=d(C),_=[[S,n(A,O)],[O,S]];return y(_,b)}function x(C){var b=C.size();if(b.length<1||b[0]!==3)throw new RangeError("Vector must be of dimensions 1x3")}function v(C){return C.reduce((b,M)=>n(b,M))}function y(C,b){if(b){if(b==="sparse")return new s(C);if(b==="dense")return new o(C);throw new TypeError('Unknown matrix type "'.concat(b,'"'))}return C}function w(C,b,M){var A=u(b);if(A===0)throw new RangeError("Rotation around zero vector");var S=rr(C)?l:null,O=S?new S(1):1,_=S?new S(-1):-1,E=S?new S(b.get([0])/A):b.get([0])/A,T=S?new S(b.get([1])/A):b.get([1])/A,R=S?new S(b.get([2])/A):b.get([2])/A,q=m(C),W=a(O,i(q)),G=d(C),H=a(q,v([E,E,W])),L=a(v([E,T,W]),v([_,R,G])),k=a(v([E,R,W]),v([T,G])),K=a(v([E,T,W]),v([R,G])),z=a(q,v([T,T,W])),oe=a(v([T,R,W]),v([_,E,G])),pe=a(v([E,R,W]),v([_,T,G])),ae=a(v([T,R,W]),v([E,G])),$=a(q,v([R,R,W])),le=[[H,L,k],[K,z,oe],[pe,ae,$]];return y(le,M)}});var hC="row",nY=["typed","Index","matrix","range"],Gu=F(hC,nY,e=>{var{typed:r,Index:t,matrix:n,range:a}=e;return r(hC,{"Matrix, number":i,"Array, number":function(l,c){return i(n(ar(l)),c).valueOf()}});function i(u,l){if(u.size().length!==2)throw new Error("Only two dimensional matrix is supported");Kr(l,u.size()[0]);var c=a(0,u.size()[1]),o=new t(l,c),s=u.subset(o);return Qe(s)?s:n([[s]])}});var vC="size",aY=["typed","config","?matrix"],Dd=F(vC,aY,e=>{var{typed:r,config:t,matrix:n}=e;return r(vC,{Matrix:function(i){return i.create(i.size())},Array:ur,string:function(i){return t.matrix==="Array"?[i.length]:n([i.length])},"number | Complex | BigNumber | Unit | boolean | null":function(i){return t.matrix==="Array"?[]:n?n([]):gd()}})});var gC="squeeze",iY=["typed","matrix"],Sd=F(gC,iY,e=>{var{typed:r,matrix:t}=e;return r(gC,{Array:function(a){return Au(ar(a))},Matrix:function(a){var i=Au(a.toArray());return Array.isArray(i)?t(i):i},any:function(a){return ar(a)}})});var xC="subset",oY=["typed","matrix","zeros","add"],Vu=F(xC,oY,e=>{var{typed:r,matrix:t,zeros:n,add:a}=e;return r(xC,{"Matrix, Index":function(l,c){return Ns(c)?t():(Ac(l,c),l.subset(c))},"Array, Index":r.referTo("Matrix, Index",function(u){return function(l,c){var o=u(t(l),c);return c.isScalar()?o:o.valueOf()}}),"Object, Index":uY,"string, Index":sY,"Matrix, Index, any, any":function(l,c,o,s){return Ns(c)?l:(Ac(l,c),l.clone().subset(c,i(o,c),s))},"Array, Index, any, any":r.referTo("Matrix, Index, any, any",function(u){return function(l,c,o,s){var m=u(t(l),c,o,s);return m.isMatrix?m.valueOf():m}}),"Array, Index, any":r.referTo("Matrix, Index, any, any",function(u){return function(l,c,o){return u(t(l),c,o,void 0).valueOf()}}),"Matrix, Index, any":r.referTo("Matrix, Index, any, any",function(u){return function(l,c,o){return u(l,c,o,void 0)}}),"string, Index, string":yC,"string, Index, string, string":yC,"Object, Index, any":fY});function i(u,l){if(typeof u=="string")throw new Error("can't boradcast a string");if(l._isScalar)return u;var c=l.size();if(c.every(o=>o>0))try{return a(u,n(c))}catch{return u}else return u}});function sY(e,r){if(!Ai(r))throw new TypeError("Index expected");if(Ns(r))return"";if(Ac(Array.from(e),r),r.size().length!==1)throw new pr(r.size().length,1);var t=e.length;Kr(r.min()[0],t),Kr(r.max()[0],t);var n=r.dimension(0),a="";return n.forEach(function(i){a+=e.charAt(i)}),a}function yC(e,r,t,n){if(!r||r.isIndex!==!0)throw new TypeError("Index expected");if(Ns(r))return e;if(Ac(Array.from(e),r),r.size().length!==1)throw new pr(r.size().length,1);if(n!==void 0){if(typeof n!="string"||n.length!==1)throw new TypeError("Single character expected as defaultValue")}else n=" ";var a=r.dimension(0),i=a.size()[0];if(i!==t.length)throw new pr(a.size()[0],t.length);var u=e.length;Kr(r.min()[0]),Kr(r.max()[0]);for(var l=[],c=0;cu)for(var o=u-1,s=l.length;o{var{typed:r,matrix:t}=e;return r(bC,{Array:u=>n(t(u)).valueOf(),Matrix:n,any:ar});function n(u){var l=u.size(),c;switch(l.length){case 1:c=u.clone();break;case 2:{var o=l[0],s=l[1];if(s===0)throw new RangeError("Cannot transpose a 2D matrix with no columns (size: "+lr(l)+")");switch(u.storage()){case"dense":c=a(u,o,s);break;case"sparse":c=i(u,o,s);break}}break;default:throw new RangeError("Matrix must be a vector or two dimensional (size: "+lr(l)+")")}return c}function a(u,l,c){for(var o=u._data,s=[],m,d=0;d{var{typed:r,transpose:t,conj:n}=e;return r(wC,{any:function(i){return n(t(i))}})});var DC="zeros",mY=["typed","config","matrix","BigNumber"],Md=F(DC,mY,e=>{var{typed:r,config:t,matrix:n,BigNumber:a}=e;return r(DC,{"":function(){return t.matrix==="Array"?i([]):i([],"default")},"...number | BigNumber | string":function(o){var s=o[o.length-1];if(typeof s=="string"){var m=o.pop();return i(o,m)}else return t.matrix==="Array"?i(o):i(o,"default")},Array:i,Matrix:function(o){var s=o.storage();return i(o.valueOf(),s)},"Array | Matrix, string":function(o,s){return i(o.valueOf(),s)}});function i(c,o){var s=u(c),m=s?new a(0):0;if(l(c),o){var d=n(o);return c.length>0?d.resize(c,m):d}else{var h=[];return c.length>0?ii(h,c,m):h}}function u(c){var o=!1;return c.forEach(function(s,m,d){rr(s)&&(o=!0,d[m]=s.toNumber())}),o}function l(c){c.forEach(function(o){if(typeof o!="number"||!Ze(o)||o<0)throw new Error("Parameters in function zeros must be positive integers")})}});var SC="fft",pY=["typed","matrix","addScalar","multiplyScalar","divideScalar","exp","tau","i","dotDivide","conj","pow","ceil","log2"],Cd=F(SC,pY,e=>{var{typed:r,matrix:t,addScalar:n,multiplyScalar:a,divideScalar:i,exp:u,tau:l,i:c,dotDivide:o,conj:s,pow:m,ceil:d,log2:h}=e;return r(SC,{Array:x,Matrix:function(b){return b.create(x(b.toArray()))}});function x(C){var b=ur(C);return b.length===1?w(C,b[0]):v(C.map(M=>x(M,b.slice(1))),0)}function v(C,b){var M=ur(C);if(b!==0)return new Array(M[0]).fill(0).map((S,O)=>v(C[O],b-1));if(M.length===1)return w(C);function A(S){var O=ur(S);return new Array(O[1]).fill(0).map((_,E)=>new Array(O[0]).fill(0).map((T,R)=>S[R][E]))}return A(v(A(C),1))}function y(C){for(var b=C.length,M=u(i(a(-1,a(c,l)),b)),A=[],S=1-b;Sa(C[k],A[b-1+k])),...new Array(O-b).fill(0)],E=[...new Array(b+b-1).fill(0).map((L,k)=>i(1,A[k])),...new Array(O-(b+b-1)).fill(0)],T=w(_),R=w(E),q=new Array(O).fill(0).map((L,k)=>a(T[k],R[k])),W=o(s(x(s(q))),O),G=[],H=b-1;HE%2===0),b/2),...w(C.filter((_,E)=>E%2===1),b/2)],A=0;A{var{typed:r,fft:t,dotDivide:n,conj:a}=e;return r(NC,{"Array | Matrix":function(u){var l=Qe(u)?u.size():ur(u);return n(a(t(a(u))),l.reduce((c,o)=>c*o,1))}})});function AC(e,r){var t=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);r&&(n=n.filter(function(a){return Object.getOwnPropertyDescriptor(e,a).enumerable})),t.push.apply(t,n)}return t}function hY(e){for(var r=1;r{var{typed:r,add:t,subtract:n,multiply:a,divide:i,max:u,map:l,abs:c,isPositive:o,isNegative:s,larger:m,smaller:d,matrix:h,bignumber:x,unaryMinus:v}=e;function y(_){return function(E,T,R,q){var W=!(T.length===2&&(T.every(S)||T.every(Ht)));if(W)throw new Error('"tspan" must be an Array of two numeric values or two units [tStart, tEnd]');var G=T[0],H=T[1],L=m(H,G),k=q.firstStep;if(k!==void 0&&!o(k))throw new Error('"firstStep" must be positive');var K=q.maxStep;if(K!==void 0&&!o(K))throw new Error('"maxStep" must be positive');var z=q.minStep;if(z&&s(z))throw new Error('"minStep" must be positive or zero');var oe=[G,H,k,z,K].filter(Le=>Le!==void 0);if(!(oe.every(S)||oe.every(Ht)))throw new Error('Inconsistent type of "t" dependant variables');for(var pe=1,ae=q.tol?q.tol:1e-4,$=q.minDelta?q.minDelta:.2,le=q.maxDelta?q.maxDelta:5,Ee=q.maxIter?q.maxIter:1e4,me=[G,H,...R,K,z].some(rr),[ge,Se,xe,be]=me?[x(_.a),x(_.c),x(_.b),x(_.bp)]:[_.a,_.c,_.b,_.bp],De=k?L?k:v(k):i(n(H,G),pe),Ae=[G],We=[R],Je=n(xe,be),J=0,re=0,ye=M(L),j=A(L);ye(Ae[J],H);){var ne=[];De=j(Ae[J],H,De),ne.push(E(Ae[J],We[J]));for(var ue=1;ueHt(Le)?Le.value:Le)));Me1/4&&(Ae.push(t(Ae[J],De)),We.push(t(We[J],a(De,xe,ne))),J++);var Ce=.84*(ae/Me)**(1/5);if(d(Ce,$)?Ce=$:m(Ce,le)&&(Ce=le),Ce=me?x(Ce):Ce,De=a(De,Ce),K&&m(c(De),K)?De=L?K:v(K):z&&d(c(De),z)&&(De=L?z:v(z)),re++,re>Ee)throw new Error("Maximum number of iterations reached, try changing options")}return{t:Ae,y:We}}}function w(_,E,T,R){var q=[[],[.5],[0,.75],[.2222222222222222,.3333333333333333,.4444444444444444]],W=[null,1/2,3/4,1],G=[2/9,1/3,4/9,0],H=[7/24,1/4,1/3,1/8],L={a:q,c:W,b:G,bp:H};return y(L)(_,E,T,R)}function C(_,E,T,R){var q=[[],[.2],[.075,.225],[.9777777777777777,-3.7333333333333334,3.5555555555555554],[2.9525986892242035,-11.595793324188385,9.822892851699436,-.2908093278463649],[2.8462752525252526,-10.757575757575758,8.906422717743473,.2784090909090909,-.2735313036020583],[.09114583333333333,0,.44923629829290207,.6510416666666666,-.322376179245283,.13095238095238096]],W=[null,1/5,3/10,4/5,8/9,1,1],G=[35/384,0,500/1113,125/192,-2187/6784,11/84,0],H=[5179/57600,0,7571/16695,393/640,-92097/339200,187/2100,1/40],L={a:q,c:W,b:G,bp:H};return y(L)(_,E,T,R)}function b(_,E,T,R){var q=R.method?R.method:"RK45",W={RK23:w,RK45:C};if(q.toUpperCase()in W){var G=hY({},R);return delete G.method,W[q.toUpperCase()](_,E,T,G)}else{var H=Object.keys(W).map(k=>'"'.concat(k,'"')),L="".concat(H.slice(0,-1).join(", ")," and ").concat(H.slice(-1));throw new Error('Unavailable method "'.concat(q,'". Available methods are ').concat(L))}}function M(_){return _?d:m}function A(_){var E=_?m:d;return function(T,R,q){var W=t(T,q);return E(W,R)?n(R,T):q}}function S(_){return rr(_)||sr(_)}function O(_,E,T,R){var q=b(_,E.toArray(),T.toArray(),R);return{t:h(q.t),y:h(q.y)}}return r("solveODE",{"function, Array, Array, Object":b,"function, Matrix, Matrix, Object":O,"function, Array, Array":(_,E,T)=>b(_,E,T,{}),"function, Matrix, Matrix":(_,E,T)=>O(_,E,T,{}),"function, Array, number | BigNumber | Unit":(_,E,T)=>{var R=b(_,E,[T],{});return{t:R.t,y:R.y.map(q=>q[0])}},"function, Matrix, number | BigNumber | Unit":(_,E,T)=>{var R=b(_,E.toArray(),[T],{});return{t:h(R.t),y:h(R.y.map(q=>q[0]))}},"function, Array, number | BigNumber | Unit, Object":(_,E,T,R)=>{var q=b(_,E,[T],R);return{t:q.t,y:q.y.map(W=>W[0])}},"function, Matrix, number | BigNumber | Unit, Object":(_,E,T,R)=>{var q=b(_,E.toArray(),[T],R);return{t:h(q.t),y:h(q.y.map(W=>W[0]))}}})});var xY="erf",yY=["typed"],Fd=F(xY,yY,e=>{var{typed:r}=e;return r("name",{number:function(u){var l=Math.abs(u);return l>=DY?Oa(u):l<=bY?Oa(u)*t(l):l<=4?Oa(u)*(1-n(l)):Oa(u)*(1-a(l))},"Array | Matrix":r.referToSelf(i=>u=>je(u,i))});function t(i){var u=i*i,l=ro[0][4]*u,c=u,o;for(o=0;o<3;o+=1)l=(l+ro[0][o])*u,c=(c+Zu[0][o])*u;return i*(l+ro[0][3])/(c+Zu[0][3])}function n(i){var u=ro[1][8]*i,l=i,c;for(c=0;c<7;c+=1)u=(u+ro[1][c])*i,l=(l+Zu[1][c])*i;var o=(u+ro[1][7])/(l+Zu[1][7]),s=parseInt(i*16)/16,m=(i-s)*(i+s);return Math.exp(-s*s)*Math.exp(-m)*o}function a(i){var u=1/(i*i),l=ro[2][5]*u,c=u,o;for(o=0;o<4;o+=1)l=(l+ro[2][o])*u,c=(c+Zu[2][o])*u;var s=u*(l+ro[2][4])/(c+Zu[2][4]);s=(wY-s)/i,u=parseInt(i*16)/16;var m=(i-u)*(i+u);return Math.exp(-u*u)*Math.exp(-m)*s}}),bY=.46875,wY=.5641895835477563,ro=[[3.1611237438705655,113.86415415105016,377.485237685302,3209.3775891384694,.18577770618460315],[.5641884969886701,8.883149794388377,66.11919063714163,298.6351381974001,881.952221241769,1712.0476126340707,2051.0783778260716,1230.3393547979972,21531153547440383e-24],[.30532663496123236,.36034489994980445,.12578172611122926,.016083785148742275,.0006587491615298378,.016315387137302097]],Zu=[[23.601290952344122,244.02463793444417,1282.6165260773723,2844.236833439171],[15.744926110709835,117.6939508913125,537.1811018620099,1621.3895745666903,3290.7992357334597,4362.619090143247,3439.3676741437216,1230.3393548037495],[2.568520192289822,1.8729528499234604,.5279051029514285,.06051834131244132,.0023352049762686918]],DY=Math.pow(2,53);var MC="zeta",SY=["typed","config","multiply","pow","divide","factorial","equal","smallerEq","isNegative","gamma","sin","subtract","add","?Complex","?BigNumber","pi"],_d=F(MC,SY,e=>{var{typed:r,config:t,multiply:n,pow:a,divide:i,factorial:u,equal:l,smallerEq:c,isNegative:o,gamma:s,sin:m,subtract:d,add:h,Complex:x,BigNumber:v,pi:y}=e;return r(MC,{number:S=>w(S,O=>O,()=>20),BigNumber:S=>w(S,O=>new v(O),()=>Math.abs(Math.log10(t.epsilon))),Complex:C});function w(S,O,_){return l(S,0)?O(-.5):l(S,1)?O(NaN):isFinite(S)?b(S,O,_,E=>E):o(S)?O(NaN):O(1)}function C(S){return S.re===0&&S.im===0?new x(-.5):S.re===1?new x(NaN,NaN):S.re===1/0&&S.im===0?new x(1):S.im===1/0||S.re===-1/0?new x(NaN,NaN):b(S,O=>O,O=>Math.round(1.3*15+.9*Math.abs(O.im)),O=>O.re)}function b(S,O,_,E){var T=_(S);if(E(S)>-(T-1)/2)return A(S,O(T),O);var R=n(a(2,S),a(O(y),d(S,1)));return R=n(R,m(n(i(O(y),2),S))),R=n(R,s(d(1,S))),n(R,b(d(1,S),O,_,E))}function M(S,O){for(var _=S,E=S;c(E,O);E=h(E,1)){var T=i(n(u(h(O,d(E,1))),a(4,E)),n(u(d(O,E)),u(n(2,E))));_=h(_,T)}return n(O,_)}function A(S,O,_){for(var E=i(1,n(M(_(0),O),d(1,a(2,d(1,S))))),T=_(0),R=_(1);c(R,O);R=h(R,1))T=h(T,i(n((-1)**(R-1),M(R,O)),a(R,S)));return n(E,T)}});var CC="mode",NY=["typed","isNaN","isNumeric"],Od=F(CC,NY,e=>{var{typed:r,isNaN:t,isNumeric:n}=e;return r(CC,{"Array | Matrix":a,"...":function(u){return a(u)}});function a(i){i=gr(i.valueOf());var u=i.length;if(u===0)throw new Error("Cannot calculate mode of an empty array");for(var l={},c=[],o=0,s=0;so&&(o=l[m],c=[m])}return c}});function Et(e,r,t){var n;return String(e).indexOf("Unexpected type")!==-1?(n=arguments.length>2?" (type: "+Fr(t)+", value: "+JSON.stringify(t)+")":" (type: "+e.data.actual+")",new TypeError("Cannot calculate "+r+", unexpected type of argument"+n)):String(e).indexOf("complex numbers")!==-1?(n=arguments.length>2?" (type: "+Fr(t)+", value: "+JSON.stringify(t)+")":"",new TypeError("Cannot calculate "+r+", no ordering relation is defined for complex numbers"+n)):e}var EC="prod",AY=["typed","config","multiplyScalar","numeric"],Bd=F(EC,AY,e=>{var{typed:r,config:t,multiplyScalar:n,numeric:a}=e;return r(EC,{"Array | Matrix":i,"Array | Matrix, number | BigNumber":function(l,c){throw new Error("prod(A, dim) is not yet supported")},"...":function(l){return i(l)}});function i(u){var l;if(An(u,function(c){try{l=l===void 0?c:n(l,c)}catch(o){throw Et(o,"prod",c)}}),typeof l=="string"&&(l=a(l,t.number)),l===void 0)throw new Error("Cannot calculate prod of an empty array");return l}});var TC="format",MY=["typed"],Pd=F(TC,MY,e=>{var{typed:r}=e;return r(TC,{any:lr,"any, Object | function | number | BigNumber":lr})});var FC="bin",CY=["typed","format"],Id=F(FC,CY,e=>{var{typed:r,format:t}=e;return r(FC,{"number | BigNumber":function(a){return t(a,{notation:"bin"})},"number | BigNumber, number | BigNumber":function(a,i){return t(a,{notation:"bin",wordSize:i})}})});var _C="oct",EY=["typed","format"],Rd=F(_C,EY,e=>{var{typed:r,format:t}=e;return r(_C,{"number | BigNumber":function(a){return t(a,{notation:"oct"})},"number | BigNumber, number | BigNumber":function(a,i){return t(a,{notation:"oct",wordSize:i})}})});var OC="hex",TY=["typed","format"],kd=F(OC,TY,e=>{var{typed:r,format:t}=e;return r(OC,{"number | BigNumber":function(a){return t(a,{notation:"hex"})},"number | BigNumber, number | BigNumber":function(a,i){return t(a,{notation:"hex",wordSize:i})}})});var qd=/\\$([\\w.]+)/g;var BC="print",FY=["typed"],Qu=F(BC,FY,e=>{var{typed:r}=e;return r(BC,{"string, Object | Array":PC,"string, Object | Array, number | Object":PC})});function PC(e,r,t){return e.replace(qd,function(n,a){var i=a.split("."),u=r[i.shift()];for(u!==void 0&&u.isMatrix&&(u=u.toArray());i.length&&u!==void 0;){var l=i.shift();u=l?u[l]:u+"."}return u!==void 0?St(u)?u:lr(u,t):n})}var IC="to",_Y=["typed","matrix","concat"],Ld=F(IC,_Y,e=>{var{typed:r,matrix:t,concat:n}=e,a=vr({typed:r,matrix:t,concat:n});return r(IC,{"Unit, Unit | string":(i,u)=>i.to(u)},a({Ds:!0}))});var RC="isPrime",OY=["typed"],zd=F(RC,OY,e=>{var{typed:r}=e;return r(RC,{number:function(n){if(n*0!==0)return!1;if(n<=3)return n>1;if(n%2===0||n%3===0)return!1;for(var a=5;a*a<=n;a+=6)if(n%a===0||n%(a+2)===0)return!1;return!0},BigNumber:function(n){if(n.toNumber()*0!==0)return!1;if(n.lte(3))return n.gt(1);if(n.mod(2).eq(0)||n.mod(3).eq(0))return!1;if(n.lt(Math.pow(2,32))){for(var a=n.toNumber(),i=5;i*i<=a;i+=6)if(a%i===0||a%(i+2)===0)return!1;return!0}function u(C,b,M){for(var A=1;!b.eq(0);)b.mod(2).eq(0)?(b=b.div(2),C=C.mul(C).mod(M)):(b=b.sub(1),A=C.mul(A).mod(M));return A}var l=n.constructor.clone({precision:n.toFixed(0).length*2});n=new l(n);for(var c=0,o=n.sub(1);o.mod(2).eq(0);)o=o.div(2),c+=1;var s=null;if(n.lt("3317044064679887385961981"))s=[2,3,5,7,11,13,17,19,23,29,31,37,41].filter(C=>Cn=>je(n,t))})});var BY="numeric",PY=["number","?bignumber","?fraction"],Ud=F(BY,PY,e=>{var{number:r,bignumber:t,fraction:n}=e,a={string:!0,number:!0,BigNumber:!0,Fraction:!0},i={number:u=>r(u),BigNumber:t?u=>t(u):Hu,Fraction:n?u=>n(u):vd};return function(l){var c=arguments.length>1&&arguments[1]!==void 0?arguments[1]:"number",o=arguments.length>2?arguments[2]:void 0;if(o!==void 0)throw new SyntaxError("numeric() takes one or two arguments");var s=Fr(l);if(!(s in a))throw new TypeError("Cannot convert "+l+' of type "'+s+'"; valid input types are '+Object.keys(a).join(", "));if(!(c in i))throw new TypeError("Cannot convert "+l+' to type "'+c+'"; valid output types are '+Object.keys(i).join(", "));return c===s?l:i[c](l)}});var kC="divideScalar",IY=["typed","numeric"],Wd=F(kC,IY,e=>{var{typed:r,numeric:t}=e;return r(kC,{"number, number":function(a,i){return a/i},"Complex, Complex":function(a,i){return a.div(i)},"BigNumber, BigNumber":function(a,i){return a.div(i)},"Fraction, Fraction":function(a,i){return a.div(i)},"Unit, number | Complex | Fraction | BigNumber | Unit":(n,a)=>n.divide(a),"number | Fraction | Complex | BigNumber, Unit":(n,a)=>a.divideInto(n)})});var qC="pow",RY=["typed","config","identity","multiply","matrix","inv","fraction","number","Complex"],Yd=F(qC,RY,e=>{var{typed:r,config:t,identity:n,multiply:a,matrix:i,inv:u,number:l,fraction:c,Complex:o}=e;return r(qC,{"number, number":s,"Complex, Complex":function(x,v){return x.pow(v)},"BigNumber, BigNumber":function(x,v){return v.isInteger()||x>=0||t.predictable?x.pow(v):new o(x.toNumber(),0).pow(v.toNumber(),0)},"Fraction, Fraction":function(x,v){var y=x.pow(v);if(y!=null)return y;if(t.predictable)throw new Error("Result of pow is non-rational and cannot be expressed as a fraction");return s(x.valueOf(),v.valueOf())},"Array, number":m,"Array, BigNumber":function(x,v){return m(x,v.toNumber())},"Matrix, number":d,"Matrix, BigNumber":function(x,v){return d(x,v.toNumber())},"Unit, number | BigNumber":function(x,v){return x.pow(v)}});function s(h,x){if(t.predictable&&!Ze(x)&&h<0)try{var v=c(x),y=l(v);if((x===y||Math.abs((x-y)/x)<1e-14)&&v.d%2===1)return(v.n%2===0?1:-1)*Math.pow(-h,x)}catch{}return t.predictable&&(h<-1&&x===1/0||h>-1&&h<0&&x===-1/0)?NaN:Ze(x)||h>=0||t.predictable?Tw(h,x):h*h<1&&x===1/0||h*h>1&&x===-1/0?0:new o(h,0).pow(x,0)}function m(h,x){if(!Ze(x))throw new TypeError("For A^b, b must be an integer (value is "+x+")");var v=ur(h);if(v.length!==2)throw new Error("For A^b, A must be 2 dimensional (A has "+v.length+" dimensions)");if(v[0]!==v[1])throw new Error("For A^b, A must be square (size is "+v[0]+"x"+v[1]+")");if(x<0)try{return m(u(h),-x)}catch(C){throw C.message==="Cannot calculate inverse, determinant is zero"?new TypeError("For A^b, when A is not invertible, b must be a positive integer (value is "+x+")"):C}for(var y=n(v[0]).valueOf(),w=h;x>=1;)(x&1)===1&&(y=a(w,y)),x>>=1,w=a(w,w);return y}function d(h,x){return i(m(h.valueOf(),x))}});var Xu="Number of decimals in function round must be an integer",LC="round",kY=["typed","config","matrix","equalScalar","zeros","BigNumber","DenseMatrix"],Hd=F(LC,kY,e=>{var{typed:r,config:t,matrix:n,equalScalar:a,zeros:i,BigNumber:u,DenseMatrix:l}=e,c=jr({typed:r,equalScalar:a}),o=Wr({typed:r,DenseMatrix:l}),s=qt({typed:r});function m(d){return Math.abs(Nu(d).exponent)}return r(LC,{number:function(h){var x=Ou(h,m(t.epsilon)),v=At(h,x,t.epsilon)?x:h;return Ou(v)},"number, number":function(h,x){var v=m(t.epsilon);if(x>=v)return Ou(h,x);var y=Ou(h,v),w=At(h,y,t.epsilon)?y:h;return Ou(w,x)},"number, BigNumber":function(h,x){if(!x.isInteger())throw new TypeError(Xu);return new u(h).toDecimalPlaces(x.toNumber())},Complex:function(h){return h.round()},"Complex, number":function(h,x){if(x%1)throw new TypeError(Xu);return h.round(x)},"Complex, BigNumber":function(h,x){if(!x.isInteger())throw new TypeError(Xu);var v=x.toNumber();return h.round(v)},BigNumber:function(h){var x=new u(h).toDecimalPlaces(m(t.epsilon)),v=$t(h,x,t.epsilon)?x:h;return v.toDecimalPlaces(0)},"BigNumber, BigNumber":function(h,x){if(!x.isInteger())throw new TypeError(Xu);var v=m(t.epsilon);if(x>=v)return h.toDecimalPlaces(x.toNumber());var y=h.toDecimalPlaces(v),w=$t(h,y,t.epsilon)?y:h;return w.toDecimalPlaces(x.toNumber())},Fraction:function(h){return h.round()},"Fraction, number":function(h,x){if(x%1)throw new TypeError(Xu);return h.round(x)},"Fraction, BigNumber":function(h,x){if(!x.isInteger())throw new TypeError(Xu);return h.round(x.toNumber())},"Unit, number, Unit":r.referToSelf(d=>function(h,x,v){var y=h.toNumeric(v);return v.multiply(d(y,x))}),"Unit, BigNumber, Unit":r.referToSelf(d=>(h,x,v)=>d(h,x.toNumber(),v)),"Unit, Unit":r.referToSelf(d=>(h,x)=>d(h,0,x)),"Array | Matrix, number, Unit":r.referToSelf(d=>(h,x,v)=>je(h,y=>d(y,x,v),!0)),"Array | Matrix, BigNumber, Unit":r.referToSelf(d=>(h,x,v)=>d(h,x.toNumber(),v)),"Array | Matrix, Unit":r.referToSelf(d=>(h,x)=>d(h,0,x)),"Array | Matrix":r.referToSelf(d=>h=>je(h,d,!0)),"SparseMatrix, number | BigNumber":r.referToSelf(d=>(h,x)=>c(h,x,d,!1)),"DenseMatrix, number | BigNumber":r.referToSelf(d=>(h,x)=>s(h,x,d,!1)),"Array, number | BigNumber":r.referToSelf(d=>(h,x)=>s(n(h),x,d,!1).valueOf()),"number | Complex | BigNumber | Fraction, SparseMatrix":r.referToSelf(d=>(h,x)=>a(h,0)?i(x.size(),x.storage()):o(x,h,d,!0)),"number | Complex | BigNumber | Fraction, DenseMatrix":r.referToSelf(d=>(h,x)=>a(h,0)?i(x.size(),x.storage()):s(x,h,d,!0)),"number | Complex | BigNumber | Fraction, Array":r.referToSelf(d=>(h,x)=>s(n(x),h,d,!0).valueOf())})});var zC="log",qY=["config","typed","divideScalar","Complex"],$d=F(zC,qY,e=>{var{typed:r,config:t,divideScalar:n,Complex:a}=e;return r(zC,{number:function(u){return u>=0||t.predictable?YM(u):new a(u,0).log()},Complex:function(u){return u.log()},BigNumber:function(u){return!u.isNegative()||t.predictable?u.ln():new a(u.toNumber(),0).log()},"any, any":r.referToSelf(i=>(u,l)=>n(i(u),i(l)))})});var UC="log1p",LY=["typed","config","divideScalar","log","Complex"],Gd=F(UC,LY,e=>{var{typed:r,config:t,divideScalar:n,log:a,Complex:i}=e;return r(UC,{number:function(c){return c>=-1||t.predictable?Mm(c):u(new i(c,0))},Complex:u,BigNumber:function(c){var o=c.plus(1);return!o.isNegative()||t.predictable?o.ln():u(new i(c.toNumber(),0))},"Array | Matrix":r.referToSelf(l=>c=>je(c,l)),"any, any":r.referToSelf(l=>(c,o)=>n(l(c),a(o)))});function u(l){var c=l.re+1;return new i(Math.log(Math.sqrt(c*c+l.im*l.im)),Math.atan2(l.im,c))}});var WC="nthRoots",zY=["config","typed","divideScalar","Complex"],Vd=F(WC,zY,e=>{var{typed:r,config:t,divideScalar:n,Complex:a}=e,i=[function(c){return new a(c,0)},function(c){return new a(0,c)},function(c){return new a(-c,0)},function(c){return new a(0,-c)}];function u(l,c){if(c<0)throw new Error("Root must be greater than zero");if(c===0)throw new Error("Root must be non-zero");if(c%1!==0)throw new Error("Root must be an integer");if(l===0||l.abs()===0)return[new a(0,0)];var o=typeof l=="number",s;(o||l.re===0||l.im===0)&&(o?s=2*+(l<0):l.im===0?s=2*+(l.re<0):s=2*+(l.im<0)+1);for(var m=l.arg(),d=l.abs(),h=[],x=Math.pow(d,1/c),v=0;v{var{typed:r,equalScalar:t,matrix:n,pow:a,DenseMatrix:i,concat:u}=e,l=lt({typed:r}),c=Zt({typed:r,DenseMatrix:i}),o=jr({typed:r,equalScalar:t}),s=Wr({typed:r,DenseMatrix:i}),m=vr({typed:r,matrix:n,concat:u}),d={};for(var h in a.signatures)Object.prototype.hasOwnProperty.call(a.signatures,h)&&!h.includes("Matrix")&&!h.includes("Array")&&(d[h]=a.signatures[h]);var x=r(d);return r(YC,m({elop:x,SS:c,DS:l,Ss:o,sS:s}))});var HC="dotDivide",WY=["typed","matrix","equalScalar","divideScalar","DenseMatrix","concat"],Qd=F(HC,WY,e=>{var{typed:r,matrix:t,equalScalar:n,divideScalar:a,DenseMatrix:i,concat:u}=e,l=Lt({typed:r,equalScalar:n}),c=lt({typed:r}),o=Zt({typed:r,DenseMatrix:i}),s=jr({typed:r,equalScalar:n}),m=Wr({typed:r,DenseMatrix:i}),d=vr({typed:r,matrix:t,concat:u});return r(HC,d({elop:a,SS:o,DS:c,SD:l,Ss:s,sS:m}))});function _i(e){var{DenseMatrix:r}=e;return function(n,a,i){var u=n.size();if(u.length!==2)throw new RangeError("Matrix must be two dimensional (size: "+lr(u)+")");var l=u[0],c=u[1];if(l!==c)throw new RangeError("Matrix must be square (size: "+lr(u)+")");var o=[];if(Qe(a)){var s=a.size(),m=a._data;if(s.length===1){if(s[0]!==l)throw new RangeError("Dimension mismatch. Matrix columns must match vector length.");for(var d=0;d{var{typed:r,matrix:t,divideScalar:n,multiplyScalar:a,subtractScalar:i,equalScalar:u,DenseMatrix:l}=e,c=_i({DenseMatrix:l});return r($C,{"SparseMatrix, Array | Matrix":function(d,h){return s(d,h)},"DenseMatrix, Array | Matrix":function(d,h){return o(d,h)},"Array, Array | Matrix":function(d,h){var x=t(d),v=o(x,h);return v.valueOf()}});function o(m,d){d=c(m,d,!0);for(var h=d._data,x=m._size[0],v=m._size[1],y=[],w=m._data,C=0;CM&&(O.push(y[R]),_.push(q))}if(u(S,0))throw new Error("Linear system cannot be solved since matrix is singular");for(var W=n(A,S),G=0,H=_.length;G{var{typed:r,matrix:t,divideScalar:n,multiplyScalar:a,subtractScalar:i,equalScalar:u,DenseMatrix:l}=e,c=_i({DenseMatrix:l});return r(GC,{"SparseMatrix, Array | Matrix":function(d,h){return s(d,h)},"DenseMatrix, Array | Matrix":function(d,h){return o(d,h)},"Array, Array | Matrix":function(d,h){var x=t(d),v=o(x,h);return v.valueOf()}});function o(m,d){d=c(m,d,!0);for(var h=d._data,x=m._size[0],v=m._size[1],y=[],w=m._data,C=v-1;C>=0;C--){var b=h[C][0]||0,M=void 0;if(u(b,0))M=0;else{var A=w[C][C];if(u(A,0))throw new Error("Linear system cannot be solved since matrix is singular");M=n(b,A);for(var S=C-1;S>=0;S--)h[S]=[i(h[S][0]||0,a(M,w[S][C]))]}y[C]=[M]}return new l({data:y,size:[x,1]})}function s(m,d){d=c(m,d,!0);for(var h=d._data,x=m._size[0],v=m._size[1],y=m._values,w=m._index,C=m._ptr,b=[],M=v-1;M>=0;M--){var A=h[M][0]||0;if(u(A,0))b[M]=[0];else{for(var S=0,O=[],_=[],E=C[M],T=C[M+1],R=T-1;R>=E;R--){var q=w[R];q===M?S=y[R]:q{var{typed:r,matrix:t,divideScalar:n,multiplyScalar:a,subtractScalar:i,equalScalar:u,DenseMatrix:l}=e,c=_i({DenseMatrix:l});return r(VC,{"SparseMatrix, Array | Matrix":function(d,h){return s(d,h)},"DenseMatrix, Array | Matrix":function(d,h){return o(d,h)},"Array, Array | Matrix":function(d,h){var x=t(d),v=o(x,h);return v.map(y=>y.valueOf())}});function o(m,d){for(var h=[c(m,d,!0)._data.map(_=>_[0])],x=m._data,v=m._size[0],y=m._size[1],w=0;wnew l({data:_.map(E=>[E]),size:[v,1]}))}function s(m,d){for(var h=[c(m,d,!0)._data.map(pe=>pe[0])],x=m._size[0],v=m._size[1],y=m._values,w=m._index,C=m._ptr,b=0;bb&&(O.push(y[q]),_.push(W))}if(u(R,0))if(u(S[b],0)){if(A===0){var k=[...S];k[b]=1;for(var K=0,z=_.length;Knew l({data:pe.map(ae=>[ae]),size:[x,1]}))}});var ZC="usolveAll",GY=["typed","matrix","divideScalar","multiplyScalar","subtractScalar","equalScalar","DenseMatrix"],jd=F(ZC,GY,e=>{var{typed:r,matrix:t,divideScalar:n,multiplyScalar:a,subtractScalar:i,equalScalar:u,DenseMatrix:l}=e,c=_i({DenseMatrix:l});return r(ZC,{"SparseMatrix, Array | Matrix":function(d,h){return s(d,h)},"DenseMatrix, Array | Matrix":function(d,h){return o(d,h)},"Array, Array | Matrix":function(d,h){var x=t(d),v=o(x,h);return v.map(y=>y.valueOf())}});function o(m,d){for(var h=[c(m,d,!0)._data.map(_=>_[0])],x=m._data,v=m._size[0],y=m._size[1],w=y-1;w>=0;w--)for(var C=h.length,b=0;b=0;O--)S[O]=i(S[O],x[O][w]);h.push(S)}}else{if(b===0)return[];h.splice(b,1),b-=1,C-=1}else{M[w]=n(M[w],x[w][w]);for(var A=w-1;A>=0;A--)M[A]=i(M[A],a(M[w],x[A][w]))}}return h.map(_=>new l({data:_.map(E=>[E]),size:[v,1]}))}function s(m,d){for(var h=[c(m,d,!0)._data.map(pe=>pe[0])],x=m._size[0],v=m._size[1],y=m._values,w=m._index,C=m._ptr,b=v-1;b>=0;b--)for(var M=h.length,A=0;A=E;q--){var W=w[q];W===b?R=y[q]:Wnew l({data:pe.map(ae=>[ae]),size:[x,1]}))}});var VY="matAlgo08xS0Sid",ZY=["typed","equalScalar"],Ju=F(VY,ZY,e=>{var{typed:r,equalScalar:t}=e;return function(a,i,u){var l=a._values,c=a._index,o=a._ptr,s=a._size,m=a._datatype||a._data===void 0?a._datatype:a.getDataType(),d=i._values,h=i._index,x=i._ptr,v=i._size,y=i._datatype||i._data===void 0?i._datatype:i.getDataType();if(s.length!==v.length)throw new pr(s.length,v.length);if(s[0]!==v[0]||s[1]!==v[1])throw new RangeError("Dimension mismatch. Matrix A ("+s+") must match Matrix B ("+v+")");if(!l||!d)throw new Error("Cannot perform operation on Pattern Sparse Matrices");var w=s[0],C=s[1],b,M=t,A=0,S=u;typeof m=="string"&&m===y&&m!=="mixed"&&(b=m,M=r.find(t,[b,b]),A=r.convert(0,b),S=r.find(u,[b,b]));for(var O=[],_=[],E=[],T=[],R=[],q,W,G,H,L=0;L{var{typed:r,matrix:t}=e;return{"Array, number":r.referTo("DenseMatrix, number",n=>(a,i)=>n(t(a),i).valueOf()),"Array, BigNumber":r.referTo("DenseMatrix, BigNumber",n=>(a,i)=>n(t(a),i).valueOf()),"number, Array":r.referTo("number, DenseMatrix",n=>(a,i)=>n(a,t(i)).valueOf()),"BigNumber, Array":r.referTo("BigNumber, DenseMatrix",n=>(a,i)=>n(a,t(i)).valueOf())}});var QC="leftShift",QY=["typed","matrix","equalScalar","zeros","DenseMatrix","concat"],eh=F(QC,QY,e=>{var{typed:r,matrix:t,equalScalar:n,zeros:a,DenseMatrix:i,concat:u}=e,l=Mn({typed:r}),c=Lt({typed:r,equalScalar:n}),o=Ju({typed:r,equalScalar:n}),s=jn({typed:r,DenseMatrix:i}),m=jr({typed:r,equalScalar:n}),d=qt({typed:r}),h=vr({typed:r,matrix:t,concat:u}),x=Ku({typed:r,matrix:t});return r(QC,{"number, number":Pw,"BigNumber, BigNumber":L2,"SparseMatrix, number | BigNumber":r.referToSelf(v=>(y,w)=>n(w,0)?y.clone():m(y,w,v,!1)),"DenseMatrix, number | BigNumber":r.referToSelf(v=>(y,w)=>n(w,0)?y.clone():d(y,w,v,!1)),"number | BigNumber, SparseMatrix":r.referToSelf(v=>(y,w)=>n(y,0)?a(w.size(),w.storage()):s(w,y,v,!0)),"number | BigNumber, DenseMatrix":r.referToSelf(v=>(y,w)=>n(y,0)?a(w.size(),w.storage()):d(w,y,v,!0))},x,h({SS:o,DS:l,SD:c}))});var XC="rightArithShift",XY=["typed","matrix","equalScalar","zeros","DenseMatrix","concat"],rh=F(XC,XY,e=>{var{typed:r,matrix:t,equalScalar:n,zeros:a,DenseMatrix:i,concat:u}=e,l=Mn({typed:r}),c=Lt({typed:r,equalScalar:n}),o=Ju({typed:r,equalScalar:n}),s=jn({typed:r,DenseMatrix:i}),m=jr({typed:r,equalScalar:n}),d=qt({typed:r}),h=vr({typed:r,matrix:t,concat:u}),x=Ku({typed:r,matrix:t});return r(XC,{"number, number":Iw,"BigNumber, BigNumber":z2,"SparseMatrix, number | BigNumber":r.referToSelf(v=>(y,w)=>n(w,0)?y.clone():m(y,w,v,!1)),"DenseMatrix, number | BigNumber":r.referToSelf(v=>(y,w)=>n(w,0)?y.clone():d(y,w,v,!1)),"number | BigNumber, SparseMatrix":r.referToSelf(v=>(y,w)=>n(y,0)?a(w.size(),w.storage()):s(w,y,v,!0)),"number | BigNumber, DenseMatrix":r.referToSelf(v=>(y,w)=>n(y,0)?a(w.size(),w.storage()):d(w,y,v,!0))},x,h({SS:o,DS:l,SD:c}))});var JC="rightLogShift",JY=["typed","matrix","equalScalar","zeros","DenseMatrix","concat"],th=F(JC,JY,e=>{var{typed:r,matrix:t,equalScalar:n,zeros:a,DenseMatrix:i,concat:u}=e,l=Mn({typed:r}),c=Lt({typed:r,equalScalar:n}),o=Ju({typed:r,equalScalar:n}),s=jn({typed:r,DenseMatrix:i}),m=jr({typed:r,equalScalar:n}),d=qt({typed:r}),h=vr({typed:r,matrix:t,concat:u}),x=Ku({typed:r,matrix:t});return r(JC,{"number, number":Rw,"SparseMatrix, number | BigNumber":r.referToSelf(v=>(y,w)=>n(w,0)?y.clone():m(y,w,v,!1)),"DenseMatrix, number | BigNumber":r.referToSelf(v=>(y,w)=>n(w,0)?y.clone():d(y,w,v,!1)),"number | BigNumber, SparseMatrix":r.referToSelf(v=>(y,w)=>n(y,0)?a(w.size(),w.storage()):s(w,y,v,!0)),"number | BigNumber, DenseMatrix":r.referToSelf(v=>(y,w)=>n(y,0)?a(w.size(),w.storage()):d(w,y,v,!0))},x,h({SS:o,DS:l,SD:c}))});var KC="and",KY=["typed","matrix","equalScalar","zeros","not","concat"],ju=F(KC,KY,e=>{var{typed:r,matrix:t,equalScalar:n,zeros:a,not:i,concat:u}=e,l=Lt({typed:r,equalScalar:n}),c=zo({typed:r,equalScalar:n}),o=jr({typed:r,equalScalar:n}),s=qt({typed:r}),m=vr({typed:r,matrix:t,concat:u});return r(KC,{"number, number":Ww,"Complex, Complex":function(h,x){return(h.re!==0||h.im!==0)&&(x.re!==0||x.im!==0)},"BigNumber, BigNumber":function(h,x){return!h.isZero()&&!x.isZero()&&!h.isNaN()&&!x.isNaN()},"Unit, Unit":r.referToSelf(d=>(h,x)=>d(h.value||0,x.value||0)),"SparseMatrix, any":r.referToSelf(d=>(h,x)=>i(x)?a(h.size(),h.storage()):o(h,x,d,!1)),"DenseMatrix, any":r.referToSelf(d=>(h,x)=>i(x)?a(h.size(),h.storage()):s(h,x,d,!1)),"any, SparseMatrix":r.referToSelf(d=>(h,x)=>i(h)?a(h.size(),h.storage()):o(x,h,d,!0)),"any, DenseMatrix":r.referToSelf(d=>(h,x)=>i(h)?a(h.size(),h.storage()):s(x,h,d,!0)),"Array, any":r.referToSelf(d=>(h,x)=>d(t(h),x).valueOf()),"any, Array":r.referToSelf(d=>(h,x)=>d(h,t(x)).valueOf())},m({SS:c,DS:l}))});var nh="compare",jY=["typed","config","matrix","equalScalar","BigNumber","Fraction","DenseMatrix","concat"],ah=F(nh,jY,e=>{var{typed:r,config:t,equalScalar:n,matrix:a,BigNumber:i,Fraction:u,DenseMatrix:l,concat:c}=e,o=lt({typed:r}),s=Lo({typed:r,equalScalar:n}),m=Wr({typed:r,DenseMatrix:l}),d=vr({typed:r,matrix:a,concat:c}),h=Pa({typed:r});return r(nh,eH({typed:r,config:t}),{"boolean, boolean":function(v,y){return v===y?0:v>y?1:-1},"BigNumber, BigNumber":function(v,y){return $t(v,y,t.epsilon)?new i(0):new i(v.cmp(y))},"Fraction, Fraction":function(v,y){return new u(v.compare(y))},"Complex, Complex":function(){throw new TypeError("No ordering relation is defined for complex numbers")}},h,d({SS:s,DS:o,Ss:m}))}),eH=F(nh,["typed","config"],e=>{var{typed:r,config:t}=e;return r(nh,{"number, number":function(a,i){return At(a,i,t.epsilon)?0:a>i?1:-1}})});var Fs=ca(eE(),1);var rE="compareNatural",rH=["typed","compare"],ih=F(rE,rH,e=>{var{typed:r,compare:t}=e,n=t.signatures["boolean,boolean"];return r(rE,{"any, any":a});function a(c,o){var s=Fr(c),m=Fr(o),d;if((s==="number"||s==="BigNumber"||s==="Fraction")&&(m==="number"||m==="BigNumber"||m==="Fraction"))return d=t(c,o),d.toString()!=="0"?d>0?1:-1:(0,Fs.default)(s,m);var h=["Array","DenseMatrix","SparseMatrix"];if(h.includes(s)||h.includes(m))return d=i(a,c,o),d!==0?d:(0,Fs.default)(s,m);if(s!==m)return(0,Fs.default)(s,m);if(s==="Complex")return tH(c,o);if(s==="Unit")return c.equalBase(o)?a(c.value,o.value):u(a,c.formatUnits(),o.formatUnits());if(s==="boolean")return n(c,o);if(s==="string")return(0,Fs.default)(c,o);if(s==="Object")return l(a,c,o);if(s==="null"||s==="undefined")return 0;throw new TypeError('Unsupported type of value "'+s+'"')}function i(c,o,s){return pa(o)&&pa(s)?u(c,o.toJSON().values,s.toJSON().values):pa(o)?i(c,o.toArray(),s):pa(s)?i(c,o,s.toArray()):Xi(o)?i(c,o.toJSON().data,s):Xi(s)?i(c,o,s.toJSON().data):Array.isArray(o)?Array.isArray(s)?u(c,o,s):i(c,o,[s]):i(c,[o],s)}function u(c,o,s){for(var m=0,d=Math.min(o.length,s.length);ms.length?1:o.lengthr.re?1:e.rer.im?1:e.im{var{typed:r,matrix:t,concat:n}=e,a=vr({typed:r,matrix:t,concat:n});return r(tE,Fm,a({elop:Fm,Ds:!0}))});var sh="equal",aH=["typed","matrix","equalScalar","DenseMatrix","concat"],uh=F(sh,aH,e=>{var{typed:r,matrix:t,equalScalar:n,DenseMatrix:a,concat:i}=e,u=lt({typed:r}),l=Zt({typed:r,DenseMatrix:a}),c=Wr({typed:r,DenseMatrix:a}),o=vr({typed:r,matrix:t,concat:i});return r(sh,iH({typed:r,equalScalar:n}),o({elop:n,SS:l,DS:u,Ss:c}))}),iH=F(sh,["typed","equalScalar"],e=>{var{typed:r,equalScalar:t}=e;return r(sh,{"any, any":function(a,i){return a===null?i===null:i===null?a===null:a===void 0?i===void 0:i===void 0?a===void 0:t(a,i)}})});var nE="equalText",oH=["typed","compareText","isZero"],fh=F(nE,oH,e=>{var{typed:r,compareText:t,isZero:n}=e;return r(nE,{"any, any":function(i,u){return n(t(i,u))}})});var ch="smaller",sH=["typed","config","matrix","DenseMatrix","concat"],lh=F(ch,sH,e=>{var{typed:r,config:t,matrix:n,DenseMatrix:a,concat:i}=e,u=lt({typed:r}),l=Zt({typed:r,DenseMatrix:a}),c=Wr({typed:r,DenseMatrix:a}),o=vr({typed:r,matrix:n,concat:i}),s=Pa({typed:r});return r(ch,uH({typed:r,config:t}),{"boolean, boolean":(m,d)=>mm.compare(d)===-1,"Complex, Complex":function(d,h){throw new TypeError("No ordering relation is defined for complex numbers")}},s,o({SS:l,DS:u,Ss:c}))}),uH=F(ch,["typed","config"],e=>{var{typed:r,config:t}=e;return r(ch,{"number, number":function(a,i){return a{var{typed:r,config:t,matrix:n,DenseMatrix:a,concat:i}=e,u=lt({typed:r}),l=Zt({typed:r,DenseMatrix:a}),c=Wr({typed:r,DenseMatrix:a}),o=vr({typed:r,matrix:n,concat:i}),s=Pa({typed:r});return r(mh,cH({typed:r,config:t}),{"boolean, boolean":(m,d)=>m<=d,"BigNumber, BigNumber":function(d,h){return d.lte(h)||$t(d,h,t.epsilon)},"Fraction, Fraction":(m,d)=>m.compare(d)!==1,"Complex, Complex":function(){throw new TypeError("No ordering relation is defined for complex numbers")}},s,o({SS:l,DS:u,Ss:c}))}),cH=F(mh,["typed","config"],e=>{var{typed:r,config:t}=e;return r(mh,{"number, number":function(a,i){return a<=i||At(a,i,t.epsilon)}})});var dh="larger",lH=["typed","config","matrix","DenseMatrix","concat"],hh=F(dh,lH,e=>{var{typed:r,config:t,matrix:n,DenseMatrix:a,concat:i}=e,u=lt({typed:r}),l=Zt({typed:r,DenseMatrix:a}),c=Wr({typed:r,DenseMatrix:a}),o=vr({typed:r,matrix:n,concat:i}),s=Pa({typed:r});return r(dh,mH({typed:r,config:t}),{"boolean, boolean":(m,d)=>m>d,"BigNumber, BigNumber":function(d,h){return d.gt(h)&&!$t(d,h,t.epsilon)},"Fraction, Fraction":(m,d)=>m.compare(d)===1,"Complex, Complex":function(){throw new TypeError("No ordering relation is defined for complex numbers")}},s,o({SS:l,DS:u,Ss:c}))}),mH=F(dh,["typed","config"],e=>{var{typed:r,config:t}=e;return r(dh,{"number, number":function(a,i){return a>i&&!At(a,i,t.epsilon)}})});var vh="largerEq",pH=["typed","config","matrix","DenseMatrix","concat"],gh=F(vh,pH,e=>{var{typed:r,config:t,matrix:n,DenseMatrix:a,concat:i}=e,u=lt({typed:r}),l=Zt({typed:r,DenseMatrix:a}),c=Wr({typed:r,DenseMatrix:a}),o=vr({typed:r,matrix:n,concat:i}),s=Pa({typed:r});return r(vh,dH({typed:r,config:t}),{"boolean, boolean":(m,d)=>m>=d,"BigNumber, BigNumber":function(d,h){return d.gte(h)||$t(d,h,t.epsilon)},"Fraction, Fraction":(m,d)=>m.compare(d)!==-1,"Complex, Complex":function(){throw new TypeError("No ordering relation is defined for complex numbers")}},s,o({SS:l,DS:u,Ss:c}))}),dH=F(vh,["typed","config"],e=>{var{typed:r,config:t}=e;return r(vh,{"number, number":function(a,i){return a>=i||At(a,i,t.epsilon)}})});var aE="deepEqual",hH=["typed","equal"],xh=F(aE,hH,e=>{var{typed:r,equal:t}=e;return r(aE,{"any, any":function(i,u){return n(i.valueOf(),u.valueOf())}});function n(a,i){if(Array.isArray(a))if(Array.isArray(i)){var u=a.length;if(u!==i.length)return!1;for(var l=0;l{var{typed:r,config:t,equalScalar:n,matrix:a,DenseMatrix:i,concat:u}=e,l=lt({typed:r}),c=Zt({typed:r,DenseMatrix:i}),o=Wr({typed:r,DenseMatrix:i}),s=vr({typed:r,matrix:a,concat:u});return r(yh,gH({typed:r,equalScalar:n}),s({elop:m,SS:c,DS:l,Ss:o}));function m(d,h){return!n(d,h)}}),gH=F(yh,["typed","equalScalar"],e=>{var{typed:r,equalScalar:t}=e;return r(yh,{"any, any":function(a,i){return a===null?i!==null:i===null?a!==null:a===void 0?i!==void 0:i===void 0?a!==void 0:!t(a,i)}})});var iE="partitionSelect",xH=["typed","isNumeric","isNaN","compare"],wh=F(iE,xH,e=>{var{typed:r,isNumeric:t,isNaN:n,compare:a}=e,i=a,u=(o,s)=>-a(o,s);return r(iE,{"Array | Matrix, number":function(s,m){return l(s,m,i)},"Array | Matrix, number, string":function(s,m,d){if(d==="asc")return l(s,m,i);if(d==="desc")return l(s,m,u);throw new Error('Compare string must be "asc" or "desc"')},"Array | Matrix, number, function":l});function l(o,s,m){if(!Ze(s)||s<0)throw new Error("k must be a non-negative integer");if(Qe(o)){var d=o.size();if(d.length>1)throw new Error("Only one dimensional matrices supported");return c(o.valueOf(),s,m)}if(Array.isArray(o))return c(o,s,m)}function c(o,s,m){if(s>=o.length)throw new Error("k out of bounds");for(var d=0;d=0){var C=o[y];o[y]=o[v],o[v]=C,--y}else++v;m(o[v],w)>0&&--v,s<=v?x=v:h=v+1}return o[s]}});var oE="sort",yH=["typed","matrix","compare","compareNatural"],Dh=F(oE,yH,e=>{var{typed:r,matrix:t,compare:n,compareNatural:a}=e,i=n,u=(s,m)=>-n(s,m);return r(oE,{Array:function(m){return c(m),m.sort(i)},Matrix:function(m){return o(m),t(m.toArray().sort(i),m.storage())},"Array, function":function(m,d){return c(m),m.sort(d)},"Matrix, function":function(m,d){return o(m),t(m.toArray().sort(d),m.storage())},"Array, string":function(m,d){return c(m),m.sort(l(d))},"Matrix, string":function(m,d){return o(m),t(m.toArray().sort(l(d)),m.storage())}});function l(s){if(s==="asc")return i;if(s==="desc")return u;if(s==="natural")return a;throw new Error('String "asc", "desc", or "natural" expected')}function c(s){if(ur(s).length!==1)throw new Error("One dimensional array expected")}function o(s){if(s.size().length!==1)throw new Error("One dimensional matrix expected")}});var sE="max",bH=["typed","config","numeric","larger"],ef=F(sE,bH,e=>{var{typed:r,config:t,numeric:n,larger:a}=e;return r(sE,{"Array | Matrix":u,"Array | Matrix, number | BigNumber":function(c,o){return ko(c,o.valueOf(),i)},"...":function(c){if(Ba(c))throw new TypeError("Scalar values expected in function max");return u(c)}});function i(l,c){try{return a(l,c)?l:c}catch(o){throw Et(o,"max",c)}}function u(l){var c;if(An(l,function(o){try{isNaN(o)&&typeof o=="number"?c=NaN:(c===void 0||a(o,c))&&(c=o)}catch(s){throw Et(s,"max",o)}}),c===void 0)throw new Error("Cannot calculate max of an empty array");return typeof c=="string"&&(c=n(c,t.number)),c}});var uE="min",wH=["typed","config","numeric","smaller"],rf=F(uE,wH,e=>{var{typed:r,config:t,numeric:n,smaller:a}=e;return r(uE,{"Array | Matrix":u,"Array | Matrix, number | BigNumber":function(c,o){return ko(c,o.valueOf(),i)},"...":function(c){if(Ba(c))throw new TypeError("Scalar values expected in function min");return u(c)}});function i(l,c){try{return a(l,c)?l:c}catch(o){throw Et(o,"min",c)}}function u(l){var c;if(An(l,function(o){try{isNaN(o)&&typeof o=="number"?c=NaN:(c===void 0||a(o,c))&&(c=o)}catch(s){throw Et(s,"min",o)}}),c===void 0)throw new Error("Cannot calculate min of an empty array");return typeof c=="string"&&(c=n(c,t.number)),c}});var DH="ImmutableDenseMatrix",SH=["smaller","DenseMatrix"],Sh=F(DH,SH,e=>{var{smaller:r,DenseMatrix:t}=e;function n(a,i){if(!(this instanceof n))throw new SyntaxError("Constructor must be called with the new operator");if(i&&!St(i))throw new Error("Invalid datatype: "+i);if(Qe(a)||Mr(a)){var u=new t(a,i);this._data=u._data,this._size=u._size,this._datatype=u._datatype,this._min=null,this._max=null}else if(a&&Mr(a.data)&&Mr(a.size))this._data=a.data,this._size=a.size,this._datatype=a.datatype,this._min=typeof a.min<"u"?a.min:null,this._max=typeof a.max<"u"?a.max:null;else{if(a)throw new TypeError("Unsupported type of data ("+Fr(a)+")");this._data=[],this._size=[0],this._datatype=i,this._min=null,this._max=null}}return n.prototype=new t,n.prototype.type="ImmutableDenseMatrix",n.prototype.isImmutableDenseMatrix=!0,n.prototype.subset=function(a){switch(arguments.length){case 1:{var i=t.prototype.subset.call(this,a);return Qe(i)?new n({data:i._data,size:i._size,datatype:i._datatype}):i}case 2:case 3:throw new Error("Cannot invoke set subset on an Immutable Matrix instance");default:throw new SyntaxError("Wrong number of arguments")}},n.prototype.set=function(){throw new Error("Cannot invoke set on an Immutable Matrix instance")},n.prototype.resize=function(){throw new Error("Cannot invoke resize on an Immutable Matrix instance")},n.prototype.reshape=function(){throw new Error("Cannot invoke reshape on an Immutable Matrix instance")},n.prototype.clone=function(){return new n({data:ar(this._data),size:ar(this._size),datatype:this._datatype})},n.prototype.toJSON=function(){return{mathjs:"ImmutableDenseMatrix",data:this._data,size:this._size,datatype:this._datatype}},n.fromJSON=function(a){return new n(a)},n.prototype.swapRows=function(){throw new Error("Cannot invoke swapRows on an Immutable Matrix instance")},n.prototype.min=function(){if(this._min===null){var a=null;this.forEach(function(i){(a===null||r(i,a))&&(a=i)}),this._min=a!==null?a:void 0}return this._min},n.prototype.max=function(){if(this._max===null){var a=null;this.forEach(function(i){(a===null||r(a,i))&&(a=i)}),this._max=a!==null?a:void 0}return this._max},n},{isClass:!0});var NH="Index",AH=["ImmutableDenseMatrix","getMatrixDataType"],Nh=F(NH,AH,e=>{var{ImmutableDenseMatrix:r,getMatrixDataType:t}=e;function n(i){if(!(this instanceof n))throw new SyntaxError("Constructor must be called with the new operator");this._dimensions=[],this._sourceSize=[],this._isScalar=!0;for(var u=0,l=arguments.length;u{t&&r.push(n)}),r}var MH="FibonacciHeap",CH=["smaller","larger"],Ah=F(MH,CH,e=>{var{smaller:r,larger:t}=e,n=1/Math.log((1+Math.sqrt(5))/2);function a(){if(!(this instanceof a))throw new SyntaxError("Constructor must be called with the new operator");this._minimum=null,this._size=0}a.prototype.type="FibonacciHeap",a.prototype.isFibonacciHeap=!0,a.prototype.insert=function(s,m){var d={key:s,value:m,degree:0};if(this._minimum){var h=this._minimum;d.left=h,d.right=h.right,h.right=d,d.right.left=d,r(s,h.key)&&(this._minimum=d)}else d.left=d,d.right=d,this._minimum=d;return this._size++,d},a.prototype.size=function(){return this._size},a.prototype.clear=function(){this._minimum=null,this._size=0},a.prototype.isEmpty=function(){return this._size===0},a.prototype.extractMinimum=function(){var s=this._minimum;if(s===null)return s;for(var m=this._minimum,d=s.degree,h=s.child;d>0;){var x=h.right;h.left.right=h.right,h.right.left=h.left,h.left=m,h.right=m.right,m.right=h,h.right.left=h,h.parent=null,h=x,d--}return s.left.right=s.right,s.right.left=s.left,s===s.right?m=null:(m=s.right,m=o(m,this._size)),this._size--,this._minimum=m,s},a.prototype.remove=function(s){this._minimum=i(this._minimum,s,-1),this.extractMinimum()};function i(s,m,d){m.key=d;var h=m.parent;return h&&r(m.key,h.key)&&(u(s,m,h),l(s,h)),r(m.key,s.key)&&(s=m),s}function u(s,m,d){m.left.right=m.right,m.right.left=m.left,d.degree--,d.child===m&&(d.child=m.right),d.degree===0&&(d.child=null),m.left=s,m.right=s.right,s.right=m,m.right.left=m,m.parent=null,m.mark=!1}function l(s,m){var d=m.parent;!d||(m.mark?(u(s,m,d),l(d)):m.mark=!0)}var c=function(m,d){m.left.right=m.right,m.right.left=m.left,m.parent=d,d.child?(m.left=d.child,m.right=d.child.right,d.child.right=m,m.right.left=m):(d.child=m,m.right=m,m.left=m),d.degree++,m.mark=!1};function o(s,m){var d=Math.floor(Math.log(m)*n)+1,h=new Array(d),x=0,v=s;if(v)for(x++,v=v.right;v!==s;)x++,v=v.right;for(var y;x>0;){for(var w=v.degree,C=v.right;y=h[w],!!y;){if(t(v.key,y.key)){var b=y;y=v,v=b}c(y,v),h[w]=null,w++}h[w]=v,v=C,x--}s=null;for(var M=0;M{var{addScalar:r,equalScalar:t,FibonacciHeap:n}=e;function a(){if(!(this instanceof a))throw new SyntaxError("Constructor must be called with the new operator");this._values=[],this._heap=new n}return a.prototype.type="Spa",a.prototype.isSpa=!0,a.prototype.set=function(i,u){if(this._values[i])this._values[i].value=u;else{var l=this._heap.insert(i,u);this._values[i]=l}},a.prototype.get=function(i){var u=this._values[i];return u?u.value:0},a.prototype.accumulate=function(i,u){var l=this._values[i];l?l.value=r(l.value,u):(l=this._heap.insert(i,u),this._values[i]=l)},a.prototype.forEach=function(i,u,l){var c=this._heap,o=this._values,s=[],m=c.extractMinimum();for(m&&s.push(m);m&&m.key<=u;)m.key>=i&&(t(m.value,0)||l(m.key,m.value,this)),m=c.extractMinimum(),m&&s.push(m);for(var d=0;d{var{on:r,config:t,addScalar:n,subtractScalar:a,multiplyScalar:i,divideScalar:u,pow:l,abs:c,fix:o,round:s,equal:m,isNumeric:d,format:h,number:x,Complex:v,BigNumber:y,Fraction:w}=e,C=x;function b(J,re){if(!(this instanceof b))throw new Error("Constructor must be called with the new operator");if(!(J==null||d(J)||Kt(J)))throw new TypeError("First parameter in Unit constructor must be number, BigNumber, Fraction, Complex, or undefined");if(this.fixPrefix=!1,this.skipAutomaticSimplification=!0,re===void 0)this.units=[],this.dimensions=K.map(j=>0);else if(typeof re=="string"){var ye=b.parse(re);this.units=ye.units,this.dimensions=ye.dimensions}else if(Ht(re)&&re.value===null)this.fixPrefix=re.fixPrefix,this.skipAutomaticSimplification=re.skipAutomaticSimplification,this.dimensions=re.dimensions.slice(0),this.units=re.units.map(j=>ht({},j));else throw new TypeError("Second parameter in Unit constructor must be a string or valueless Unit");this.value=this._normalize(J)}Object.defineProperty(b,"name",{value:"Unit"}),b.prototype.constructor=b,b.prototype.type="Unit",b.prototype.isUnit=!0;var M,A,S;function O(){for(;S===" "||S===" ";)T()}function _(J){return J>="0"&&J<="9"||J==="."}function E(J){return J>="0"&&J<="9"}function T(){A++,S=M.charAt(A)}function R(J){A=J,S=M.charAt(A)}function q(){var J="",re=A;if(S==="+"?T():S==="-"&&(J+=S,T()),!_(S))return R(re),null;if(S==="."){if(J+=S,T(),!E(S))return R(re),null}else{for(;E(S);)J+=S,T();S==="."&&(J+=S,T())}for(;E(S);)J+=S,T();if(S==="E"||S==="e"){var ye="",j=A;if(ye+=S,T(),(S==="+"||S==="-")&&(ye+=S,T()),!E(S))return R(j),J;for(J=J+ye;E(S);)J+=S,T()}return J}function W(){for(var J="";E(S)||b.isValidAlpha(S);)J+=S,T();var re=J.charAt(0);return b.isValidAlpha(re)?J:null}function G(J){return S===J?(T(),J):null}b.parse=function(J,re){if(re=re||{},M=J,A=-1,S="",typeof M!="string")throw new TypeError("Invalid argument in Unit.parse, string expected");var ye=new b;ye.units=[];var j=1,ne=!1;T(),O();var ue=q(),Me=null;if(ue){if(t.number==="BigNumber")Me=new y(ue);else if(t.number==="Fraction")try{Me=new w(ue)}catch{Me=parseFloat(ue)}else Me=parseFloat(ue);O(),G("*")?(j=1,ne=!0):G("/")&&(j=-1,ne=!0)}for(var Ce=[],Le=1;;){for(O();S==="(";)Ce.push(j),Le*=j,j=1,T(),O();var Ie=void 0;if(S){var fr=S;if(Ie=W(),Ie===null)throw new SyntaxError('Unexpected "'+fr+'" in "'+M+'" at index '+A.toString())}else break;var or=H(Ie);if(or===null)throw new SyntaxError('Unit "'+Ie+'" not found.');var Ke=j*Le;if(O(),G("^")){O();var Pr=q();if(Pr===null)throw new SyntaxError('In "'+J+'", "^" must be followed by a floating-point number');Ke*=Pr}ye.units.push({unit:or.unit,prefix:or.prefix,power:Ke});for(var ee=0;ee1||Math.abs(this.units[0].power-1)>1e-15},b.prototype._normalize=function(J){if(J==null||this.units.length===0)return J;for(var re=J,ye=b._getNumberConverter(Fr(J)),j=0;j{if(Xe($,J)){var re=$[J],ye=re.prefixes[""];return{unit:re,prefix:ye}}for(var j in $)if(Xe($,j)&&uM(J,j)){var ne=$[j],ue=J.length-j.length,Me=J.substring(0,ue),Ce=Xe(ne.prefixes,Me)?ne.prefixes[Me]:void 0;if(Ce!==void 0)return{unit:ne,prefix:Ce}}return null},{hasher:J=>J[0],limit:100});b.isValuelessUnit=function(J){return H(J)!==null},b.prototype.hasBase=function(J){if(typeof J=="string"&&(J=z[J]),!J)return!1;for(var re=0;re1e-12)return!1;return!0},b.prototype.equalBase=function(J){for(var re=0;re1e-12)return!1;return!0},b.prototype.equals=function(J){return this.equalBase(J)&&m(this.value,J.value)},b.prototype.multiply=function(J){for(var re=this.clone(),ye=Ht(J)?J:new b(J),j=0;j1e-12&&(Xe(ge,Ce)?re.push({unit:ge[Ce].unit,prefix:ge[Ce].prefix,power:J.dimensions[Me]||0}):ue=!0)}re.length1e-12)if(Xe(me.si,j))re.push({unit:me.si[j].unit,prefix:me.si[j].prefix,power:J.dimensions[ye]||0});else throw new Error("Cannot express custom unit "+j+" in SI units")}return J.units=re,J.fixPrefix=!0,J.skipAutomaticSimplification=!0,this.value!==null?(J.value=null,this.to(J)):J},b.prototype.formatUnits=function(){for(var J="",re="",ye=0,j=0,ne=0;ne0?(ye++,J+=" "+this.units[ne].prefix.name+this.units[ne].unit.name,Math.abs(this.units[ne].power-1)>1e-15&&(J+="^"+this.units[ne].power)):this.units[ne].power<0&&j++;if(j>0)for(var ue=0;ue0?(re+=" "+this.units[ue].prefix.name+this.units[ue].unit.name,Math.abs(this.units[ue].power+1)>1e-15&&(re+="^"+-this.units[ue].power)):(re+=" "+this.units[ue].prefix.name+this.units[ue].unit.name,re+="^"+this.units[ue].power));J=J.substr(1),re=re.substr(1),ye>1&&j>0&&(J="("+J+")"),j>1&&ye>0&&(re="("+re+")");var Me=J;return ye>0&&j>0&&(Me+=" / "),Me+=re,Me},b.prototype.format=function(J){var re=this.skipAutomaticSimplification||this.value===null?this.clone():this.simplify(),ye=!1;typeof re.value<"u"&&re.value!==null&&Kt(re.value)&&(ye=Math.abs(re.value.re)<1e-14);for(var j in re.units)Xe(re.units,j)&&re.units[j].unit&&(re.units[j].unit.name==="VA"&&ye?re.units[j].unit=$.VAR:re.units[j].unit.name==="VAR"&&!ye&&(re.units[j].unit=$.VA));re.units.length===1&&!re.fixPrefix&&Math.abs(re.units[0].power-Math.round(re.units[0].power))<1e-14&&(re.units[0].prefix=re._bestPrefix());var ne=re._denormalize(re.value),ue=re.value!==null?h(ne,J||{}):"",Me=re.formatUnits();return re.value&&Kt(re.value)&&(ue="("+ue+")"),Me.length>0&&ue.length>0&&(ue+=" "),ue+=Me,ue},b.prototype._bestPrefix=function(){if(this.units.length!==1)throw new Error("Can only compute the best prefix for single units with integer powers, like kg, s^2, N^-1, and so forth!");if(Math.abs(this.units[0].power-Math.round(this.units[0].power))>=1e-14)throw new Error("Can only compute the best prefix for single units with integer powers, like kg, s^2, N^-1, and so forth!");var J=this.value!==null?c(this.value):0,re=c(this.units[0].unit.value),ye=this.units[0].prefix;if(J===0)return ye;var j=this.units[0].power,ne=Math.log(J/Math.pow(ye.value*re,j))/Math.LN10-1.2;if(ne>-2.200001&&ne<1.800001)return ye;ne=Math.abs(ne);var ue=this.units[0].unit.prefixes;for(var Me in ue)if(Xe(ue,Me)){var Ce=ue[Me];if(Ce.scientific){var Le=Math.abs(Math.log(J/Math.pow(Ce.value*re,j))/Math.LN10-1.2);(Le0)},$={meter:{name:"meter",base:z.LENGTH,prefixes:k.LONG,value:1,offset:0},inch:{name:"inch",base:z.LENGTH,prefixes:k.NONE,value:.0254,offset:0},foot:{name:"foot",base:z.LENGTH,prefixes:k.NONE,value:.3048,offset:0},yard:{name:"yard",base:z.LENGTH,prefixes:k.NONE,value:.9144,offset:0},mile:{name:"mile",base:z.LENGTH,prefixes:k.NONE,value:1609.344,offset:0},link:{name:"link",base:z.LENGTH,prefixes:k.NONE,value:.201168,offset:0},rod:{name:"rod",base:z.LENGTH,prefixes:k.NONE,value:5.0292,offset:0},chain:{name:"chain",base:z.LENGTH,prefixes:k.NONE,value:20.1168,offset:0},angstrom:{name:"angstrom",base:z.LENGTH,prefixes:k.NONE,value:1e-10,offset:0},m:{name:"m",base:z.LENGTH,prefixes:k.SHORT,value:1,offset:0},in:{name:"in",base:z.LENGTH,prefixes:k.NONE,value:.0254,offset:0},ft:{name:"ft",base:z.LENGTH,prefixes:k.NONE,value:.3048,offset:0},yd:{name:"yd",base:z.LENGTH,prefixes:k.NONE,value:.9144,offset:0},mi:{name:"mi",base:z.LENGTH,prefixes:k.NONE,value:1609.344,offset:0},li:{name:"li",base:z.LENGTH,prefixes:k.NONE,value:.201168,offset:0},rd:{name:"rd",base:z.LENGTH,prefixes:k.NONE,value:5.02921,offset:0},ch:{name:"ch",base:z.LENGTH,prefixes:k.NONE,value:20.1168,offset:0},mil:{name:"mil",base:z.LENGTH,prefixes:k.NONE,value:254e-7,offset:0},m2:{name:"m2",base:z.SURFACE,prefixes:k.SQUARED,value:1,offset:0},sqin:{name:"sqin",base:z.SURFACE,prefixes:k.NONE,value:64516e-8,offset:0},sqft:{name:"sqft",base:z.SURFACE,prefixes:k.NONE,value:.09290304,offset:0},sqyd:{name:"sqyd",base:z.SURFACE,prefixes:k.NONE,value:.83612736,offset:0},sqmi:{name:"sqmi",base:z.SURFACE,prefixes:k.NONE,value:2589988110336e-6,offset:0},sqrd:{name:"sqrd",base:z.SURFACE,prefixes:k.NONE,value:25.29295,offset:0},sqch:{name:"sqch",base:z.SURFACE,prefixes:k.NONE,value:404.6873,offset:0},sqmil:{name:"sqmil",base:z.SURFACE,prefixes:k.NONE,value:64516e-14,offset:0},acre:{name:"acre",base:z.SURFACE,prefixes:k.NONE,value:4046.86,offset:0},hectare:{name:"hectare",base:z.SURFACE,prefixes:k.NONE,value:1e4,offset:0},m3:{name:"m3",base:z.VOLUME,prefixes:k.CUBIC,value:1,offset:0},L:{name:"L",base:z.VOLUME,prefixes:k.SHORT,value:.001,offset:0},l:{name:"l",base:z.VOLUME,prefixes:k.SHORT,value:.001,offset:0},litre:{name:"litre",base:z.VOLUME,prefixes:k.LONG,value:.001,offset:0},cuin:{name:"cuin",base:z.VOLUME,prefixes:k.NONE,value:16387064e-12,offset:0},cuft:{name:"cuft",base:z.VOLUME,prefixes:k.NONE,value:.028316846592,offset:0},cuyd:{name:"cuyd",base:z.VOLUME,prefixes:k.NONE,value:.764554857984,offset:0},teaspoon:{name:"teaspoon",base:z.VOLUME,prefixes:k.NONE,value:5e-6,offset:0},tablespoon:{name:"tablespoon",base:z.VOLUME,prefixes:k.NONE,value:15e-6,offset:0},drop:{name:"drop",base:z.VOLUME,prefixes:k.NONE,value:5e-8,offset:0},gtt:{name:"gtt",base:z.VOLUME,prefixes:k.NONE,value:5e-8,offset:0},minim:{name:"minim",base:z.VOLUME,prefixes:k.NONE,value:6161152e-14,offset:0},fluiddram:{name:"fluiddram",base:z.VOLUME,prefixes:k.NONE,value:36966911e-13,offset:0},fluidounce:{name:"fluidounce",base:z.VOLUME,prefixes:k.NONE,value:2957353e-11,offset:0},gill:{name:"gill",base:z.VOLUME,prefixes:k.NONE,value:.0001182941,offset:0},cc:{name:"cc",base:z.VOLUME,prefixes:k.NONE,value:1e-6,offset:0},cup:{name:"cup",base:z.VOLUME,prefixes:k.NONE,value:.0002365882,offset:0},pint:{name:"pint",base:z.VOLUME,prefixes:k.NONE,value:.0004731765,offset:0},quart:{name:"quart",base:z.VOLUME,prefixes:k.NONE,value:.0009463529,offset:0},gallon:{name:"gallon",base:z.VOLUME,prefixes:k.NONE,value:.003785412,offset:0},beerbarrel:{name:"beerbarrel",base:z.VOLUME,prefixes:k.NONE,value:.1173478,offset:0},oilbarrel:{name:"oilbarrel",base:z.VOLUME,prefixes:k.NONE,value:.1589873,offset:0},hogshead:{name:"hogshead",base:z.VOLUME,prefixes:k.NONE,value:.238481,offset:0},fldr:{name:"fldr",base:z.VOLUME,prefixes:k.NONE,value:36966911e-13,offset:0},floz:{name:"floz",base:z.VOLUME,prefixes:k.NONE,value:2957353e-11,offset:0},gi:{name:"gi",base:z.VOLUME,prefixes:k.NONE,value:.0001182941,offset:0},cp:{name:"cp",base:z.VOLUME,prefixes:k.NONE,value:.0002365882,offset:0},pt:{name:"pt",base:z.VOLUME,prefixes:k.NONE,value:.0004731765,offset:0},qt:{name:"qt",base:z.VOLUME,prefixes:k.NONE,value:.0009463529,offset:0},gal:{name:"gal",base:z.VOLUME,prefixes:k.NONE,value:.003785412,offset:0},bbl:{name:"bbl",base:z.VOLUME,prefixes:k.NONE,value:.1173478,offset:0},obl:{name:"obl",base:z.VOLUME,prefixes:k.NONE,value:.1589873,offset:0},g:{name:"g",base:z.MASS,prefixes:k.SHORT,value:.001,offset:0},gram:{name:"gram",base:z.MASS,prefixes:k.LONG,value:.001,offset:0},ton:{name:"ton",base:z.MASS,prefixes:k.SHORT,value:907.18474,offset:0},t:{name:"t",base:z.MASS,prefixes:k.SHORT,value:1e3,offset:0},tonne:{name:"tonne",base:z.MASS,prefixes:k.LONG,value:1e3,offset:0},grain:{name:"grain",base:z.MASS,prefixes:k.NONE,value:6479891e-11,offset:0},dram:{name:"dram",base:z.MASS,prefixes:k.NONE,value:.0017718451953125,offset:0},ounce:{name:"ounce",base:z.MASS,prefixes:k.NONE,value:.028349523125,offset:0},poundmass:{name:"poundmass",base:z.MASS,prefixes:k.NONE,value:.45359237,offset:0},hundredweight:{name:"hundredweight",base:z.MASS,prefixes:k.NONE,value:45.359237,offset:0},stick:{name:"stick",base:z.MASS,prefixes:k.NONE,value:.115,offset:0},stone:{name:"stone",base:z.MASS,prefixes:k.NONE,value:6.35029318,offset:0},gr:{name:"gr",base:z.MASS,prefixes:k.NONE,value:6479891e-11,offset:0},dr:{name:"dr",base:z.MASS,prefixes:k.NONE,value:.0017718451953125,offset:0},oz:{name:"oz",base:z.MASS,prefixes:k.NONE,value:.028349523125,offset:0},lbm:{name:"lbm",base:z.MASS,prefixes:k.NONE,value:.45359237,offset:0},cwt:{name:"cwt",base:z.MASS,prefixes:k.NONE,value:45.359237,offset:0},s:{name:"s",base:z.TIME,prefixes:k.SHORT,value:1,offset:0},min:{name:"min",base:z.TIME,prefixes:k.NONE,value:60,offset:0},h:{name:"h",base:z.TIME,prefixes:k.NONE,value:3600,offset:0},second:{name:"second",base:z.TIME,prefixes:k.LONG,value:1,offset:0},sec:{name:"sec",base:z.TIME,prefixes:k.LONG,value:1,offset:0},minute:{name:"minute",base:z.TIME,prefixes:k.NONE,value:60,offset:0},hour:{name:"hour",base:z.TIME,prefixes:k.NONE,value:3600,offset:0},day:{name:"day",base:z.TIME,prefixes:k.NONE,value:86400,offset:0},week:{name:"week",base:z.TIME,prefixes:k.NONE,value:7*86400,offset:0},month:{name:"month",base:z.TIME,prefixes:k.NONE,value:2629800,offset:0},year:{name:"year",base:z.TIME,prefixes:k.NONE,value:31557600,offset:0},decade:{name:"decade",base:z.TIME,prefixes:k.NONE,value:315576e3,offset:0},century:{name:"century",base:z.TIME,prefixes:k.NONE,value:315576e4,offset:0},millennium:{name:"millennium",base:z.TIME,prefixes:k.NONE,value:315576e5,offset:0},hertz:{name:"Hertz",base:z.FREQUENCY,prefixes:k.LONG,value:1,offset:0,reciprocal:!0},Hz:{name:"Hz",base:z.FREQUENCY,prefixes:k.SHORT,value:1,offset:0,reciprocal:!0},rad:{name:"rad",base:z.ANGLE,prefixes:k.SHORT,value:1,offset:0},radian:{name:"radian",base:z.ANGLE,prefixes:k.LONG,value:1,offset:0},deg:{name:"deg",base:z.ANGLE,prefixes:k.SHORT,value:null,offset:0},degree:{name:"degree",base:z.ANGLE,prefixes:k.LONG,value:null,offset:0},grad:{name:"grad",base:z.ANGLE,prefixes:k.SHORT,value:null,offset:0},gradian:{name:"gradian",base:z.ANGLE,prefixes:k.LONG,value:null,offset:0},cycle:{name:"cycle",base:z.ANGLE,prefixes:k.NONE,value:null,offset:0},arcsec:{name:"arcsec",base:z.ANGLE,prefixes:k.NONE,value:null,offset:0},arcmin:{name:"arcmin",base:z.ANGLE,prefixes:k.NONE,value:null,offset:0},A:{name:"A",base:z.CURRENT,prefixes:k.SHORT,value:1,offset:0},ampere:{name:"ampere",base:z.CURRENT,prefixes:k.LONG,value:1,offset:0},K:{name:"K",base:z.TEMPERATURE,prefixes:k.SHORT,value:1,offset:0},degC:{name:"degC",base:z.TEMPERATURE,prefixes:k.SHORT,value:1,offset:273.15},degF:{name:"degF",base:z.TEMPERATURE,prefixes:k.SHORT,value:new w(5,9),offset:459.67},degR:{name:"degR",base:z.TEMPERATURE,prefixes:k.SHORT,value:new w(5,9),offset:0},kelvin:{name:"kelvin",base:z.TEMPERATURE,prefixes:k.LONG,value:1,offset:0},celsius:{name:"celsius",base:z.TEMPERATURE,prefixes:k.LONG,value:1,offset:273.15},fahrenheit:{name:"fahrenheit",base:z.TEMPERATURE,prefixes:k.LONG,value:new w(5,9),offset:459.67},rankine:{name:"rankine",base:z.TEMPERATURE,prefixes:k.LONG,value:new w(5,9),offset:0},mol:{name:"mol",base:z.AMOUNT_OF_SUBSTANCE,prefixes:k.SHORT,value:1,offset:0},mole:{name:"mole",base:z.AMOUNT_OF_SUBSTANCE,prefixes:k.LONG,value:1,offset:0},cd:{name:"cd",base:z.LUMINOUS_INTENSITY,prefixes:k.SHORT,value:1,offset:0},candela:{name:"candela",base:z.LUMINOUS_INTENSITY,prefixes:k.LONG,value:1,offset:0},N:{name:"N",base:z.FORCE,prefixes:k.SHORT,value:1,offset:0},newton:{name:"newton",base:z.FORCE,prefixes:k.LONG,value:1,offset:0},dyn:{name:"dyn",base:z.FORCE,prefixes:k.SHORT,value:1e-5,offset:0},dyne:{name:"dyne",base:z.FORCE,prefixes:k.LONG,value:1e-5,offset:0},lbf:{name:"lbf",base:z.FORCE,prefixes:k.NONE,value:4.4482216152605,offset:0},poundforce:{name:"poundforce",base:z.FORCE,prefixes:k.NONE,value:4.4482216152605,offset:0},kip:{name:"kip",base:z.FORCE,prefixes:k.LONG,value:4448.2216,offset:0},kilogramforce:{name:"kilogramforce",base:z.FORCE,prefixes:k.NONE,value:9.80665,offset:0},J:{name:"J",base:z.ENERGY,prefixes:k.SHORT,value:1,offset:0},joule:{name:"joule",base:z.ENERGY,prefixes:k.LONG,value:1,offset:0},erg:{name:"erg",base:z.ENERGY,prefixes:k.SHORTLONG,value:1e-7,offset:0},Wh:{name:"Wh",base:z.ENERGY,prefixes:k.SHORT,value:3600,offset:0},BTU:{name:"BTU",base:z.ENERGY,prefixes:k.BTU,value:1055.05585262,offset:0},eV:{name:"eV",base:z.ENERGY,prefixes:k.SHORT,value:1602176565e-28,offset:0},electronvolt:{name:"electronvolt",base:z.ENERGY,prefixes:k.LONG,value:1602176565e-28,offset:0},W:{name:"W",base:z.POWER,prefixes:k.SHORT,value:1,offset:0},watt:{name:"watt",base:z.POWER,prefixes:k.LONG,value:1,offset:0},hp:{name:"hp",base:z.POWER,prefixes:k.NONE,value:745.6998715386,offset:0},VAR:{name:"VAR",base:z.POWER,prefixes:k.SHORT,value:v.I,offset:0},VA:{name:"VA",base:z.POWER,prefixes:k.SHORT,value:1,offset:0},Pa:{name:"Pa",base:z.PRESSURE,prefixes:k.SHORT,value:1,offset:0},psi:{name:"psi",base:z.PRESSURE,prefixes:k.NONE,value:6894.75729276459,offset:0},atm:{name:"atm",base:z.PRESSURE,prefixes:k.NONE,value:101325,offset:0},bar:{name:"bar",base:z.PRESSURE,prefixes:k.SHORTLONG,value:1e5,offset:0},torr:{name:"torr",base:z.PRESSURE,prefixes:k.NONE,value:133.322,offset:0},mmHg:{name:"mmHg",base:z.PRESSURE,prefixes:k.NONE,value:133.322,offset:0},mmH2O:{name:"mmH2O",base:z.PRESSURE,prefixes:k.NONE,value:9.80665,offset:0},cmH2O:{name:"cmH2O",base:z.PRESSURE,prefixes:k.NONE,value:98.0665,offset:0},coulomb:{name:"coulomb",base:z.ELECTRIC_CHARGE,prefixes:k.LONG,value:1,offset:0},C:{name:"C",base:z.ELECTRIC_CHARGE,prefixes:k.SHORT,value:1,offset:0},farad:{name:"farad",base:z.ELECTRIC_CAPACITANCE,prefixes:k.LONG,value:1,offset:0},F:{name:"F",base:z.ELECTRIC_CAPACITANCE,prefixes:k.SHORT,value:1,offset:0},volt:{name:"volt",base:z.ELECTRIC_POTENTIAL,prefixes:k.LONG,value:1,offset:0},V:{name:"V",base:z.ELECTRIC_POTENTIAL,prefixes:k.SHORT,value:1,offset:0},ohm:{name:"ohm",base:z.ELECTRIC_RESISTANCE,prefixes:k.SHORTLONG,value:1,offset:0},henry:{name:"henry",base:z.ELECTRIC_INDUCTANCE,prefixes:k.LONG,value:1,offset:0},H:{name:"H",base:z.ELECTRIC_INDUCTANCE,prefixes:k.SHORT,value:1,offset:0},siemens:{name:"siemens",base:z.ELECTRIC_CONDUCTANCE,prefixes:k.LONG,value:1,offset:0},S:{name:"S",base:z.ELECTRIC_CONDUCTANCE,prefixes:k.SHORT,value:1,offset:0},weber:{name:"weber",base:z.MAGNETIC_FLUX,prefixes:k.LONG,value:1,offset:0},Wb:{name:"Wb",base:z.MAGNETIC_FLUX,prefixes:k.SHORT,value:1,offset:0},tesla:{name:"tesla",base:z.MAGNETIC_FLUX_DENSITY,prefixes:k.LONG,value:1,offset:0},T:{name:"T",base:z.MAGNETIC_FLUX_DENSITY,prefixes:k.SHORT,value:1,offset:0},b:{name:"b",base:z.BIT,prefixes:k.BINARY_SHORT,value:1,offset:0},bits:{name:"bits",base:z.BIT,prefixes:k.BINARY_LONG,value:1,offset:0},B:{name:"B",base:z.BIT,prefixes:k.BINARY_SHORT,value:8,offset:0},bytes:{name:"bytes",base:z.BIT,prefixes:k.BINARY_LONG,value:8,offset:0}},le={meters:"meter",inches:"inch",feet:"foot",yards:"yard",miles:"mile",links:"link",rods:"rod",chains:"chain",angstroms:"angstrom",lt:"l",litres:"litre",liter:"litre",liters:"litre",teaspoons:"teaspoon",tablespoons:"tablespoon",minims:"minim",fluiddrams:"fluiddram",fluidounces:"fluidounce",gills:"gill",cups:"cup",pints:"pint",quarts:"quart",gallons:"gallon",beerbarrels:"beerbarrel",oilbarrels:"oilbarrel",hogsheads:"hogshead",gtts:"gtt",grams:"gram",tons:"ton",tonnes:"tonne",grains:"grain",drams:"dram",ounces:"ounce",poundmasses:"poundmass",hundredweights:"hundredweight",sticks:"stick",lb:"lbm",lbs:"lbm",kips:"kip",kgf:"kilogramforce",acres:"acre",hectares:"hectare",sqfeet:"sqft",sqyard:"sqyd",sqmile:"sqmi",sqmiles:"sqmi",mmhg:"mmHg",mmh2o:"mmH2O",cmh2o:"cmH2O",seconds:"second",secs:"second",minutes:"minute",mins:"minute",hours:"hour",hr:"hour",hrs:"hour",days:"day",weeks:"week",months:"month",years:"year",decades:"decade",centuries:"century",millennia:"millennium",hertz:"hertz",radians:"radian",degrees:"degree",gradians:"gradian",cycles:"cycle",arcsecond:"arcsec",arcseconds:"arcsec",arcminute:"arcmin",arcminutes:"arcmin",BTUs:"BTU",watts:"watt",joules:"joule",amperes:"ampere",amps:"ampere",amp:"ampere",coulombs:"coulomb",volts:"volt",ohms:"ohm",farads:"farad",webers:"weber",teslas:"tesla",electronvolts:"electronvolt",moles:"mole",bit:"bits",byte:"bytes"};function Ee(J){if(J.number==="BigNumber"){var re=Ic(y);$.rad.value=new y(1),$.deg.value=re.div(180),$.grad.value=re.div(200),$.cycle.value=re.times(2),$.arcsec.value=re.div(648e3),$.arcmin.value=re.div(10800)}else $.rad.value=1,$.deg.value=Math.PI/180,$.grad.value=Math.PI/200,$.cycle.value=Math.PI*2,$.arcsec.value=Math.PI/648e3,$.arcmin.value=Math.PI/10800;$.radian.value=$.rad.value,$.degree.value=$.deg.value,$.gradian.value=$.grad.value}Ee(t),r&&r("config",function(J,re){J.number!==re.number&&Ee(J)});var me={si:{NONE:{unit:ae,prefix:k.NONE[""]},LENGTH:{unit:$.m,prefix:k.SHORT[""]},MASS:{unit:$.g,prefix:k.SHORT.k},TIME:{unit:$.s,prefix:k.SHORT[""]},CURRENT:{unit:$.A,prefix:k.SHORT[""]},TEMPERATURE:{unit:$.K,prefix:k.SHORT[""]},LUMINOUS_INTENSITY:{unit:$.cd,prefix:k.SHORT[""]},AMOUNT_OF_SUBSTANCE:{unit:$.mol,prefix:k.SHORT[""]},ANGLE:{unit:$.rad,prefix:k.SHORT[""]},BIT:{unit:$.bits,prefix:k.SHORT[""]},FORCE:{unit:$.N,prefix:k.SHORT[""]},ENERGY:{unit:$.J,prefix:k.SHORT[""]},POWER:{unit:$.W,prefix:k.SHORT[""]},PRESSURE:{unit:$.Pa,prefix:k.SHORT[""]},ELECTRIC_CHARGE:{unit:$.C,prefix:k.SHORT[""]},ELECTRIC_CAPACITANCE:{unit:$.F,prefix:k.SHORT[""]},ELECTRIC_POTENTIAL:{unit:$.V,prefix:k.SHORT[""]},ELECTRIC_RESISTANCE:{unit:$.ohm,prefix:k.SHORT[""]},ELECTRIC_INDUCTANCE:{unit:$.H,prefix:k.SHORT[""]},ELECTRIC_CONDUCTANCE:{unit:$.S,prefix:k.SHORT[""]},MAGNETIC_FLUX:{unit:$.Wb,prefix:k.SHORT[""]},MAGNETIC_FLUX_DENSITY:{unit:$.T,prefix:k.SHORT[""]},FREQUENCY:{unit:$.Hz,prefix:k.SHORT[""]}}};me.cgs=JSON.parse(JSON.stringify(me.si)),me.cgs.LENGTH={unit:$.m,prefix:k.SHORT.c},me.cgs.MASS={unit:$.g,prefix:k.SHORT[""]},me.cgs.FORCE={unit:$.dyn,prefix:k.SHORT[""]},me.cgs.ENERGY={unit:$.erg,prefix:k.NONE[""]},me.us=JSON.parse(JSON.stringify(me.si)),me.us.LENGTH={unit:$.ft,prefix:k.NONE[""]},me.us.MASS={unit:$.lbm,prefix:k.NONE[""]},me.us.TEMPERATURE={unit:$.degF,prefix:k.NONE[""]},me.us.FORCE={unit:$.lbf,prefix:k.NONE[""]},me.us.ENERGY={unit:$.BTU,prefix:k.BTU[""]},me.us.POWER={unit:$.hp,prefix:k.NONE[""]},me.us.PRESSURE={unit:$.psi,prefix:k.NONE[""]},me.auto=JSON.parse(JSON.stringify(me.si));var ge=me.auto;b.setUnitSystem=function(J){if(Xe(me,J))ge=me[J];else throw new Error("Unit system "+J+" does not exist. Choices are: "+Object.keys(me).join(", "))},b.getUnitSystem=function(){for(var J in me)if(Xe(me,J)&&me[J]===ge)return J},b.typeConverters={BigNumber:function(re){return re!=null&&re.isFraction?new y(re.n).div(re.d).times(re.s):new y(re+"")},Fraction:function(re){return new w(re)},Complex:function(re){return re},number:function(re){return re!=null&&re.isFraction?x(re):re}},b.prototype._numberConverter=function(){var J=b.typeConverters[this.valueType()];if(J)return J;throw new TypeError('Unsupported Unit value type "'+this.valueType()+'"')},b._getNumberConverter=function(J){if(!b.typeConverters[J])throw new TypeError('Unsupported type "'+J+'"');return b.typeConverters[J]};for(var Se in $)if(Xe($,Se)){var xe=$[Se];xe.dimensions=xe.base.dimensions}for(var be in le)if(Xe(le,be)){var De=$[le[be]],Ae={};for(var We in De)Xe(De,We)&&(Ae[We]=De[We]);Ae.name=be,$[be]=Ae}b.isValidAlpha=function(re){return/^[a-zA-Z]$/.test(re)};function Je(J){for(var re=0;re0&&!(b.isValidAlpha(S)||E(S)))throw new Error('Invalid unit name (only alphanumeric characters are allowed): "'+J+'"')}}return b.createUnit=function(J,re){if(typeof J!="object")throw new TypeError("createUnit expects first parameter to be of type 'Object'");if(re&&re.override){for(var ye in J)if(Xe(J,ye)&&b.deleteUnit(ye),J[ye].aliases)for(var j=0;j"u"||re===null)&&(re={}),typeof J!="string")throw new TypeError("createUnitSingle expects first parameter to be of type 'string'");if(Xe($,J))throw new Error('Cannot create unit "'+J+'": a unit with that name already exists');Je(J);var ye=null,j=[],ne=0,ue,Me,Ce;if(re&&re.type==="Unit")ye=re.clone();else if(typeof re=="string")re!==""&&(ue=re);else if(typeof re=="object")ue=re.definition,Me=re.prefixes,ne=re.offset,Ce=re.baseName,re.aliases&&(j=re.aliases.valueOf());else throw new TypeError('Cannot create unit "'+J+'" from "'+re.toString()+'": expecting "string" or "Unit" or "Object"');if(j){for(var Le=0;Le1e-12){ce=!1;break}if(ce){Pr=!0,Ie.base=z[ee];break}}if(!Pr){Ce=Ce||J+"_STUFF";var Be={dimensions:ye.dimensions.slice(0)};Be.key=Ce,z[Ce]=Be,ge[Ce]={unit:Ie,prefix:k.NONE[""]},Ie.base=z[Ce]}}else{if(Ce=Ce||J+"_STUFF",K.indexOf(Ce)>=0)throw new Error('Cannot create new base unit "'+J+'": a base unit with that name already exists (and cannot be overridden)');K.push(Ce);for(var fr in z)Xe(z,fr)&&(z[fr].dimensions[K.length-1]=0);for(var or={dimensions:[]},Ke=0;Ke{var{typed:r,Unit:t}=e;return r(dE,{Unit:function(a){return a.clone()},string:function(a){return t.isValuelessUnit(a)?new t(null,a):t.parse(a,{allowNoUnits:!0})},"number | BigNumber | Fraction | Complex, string | Unit":function(a,i){return new t(a,i)},"number | BigNumber | Fraction":function(a){return new t(a)},"Array | Matrix":r.referToSelf(n=>a=>je(a,n))})});var hE="sparse",BH=["typed","SparseMatrix"],Fh=F(hE,BH,e=>{var{typed:r,SparseMatrix:t}=e;return r(hE,{"":function(){return new t([])},string:function(a){return new t([],a)},"Array | Matrix":function(a){return new t(a)},"Array | Matrix, string":function(a,i){return new t(a,i)}})});var vE="createUnit",PH=["typed","Unit"],_h=F(vE,PH,e=>{var{typed:r,Unit:t}=e;return r(vE,{"Object, Object":function(a,i){return t.createUnit(a,i)},Object:function(a){return t.createUnit(a,{})},"string, Unit | string | Object, Object":function(a,i,u){var l={};return l[a]=i,t.createUnit(l,u)},"string, Unit | string | Object":function(a,i){var u={};return u[a]=i,t.createUnit(u,{})},string:function(a){var i={};return i[a]={},t.createUnit(i,{})}})});var gE="acos",IH=["typed","config","Complex"],Oh=F(gE,IH,e=>{var{typed:r,config:t,Complex:n}=e;return r(gE,{number:function(i){return i>=-1&&i<=1||t.predictable?Math.acos(i):new n(i,0).acos()},Complex:function(i){return i.acos()},BigNumber:function(i){return i.acos()}})});var xE="acosh",RH=["typed","config","Complex"],Bh=F(xE,RH,e=>{var{typed:r,config:t,Complex:n}=e;return r(xE,{number:function(i){return i>=1||t.predictable?$w(i):i<=-1?new n(Math.log(Math.sqrt(i*i-1)-i),Math.PI):new n(i,0).acosh()},Complex:function(i){return i.acosh()},BigNumber:function(i){return i.acosh()}})});var yE="acot",kH=["typed","BigNumber"],Ph=F(yE,kH,e=>{var{typed:r,BigNumber:t}=e;return r(yE,{number:Gw,Complex:function(a){return a.acot()},BigNumber:function(a){return new t(1).div(a).atan()}})});var bE="acoth",qH=["typed","config","Complex","BigNumber"],Ih=F(bE,qH,e=>{var{typed:r,config:t,Complex:n,BigNumber:a}=e;return r(bE,{number:function(u){return u>=1||u<=-1||t.predictable?Vw(u):new n(u,0).acoth()},Complex:function(u){return u.acoth()},BigNumber:function(u){return new a(1).div(u).atanh()}})});var wE="acsc",LH=["typed","config","Complex","BigNumber"],Rh=F(wE,LH,e=>{var{typed:r,config:t,Complex:n,BigNumber:a}=e;return r(wE,{number:function(u){return u<=-1||u>=1||t.predictable?Zw(u):new n(u,0).acsc()},Complex:function(u){return u.acsc()},BigNumber:function(u){return new a(1).div(u).asin()}})});var DE="acsch",zH=["typed","BigNumber"],kh=F(DE,zH,e=>{var{typed:r,BigNumber:t}=e;return r(DE,{number:Qw,Complex:function(a){return a.acsch()},BigNumber:function(a){return new t(1).div(a).asinh()}})});var SE="asec",UH=["typed","config","Complex","BigNumber"],qh=F(SE,UH,e=>{var{typed:r,config:t,Complex:n,BigNumber:a}=e;return r(SE,{number:function(u){return u<=-1||u>=1||t.predictable?Xw(u):new n(u,0).asec()},Complex:function(u){return u.asec()},BigNumber:function(u){return new a(1).div(u).acos()}})});var NE="asech",WH=["typed","config","Complex","BigNumber"],Lh=F(NE,WH,e=>{var{typed:r,config:t,Complex:n,BigNumber:a}=e;return r(NE,{number:function(u){if(u<=1&&u>=-1||t.predictable){var l=1/u;if(l>0||t.predictable)return Jw(u);var c=Math.sqrt(l*l-1);return new n(Math.log(c-l),Math.PI)}return new n(u,0).asech()},Complex:function(u){return u.asech()},BigNumber:function(u){return new a(1).div(u).acosh()}})});var AE="asin",YH=["typed","config","Complex"],zh=F(AE,YH,e=>{var{typed:r,config:t,Complex:n}=e;return r(AE,{number:function(i){return i>=-1&&i<=1||t.predictable?Math.asin(i):new n(i,0).asin()},Complex:function(i){return i.asin()},BigNumber:function(i){return i.asin()}})});var HH="asinh",$H=["typed"],Uh=F(HH,$H,e=>{var{typed:r}=e;return r("asinh",{number:Kw,Complex:function(n){return n.asinh()},BigNumber:function(n){return n.asinh()}})});var GH="atan",VH=["typed"],Wh=F(GH,VH,e=>{var{typed:r}=e;return r("atan",{number:function(n){return Math.atan(n)},Complex:function(n){return n.atan()},BigNumber:function(n){return n.atan()}})});var ME="atan2",ZH=["typed","matrix","equalScalar","BigNumber","DenseMatrix","concat"],Yh=F(ME,ZH,e=>{var{typed:r,matrix:t,equalScalar:n,BigNumber:a,DenseMatrix:i,concat:u}=e,l=Lt({typed:r,equalScalar:n}),c=lt({typed:r}),o=Zp({typed:r,equalScalar:n}),s=jr({typed:r,equalScalar:n}),m=Wr({typed:r,DenseMatrix:i}),d=vr({typed:r,matrix:t,concat:u});return r(ME,{"number, number":Math.atan2,"BigNumber, BigNumber":(h,x)=>a.atan2(h,x)},d({scalar:"number | BigNumber",SS:o,DS:c,SD:l,Ss:s,sS:m}))});var CE="atanh",QH=["typed","config","Complex"],Hh=F(CE,QH,e=>{var{typed:r,config:t,Complex:n}=e;return r(CE,{number:function(i){return i<=1&&i>=-1||t.predictable?jw(i):new n(i,0).atanh()},Complex:function(i){return i.atanh()},BigNumber:function(i){return i.atanh()}})});var Ra=F("trigUnit",["typed"],e=>{var{typed:r}=e;return{Unit:r.referToSelf(t=>n=>{if(!n.hasBase(n.constructor.BASE_UNITS.ANGLE))throw new TypeError("Unit in function cot is no angle");return r.find(t,n.valueType())(n.value)})}});var EE="cos",XH=["typed"],$h=F(EE,XH,e=>{var{typed:r}=e,t=Ra({typed:r});return r(EE,{number:Math.cos,"Complex | BigNumber":n=>n.cos()},t)});var TE="cosh",JH=["typed"],Gh=F(TE,JH,e=>{var{typed:r}=e;return r(TE,{number:Em,"Complex | BigNumber":t=>t.cosh()})});var FE="cot",KH=["typed","BigNumber"],Vh=F(FE,KH,e=>{var{typed:r,BigNumber:t}=e,n=Ra({typed:r});return r(FE,{number:eD,Complex:a=>a.cot(),BigNumber:a=>new t(1).div(a.tan())},n)});var _E="coth",jH=["typed","BigNumber"],Zh=F(_E,jH,e=>{var{typed:r,BigNumber:t}=e;return r(_E,{number:rD,Complex:n=>n.coth(),BigNumber:n=>new t(1).div(n.tanh())})});var OE="csc",e$=["typed","BigNumber"],Qh=F(OE,e$,e=>{var{typed:r,BigNumber:t}=e,n=Ra({typed:r});return r(OE,{number:tD,Complex:a=>a.csc(),BigNumber:a=>new t(1).div(a.sin())},n)});var BE="csch",r$=["typed","BigNumber"],Xh=F(BE,r$,e=>{var{typed:r,BigNumber:t}=e;return r(BE,{number:nD,Complex:n=>n.csch(),BigNumber:n=>new t(1).div(n.sinh())})});var PE="sec",t$=["typed","BigNumber"],Jh=F(PE,t$,e=>{var{typed:r,BigNumber:t}=e,n=Ra({typed:r});return r(PE,{number:aD,Complex:a=>a.sec(),BigNumber:a=>new t(1).div(a.cos())},n)});var IE="sech",n$=["typed","BigNumber"],Kh=F(IE,n$,e=>{var{typed:r,BigNumber:t}=e;return r(IE,{number:iD,Complex:n=>n.sech(),BigNumber:n=>new t(1).div(n.cosh())})});var RE="sin",a$=["typed"],jh=F(RE,a$,e=>{var{typed:r}=e,t=Ra({typed:r});return r(RE,{number:Math.sin,"Complex | BigNumber":n=>n.sin()},t)});var kE="sinh",i$=["typed"],ev=F(kE,i$,e=>{var{typed:r}=e;return r(kE,{number:oD,"Complex | BigNumber":t=>t.sinh()})});var qE="tan",o$=["typed"],rv=F(qE,o$,e=>{var{typed:r}=e,t=Ra({typed:r});return r(qE,{number:Math.tan,"Complex | BigNumber":n=>n.tan()},t)});var s$="tanh",u$=["typed"],tv=F(s$,u$,e=>{var{typed:r}=e;return r("tanh",{number:Tm,"Complex | BigNumber":t=>t.tanh()})});var LE="setCartesian",f$=["typed","size","subset","compareNatural","Index","DenseMatrix"],nv=F(LE,f$,e=>{var{typed:r,size:t,subset:n,compareNatural:a,Index:i,DenseMatrix:u}=e;return r(LE,{"Array | Matrix, Array | Matrix":function(c,o){var s=[];if(n(t(c),new i(0))!==0&&n(t(o),new i(0))!==0){var m=gr(Array.isArray(c)?c:c.toArray()).sort(a),d=gr(Array.isArray(o)?o:o.toArray()).sort(a);s=[];for(var h=0;h{var{typed:r,size:t,subset:n,compareNatural:a,Index:i,DenseMatrix:u}=e;return r(zE,{"Array | Matrix, Array | Matrix":function(c,o){var s;if(n(t(c),new i(0))===0)s=[];else{if(n(t(o),new i(0))===0)return gr(c.toArray());var m=Ji(gr(Array.isArray(c)?c:c.toArray()).sort(a)),d=Ji(gr(Array.isArray(o)?o:o.toArray()).sort(a));s=[];for(var h,x=0;x{var{typed:r,size:t,subset:n,compareNatural:a,Index:i,DenseMatrix:u}=e;return r(UE,{"Array | Matrix":function(c){var o;if(n(t(c),new i(0))===0)o=[];else{var s=gr(Array.isArray(c)?c:c.toArray()).sort(a);o=[],o.push(s[0]);for(var m=1;m{var{typed:r,size:t,subset:n,compareNatural:a,Index:i,DenseMatrix:u}=e;return r(WE,{"Array | Matrix, Array | Matrix":function(c,o){var s;if(n(t(c),new i(0))===0||n(t(o),new i(0))===0)s=[];else{var m=Ji(gr(Array.isArray(c)?c:c.toArray()).sort(a)),d=Ji(gr(Array.isArray(o)?o:o.toArray()).sort(a));s=[];for(var h=0;h{var{typed:r,size:t,subset:n,compareNatural:a,Index:i}=e;return r(YE,{"Array | Matrix, Array | Matrix":function(l,c){if(n(t(l),new i(0))===0)return!0;if(n(t(c),new i(0))===0)return!1;for(var o=Ji(gr(Array.isArray(l)?l:l.toArray()).sort(a)),s=Ji(gr(Array.isArray(c)?c:c.toArray()).sort(a)),m,d=0;d{var{typed:r,size:t,subset:n,compareNatural:a,Index:i}=e;return r(HE,{"number | BigNumber | Fraction | Complex, Array | Matrix":function(l,c){if(n(t(c),new i(0))===0)return 0;for(var o=gr(Array.isArray(c)?c:c.toArray()),s=0,m=0;m{var{typed:r,size:t,subset:n,compareNatural:a,Index:i}=e;return r($E,{"Array | Matrix":function(o){if(n(t(o),new i(0))===0)return[];for(var s=gr(Array.isArray(o)?o:o.toArray()).sort(a),m=[],d=0;d.toString(2).length<=s.length;)m.push(u(s,d.toString(2).split("").reverse())),d++;return l(m)}});function u(c,o){for(var s=[],m=0;m0;s--)for(var m=0;mc[m+1].length&&(o=c[m],c[m]=c[m+1],c[m+1]=o);return c}});var GE="setSize",v$=["typed","compareNatural"],cv=F(GE,v$,e=>{var{typed:r,compareNatural:t}=e;return r(GE,{"Array | Matrix":function(a){return Array.isArray(a)?gr(a).length:gr(a.toArray()).length},"Array | Matrix, boolean":function(a,i){if(i===!1||a.length===0)return Array.isArray(a)?gr(a).length:gr(a.toArray()).length;for(var u=gr(Array.isArray(a)?a:a.toArray()).sort(t),l=1,c=1;c{var{typed:r,size:t,concat:n,subset:a,setDifference:i,Index:u}=e;return r(VE,{"Array | Matrix, Array | Matrix":function(c,o){if(a(t(c),new u(0))===0)return gr(o);if(a(t(o),new u(0))===0)return gr(c);var s=gr(c),m=gr(o);return n(i(s,m),i(m,s))}})});var ZE="setUnion",x$=["typed","size","concat","subset","setIntersect","setSymDifference","Index"],mv=F(ZE,x$,e=>{var{typed:r,size:t,concat:n,subset:a,setIntersect:i,setSymDifference:u,Index:l}=e;return r(ZE,{"Array | Matrix, Array | Matrix":function(o,s){if(a(t(o),new l(0))===0)return gr(s);if(a(t(s),new l(0))===0)return gr(o);var m=gr(o),d=gr(s);return n(u(m,d),i(m,d))}})});var QE="add",y$=["typed","matrix","addScalar","equalScalar","DenseMatrix","SparseMatrix","concat"],pv=F(QE,y$,e=>{var{typed:r,matrix:t,addScalar:n,equalScalar:a,DenseMatrix:i,SparseMatrix:u,concat:l}=e,c=Mn({typed:r}),o=Ru({typed:r,equalScalar:a}),s=jn({typed:r,DenseMatrix:i}),m=vr({typed:r,matrix:t,concat:l});return r(QE,{"any, any":n,"any, any, ...any":r.referToSelf(d=>(h,x,v)=>{for(var y=d(h,x),w=0;w{var{typed:r,abs:t,addScalar:n,divideScalar:a,multiplyScalar:i,sqrt:u,smaller:l,isPositive:c}=e;return r(XE,{"... number | BigNumber":o,Array:o,Matrix:s=>o(gr(s.toArray()))});function o(s){for(var m=0,d=0,h=0;h{var{typed:r,abs:t,add:n,pow:a,conj:i,sqrt:u,multiply:l,equalScalar:c,larger:o,smaller:s,matrix:m,ctranspose:d,eigs:h}=e;return r(JE,{number:Math.abs,Complex:function(_){return _.abs()},BigNumber:function(_){return _.abs()},boolean:function(_){return Math.abs(_)},Array:function(_){return S(m(_),2)},Matrix:function(_){return S(_,2)},"Array, number | BigNumber | string":function(_,E){return S(m(_),E)},"Matrix, number | BigNumber | string":function(_,E){return S(_,E)}});function x(O){var _=0;return O.forEach(function(E){var T=t(E);o(T,_)&&(_=T)},!0),_}function v(O){var _;return O.forEach(function(E){var T=t(E);(!_||s(T,_))&&(_=T)},!0),_||0}function y(O,_){if(_===Number.POSITIVE_INFINITY||_==="inf")return x(O);if(_===Number.NEGATIVE_INFINITY||_==="-inf")return v(O);if(_==="fro")return S(O,2);if(typeof _=="number"&&!isNaN(_)){if(!c(_,0)){var E=0;return O.forEach(function(T){E=n(a(t(T),_),E)},!0),a(E,1/_)}return Number.POSITIVE_INFINITY}throw new Error("Unsupported parameter value")}function w(O){var _=0;return O.forEach(function(E,T){_=n(_,l(E,i(E)))}),t(u(_))}function C(O){var _=[],E=0;return O.forEach(function(T,R){var q=R[1],W=n(_[q]||0,t(T));o(W,E)&&(E=W),_[q]=W},!0),E}function b(O){var _=O.size();if(_[0]!==_[1])throw new RangeError("Invalid matrix dimensions");var E=d(O),T=l(E,O),R=h(T).values.toArray(),q=R[R.length-1];return t(u(q))}function M(O){var _=[],E=0;return O.forEach(function(T,R){var q=R[0],W=n(_[q]||0,t(T));o(W,E)&&(E=W),_[q]=W},!0),E}function A(O,_){if(_===1)return C(O);if(_===Number.POSITIVE_INFINITY||_==="inf")return M(O);if(_==="fro")return w(O);if(_===2)return b(O);throw new Error("Unsupported parameter value "+_)}function S(O,_){var E=O.size();if(E.length===1)return y(O,_);if(E.length===2){if(E[0]&&E[1])return A(O,_);throw new RangeError("Invalid matrix dimensions")}}});var KE="dot",D$=["typed","addScalar","multiplyScalar","conj","size"],vv=F(KE,D$,e=>{var{typed:r,addScalar:t,multiplyScalar:n,conj:a,size:i}=e;return r(KE,{"Array | DenseMatrix, Array | DenseMatrix":l,"SparseMatrix, SparseMatrix":c});function u(s,m){var d=o(s),h=o(m),x,v;if(d.length===1)x=d[0];else if(d.length===2&&d[1]===1)x=d[0];else throw new RangeError("Expected a column vector, instead got a matrix of size ("+d.join(", ")+")");if(h.length===1)v=h[0];else if(h.length===2&&h[1]===1)v=h[0];else throw new RangeError("Expected a column vector, instead got a matrix of size ("+h.join(", ")+")");if(x!==v)throw new RangeError("Vectors must have equal length ("+x+" != "+v+")");if(x===0)throw new RangeError("Cannot calculate the dot product of empty vectors");return x}function l(s,m){var d=u(s,m),h=Qe(s)?s._data:s,x=Qe(s)?s._datatype||s.getDataType():void 0,v=Qe(m)?m._data:m,y=Qe(m)?m._datatype||m.getDataType():void 0,w=o(s).length===2,C=o(m).length===2,b=t,M=n;if(x&&y&&x===y&&typeof x=="string"&&x!=="mixed"){var A=x;b=r.find(t,[A,A]),M=r.find(n,[A,A])}if(!w&&!C){for(var S=M(a(h[0]),v[0]),O=1;OS){M++;continue}A===S&&(y=w(y,C(h[b],v[M])),b++,M++)}return y}function o(s){return Qe(s)?s.size():i(s)}});var S$="trace",N$=["typed","matrix","add"],gv=F(S$,N$,e=>{var{typed:r,matrix:t,add:n}=e;return r("trace",{Array:function(l){return a(t(l))},SparseMatrix:i,DenseMatrix:a,any:ar});function a(u){var l=u._size,c=u._data;switch(l.length){case 1:if(l[0]===1)return ar(c[0]);throw new RangeError("Matrix must be square (size: "+lr(l)+")");case 2:{var o=l[0],s=l[1];if(o===s){for(var m=0,d=0;d0)for(var x=0;xx)break}return h}throw new RangeError("Matrix must be square (size: "+lr(s)+")")}});var jE="index",A$=["typed","Index"],xv=F(jE,A$,e=>{var{typed:r,Index:t}=e;return r(jE,{"...number | string | BigNumber | Range | Array | Matrix":function(a){var i=a.map(function(l){return rr(l)?l.toNumber():Mr(l)||Qe(l)?l.map(function(c){return rr(c)?c.toNumber():c}):l}),u=new t;return t.apply(u,i),u}})});var yv=new Set(["end"]);var M$="Node",C$=["mathWithTransform"],bv=F(M$,C$,e=>{var{mathWithTransform:r}=e;function t(a){for(var i of[...yv])if(a.has(i))throw new Error('Scope contains an illegal symbol, "'+i+'" is a reserved keyword')}class n{get type(){return"Node"}get isNode(){return!0}evaluate(i){return this.compile().evaluate(i)}compile(){var i=this._compile(r,{}),u={},l=null;function c(o){var s=Ki(o);return t(s),i(s,u,l)}return{evaluate:c}}_compile(i,u){throw new Error("Method _compile must be implemented by type "+this.type)}forEach(i){throw new Error("Cannot run forEach on a Node interface")}map(i){throw new Error("Cannot run map on a Node interface")}_ifNode(i){if(!Nr(i))throw new TypeError("Callback function must return a Node");return i}traverse(i){i(this,null,null);function u(l,c){l.forEach(function(o,s,m){c(o,s,m),u(o,c)})}u(this,i)}transform(i){function u(l,c,o){var s=i(l,c,o);return s!==l?s:l.map(u)}return u(this,null,null)}filter(i){var u=[];return this.traverse(function(l,c,o){i(l,c,o)&&u.push(l)}),u}clone(){throw new Error("Cannot clone a Node interface")}cloneDeep(){return this.map(function(i){return i.cloneDeep()})}equals(i){return i?this.type===i.type&&ni(this,i):!1}toString(i){var u=this._getCustomString(i);return typeof u<"u"?u:this._toString(i)}_toString(){throw new Error("_toString not implemented for "+this.type)}toJSON(){throw new Error("Cannot serialize object: toJSON not implemented by "+this.type)}toHTML(i){var u=this._getCustomString(i);return typeof u<"u"?u:this._toHTML(i)}_toHTML(){throw new Error("_toHTML not implemented for "+this.type)}toTex(i){var u=this._getCustomString(i);return typeof u<"u"?u:this._toTex(i)}_toTex(i){throw new Error("_toTex not implemented for "+this.type)}_getCustomString(i){if(i&&typeof i=="object")switch(typeof i.handler){case"object":case"undefined":return;case"function":return i.handler(this,i);default:throw new TypeError("Object or function expected as callback")}}getIdentifier(){return this.type}getContent(){return this}}return n},{isClass:!0,isNode:!0});function mt(e){return e&&e.isIndexError?new tn(e.index+1,e.min+1,e.max!==void 0?e.max+1:void 0):e}function wv(e){var{subset:r}=e;return function(n,a){try{if(Array.isArray(n))return r(n,a);if(n&&typeof n.subset=="function")return n.subset(a);if(typeof n=="string")return r(n,a);if(typeof n=="object"){if(!a.isObjectProperty())throw new TypeError("Cannot apply a numeric index as object property");return wt(n,a.getObjectProperty())}else throw new TypeError("Cannot apply index: unsupported type of object")}catch(i){throw mt(i)}}}var Dv="AccessorNode",E$=["subset","Node"],Sv=F(Dv,E$,e=>{var{subset:r,Node:t}=e,n=wv({subset:r});function a(u){return!(qn(u)||jt(u)||yr(u)||gn(u)||Ci(u)||en(u)||at(u))}class i extends t{constructor(l,c){if(super(),!Nr(l))throw new TypeError('Node expected for parameter "object"');if(!Qn(c))throw new TypeError('IndexNode expected for parameter "index"');this.object=l,this.index=c}get name(){return this.index?this.index.isObjectProperty()?this.index.getObjectProperty():"":this.object.name||""}get type(){return Dv}get isAccessorNode(){return!0}_compile(l,c){var o=this.object._compile(l,c),s=this.index._compile(l,c);if(this.index.isObjectProperty()){var m=this.index.getObjectProperty();return function(h,x,v){return wt(o(h,x,v),m)}}else return function(h,x,v){var y=o(h,x,v),w=s(h,x,y);return n(y,w)}}forEach(l){l(this.object,"object",this),l(this.index,"index",this)}map(l){return new i(this._ifNode(l(this.object,"object",this)),this._ifNode(l(this.index,"index",this)))}clone(){return new i(this.object,this.index)}_toString(l){var c=this.object.toString(l);return a(this.object)&&(c="("+c+")"),c+this.index.toString(l)}_toHTML(l){var c=this.object.toHTML(l);return a(this.object)&&(c='('+c+')'),c+this.index.toHTML(l)}_toTex(l){var c=this.object.toTex(l);return a(this.object)&&(c="\\\\left(' + object + '\\\\right)"),c+this.index.toTex(l)}toJSON(){return{mathjs:Dv,object:this.object,index:this.index}}static fromJSON(l){return new i(l.object,l.index)}}return Hr(i,"name",Dv),i},{isClass:!0,isNode:!0});var Nv="ArrayNode",T$=["Node"],Av=F(Nv,T$,e=>{var{Node:r}=e;class t extends r{constructor(a){if(super(),this.items=a||[],!Array.isArray(this.items)||!this.items.every(Nr))throw new TypeError("Array containing Nodes expected")}get type(){return Nv}get isArrayNode(){return!0}_compile(a,i){var u=Xn(this.items,function(o){return o._compile(a,i)}),l=a.config.matrix!=="Array";if(l){var c=a.matrix;return function(s,m,d){return c(Xn(u,function(h){return h(s,m,d)}))}}else return function(s,m,d){return Xn(u,function(h){return h(s,m,d)})}}forEach(a){for(var i=0;i['+i.join(',')+']'}_toTex(a){function i(u,l){var c=u.some(jt)&&!u.every(jt),o=l||c,s=o?"&":"\\\\\\\\",m=u.map(function(d){return d.items?i(d.items,!l):d.toTex(a)}).join(s);return c||!o||o&&!l?"\\\\begin{bmatrix}"+m+"\\\\end{bmatrix}":m}return i(this.items,!1)}}return Hr(t,"name",Nv),t},{isClass:!0,isNode:!0});function eT(e){var{subset:r,matrix:t}=e;return function(a,i,u){try{if(Array.isArray(a)){var l=t(a).subset(i,u).valueOf();return l.forEach((c,o)=>{a[o]=c}),a}else{if(a&&typeof a.subset=="function")return a.subset(i,u);if(typeof a=="string")return r(a,i,u);if(typeof a=="object"){if(!i.isObjectProperty())throw TypeError("Cannot apply a numeric index as object property");return Ei(a,i.getObjectProperty(),u),a}else throw new TypeError("Cannot apply index: unsupported type of object")}}catch(c){throw mt(c)}}}var ka=[{AssignmentNode:{},FunctionAssignmentNode:{}},{ConditionalNode:{latexLeftParens:!1,latexRightParens:!1,latexParens:!1}},{"OperatorNode:or":{op:"or",associativity:"left",associativeWith:[]}},{"OperatorNode:xor":{op:"xor",associativity:"left",associativeWith:[]}},{"OperatorNode:and":{op:"and",associativity:"left",associativeWith:[]}},{"OperatorNode:bitOr":{op:"|",associativity:"left",associativeWith:[]}},{"OperatorNode:bitXor":{op:"^|",associativity:"left",associativeWith:[]}},{"OperatorNode:bitAnd":{op:"&",associativity:"left",associativeWith:[]}},{"OperatorNode:equal":{op:"==",associativity:"left",associativeWith:[]},"OperatorNode:unequal":{op:"!=",associativity:"left",associativeWith:[]},"OperatorNode:smaller":{op:"<",associativity:"left",associativeWith:[]},"OperatorNode:larger":{op:">",associativity:"left",associativeWith:[]},"OperatorNode:smallerEq":{op:"<=",associativity:"left",associativeWith:[]},"OperatorNode:largerEq":{op:">=",associativity:"left",associativeWith:[]},RelationalNode:{associativity:"left",associativeWith:[]}},{"OperatorNode:leftShift":{op:"<<",associativity:"left",associativeWith:[]},"OperatorNode:rightArithShift":{op:">>",associativity:"left",associativeWith:[]},"OperatorNode:rightLogShift":{op:">>>",associativity:"left",associativeWith:[]}},{"OperatorNode:to":{op:"to",associativity:"left",associativeWith:[]}},{RangeNode:{}},{"OperatorNode:add":{op:"+",associativity:"left",associativeWith:["OperatorNode:add","OperatorNode:subtract"]},"OperatorNode:subtract":{op:"-",associativity:"left",associativeWith:[]}},{"OperatorNode:multiply":{op:"*",associativity:"left",associativeWith:["OperatorNode:multiply","OperatorNode:divide","Operator:dotMultiply","Operator:dotDivide"]},"OperatorNode:divide":{op:"/",associativity:"left",associativeWith:[],latexLeftParens:!1,latexRightParens:!1,latexParens:!1},"OperatorNode:dotMultiply":{op:".*",associativity:"left",associativeWith:["OperatorNode:multiply","OperatorNode:divide","OperatorNode:dotMultiply","OperatorNode:doDivide"]},"OperatorNode:dotDivide":{op:"./",associativity:"left",associativeWith:[]},"OperatorNode:mod":{op:"mod",associativity:"left",associativeWith:[]}},{"OperatorNode:multiply":{associativity:"left",associativeWith:["OperatorNode:multiply","OperatorNode:divide","Operator:dotMultiply","Operator:dotDivide"]}},{"OperatorNode:unaryPlus":{op:"+",associativity:"right"},"OperatorNode:unaryMinus":{op:"-",associativity:"right"},"OperatorNode:bitNot":{op:"~",associativity:"right"},"OperatorNode:not":{op:"not",associativity:"right"}},{"OperatorNode:pow":{op:"^",associativity:"right",associativeWith:[],latexRightParens:!1},"OperatorNode:dotPow":{op:".^",associativity:"right",associativeWith:[]}},{"OperatorNode:factorial":{op:"!",associativity:"left"}},{"OperatorNode:ctranspose":{op:"'",associativity:"left"}}];function Mv(e,r){if(!r||r!=="auto")return e;for(var t=e;en(t);)t=t.content;return t}function Qr(e,r,t,n){var a=e;r!=="keep"&&(a=e.getContent());for(var i=a.getIdentifier(),u=null,l=0;l{var{subset:r,matrix:t,Node:n}=e,a=wv({subset:r}),i=eT({subset:r,matrix:t});function u(c,o,s){o||(o="keep");var m=Qr(c,o,s),d=Qr(c.value,o,s);return o==="all"||d!==null&&d<=m}class l extends n{constructor(o,s,m){if(super(),this.object=o,this.index=m?s:null,this.value=m||s,!at(o)&&!qn(o))throw new TypeError('SymbolNode or AccessorNode expected as "object"');if(at(o)&&o.name==="end")throw new Error('Cannot assign to symbol "end"');if(this.index&&!Qn(this.index))throw new TypeError('IndexNode expected as "index"');if(!Nr(this.value))throw new TypeError('Node expected as "value"')}get name(){return this.index?this.index.isObjectProperty()?this.index.getObjectProperty():"":this.object.name||""}get type(){return Ev}get isAssignmentNode(){return!0}_compile(o,s){var m=this.object._compile(o,s),d=this.index?this.index._compile(o,s):null,h=this.value._compile(o,s),x=this.object.name;if(this.index)if(this.index.isObjectProperty()){var v=this.index.getObjectProperty();return function(M,A,S){var O=m(M,A,S),_=h(M,A,S);return Ei(O,v,_),_}}else{if(at(this.object))return function(M,A,S){var O=m(M,A,S),_=h(M,A,S),E=d(M,A,O);return M.set(x,i(O,E,_)),_};var y=this.object.object._compile(o,s);if(this.object.index.isObjectProperty()){var w=this.object.index.getObjectProperty();return function(M,A,S){var O=y(M,A,S),_=wt(O,w),E=d(M,A,_),T=h(M,A,S);return Ei(O,w,i(_,E,T)),T}}else{var C=this.object.index._compile(o,s);return function(M,A,S){var O=y(M,A,S),_=C(M,A,O),E=a(O,_),T=d(M,A,E),R=h(M,A,S);return i(O,_,i(E,T,R)),R}}}else{if(!at(this.object))throw new TypeError("SymbolNode expected as object");return function(M,A,S){var O=h(M,A,S);return M.set(x,O),O}}}forEach(o){o(this.object,"object",this),this.index&&o(this.index,"index",this),o(this.value,"value",this)}map(o){var s=this._ifNode(o(this.object,"object",this)),m=this.index?this._ifNode(o(this.index,"index",this)):null,d=this._ifNode(o(this.value,"value",this));return new l(s,m,d)}clone(){return new l(this.object,this.index,this.value)}_toString(o){var s=this.object.toString(o),m=this.index?this.index.toString(o):"",d=this.value.toString(o);return u(this,o&&o.parenthesis,o&&o.implicit)&&(d="("+d+")"),s+m+" = "+d}toJSON(){return{mathjs:Ev,object:this.object,index:this.index,value:this.value}}static fromJSON(o){return new l(o.object,o.index,o.value)}_toHTML(o){var s=this.object.toHTML(o),m=this.index?this.index.toHTML(o):"",d=this.value.toHTML(o);return u(this,o&&o.parenthesis,o&&o.implicit)&&(d='('+d+')'),s+m+'='+d}_toTex(o){var s=this.object.toTex(o),m=this.index?this.index.toTex(o):"",d=this.value.toTex(o);return u(this,o&&o.parenthesis,o&&o.implicit)&&(d="\\\\left(".concat(d,"\\\\right)")),s+m+"="+d}}return Hr(l,"name",Ev),l},{isClass:!0,isNode:!0});var Fv="BlockNode",_$=["ResultSet","Node"],_v=F(Fv,_$,e=>{var{ResultSet:r,Node:t}=e;class n extends t{constructor(i){if(super(),!Array.isArray(i))throw new Error("Array expected");this.blocks=i.map(function(u){var l=u&&u.node,c=u&&u.visible!==void 0?u.visible:!0;if(!Nr(l))throw new TypeError('Property "node" must be a Node');if(typeof c!="boolean")throw new TypeError('Property "visible" must be a boolean');return{node:l,visible:c}})}get type(){return Fv}get isBlockNode(){return!0}_compile(i,u){var l=Xn(this.blocks,function(c){return{evaluate:c.node._compile(i,u),visible:c.visible}});return function(o,s,m){var d=[];return Fo(l,function(x){var v=x.evaluate(o,s,m);x.visible&&d.push(v)}),new r(d)}}forEach(i){for(var u=0;u;')}).join('
')}_toTex(i){return this.blocks.map(function(u){return u.node.toTex(i)+(u.visible?"":";")}).join(\`\\\\;\\\\; -\`)}}return Hr(n,"name",Fv),n},{isClass:!0,isNode:!0});var Ov="ConditionalNode",O$=["Node"],Bv=F(Ov,O$,e=>{var{Node:r}=e;function t(a){if(typeof a=="number"||typeof a=="boolean"||typeof a=="string")return!!a;if(a){if(rr(a))return!a.isZero();if(Kt(a))return!!(a.re||a.im);if(Ht(a))return!!a.value}if(a==null)return!1;throw new TypeError('Unsupported type of condition "'+Fr(a)+'"')}class n extends r{constructor(i,u,l){if(super(),!Nr(i))throw new TypeError("Parameter condition must be a Node");if(!Nr(u))throw new TypeError("Parameter trueExpr must be a Node");if(!Nr(l))throw new TypeError("Parameter falseExpr must be a Node");this.condition=i,this.trueExpr=u,this.falseExpr=l}get type(){return Ov}get isConditionalNode(){return!0}_compile(i,u){var l=this.condition._compile(i,u),c=this.trueExpr._compile(i,u),o=this.falseExpr._compile(i,u);return function(m,d,h){return t(l(m,d,h))?c(m,d,h):o(m,d,h)}}forEach(i){i(this.condition,"condition",this),i(this.trueExpr,"trueExpr",this),i(this.falseExpr,"falseExpr",this)}map(i){return new n(this._ifNode(i(this.condition,"condition",this)),this._ifNode(i(this.trueExpr,"trueExpr",this)),this._ifNode(i(this.falseExpr,"falseExpr",this)))}clone(){return new n(this.condition,this.trueExpr,this.falseExpr)}_toString(i){var u=i&&i.parenthesis?i.parenthesis:"keep",l=Qr(this,u,i&&i.implicit),c=this.condition.toString(i),o=Qr(this.condition,u,i&&i.implicit);(u==="all"||this.condition.type==="OperatorNode"||o!==null&&o<=l)&&(c="("+c+")");var s=this.trueExpr.toString(i),m=Qr(this.trueExpr,u,i&&i.implicit);(u==="all"||this.trueExpr.type==="OperatorNode"||m!==null&&m<=l)&&(s="("+s+")");var d=this.falseExpr.toString(i),h=Qr(this.falseExpr,u,i&&i.implicit);return(u==="all"||this.falseExpr.type==="OperatorNode"||h!==null&&h<=l)&&(d="("+d+")"),c+" ? "+s+" : "+d}toJSON(){return{mathjs:Ov,condition:this.condition,trueExpr:this.trueExpr,falseExpr:this.falseExpr}}static fromJSON(i){return new n(i.condition,i.trueExpr,i.falseExpr)}_toHTML(i){var u=i&&i.parenthesis?i.parenthesis:"keep",l=Qr(this,u,i&&i.implicit),c=this.condition.toHTML(i),o=Qr(this.condition,u,i&&i.implicit);(u==="all"||this.condition.type==="OperatorNode"||o!==null&&o<=l)&&(c='('+c+')');var s=this.trueExpr.toHTML(i),m=Qr(this.trueExpr,u,i&&i.implicit);(u==="all"||this.trueExpr.type==="OperatorNode"||m!==null&&m<=l)&&(s='('+s+')');var d=this.falseExpr.toHTML(i),h=Qr(this.falseExpr,u,i&&i.implicit);return(u==="all"||this.falseExpr.type==="OperatorNode"||h!==null&&h<=l)&&(d='('+d+')'),c+'?'+s+':'+d}_toTex(i){return"\\\\begin{cases} {"+this.trueExpr.toTex(i)+"}, &\\\\quad{\\\\text{if }\\\\;"+this.condition.toTex(i)+"}\\\\\\\\{"+this.falseExpr.toTex(i)+"}, &\\\\quad{\\\\text{otherwise}}\\\\end{cases}"}}return Hr(n,"name",Ov),n},{isClass:!0,isNode:!0});var iT=ca(nT(),1);var xD={Alpha:"A",alpha:"\\\\alpha",Beta:"B",beta:"\\\\beta",Gamma:"\\\\Gamma",gamma:"\\\\gamma",Delta:"\\\\Delta",delta:"\\\\delta",Epsilon:"E",epsilon:"\\\\epsilon",varepsilon:"\\\\varepsilon",Zeta:"Z",zeta:"\\\\zeta",Eta:"H",eta:"\\\\eta",Theta:"\\\\Theta",theta:"\\\\theta",vartheta:"\\\\vartheta",Iota:"I",iota:"\\\\iota",Kappa:"K",kappa:"\\\\kappa",varkappa:"\\\\varkappa",Lambda:"\\\\Lambda",lambda:"\\\\lambda",Mu:"M",mu:"\\\\mu",Nu:"N",nu:"\\\\nu",Xi:"\\\\Xi",xi:"\\\\xi",Omicron:"O",omicron:"o",Pi:"\\\\Pi",pi:"\\\\pi",varpi:"\\\\varpi",Rho:"P",rho:"\\\\rho",varrho:"\\\\varrho",Sigma:"\\\\Sigma",sigma:"\\\\sigma",varsigma:"\\\\varsigma",Tau:"T",tau:"\\\\tau",Upsilon:"\\\\Upsilon",upsilon:"\\\\upsilon",Phi:"\\\\Phi",phi:"\\\\phi",varphi:"\\\\varphi",Chi:"X",chi:"\\\\chi",Psi:"\\\\Psi",psi:"\\\\psi",Omega:"\\\\Omega",omega:"\\\\omega",true:"\\\\mathrm{True}",false:"\\\\mathrm{False}",i:"i",inf:"\\\\infty",Inf:"\\\\infty",infinity:"\\\\infty",Infinity:"\\\\infty",oo:"\\\\infty",lim:"\\\\lim",undefined:"\\\\mathbf{?}"},$r={transpose:"^\\\\top",ctranspose:"^H",factorial:"!",pow:"^",dotPow:".^\\\\wedge",unaryPlus:"+",unaryMinus:"-",bitNot:"\\\\~",not:"\\\\neg",multiply:"\\\\cdot",divide:"\\\\frac",dotMultiply:".\\\\cdot",dotDivide:".:",mod:"\\\\mod",add:"+",subtract:"-",to:"\\\\rightarrow",leftShift:"<<",rightArithShift:">>",rightLogShift:">>>",equal:"=",unequal:"\\\\neq",smaller:"<",larger:">",smallerEq:"\\\\leq",largerEq:"\\\\geq",bitAnd:"\\\\&",bitXor:"\\\\underline{|}",bitOr:"|",and:"\\\\wedge",xor:"\\\\veebar",or:"\\\\vee"},yD={abs:{1:"\\\\left|\${args[0]}\\\\right|"},add:{2:"\\\\left(\${args[0]}".concat($r.add,"\${args[1]}\\\\right)")},cbrt:{1:"\\\\sqrt[3]{\${args[0]}}"},ceil:{1:"\\\\left\\\\lceil\${args[0]}\\\\right\\\\rceil"},cube:{1:"\\\\left(\${args[0]}\\\\right)^3"},divide:{2:"\\\\frac{\${args[0]}}{\${args[1]}}"},dotDivide:{2:"\\\\left(\${args[0]}".concat($r.dotDivide,"\${args[1]}\\\\right)")},dotMultiply:{2:"\\\\left(\${args[0]}".concat($r.dotMultiply,"\${args[1]}\\\\right)")},dotPow:{2:"\\\\left(\${args[0]}".concat($r.dotPow,"\${args[1]}\\\\right)")},exp:{1:"\\\\exp\\\\left(\${args[0]}\\\\right)"},expm1:"\\\\left(e".concat($r.pow,"{\${args[0]}}-1\\\\right)"),fix:{1:"\\\\mathrm{\${name}}\\\\left(\${args[0]}\\\\right)"},floor:{1:"\\\\left\\\\lfloor\${args[0]}\\\\right\\\\rfloor"},gcd:"\\\\gcd\\\\left(\${args}\\\\right)",hypot:"\\\\hypot\\\\left(\${args}\\\\right)",log:{1:"\\\\ln\\\\left(\${args[0]}\\\\right)",2:"\\\\log_{\${args[1]}}\\\\left(\${args[0]}\\\\right)"},log10:{1:"\\\\log_{10}\\\\left(\${args[0]}\\\\right)"},log1p:{1:"\\\\ln\\\\left(\${args[0]}+1\\\\right)",2:"\\\\log_{\${args[1]}}\\\\left(\${args[0]}+1\\\\right)"},log2:"\\\\log_{2}\\\\left(\${args[0]}\\\\right)",mod:{2:"\\\\left(\${args[0]}".concat($r.mod,"\${args[1]}\\\\right)")},multiply:{2:"\\\\left(\${args[0]}".concat($r.multiply,"\${args[1]}\\\\right)")},norm:{1:"\\\\left\\\\|\${args[0]}\\\\right\\\\|",2:void 0},nthRoot:{2:"\\\\sqrt[\${args[1]}]{\${args[0]}}"},nthRoots:{2:"\\\\{y : $y^{args[1]} = {\${args[0]}}\\\\}"},pow:{2:"\\\\left(\${args[0]}\\\\right)".concat($r.pow,"{\${args[1]}}")},round:{1:"\\\\left\\\\lfloor\${args[0]}\\\\right\\\\rceil",2:void 0},sign:{1:"\\\\mathrm{\${name}}\\\\left(\${args[0]}\\\\right)"},sqrt:{1:"\\\\sqrt{\${args[0]}}"},square:{1:"\\\\left(\${args[0]}\\\\right)^2"},subtract:{2:"\\\\left(\${args[0]}".concat($r.subtract,"\${args[1]}\\\\right)")},unaryMinus:{1:"".concat($r.unaryMinus,"\\\\left(\${args[0]}\\\\right)")},unaryPlus:{1:"".concat($r.unaryPlus,"\\\\left(\${args[0]}\\\\right)")},bitAnd:{2:"\\\\left(\${args[0]}".concat($r.bitAnd,"\${args[1]}\\\\right)")},bitNot:{1:$r.bitNot+"\\\\left(\${args[0]}\\\\right)"},bitOr:{2:"\\\\left(\${args[0]}".concat($r.bitOr,"\${args[1]}\\\\right)")},bitXor:{2:"\\\\left(\${args[0]}".concat($r.bitXor,"\${args[1]}\\\\right)")},leftShift:{2:"\\\\left(\${args[0]}".concat($r.leftShift,"\${args[1]}\\\\right)")},rightArithShift:{2:"\\\\left(\${args[0]}".concat($r.rightArithShift,"\${args[1]}\\\\right)")},rightLogShift:{2:"\\\\left(\${args[0]}".concat($r.rightLogShift,"\${args[1]}\\\\right)")},bellNumbers:{1:"\\\\mathrm{B}_{\${args[0]}}"},catalan:{1:"\\\\mathrm{C}_{\${args[0]}}"},stirlingS2:{2:"\\\\mathrm{S}\\\\left(\${args}\\\\right)"},arg:{1:"\\\\arg\\\\left(\${args[0]}\\\\right)"},conj:{1:"\\\\left(\${args[0]}\\\\right)^*"},im:{1:"\\\\Im\\\\left\\\\lbrace\${args[0]}\\\\right\\\\rbrace"},re:{1:"\\\\Re\\\\left\\\\lbrace\${args[0]}\\\\right\\\\rbrace"},and:{2:"\\\\left(\${args[0]}".concat($r.and,"\${args[1]}\\\\right)")},not:{1:$r.not+"\\\\left(\${args[0]}\\\\right)"},or:{2:"\\\\left(\${args[0]}".concat($r.or,"\${args[1]}\\\\right)")},xor:{2:"\\\\left(\${args[0]}".concat($r.xor,"\${args[1]}\\\\right)")},cross:{2:"\\\\left(\${args[0]}\\\\right)\\\\times\\\\left(\${args[1]}\\\\right)"},ctranspose:{1:"\\\\left(\${args[0]}\\\\right)".concat($r.ctranspose)},det:{1:"\\\\det\\\\left(\${args[0]}\\\\right)"},dot:{2:"\\\\left(\${args[0]}\\\\cdot\${args[1]}\\\\right)"},expm:{1:"\\\\exp\\\\left(\${args[0]}\\\\right)"},inv:{1:"\\\\left(\${args[0]}\\\\right)^{-1}"},pinv:{1:"\\\\left(\${args[0]}\\\\right)^{+}"},sqrtm:{1:"{\${args[0]}}".concat($r.pow,"{\\\\frac{1}{2}}")},trace:{1:"\\\\mathrm{tr}\\\\left(\${args[0]}\\\\right)"},transpose:{1:"\\\\left(\${args[0]}\\\\right)".concat($r.transpose)},combinations:{2:"\\\\binom{\${args[0]}}{\${args[1]}}"},combinationsWithRep:{2:"\\\\left(\\\\!\\\\!{\\\\binom{\${args[0]}}{\${args[1]}}}\\\\!\\\\!\\\\right)"},factorial:{1:"\\\\left(\${args[0]}\\\\right)".concat($r.factorial)},gamma:{1:"\\\\Gamma\\\\left(\${args[0]}\\\\right)"},lgamma:{1:"\\\\ln\\\\Gamma\\\\left(\${args[0]}\\\\right)"},equal:{2:"\\\\left(\${args[0]}".concat($r.equal,"\${args[1]}\\\\right)")},larger:{2:"\\\\left(\${args[0]}".concat($r.larger,"\${args[1]}\\\\right)")},largerEq:{2:"\\\\left(\${args[0]}".concat($r.largerEq,"\${args[1]}\\\\right)")},smaller:{2:"\\\\left(\${args[0]}".concat($r.smaller,"\${args[1]}\\\\right)")},smallerEq:{2:"\\\\left(\${args[0]}".concat($r.smallerEq,"\${args[1]}\\\\right)")},unequal:{2:"\\\\left(\${args[0]}".concat($r.unequal,"\${args[1]}\\\\right)")},erf:{1:"erf\\\\left(\${args[0]}\\\\right)"},max:"\\\\max\\\\left(\${args}\\\\right)",min:"\\\\min\\\\left(\${args}\\\\right)",variance:"\\\\mathrm{Var}\\\\left(\${args}\\\\right)",acos:{1:"\\\\cos^{-1}\\\\left(\${args[0]}\\\\right)"},acosh:{1:"\\\\cosh^{-1}\\\\left(\${args[0]}\\\\right)"},acot:{1:"\\\\cot^{-1}\\\\left(\${args[0]}\\\\right)"},acoth:{1:"\\\\coth^{-1}\\\\left(\${args[0]}\\\\right)"},acsc:{1:"\\\\csc^{-1}\\\\left(\${args[0]}\\\\right)"},acsch:{1:"\\\\mathrm{csch}^{-1}\\\\left(\${args[0]}\\\\right)"},asec:{1:"\\\\sec^{-1}\\\\left(\${args[0]}\\\\right)"},asech:{1:"\\\\mathrm{sech}^{-1}\\\\left(\${args[0]}\\\\right)"},asin:{1:"\\\\sin^{-1}\\\\left(\${args[0]}\\\\right)"},asinh:{1:"\\\\sinh^{-1}\\\\left(\${args[0]}\\\\right)"},atan:{1:"\\\\tan^{-1}\\\\left(\${args[0]}\\\\right)"},atan2:{2:"\\\\mathrm{atan2}\\\\left(\${args}\\\\right)"},atanh:{1:"\\\\tanh^{-1}\\\\left(\${args[0]}\\\\right)"},cos:{1:"\\\\cos\\\\left(\${args[0]}\\\\right)"},cosh:{1:"\\\\cosh\\\\left(\${args[0]}\\\\right)"},cot:{1:"\\\\cot\\\\left(\${args[0]}\\\\right)"},coth:{1:"\\\\coth\\\\left(\${args[0]}\\\\right)"},csc:{1:"\\\\csc\\\\left(\${args[0]}\\\\right)"},csch:{1:"\\\\mathrm{csch}\\\\left(\${args[0]}\\\\right)"},sec:{1:"\\\\sec\\\\left(\${args[0]}\\\\right)"},sech:{1:"\\\\mathrm{sech}\\\\left(\${args[0]}\\\\right)"},sin:{1:"\\\\sin\\\\left(\${args[0]}\\\\right)"},sinh:{1:"\\\\sinh\\\\left(\${args[0]}\\\\right)"},tan:{1:"\\\\tan\\\\left(\${args[0]}\\\\right)"},tanh:{1:"\\\\tanh\\\\left(\${args[0]}\\\\right)"},to:{2:"\\\\left(\${args[0]}".concat($r.to,"\${args[1]}\\\\right)")},numeric:function(r,t){return r.args[0].toTex()},number:{0:"0",1:"\\\\left(\${args[0]}\\\\right)",2:"\\\\left(\\\\left(\${args[0]}\\\\right)\${args[1]}\\\\right)"},string:{0:'\\\\mathtt{""}',1:"\\\\mathrm{string}\\\\left(\${args[0]}\\\\right)"},bignumber:{0:"0",1:"\\\\left(\${args[0]}\\\\right)"},complex:{0:"0",1:"\\\\left(\${args[0]}\\\\right)",2:"\\\\left(\\\\left(\${args[0]}\\\\right)+".concat(xD.i,"\\\\cdot\\\\left(\${args[1]}\\\\right)\\\\right)")},matrix:{0:"\\\\begin{bmatrix}\\\\end{bmatrix}",1:"\\\\left(\${args[0]}\\\\right)",2:"\\\\left(\${args[0]}\\\\right)"},sparse:{0:"\\\\begin{bsparse}\\\\end{bsparse}",1:"\\\\left(\${args[0]}\\\\right)"},unit:{1:"\\\\left(\${args[0]}\\\\right)",2:"\\\\left(\\\\left(\${args[0]}\\\\right)\${args[1]}\\\\right)"}},oT="\\\\mathrm{\${name}}\\\\left(\${args}\\\\right)",aT={deg:"^\\\\circ"};function Pv(e){return(0,iT.default)(e,{preserveFormatting:!0})}function Iv(e,r){return r=typeof r>"u"?!1:r,r?Xe(aT,e)?aT[e]:"\\\\mathrm{"+Pv(e)+"}":Xe(xD,e)?xD[e]:Pv(e)}var Rv="ConstantNode",R$=["Node"],kv=F(Rv,R$,e=>{var{Node:r}=e;class t extends r{constructor(a){super(),this.value=a}get type(){return Rv}get isConstantNode(){return!0}_compile(a,i){var u=this.value;return function(){return u}}forEach(a){}map(a){return this.clone()}clone(){return new t(this.value)}_toString(a){return lr(this.value,a)}_toHTML(a){var i=this._toString(a);switch(Fr(this.value)){case"number":case"BigNumber":case"Fraction":return''+i+"";case"string":return''+i+"";case"boolean":return''+i+"";case"null":return''+i+"";case"undefined":return''+i+"";default:return''+i+""}}toJSON(){return{mathjs:Rv,value:this.value}}static fromJSON(a){return new t(a.value)}_toTex(a){var i=this._toString(a),u=Fr(this.value);switch(u){case"string":return"\\\\mathtt{"+Pv(i)+"}";case"number":case"BigNumber":{var l=u==="BigNumber"?this.value.isFinite():isFinite(this.value);if(!l)return this.value.valueOf()<0?"-\\\\infty":"\\\\infty";var c=i.toLowerCase().indexOf("e");return c!==-1?i.substring(0,c)+"\\\\cdot10^{"+i.substring(c+1)+"}":i}case"Fraction":return this.value.toLatex();default:return i}}}return Hr(t,"name",Rv),t},{isClass:!0,isNode:!0});var qv="FunctionAssignmentNode",k$=["typed","Node"],Lv=F(qv,k$,e=>{var{typed:r,Node:t}=e;function n(i,u,l){var c=Qr(i,u,l),o=Qr(i.expr,u,l);return u==="all"||o!==null&&o<=c}class a extends t{constructor(u,l,c){if(super(),typeof u!="string")throw new TypeError('String expected for parameter "name"');if(!Array.isArray(l))throw new TypeError('Array containing strings or objects expected for parameter "params"');if(!Nr(c))throw new TypeError('Node expected for parameter "expr"');if(yv.has(u))throw new Error('Illegal function name, "'+u+'" is a reserved keyword');var o=new Set;for(var s of l){var m=typeof s=="string"?s:s.name;if(o.has(m))throw new Error('Duplicate parameter name "'.concat(m,'"'));o.add(m)}this.name=u,this.params=l.map(function(d){return d&&d.name||d}),this.types=l.map(function(d){return d&&d.type||"any"}),this.expr=c}get type(){return qv}get isFunctionAssignmentNode(){return!0}_compile(u,l){var c=Object.create(l);Fo(this.params,function(x){c[x]=!0});var o=this.expr._compile(u,c),s=this.name,m=this.params,d=Xb(this.types,","),h=s+"("+Xb(this.params,", ")+")";return function(v,y,w){var C={};C[d]=function(){for(var M=Object.create(y),A=0;A'+rn(this.params[o])+"");var s=this.expr.toHTML(u);return n(this,l,u&&u.implicit)&&(s='('+s+')'),''+rn(this.name)+'('+c.join(',')+')='+s}_toTex(u){var l=u&&u.parenthesis?u.parenthesis:"keep",c=this.expr.toTex(u);return n(this,l,u&&u.implicit)&&(c="\\\\left(".concat(c,"\\\\right)")),"\\\\mathrm{"+this.name+"}\\\\left("+this.params.map(Iv).join(",")+"\\\\right)="+c}}return Hr(a,"name",qv),a},{isClass:!0,isNode:!0});var zv="IndexNode",q$=["Node","size"],Uv=F(zv,q$,e=>{var{Node:r,size:t}=e;class n extends r{constructor(i,u){if(super(),this.dimensions=i,this.dotNotation=u||!1,!Array.isArray(i)||!i.every(Nr))throw new TypeError('Array containing Nodes expected for parameter "dimensions"');if(this.dotNotation&&!this.isObjectProperty())throw new Error("dotNotation only applicable for object properties")}get type(){return zv}get isIndexNode(){return!0}_compile(i,u){var l=Xn(this.dimensions,function(o,s){var m=o.filter(x=>x.isSymbolNode&&x.name==="end").length>0;if(m){var d=Object.create(u);d.end=!0;var h=o._compile(i,d);return function(v,y,w){if(!Qe(w)&&!Mr(w)&&!St(w))throw new TypeError('Cannot resolve "end": context must be a Matrix, Array, or string but is '+Fr(w));var C=t(w).valueOf(),b=Object.create(y);return b.end=C[s],h(v,b,w)}}else return o._compile(i,u)}),c=wt(i,"index");return function(s,m,d){var h=Xn(l,function(x){return x(s,m,d)});return c(...h)}}forEach(i){for(var u=0;u.'+rn(this.getObjectProperty())+"":'['+u.join(',')+']'}_toTex(i){var u=this.dimensions.map(function(l){return l.toTex(i)});return this.dotNotation?"."+this.getObjectProperty():"_{"+u.join(",")+"}"}}return Hr(n,"name",zv),n},{isClass:!0,isNode:!0});var Wv="ObjectNode",L$=["Node"],Yv=F(Wv,L$,e=>{var{Node:r}=e;class t extends r{constructor(a){if(super(),this.properties=a||{},a&&(typeof a!="object"||!Object.keys(a).every(function(i){return Nr(a[i])})))throw new TypeError("Object containing Nodes expected")}get type(){return Wv}get isObjectNode(){return!0}_compile(a,i){var u={};for(var l in this.properties)if(Xe(this.properties,l)){var c=Ss(l),o=JSON.parse(c),s=wt(this.properties,l);u[o]=s._compile(a,i)}return function(d,h,x){var v={};for(var y in u)Xe(u,y)&&(v[y]=u[y](d,h,x));return v}}forEach(a){for(var i in this.properties)Xe(this.properties,i)&&a(this.properties[i],"properties["+Ss(i)+"]",this)}map(a){var i={};for(var u in this.properties)Xe(this.properties,u)&&(i[u]=this._ifNode(a(this.properties[u],"properties["+Ss(u)+"]",this)));return new t(i)}clone(){var a={};for(var i in this.properties)Xe(this.properties,i)&&(a[i]=this.properties[i]);return new t(a)}_toString(a){var i=[];for(var u in this.properties)Xe(this.properties,u)&&i.push(Ss(u)+": "+this.properties[u].toString(a));return"{"+i.join(", ")+"}"}toJSON(){return{mathjs:Wv,properties:this.properties}}static fromJSON(a){return new t(a.properties)}_toHTML(a){var i=[];for(var u in this.properties)Xe(this.properties,u)&&i.push(''+rn(u)+':'+this.properties[u].toHTML(a));return'{'+i.join(',')+'}'}_toTex(a){var i=[];for(var u in this.properties)Xe(this.properties,u)&&i.push("\\\\mathbf{"+u+":} & "+this.properties[u].toTex(a)+"\\\\\\\\");var l="\\\\left\\\\{\\\\begin{array}{ll}"+i.join(\` -\`)+"\\\\end{array}\\\\right\\\\}";return l}}return Hr(t,"name",Wv),t},{isClass:!0,isNode:!0});function _s(e,r){return new Eu(e,new Ms(r),new Set(Object.keys(r)))}var Hv="OperatorNode",z$=["Node"],$v=F(Hv,z$,e=>{var{Node:r}=e;function t(i,u){var l=i;if(u==="auto")for(;en(l);)l=l.content;return yr(l)?!0:ct(l)?t(l.args[0],u):!1}function n(i,u,l,c,o){var s=Qr(i,u,l),m=tf(i,u);if(u==="all"||c.length>2&&i.getIdentifier()!=="OperatorNode:add"&&i.getIdentifier()!=="OperatorNode:multiply")return c.map(function(T){switch(T.getContent().type){case"ArrayNode":case"ConstantNode":case"SymbolNode":case"ParenthesisNode":return!1;default:return!0}});var d;switch(c.length){case 0:d=[];break;case 1:{var h=Qr(c[0],u,l,i);if(o&&h!==null){var x,v;if(u==="keep"?(x=c[0].getIdentifier(),v=i.getIdentifier()):(x=c[0].getContent().getIdentifier(),v=i.getContent().getIdentifier()),ka[s][v].latexLeftParens===!1){d=[!1];break}if(ka[h][x].latexParens===!1){d=[!1];break}}if(h===null){d=[!1];break}if(h<=s){d=[!0];break}d=[!1]}break;case 2:{var y,w=Qr(c[0],u,l,i),C=Cv(i,c[0],u);w===null?y=!1:w===s&&m==="right"&&!C||w=2&&i.getIdentifier()==="OperatorNode:multiply"&&i.implicit&&u!=="all"&&l==="hide")for(var E=1;E2&&(this.getIdentifier()==="OperatorNode:add"||this.getIdentifier()==="OperatorNode:multiply")){var y=o.map(function(w,C){return w=w.toString(u),s[C]&&(w="("+w+")"),w});return this.implicit&&this.getIdentifier()==="OperatorNode:multiply"&&c==="hide"?y.join(" "):y.join(" "+this.op+" ")}else return this.fn+"("+this.args.join(", ")+")"}toJSON(){return{mathjs:Hv,op:this.op,fn:this.fn,args:this.args,implicit:this.implicit,isPercentage:this.isPercentage}}static fromJSON(u){return new a(u.op,u.fn,u.args,u.implicit,u.isPercentage)}_toHTML(u){var l=u&&u.parenthesis?u.parenthesis:"keep",c=u&&u.implicit?u.implicit:"hide",o=this.args,s=n(this,l,c,o,!1);if(o.length===1){var m=tf(this,l),d=o[0].toHTML(u);return s[0]&&(d='('+d+')'),m==="right"?''+rn(this.op)+""+d:d+''+rn(this.op)+""}else if(o.length===2){var h=o[0].toHTML(u),x=o[1].toHTML(u);return s[0]&&(h='('+h+')'),s[1]&&(x='('+x+')'),this.implicit&&this.getIdentifier()==="OperatorNode:multiply"&&c==="hide"?h+''+x:h+''+rn(this.op)+""+x}else{var v=o.map(function(y,w){return y=y.toHTML(u),s[w]&&(y='('+y+')'),y});return o.length>2&&(this.getIdentifier()==="OperatorNode:add"||this.getIdentifier()==="OperatorNode:multiply")?this.implicit&&this.getIdentifier()==="OperatorNode:multiply"&&c==="hide"?v.join(''):v.join(''+rn(this.op)+""):''+rn(this.fn)+'('+v.join(',')+')'}}_toTex(u){var l=u&&u.parenthesis?u.parenthesis:"keep",c=u&&u.implicit?u.implicit:"hide",o=this.args,s=n(this,l,c,o,!0),m=$r[this.fn];if(m=typeof m>"u"?this.op:m,o.length===1){var d=tf(this,l),h=o[0].toTex(u);return s[0]&&(h="\\\\left(".concat(h,"\\\\right)")),d==="right"?m+h:h+m}else if(o.length===2){var x=o[0],v=x.toTex(u);s[0]&&(v="\\\\left(".concat(v,"\\\\right)"));var y=o[1],w=y.toTex(u);s[1]&&(w="\\\\left(".concat(w,"\\\\right)"));var C;switch(l==="keep"?C=x.getIdentifier():C=x.getContent().getIdentifier(),this.getIdentifier()){case"OperatorNode:divide":return m+"{"+v+"}{"+w+"}";case"OperatorNode:pow":switch(v="{"+v+"}",w="{"+w+"}",C){case"ConditionalNode":case"OperatorNode:divide":v="\\\\left(".concat(v,"\\\\right)")}break;case"OperatorNode:multiply":if(this.implicit&&c==="hide")return v+"~"+w}return v+m+w}else if(o.length>2&&(this.getIdentifier()==="OperatorNode:add"||this.getIdentifier()==="OperatorNode:multiply")){var b=o.map(function(M,A){return M=M.toTex(u),s[A]&&(M="\\\\left(".concat(M,"\\\\right)")),M});return this.getIdentifier()==="OperatorNode:multiply"&&this.implicit&&c==="hide"?b.join("~"):b.join(m)}else return"\\\\mathrm{"+this.fn+"}\\\\left("+o.map(function(M){return M.toTex(u)}).join(",")+"\\\\right)"}getIdentifier(){return this.type+":"+this.fn}}return Hr(a,"name",Hv),a},{isClass:!0,isNode:!0});var Gv="ParenthesisNode",U$=["Node"],Vv=F(Gv,U$,e=>{var{Node:r}=e;class t extends r{constructor(a){if(super(),!Nr(a))throw new TypeError('Node expected for parameter "content"');this.content=a}get type(){return Gv}get isParenthesisNode(){return!0}_compile(a,i){return this.content._compile(a,i)}getContent(){return this.content.getContent()}forEach(a){a(this.content,"content",this)}map(a){var i=a(this.content,"content",this);return new t(i)}clone(){return new t(this.content)}_toString(a){return!a||a&&!a.parenthesis||a&&a.parenthesis==="keep"?"("+this.content.toString(a)+")":this.content.toString(a)}toJSON(){return{mathjs:Gv,content:this.content}}static fromJSON(a){return new t(a.content)}_toHTML(a){return!a||a&&!a.parenthesis||a&&a.parenthesis==="keep"?'('+this.content.toHTML(a)+')':this.content.toHTML(a)}_toTex(a){return!a||a&&!a.parenthesis||a&&a.parenthesis==="keep"?"\\\\left(".concat(this.content.toTex(a),"\\\\right)"):this.content.toTex(a)}}return Hr(t,"name",Gv),t},{isClass:!0,isNode:!0});var Zv="RangeNode",W$=["Node"],Qv=F(Zv,W$,e=>{var{Node:r}=e;function t(a,i,u){var l=Qr(a,i,u),c={},o=Qr(a.start,i,u);if(c.start=o!==null&&o<=l||i==="all",a.step){var s=Qr(a.step,i,u);c.step=s!==null&&s<=l||i==="all"}var m=Qr(a.end,i,u);return c.end=m!==null&&m<=l||i==="all",c}class n extends r{constructor(i,u,l){if(super(),!Nr(i))throw new TypeError("Node expected");if(!Nr(u))throw new TypeError("Node expected");if(l&&!Nr(l))throw new TypeError("Node expected");if(arguments.length>3)throw new Error("Too many arguments");this.start=i,this.end=u,this.step=l||null}get type(){return Zv}get isRangeNode(){return!0}needsEnd(){var i=this.filter(function(u){return at(u)&&u.name==="end"});return i.length>0}_compile(i,u){var l=i.range,c=this.start._compile(i,u),o=this.end._compile(i,u);if(this.step){var s=this.step._compile(i,u);return function(d,h,x){return l(c(d,h,x),o(d,h,x),s(d,h,x))}}else return function(d,h,x){return l(c(d,h,x),o(d,h,x))}}forEach(i){i(this.start,"start",this),i(this.end,"end",this),this.step&&i(this.step,"step",this)}map(i){return new n(this._ifNode(i(this.start,"start",this)),this._ifNode(i(this.end,"end",this)),this.step&&this._ifNode(i(this.step,"step",this)))}clone(){return new n(this.start,this.end,this.step&&this.step)}_toString(i){var u=i&&i.parenthesis?i.parenthesis:"keep",l=t(this,u,i&&i.implicit),c,o=this.start.toString(i);if(l.start&&(o="("+o+")"),c=o,this.step){var s=this.step.toString(i);l.step&&(s="("+s+")"),c+=":"+s}var m=this.end.toString(i);return l.end&&(m="("+m+")"),c+=":"+m,c}toJSON(){return{mathjs:Zv,start:this.start,end:this.end,step:this.step}}static fromJSON(i){return new n(i.start,i.end,i.step)}_toHTML(i){var u=i&&i.parenthesis?i.parenthesis:"keep",l=t(this,u,i&&i.implicit),c,o=this.start.toHTML(i);if(l.start&&(o='('+o+')'),c=o,this.step){var s=this.step.toHTML(i);l.step&&(s='('+s+')'),c+=':'+s}var m=this.end.toHTML(i);return l.end&&(m='('+m+')'),c+=':'+m,c}_toTex(i){var u=i&&i.parenthesis?i.parenthesis:"keep",l=t(this,u,i&&i.implicit),c=this.start.toTex(i);if(l.start&&(c="\\\\left(".concat(c,"\\\\right)")),this.step){var o=this.step.toTex(i);l.step&&(o="\\\\left(".concat(o,"\\\\right)")),c+=":"+o}var s=this.end.toTex(i);return l.end&&(s="\\\\left(".concat(s,"\\\\right)")),c+=":"+s,c}}return Hr(n,"name",Zv),n},{isClass:!0,isNode:!0});var Xv="RelationalNode",Y$=["Node"],Jv=F(Xv,Y$,e=>{var{Node:r}=e,t={equal:"==",unequal:"!=",smaller:"<",larger:">",smallerEq:"<=",largerEq:">="};class n extends r{constructor(i,u){if(super(),!Array.isArray(i))throw new TypeError("Parameter conditionals must be an array");if(!Array.isArray(u))throw new TypeError("Parameter params must be an array");if(i.length!==u.length-1)throw new TypeError("Parameter params must contain exactly one more element than parameter conditionals");this.conditionals=i,this.params=u}get type(){return Xv}get isRelationalNode(){return!0}_compile(i,u){var l=this,c=this.params.map(o=>o._compile(i,u));return function(s,m,d){for(var h,x=c[0](s,m,d),v=0;vi(u,"params["+l+"]",this),this)}map(i){return new n(this.conditionals.slice(),this.params.map((u,l)=>this._ifNode(i(u,"params["+l+"]",this)),this))}clone(){return new n(this.conditionals,this.params)}_toString(i){for(var u=i&&i.parenthesis?i.parenthesis:"keep",l=Qr(this,u,i&&i.implicit),c=this.params.map(function(m,d){var h=Qr(m,u,i&&i.implicit);return u==="all"||h!==null&&h<=l?"("+m.toString(i)+")":m.toString(i)}),o=c[0],s=0;s('+m.toHTML(i)+')':m.toHTML(i)}),o=c[0],s=0;s'+rn(t[this.conditionals[s]])+""+c[s+1];return o}_toTex(i){for(var u=i&&i.parenthesis?i.parenthesis:"keep",l=Qr(this,u,i&&i.implicit),c=this.params.map(function(m,d){var h=Qr(m,u,i&&i.implicit);return u==="all"||h!==null&&h<=l?"\\\\left("+m.toTex(i)+"\\right)":m.toTex(i)}),o=c[0],s=0;s{var{math:r,Unit:t,Node:n}=e;function a(u){return t?t.isValuelessUnit(u):!1}class i extends n{constructor(l){if(super(),typeof l!="string")throw new TypeError('String expected for parameter "name"');this.name=l}get type(){return"SymbolNode"}get isSymbolNode(){return!0}_compile(l,c){var o=this.name;if(c[o]===!0)return function(m,d,h){return wt(d,o)};if(o in l)return function(m,d,h){return m.has(o)?m.get(o):wt(l,o)};var s=a(o);return function(m,d,h){return m.has(o)?m.get(o):s?new t(null,o):i.onUndefinedSymbol(o)}}forEach(l){}map(l){return this.clone()}static onUndefinedSymbol(l){throw new Error("Undefined symbol "+l)}clone(){return new i(this.name)}_toString(l){return this.name}_toHTML(l){var c=rn(this.name);return c==="true"||c==="false"?''+c+"":c==="i"?''+c+"":c==="Infinity"?''+c+"":c==="NaN"?''+c+"":c==="null"?''+c+"":c==="undefined"?''+c+"":''+c+""}toJSON(){return{mathjs:"SymbolNode",name:this.name}}static fromJSON(l){return new i(l.name)}_toTex(l){var c=!1;typeof r[this.name]>"u"&&a(this.name)&&(c=!0);var o=Iv(this.name,c);return o[0]==="\\\\"?o:" "+o}}return i},{isClass:!0,isNode:!0});var jv="FunctionNode",G$=["math","Node","SymbolNode"],eg=F(jv,G$,e=>{var r,{math:t,Node:n,SymbolNode:a}=e,i=c=>lr(c,{truncate:78});function u(c,o,s){for(var m="",d=/\\$(?:\\{([a-z_][a-z_0-9]*)(?:\\[([0-9]+)\\])?\\}|\\$)/gi,h=0,x;(x=d.exec(c))!==null;)if(m+=c.substring(h,x.index),h=x.index,x[0]==="$$")m+="$",h++;else{h+=x[0].length;var v=o[x[1]];if(!v)throw new ReferenceError("Template: Property "+x[1]+" does not exist.");if(x[2]===void 0)switch(typeof v){case"string":m+=v;break;case"object":if(Nr(v))m+=v.toTex(s);else if(Array.isArray(v))m+=v.map(function(y,w){if(Nr(y))return y.toTex(s);throw new TypeError("Template: "+x[1]+"["+w+"] is not a Node.")}).join(",");else throw new TypeError("Template: "+x[1]+" has to be a Node, String or array of Nodes");break;default:throw new TypeError("Template: "+x[1]+" has to be a Node, String or array of Nodes")}else if(Nr(v[x[2]]&&v[x[2]]))m+=v[x[2]].toTex(s);else throw new TypeError("Template: "+x[1]+"["+x[2]+"] is not a Node.")}return m+=c.slice(h),m}class l extends n{constructor(o,s){if(super(),typeof o=="string"&&(o=new a(o)),!Nr(o))throw new TypeError('Node expected as parameter "fn"');if(!Array.isArray(s)||!s.every(Nr))throw new TypeError('Array containing Nodes expected for parameter "args"');this.fn=o,this.args=s||[]}get name(){return this.fn.name||""}get type(){return jv}get isFunctionNode(){return!0}_compile(o,s){var m=this.args.map(_=>_._compile(o,s));if(at(this.fn)){var d=this.fn.name;if(s[d]){var w=this.args;return function(E,T,R){var q=wt(T,d);if(typeof q!="function")throw new TypeError("Argument '".concat(d,"' was not a function; received: ").concat(i(q)));if(q.rawArgs)return q(w,o,_s(E,T));var W=m.map(G=>G(E,T,R));return q.apply(q,W)}}else{var h=d in o?wt(o,d):void 0,x=typeof h=="function"&&h.rawArgs===!0,v=_=>{var E;if(_.has(d))E=_.get(d);else if(d in o)E=wt(o,d);else return l.onUndefinedFunction(d);if(typeof E=="function")return E;throw new TypeError("'".concat(d,\`' is not a function; its value is: - \`).concat(i(E)))};if(x){var y=this.args;return function(E,T,R){var q=v(E);return q(y,o,_s(E,T))}}else switch(m.length){case 0:return function(E,T,R){var q=v(E);return q()};case 1:return function(E,T,R){var q=v(E),W=m[0];return q(W(E,T,R))};case 2:return function(E,T,R){var q=v(E),W=m[0],G=m[1];return q(W(E,T,R),G(E,T,R))};default:return function(E,T,R){var q=v(E),W=m.map(G=>G(E,T,R));return q(...W)}}}}else if(qn(this.fn)&&Qn(this.fn.index)&&this.fn.index.isObjectProperty()){var C=this.fn.object._compile(o,s),b=this.fn.index.getObjectProperty(),M=this.args;return function(E,T,R){var q=C(E,T,R),W=gM(q,b);if(W!=null&&W.rawArgs)return W(M,o,_s(E,T));var G=m.map(H=>H(E,T,R));return W.apply(q,G)}}else{var A=this.fn.toString(),S=this.fn._compile(o,s),O=this.args;return function(E,T,R){var q=S(E,T,R);if(typeof q!="function")throw new TypeError("Expression '".concat(A,"' did not evaluate to a function; value is:")+\` - \`.concat(i(q)));if(q.rawArgs)return q(O,o,_s(E,T));var W=m.map(G=>G(E,T,R));return q.apply(q,W)}}}forEach(o){o(this.fn,"fn",this);for(var s=0;s'+rn(this.fn)+'('+s.join(',')+')'}toTex(o){var s;return o&&typeof o.handler=="object"&&Xe(o.handler,this.name)&&(s=o.handler[this.name](this,o)),typeof s<"u"?s:super.toTex(o)}_toTex(o){var s=this.args.map(function(h){return h.toTex(o)}),m;yD[this.name]&&(m=yD[this.name]),t[this.name]&&(typeof t[this.name].toTex=="function"||typeof t[this.name].toTex=="object"||typeof t[this.name].toTex=="string")&&(m=t[this.name].toTex);var d;switch(typeof m){case"function":d=m(this,o);break;case"string":d=u(m,this,o);break;case"object":switch(typeof m[s.length]){case"function":d=m[s.length](this,o);break;case"string":d=u(m[s.length],this,o);break}}return typeof d<"u"?d:u(oT,this,o)}getIdentifier(){return this.type+":"+this.name}}return r=l,Hr(l,"name",jv),Hr(l,"onUndefinedFunction",function(c){throw new Error("Undefined function "+c)}),Hr(l,"fromJSON",function(c){return new r(c.fn,c.args)}),l},{isClass:!0,isNode:!0});var sT="parse",V$=["typed","numeric","config","AccessorNode","ArrayNode","AssignmentNode","BlockNode","ConditionalNode","ConstantNode","FunctionAssignmentNode","FunctionNode","IndexNode","ObjectNode","OperatorNode","ParenthesisNode","RangeNode","RelationalNode","SymbolNode"],rg=F(sT,V$,e=>{var{typed:r,numeric:t,config:n,AccessorNode:a,ArrayNode:i,AssignmentNode:u,BlockNode:l,ConditionalNode:c,ConstantNode:o,FunctionAssignmentNode:s,FunctionNode:m,IndexNode:d,ObjectNode:h,OperatorNode:x,ParenthesisNode:v,RangeNode:y,RelationalNode:w,SymbolNode:C}=e,b=r(sT,{string:function(Q){return pe(Q,{})},"Array | Matrix":function(Q){return M(Q,{})},"string, Object":function(Q,ve){var Pe=ve.nodes!==void 0?ve.nodes:{};return pe(Q,Pe)},"Array | Matrix, Object":M});function M(B){var Q=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},ve=Q.nodes!==void 0?Q.nodes:{};return je(B,function(Pe){if(typeof Pe!="string")throw new TypeError("String expected");return pe(Pe,ve)})}var A={NULL:0,DELIMITER:1,NUMBER:2,SYMBOL:3,UNKNOWN:4},S={",":!0,"(":!0,")":!0,"[":!0,"]":!0,"{":!0,"}":!0,'"':!0,"'":!0,";":!0,"+":!0,"-":!0,"*":!0,".*":!0,"/":!0,"./":!0,"%":!0,"^":!0,".^":!0,"~":!0,"!":!0,"&":!0,"|":!0,"^|":!0,"=":!0,":":!0,"?":!0,"==":!0,"!=":!0,"<":!0,">":!0,"<=":!0,">=":!0,"<<":!0,">>":!0,">>>":!0},O={mod:!0,to:!0,in:!0,and:!0,xor:!0,or:!0,not:!0},_={true:!0,false:!1,null:null,undefined:void 0},E=["NaN","Infinity"],T={'"':'"',"'":"'","\\\\":"\\\\","/":"/",b:"\\b",f:"\\f",n:\` -\`,r:"\\r",t:" "};function R(){return{extraNodes:{},expression:"",comment:"",index:0,token:"",tokenType:A.NULL,nestingLevel:0,conditionalLevel:null}}function q(B,Q){return B.expression.substr(B.index,Q)}function W(B){return q(B,1)}function G(B){B.index++}function H(B){return B.expression.charAt(B.index-1)}function L(B){return B.expression.charAt(B.index+1)}function k(B){for(B.tokenType=A.NULL,B.token="",B.comment="";;){if(W(B)==="#")for(;W(B)!==\` -\`&&W(B)!=="";)B.comment+=W(B),G(B);if(b.isWhitespace(W(B),B.nestingLevel))G(B);else break}if(W(B)===""){B.tokenType=A.DELIMITER;return}if(W(B)===\` -\`&&!B.nestingLevel){B.tokenType=A.DELIMITER,B.token=W(B),G(B);return}var Q=W(B),ve=q(B,2),Pe=q(B,3);if(Pe.length===3&&S[Pe]){B.tokenType=A.DELIMITER,B.token=Pe,G(B),G(B),G(B);return}if(ve.length===2&&S[ve]){B.tokenType=A.DELIMITER,B.token=ve,G(B),G(B);return}if(S[Q]){B.tokenType=A.DELIMITER,B.token=Q,G(B);return}if(b.isDigitDot(Q)){B.tokenType=A.NUMBER;var tr=q(B,2);if(tr==="0b"||tr==="0o"||tr==="0x"){for(B.token+=W(B),G(B),B.token+=W(B),G(B);b.isHexDigit(W(B));)B.token+=W(B),G(B);if(W(B)===".")for(B.token+=".",G(B);b.isHexDigit(W(B));)B.token+=W(B),G(B);else if(W(B)==="i")for(B.token+="i",G(B);b.isDigit(W(B));)B.token+=W(B),G(B);return}if(W(B)==="."){if(B.token+=W(B),G(B),!b.isDigit(W(B))){B.tokenType=A.DELIMITER;return}}else{for(;b.isDigit(W(B));)B.token+=W(B),G(B);b.isDecimalMark(W(B),L(B))&&(B.token+=W(B),G(B))}for(;b.isDigit(W(B));)B.token+=W(B),G(B);if(W(B)==="E"||W(B)==="e"){if(b.isDigit(L(B))||L(B)==="-"||L(B)==="+"){if(B.token+=W(B),G(B),(W(B)==="+"||W(B)==="-")&&(B.token+=W(B),G(B)),!b.isDigit(W(B)))throw Re(B,'Digit expected, got "'+W(B)+'"');for(;b.isDigit(W(B));)B.token+=W(B),G(B);if(b.isDecimalMark(W(B),L(B)))throw Re(B,'Digit expected, got "'+W(B)+'"')}else if(L(B)===".")throw G(B),Re(B,'Digit expected, got "'+W(B)+'"')}return}if(b.isAlpha(W(B),H(B),L(B))){for(;b.isAlpha(W(B),H(B),L(B))||b.isDigit(W(B));)B.token+=W(B),G(B);Xe(O,B.token)?B.tokenType=A.DELIMITER:B.tokenType=A.SYMBOL;return}for(B.tokenType=A.UNKNOWN;W(B)!=="";)B.token+=W(B),G(B);throw Re(B,'Syntax error in part "'+B.token+'"')}function K(B){do k(B);while(B.token===\` -\`)}function z(B){B.nestingLevel++}function oe(B){B.nestingLevel--}b.isAlpha=function(Q,ve,Pe){return b.isValidLatinOrGreek(Q)||b.isValidMathSymbol(Q,Pe)||b.isValidMathSymbol(ve,Q)},b.isValidLatinOrGreek=function(Q){return/^[a-zA-Z_$\\u00C0-\\u02AF\\u0370-\\u03FF\\u2100-\\u214F]$/.test(Q)},b.isValidMathSymbol=function(Q,ve){return/^[\\uD835]$/.test(Q)&&/^[\\uDC00-\\uDFFF]$/.test(ve)&&/^[^\\uDC55\\uDC9D\\uDCA0\\uDCA1\\uDCA3\\uDCA4\\uDCA7\\uDCA8\\uDCAD\\uDCBA\\uDCBC\\uDCC4\\uDD06\\uDD0B\\uDD0C\\uDD15\\uDD1D\\uDD3A\\uDD3F\\uDD45\\uDD47-\\uDD49\\uDD51\\uDEA6\\uDEA7\\uDFCC\\uDFCD]$/.test(ve)},b.isWhitespace=function(Q,ve){return Q===" "||Q===" "||Q===\` -\`&&ve>0},b.isDecimalMark=function(Q,ve){return Q==="."&&ve!=="/"&&ve!=="*"&&ve!=="^"},b.isDigitDot=function(Q){return Q>="0"&&Q<="9"||Q==="."},b.isDigit=function(Q){return Q>="0"&&Q<="9"},b.isHexDigit=function(Q){return Q>="0"&&Q<="9"||Q>="a"&&Q<="f"||Q>="A"&&Q<="F"};function pe(B,Q){var ve=R();ht(ve,{expression:B,extraNodes:Q}),k(ve);var Pe=ae(ve);if(ve.token!=="")throw ve.tokenType===A.DELIMITER?Ye(ve,"Unexpected operator "+ve.token):Re(ve,'Unexpected part "'+ve.token+'"');return Pe}function ae(B){var Q,ve=[],Pe;for(B.token!==""&&B.token!==\` -\`&&B.token!==";"&&(Q=$(B),B.comment&&(Q.comment=B.comment));B.token===\` -\`||B.token===";";)ve.length===0&&Q&&(Pe=B.token!==";",ve.push({node:Q,visible:Pe})),k(B),B.token!==\` -\`&&B.token!==";"&&B.token!==""&&(Q=$(B),B.comment&&(Q.comment=B.comment),Pe=B.token!==";",ve.push({node:Q,visible:Pe}));return ve.length>0?new l(ve):(Q||(Q=new o(void 0),B.comment&&(Q.comment=B.comment)),Q)}function $(B){var Q,ve,Pe,tr,cr=le(B);if(B.token==="="){if(at(cr))return Q=cr.name,K(B),Pe=$(B),new u(new C(Q),Pe);if(qn(cr))return K(B),Pe=$(B),new u(cr.object,cr.index,Pe);if(gn(cr)&&at(cr.fn)&&(tr=!0,ve=[],Q=cr.name,cr.args.forEach(function(Xr,Pt){at(Xr)?ve[Pt]=Xr.name:tr=!1}),tr))return K(B),Pe=$(B),new s(Q,ve,Pe);throw Re(B,"Invalid left hand side of assignment operator =")}return cr}function le(B){for(var Q=Ee(B);B.token==="?";){var ve=B.conditionalLevel;B.conditionalLevel=B.nestingLevel,K(B);var Pe=Q,tr=$(B);if(B.token!==":")throw Re(B,"False part of conditional expression expected");B.conditionalLevel=null,K(B);var cr=$(B);Q=new c(Pe,tr,cr),B.conditionalLevel=ve}return Q}function Ee(B){for(var Q=me(B);B.token==="or";)K(B),Q=new x("or","or",[Q,me(B)]);return Q}function me(B){for(var Q=ge(B);B.token==="xor";)K(B),Q=new x("xor","xor",[Q,ge(B)]);return Q}function ge(B){for(var Q=Se(B);B.token==="and";)K(B),Q=new x("and","and",[Q,Se(B)]);return Q}function Se(B){for(var Q=xe(B);B.token==="|";)K(B),Q=new x("|","bitOr",[Q,xe(B)]);return Q}function xe(B){for(var Q=be(B);B.token==="^|";)K(B),Q=new x("^|","bitXor",[Q,be(B)]);return Q}function be(B){for(var Q=De(B);B.token==="&";)K(B),Q=new x("&","bitAnd",[Q,De(B)]);return Q}function De(B){for(var Q=[Ae(B)],ve=[],Pe={"==":"equal","!=":"unequal","<":"smaller",">":"larger","<=":"smallerEq",">=":"largerEq"};Xe(Pe,B.token);){var tr={name:B.token,fn:Pe[B.token]};ve.push(tr),K(B),Q.push(Ae(B))}return Q.length===1?Q[0]:Q.length===2?new x(ve[0].name,ve[0].fn,Q):new w(ve.map(cr=>cr.fn),Q)}function Ae(B){var Q,ve,Pe,tr;Q=We(B);for(var cr={"<<":"leftShift",">>":"rightArithShift",">>>":"rightLogShift"};Xe(cr,B.token);)ve=B.token,Pe=cr[ve],K(B),tr=[Q,We(B)],Q=new x(ve,Pe,tr);return Q}function We(B){var Q,ve,Pe,tr;Q=Je(B);for(var cr={to:"to",in:"to"};Xe(cr,B.token);)ve=B.token,Pe=cr[ve],K(B),ve==="in"&&B.token===""?Q=new x("*","multiply",[Q,new C("in")],!0):(tr=[Q,Je(B)],Q=new x(ve,Pe,tr));return Q}function Je(B){var Q,ve=[];if(B.token===":"?Q=new o(1):Q=J(B),B.token===":"&&B.conditionalLevel!==B.nestingLevel){for(ve.push(Q);B.token===":"&&ve.length<3;)K(B),B.token===")"||B.token==="]"||B.token===","||B.token===""?ve.push(new C("end")):ve.push(J(B));ve.length===3?Q=new y(ve[0],ve[2],ve[1]):Q=new y(ve[0],ve[1])}return Q}function J(B){var Q,ve,Pe,tr;Q=re(B);for(var cr={"+":"add","-":"subtract"};Xe(cr,B.token);){ve=B.token,Pe=cr[ve],K(B);var Xr=re(B);Xr.isPercentage?tr=[Q,new x("*","multiply",[Q,Xr])]:tr=[Q,Xr],Q=new x(ve,Pe,tr)}return Q}function re(B){var Q,ve,Pe,tr;Q=ye(B),ve=Q;for(var cr={"*":"multiply",".*":"dotMultiply","/":"divide","./":"dotDivide"};Xe(cr,B.token);)Pe=B.token,tr=cr[Pe],K(B),ve=ye(B),Q=new x(Pe,tr,[Q,ve]);return Q}function ye(B){var Q,ve;for(Q=j(B),ve=Q;B.tokenType===A.SYMBOL||B.token==="in"&&yr(Q)||B.tokenType===A.NUMBER&&!yr(ve)&&(!ct(ve)||ve.op==="!")||B.token==="(";)ve=j(B),Q=new x("*","multiply",[Q,ve],!0);return Q}function j(B){for(var Q=ne(B),ve=Q,Pe=[];B.token==="/"&&Nc(ve);)if(Pe.push(ht({},B)),K(B),B.tokenType===A.NUMBER)if(Pe.push(ht({},B)),K(B),B.tokenType===A.SYMBOL||B.token==="(")ht(B,Pe.pop()),Pe.pop(),ve=ne(B),Q=new x("/","divide",[Q,ve]);else{Pe.pop(),ht(B,Pe.pop());break}else{ht(B,Pe.pop());break}return Q}function ne(B){var Q,ve,Pe,tr;Q=ue(B);for(var cr={"%":"mod",mod:"mod"};Xe(cr,B.token);)ve=B.token,Pe=cr[ve],K(B),ve==="%"&&B.tokenType===A.DELIMITER&&B.token!=="("?Q=new x("/","divide",[Q,new o(100)],!1,!0):(tr=[Q,ue(B)],Q=new x(ve,Pe,tr));return Q}function ue(B){var Q,ve,Pe,tr={"-":"unaryMinus","+":"unaryPlus","~":"bitNot",not:"not"};return Xe(tr,B.token)?(Pe=tr[B.token],Q=B.token,K(B),ve=[ue(B)],new x(Q,Pe,ve)):Me(B)}function Me(B){var Q,ve,Pe,tr;return Q=Ce(B),(B.token==="^"||B.token===".^")&&(ve=B.token,Pe=ve==="^"?"pow":"dotPow",K(B),tr=[Q,ue(B)],Q=new x(ve,Pe,tr)),Q}function Ce(B){var Q,ve,Pe,tr;Q=Le(B);for(var cr={"!":"factorial","'":"ctranspose"};Xe(cr,B.token);)ve=B.token,Pe=cr[ve],k(B),tr=[Q],Q=new x(ve,Pe,tr),Q=fr(B,Q);return Q}function Le(B){var Q=[];if(B.tokenType===A.SYMBOL&&Xe(B.extraNodes,B.token)){var ve=B.extraNodes[B.token];if(k(B),B.token==="("){if(Q=[],z(B),k(B),B.token!==")")for(Q.push($(B));B.token===",";)k(B),Q.push($(B));if(B.token!==")")throw Re(B,"Parenthesis ) expected");oe(B),k(B)}return new ve(Q)}return Ie(B)}function Ie(B){var Q,ve;return B.tokenType===A.SYMBOL||B.tokenType===A.DELIMITER&&B.token in O?(ve=B.token,k(B),Xe(_,ve)?Q=new o(_[ve]):E.indexOf(ve)!==-1?Q=new o(t(ve,"number")):Q=new C(ve),Q=fr(B,Q),Q):or(B)}function fr(B,Q,ve){for(var Pe;(B.token==="("||B.token==="["||B.token===".")&&(!ve||ve.indexOf(B.token)!==-1);)if(Pe=[],B.token==="(")if(at(Q)||qn(Q)){if(z(B),k(B),B.token!==")")for(Pe.push($(B));B.token===",";)k(B),Pe.push($(B));if(B.token!==")")throw Re(B,"Parenthesis ) expected");oe(B),k(B),Q=new m(Q,Pe)}else return Q;else if(B.token==="["){if(z(B),k(B),B.token!=="]")for(Pe.push($(B));B.token===",";)k(B),Pe.push($(B));if(B.token!=="]")throw Re(B,"Parenthesis ] expected");oe(B),k(B),Q=new a(Q,new d(Pe))}else{k(B);var tr=B.tokenType===A.SYMBOL||B.tokenType===A.DELIMITER&&B.token in O;if(!tr)throw Re(B,"Property name expected after dot");Pe.push(new o(B.token)),k(B);var cr=!0;Q=new a(Q,new d(Pe,cr))}return Q}function or(B){var Q,ve;return B.token==='"'||B.token==="'"?(ve=Ke(B,B.token),Q=new o(ve),Q=fr(B,Q),Q):Pr(B)}function Ke(B,Q){for(var ve="";W(B)!==""&&W(B)!==Q;)if(W(B)==="\\\\"){G(B);var Pe=W(B),tr=T[Pe];if(tr!==void 0)ve+=tr,B.index+=1;else if(Pe==="u"){var cr=B.expression.slice(B.index+1,B.index+5);if(/^[0-9A-Fa-f]{4}$/.test(cr))ve+=String.fromCharCode(parseInt(cr,16)),B.index+=5;else throw Re(B,"Invalid unicode character \\\\u".concat(cr))}else throw Re(B,"Bad escape character \\\\".concat(Pe))}else ve+=W(B),G(B);if(k(B),B.token!==Q)throw Re(B,"End of string ".concat(Q," expected"));return k(B),ve}function Pr(B){var Q,ve,Pe,tr;if(B.token==="["){if(z(B),k(B),B.token!=="]"){var cr=ee(B);if(B.token===";"){for(Pe=1,ve=[cr];B.token===";";)k(B),B.token!=="]"&&(ve[Pe]=ee(B),Pe++);if(B.token!=="]")throw Re(B,"End of matrix ] expected");oe(B),k(B),tr=ve[0].items.length;for(var Xr=1;Xr{var{typed:r,parse:t}=e;return r(uT,{string:function(a){return t(a).compile()},"Array | Matrix":function(a){return je(a,function(i){return t(i).compile()})}})});var fT="evaluate",Q$=["typed","parse"],ng=F(fT,Q$,e=>{var{typed:r,parse:t}=e;return r(fT,{string:function(a){var i=Oo();return t(a).compile().evaluate(i)},"string, Map | Object":function(a,i){return t(a).compile().evaluate(i)},"Array | Matrix":function(a){var i=Oo();return je(a,function(u){return t(u).compile().evaluate(i)})},"Array | Matrix, Map | Object":function(a,i){return je(a,function(u){return t(u).compile().evaluate(i)})}})});var X$="Parser",J$=["evaluate"],ag=F(X$,J$,e=>{var{evaluate:r}=e;function t(){if(!(this instanceof t))throw new SyntaxError("Constructor must be called with the new operator");Object.defineProperty(this,"scope",{value:Oo(),writable:!1})}return t.prototype.type="Parser",t.prototype.isParser=!0,t.prototype.evaluate=function(n){return r(n,this.scope)},t.prototype.get=function(n){if(this.scope.has(n))return this.scope.get(n)},t.prototype.getAll=function(){return bM(this.scope)},t.prototype.getAllAsMap=function(){return this.scope},t.prototype.set=function(n,a){return this.scope.set(n,a),a},t.prototype.remove=function(n){this.scope.delete(n)},t.prototype.clear=function(){this.scope.clear()},t},{isClass:!0});var cT="parser",K$=["typed","Parser"],ig=F(cT,K$,e=>{var{typed:r,Parser:t}=e;return r(cT,{"":function(){return new t}})});var lT="lup",j$=["typed","matrix","abs","addScalar","divideScalar","multiplyScalar","subtractScalar","larger","equalScalar","unaryMinus","DenseMatrix","SparseMatrix","Spa"],og=F(lT,j$,e=>{var{typed:r,matrix:t,abs:n,addScalar:a,divideScalar:i,multiplyScalar:u,subtractScalar:l,larger:c,equalScalar:o,unaryMinus:s,DenseMatrix:m,SparseMatrix:d,Spa:h}=e;return r(lT,{DenseMatrix:function(w){return x(w)},SparseMatrix:function(w){return v(w)},Array:function(w){var C=t(w),b=x(C);return{L:b.L.valueOf(),U:b.U.valueOf(),p:b.p}}});function x(y){var w=y._size[0],C=y._size[1],b=Math.min(w,C),M=ar(y._data),A=[],S=[w,b],O=[],_=[b,C],E,T,R,q=[];for(E=0;E0)for(E=0;E0&&$.forEach(0,L-1,function(xe,be){d._forEachRow(xe,O,_,E,function(De,Ae){De>xe&&$.accumulate(De,s(u(Ae,be)))})});var me=L,ge=$.get(L),Se=n(ge);$.forEach(L+1,w-1,function(xe,be){var De=n(be);c(De,Se)&&(me=xe,Se=De,ge=be)}),L!==me&&(d._swapRows(L,me,T[1],O,_,E),d._swapRows(L,me,G[1],R,q,W),$.swap(L,me),oe(L,me)),$.forEach(0,w-1,function(xe,be){xe<=L?(R.push(be),q.push(xe)):(be=i(be,ge),o(be,0)||(O.push(be),_.push(xe)))})};for(L=0;L{var{typed:r,matrix:t,zeros:n,identity:a,isZero:i,equal:u,sign:l,sqrt:c,conj:o,unaryMinus:s,addScalar:m,divideScalar:d,multiplyScalar:h,subtractScalar:x,complex:v}=e;return ht(r(mT,{DenseMatrix:function(M){return w(M)},SparseMatrix:function(M){return C(M)},Array:function(M){var A=t(M),S=w(A);return{Q:S.Q.valueOf(),R:S.R.valueOf()}}}),{_denseQRimpl:y});function y(b){var M=b._size[0],A=b._size[1],S=a([M],"dense"),O=S._data,_=b.clone(),E=_._data,T,R,q,W=n([M],"");for(q=0;q0)for(var S=A[0][0].type==="Complex"?v(0):0,O=0;O=0;){var c=t[u+l],o=t[n+c];o===-1?(l--,i[r++]=c):(t[n+c]=t[a+o],++l,t[u+l]=o)}return r}function dT(e,r){if(!e)return null;var t=0,n,a=[],i=[],u=0,l=r,c=2*r;for(n=0;n=0;n--)e[n]!==-1&&(i[l+n]=i[u+e[n]],i[u+e[n]]=n);for(n=0;n{var{add:r,multiply:t,transpose:n}=e;return function(s,m){if(!m||s<=0||s>3)return null;var d=m._size,h=d[0],x=d[1],v=0,y=Math.max(16,10*Math.sqrt(x));y=Math.min(x-2,y);var w=a(s,m,h,x,y);vT(w,c,null);for(var C=w._index,b=w._ptr,M=b[x],A=[],S=[],O=0,_=x+1,E=2*(x+1),T=3*(x+1),R=4*(x+1),q=5*(x+1),W=6*(x+1),G=7*(x+1),H=A,L=i(x,b,S,O,T,H,E,G,_,W,R,q),k=u(x,b,S,q,R,W,y,_,T,H,E),K=0,z,oe,pe,ae,$,le,Ee,me,ge,Se,xe,be,De,Ae,We,Je;kJ?(le=pe,Ee=j,me=S[O+pe]-J):(le=C[j++],Ee=b[le],me=S[O+le]),$=1;$<=me;$++)z=C[Ee++],!((ge=S[_+z])<=0)&&(ye+=ge,S[_+z]=-ge,C[ue++]=z,S[E+z]!==-1&&(H[S[E+z]]=H[z]),H[z]!==-1?S[E+H[z]]=S[E+z]:S[T+S[q+z]]=S[E+z]);le!==pe&&(b[le]=ui(pe),S[W+le]=0)}for(J!==0&&(M=ue),S[q+pe]=ye,b[pe]=ne,S[O+pe]=ue-ne,S[R+pe]=-2,L=l(L,v,S,W,x),Se=ne;Se=L?S[W+le]-=ge:S[W+le]!==0&&(S[W+le]=S[q+le]+Me)}for(Se=ne;Se0?(Je+=Ce,C[Ae++]=le,We+=le):(b[le]=ui(pe),S[W+le]=0)}S[R+z]=Ae-be+1;var Le=Ae,Ie=be+S[O+z];for(j=De+1;j=0))for(We=H[z],z=S[G+We],S[G+We]=-1;z!==-1&&S[E+z]!==-1;z=S[E+z],L++){for(me=S[O+z],xe=S[R+z],j=b[z]+1;j<=b[z]+me-1;j++)S[W+C[j]]=L;var or=z;for(oe=S[E+z];oe!==-1;){var Ke=S[O+oe]===me&&S[R+oe]===xe;for(j=b[oe]+1;Ke&&j<=b[oe]+me-1;j++)S[W+C[j]]!==L&&(Ke=0);Ke?(b[oe]=ui(z),S[_+z]+=S[_+oe],S[_+oe]=0,S[R+oe]=-1,oe=S[E+oe],S[E+or]=oe):(or=oe,oe=S[E+oe])}}for(j=ne,Se=ne;Se=0;oe--)S[_+oe]>0||(S[E+oe]=S[T+b[oe]],S[T+b[oe]]=oe);for(le=x;le>=0;le--)S[_+le]<=0||b[le]!==-1&&(S[E+le]=S[T+b[le]],S[T+b[le]]=le);for(pe=0,z=0;z<=x;z++)b[z]===-1&&(pe=ug(z,pe,S,T,E,A,W));return A.splice(A.length-1,1),A};function a(o,s,m,d,h){var x=n(s);if(o===1&&d===m)return r(s,x);if(o===2){for(var v=x._index,y=x._ptr,w=0,C=0;Ch))for(var M=y[C+1];bv)m[y+A]=0,m[h+A]=-1,M++,s[A]=ui(o),m[y+o]++;else{var O=m[w+S];O!==-1&&(C[O]=A),m[b+A]=m[w+S],m[w+S]=A}}return M}function l(o,s,m,d,h){if(o<2||o+s<0){for(var x=0;x{var{transpose:r}=e;return function(t,n,a,i){if(!t||!n||!a)return null;var u=t._size,l=u[0],c=u[1],o,s,m,d,h,x,v,y=4*c+(i?c+l+1:0),w=[],C=0,b=c,M=2*c,A=3*c,S=4*c,O=5*c+1;for(m=0;m=1&&_[s]++,q.jleaf===2&&_[q.q]--}n[s]!==-1&&(w[C+s]=n[s])}for(s=0;s{var{add:r,multiply:t,transpose:n}=e,a=gT({add:r,multiply:t,transpose:n}),i=yT({transpose:n});return function(c,o,s){var m=o._ptr,d=o._size,h=d[1],x,v={};if(v.q=a(c,o),c&&!v.q)return null;if(s){var y=c?pT(o,null,v.q,0):o;v.parent=hT(y,1);var w=dT(v.parent,h);if(v.cp=i(y,v.parent,w,1),y&&v.parent&&v.cp&&u(y,v))for(v.unz=0,x=0;x=0;O--)for(E=o[O],T=o[O+1],_=E;_=0;S--)v[S]=-1,O=y[S],O!==-1&&(w[A+O]++===0&&(w[M+O]=S),w[C+S]=w[b+O],w[b+O]=S);for(c.lnz=0,c.m2=d,O=0;O=0;){e=n[d];var h=a?a[e]:e;Rc(u,e)||(fg(u,e),n[c+d]=h<0?0:bD(u[h]));var x=1;for(s=n[c+d],m=h<0?0:bD(u[h+1]);s{var{divideScalar:r,multiply:t,subtract:n}=e;return function(i,u,l,c,o,s,m){var d=i._values,h=i._index,x=i._ptr,v=i._size,y=v[1],w=u._values,C=u._index,b=u._ptr,M,A,S,O,_=DT(i,u,l,c,s);for(M=_;M{var{abs:r,divideScalar:t,multiply:n,subtract:a,larger:i,largerEq:u,SparseMatrix:l}=e,c=ST({divideScalar:t,multiply:n,subtract:a});return function(s,m,d){if(!s)return null;var h=s._size,x=h[1],v,y=100,w=100;m&&(v=m.q,y=m.lnz||y,w=m.unz||w);var C=[],b=[],M=[],A=new l({values:C,index:b,ptr:M,size:[x,x]}),S=[],O=[],_=[],E=new l({values:S,index:O,ptr:_,size:[x,x]}),T=[],R,q,W=[],G=[];for(R=0;R{var{typed:r,abs:t,add:n,multiply:a,transpose:i,divideScalar:u,subtract:l,larger:c,largerEq:o,SparseMatrix:s}=e,m=bT({add:n,multiply:a,transpose:i}),d=NT({abs:t,divideScalar:u,multiply:a,subtract:l,larger:c,largerEq:o,SparseMatrix:s});return r(AT,{"SparseMatrix, number, number":function(x,v,y){if(!Ze(v)||v<0||v>3)throw new Error("Symbolic Ordering and Analysis order must be an integer number in the interval [0, 3]");if(y<0||y>1)throw new Error("Partial pivoting threshold must be a number from 0 to 1");var w=m(v,x,!1),C=d(x,w,y);return{L:C.L,U:C.U,p:C.pinv,q:w.q,toString:function(){return"L: "+this.L.toString()+\` -U: \`+this.U.toString()+\` -p: \`+this.p.toString()+(this.q?\` -q: \`+this.q.toString():"")+\` -\`}}}})});function wD(e,r){var t,n=r.length,a=[];if(e)for(t=0;t{var{typed:r,matrix:t,lup:n,slu:a,usolve:i,lsolve:u,DenseMatrix:l}=e,c=_i({DenseMatrix:l});return r(MT,{"Array, Array | Matrix":function(d,h){d=t(d);var x=n(d),v=s(x.L,x.U,x.p,null,h);return v.valueOf()},"DenseMatrix, Array | Matrix":function(d,h){var x=n(d);return s(x.L,x.U,x.p,null,h)},"SparseMatrix, Array | Matrix":function(d,h){var x=n(d);return s(x.L,x.U,x.p,null,h)},"SparseMatrix, Array | Matrix, number, number":function(d,h,x,v){var y=a(d,x,v);return s(y.L,y.U,y.p,y.q,h)},"Object, Array | Matrix":function(d,h){return s(d.L,d.U,d.p,d.q,h)}});function o(m){if(Qe(m))return m;if(Mr(m))return t(m);throw new TypeError("Invalid Matrix LU decomposition")}function s(m,d,h,x,v){m=o(m),d=o(d),h&&(v=c(m,v,!0),v._data=wD(h,v._data));var y=u(m,v),w=i(d,y);return x&&(w._data=wD(x,w._data)),w}});var CT="polynomialRoot",pG=["typed","isZero","equalScalar","add","subtract","multiply","divide","sqrt","unaryMinus","cbrt","typeOf","im","re"],mg=F(CT,pG,e=>{var{typed:r,isZero:t,equalScalar:n,add:a,subtract:i,multiply:u,divide:l,sqrt:c,unaryMinus:o,cbrt:s,typeOf:m,im:d,re:h}=e;return r(CT,{"number|Complex, ...number|Complex":(x,v)=>{for(var y=[x,...v];y.length>0&&t(y[y.length-1]);)y.pop();if(y.length<2)throw new RangeError("Polynomial [".concat(x,", ").concat(v,"] must have a non-zero non-constant coefficient"));switch(y.length){case 2:return[o(l(y[0],y[1]))];case 3:{var[w,C,b]=y,M=u(2,b),A=u(C,C),S=u(4,b,w);if(n(A,S))return[l(o(C),M)];var O=c(i(A,S));return[l(i(O,C),M),l(i(o(O),C),M)]}case 4:{var[_,E,T,R]=y,q=o(u(3,R)),W=u(T,T),G=u(3,R,E),H=a(u(2,T,T,T),u(27,R,R,_)),L=u(9,R,T,E);if(n(W,G)&&n(H,L))return[l(T,q)];var k=i(W,G),K=i(H,L),z=a(u(18,R,T,E,_),u(T,T,E,E)),oe=a(u(4,T,T,T,_),u(4,R,E,E,E),u(27,R,R,_,_));if(n(z,oe))return[l(i(u(4,R,T,E),a(u(9,R,R,_),u(T,T,T))),u(R,k)),l(i(u(9,R,_),u(T,E)),u(2,k))];var pe;n(W,G)?pe=K:pe=l(a(K,c(i(u(K,K),u(4,k,k,k)))),2);var ae=!0,$=s(pe,ae).toArray().map(le=>l(a(T,le,l(k,le)),q));return $.map(le=>m(le)==="Complex"&&n(h(le),h(le)+d(le))?h(le):le)}default:throw new RangeError("only implemented for cubic or lower-order polynomials, not ".concat(y))}}})});var dG="Help",hG=["evaluate"],pg=F(dG,hG,e=>{var{evaluate:r}=e;function t(n){if(!(this instanceof t))throw new SyntaxError("Constructor must be called with the new operator");if(!n)throw new Error('Argument "doc" missing');this.doc=n}return t.prototype.type="Help",t.prototype.isHelp=!0,t.prototype.toString=function(){var n=this.doc||{},a=\` -\`;if(n.name&&(a+="Name: "+n.name+\` - -\`),n.category&&(a+="Category: "+n.category+\` - -\`),n.description&&(a+=\`Description: - \`+n.description+\` - -\`),n.syntax&&(a+=\`Syntax: - \`+n.syntax.join(\` - \`)+\` - -\`),n.examples){a+=\`Examples: -\`;for(var i=!1,u=r("config()"),l={config:m=>(i=!0,r("config(newConfig)",{newConfig:m}))},c=0;ci!=="mathjs").forEach(i=>{a[i]=n[i]}),new t(a)},t.prototype.valueOf=t.prototype.toString,t},{isClass:!0});var vG="Chain",gG=["?on","math","typed"],dg=F(vG,gG,e=>{var{on:r,math:t,typed:n}=e;function a(o){if(!(this instanceof a))throw new SyntaxError("Constructor must be called with the new operator");bu(o)?this.value=o.value:this.value=o}a.prototype.type="Chain",a.prototype.isChain=!0,a.prototype.done=function(){return this.value},a.prototype.valueOf=function(){return this.value},a.prototype.toString=function(){return lr(this.value)},a.prototype.toJSON=function(){return{mathjs:"Chain",value:this.value}},a.fromJSON=function(o){return new a(o.value)};function i(o,s){typeof s=="function"&&(a.prototype[o]=l(s))}function u(o,s){Du(a.prototype,o,function(){var d=s();if(typeof d=="function")return l(d)})}function l(o){return function(){if(arguments.length===0)return new a(o(this.value));for(var s=[this.value],m=0;mo[x])};for(var d in o)m(d)}};var c={expression:!0,docs:!0,type:!0,classes:!0,json:!0,error:!0,isChain:!0};return a.createProxy(t),r&&r("import",function(o,s,m){m||u(o,s)}),a},{isClass:!0});var DD={name:"e",category:"Constants",syntax:["e"],description:"Euler's number, the base of the natural logarithm. Approximately equal to 2.71828",examples:["e","e ^ 2","exp(2)","log(e)"],seealso:["exp"]};var ET={name:"false",category:"Constants",syntax:["false"],description:"Boolean value false",examples:["false"],seealso:["true"]};var TT={name:"i",category:"Constants",syntax:["i"],description:"Imaginary unit, defined as i*i=-1. A complex number is described as a + b*i, where a is the real part, and b is the imaginary part.",examples:["i","i * i","sqrt(-1)"],seealso:[]};var FT={name:"Infinity",category:"Constants",syntax:["Infinity"],description:"Infinity, a number which is larger than the maximum number that can be handled by a floating point number.",examples:["Infinity","1 / 0"],seealso:[]};var _T={name:"LN10",category:"Constants",syntax:["LN10"],description:"Returns the natural logarithm of 10, approximately equal to 2.302",examples:["LN10","log(10)"],seealso:[]};var OT={name:"LN2",category:"Constants",syntax:["LN2"],description:"Returns the natural logarithm of 2, approximately equal to 0.693",examples:["LN2","log(2)"],seealso:[]};var BT={name:"LOG10E",category:"Constants",syntax:["LOG10E"],description:"Returns the base-10 logarithm of E, approximately equal to 0.434",examples:["LOG10E","log(e, 10)"],seealso:[]};var PT={name:"LOG2E",category:"Constants",syntax:["LOG2E"],description:"Returns the base-2 logarithm of E, approximately equal to 1.442",examples:["LOG2E","log(e, 2)"],seealso:[]};var IT={name:"NaN",category:"Constants",syntax:["NaN"],description:"Not a number",examples:["NaN","0 / 0"],seealso:[]};var RT={name:"null",category:"Constants",syntax:["null"],description:"Value null",examples:["null"],seealso:["true","false"]};var kT={name:"phi",category:"Constants",syntax:["phi"],description:"Phi is the golden ratio. Two quantities are in the golden ratio if their ratio is the same as the ratio of their sum to the larger of the two quantities. Phi is defined as \`(1 + sqrt(5)) / 2\` and is approximately 1.618034...",examples:["phi"],seealso:[]};var SD={name:"pi",category:"Constants",syntax:["pi"],description:"The number pi is a mathematical constant that is the ratio of a circle's circumference to its diameter, and is approximately equal to 3.14159",examples:["pi","sin(pi/2)"],seealso:["tau"]};var qT={name:"SQRT1_2",category:"Constants",syntax:["SQRT1_2"],description:"Returns the square root of 1/2, approximately equal to 0.707",examples:["SQRT1_2","sqrt(1/2)"],seealso:[]};var LT={name:"SQRT2",category:"Constants",syntax:["SQRT2"],description:"Returns the square root of 2, approximately equal to 1.414",examples:["SQRT2","sqrt(2)"],seealso:[]};var zT={name:"tau",category:"Constants",syntax:["tau"],description:"Tau is the ratio constant of a circle's circumference to radius, equal to 2 * pi, approximately 6.2832.",examples:["tau","2 * pi"],seealso:["pi"]};var UT={name:"true",category:"Constants",syntax:["true"],description:"Boolean value true",examples:["true"],seealso:["false"]};var WT={name:"version",category:"Constants",syntax:["version"],description:"A string with the version number of math.js",examples:["version"],seealso:[]};var YT={name:"bignumber",category:"Construction",syntax:["bignumber(x)"],description:"Create a big number from a number or string.",examples:["0.1 + 0.2","bignumber(0.1) + bignumber(0.2)",'bignumber("7.2")','bignumber("7.2e500")',"bignumber([0.1, 0.2, 0.3])"],seealso:["boolean","complex","fraction","index","matrix","string","unit"]};var HT={name:"boolean",category:"Construction",syntax:["x","boolean(x)"],description:"Convert a string or number into a boolean.",examples:["boolean(0)","boolean(1)","boolean(3)",'boolean("true")','boolean("false")',"boolean([1, 0, 1, 1])"],seealso:["bignumber","complex","index","matrix","number","string","unit"]};var $T={name:"complex",category:"Construction",syntax:["complex()","complex(re, im)","complex(string)"],description:"Create a complex number.",examples:["complex()","complex(2, 3)",'complex("7 - 2i")'],seealso:["bignumber","boolean","index","matrix","number","string","unit"]};var GT={name:"createUnit",category:"Construction",syntax:["createUnit(definitions)","createUnit(name, definition)"],description:"Create a user-defined unit and register it with the Unit type.",examples:['createUnit("foo")','createUnit("knot", {definition: "0.514444444 m/s", aliases: ["knots", "kt", "kts"]})','createUnit("mph", "1 mile/hour")'],seealso:["unit","splitUnit"]};var VT={name:"fraction",category:"Construction",syntax:["fraction(num)","fraction(matrix)","fraction(num,den)","fraction({n: num, d: den})"],description:"Create a fraction from a number or from integer numerator and denominator.",examples:["fraction(0.125)","fraction(1, 3) + fraction(2, 5)","fraction({n: 333, d: 53})","fraction([sqrt(9), sqrt(10), sqrt(11)])"],seealso:["bignumber","boolean","complex","index","matrix","string","unit"]};var ZT={name:"index",category:"Construction",syntax:["[start]","[start:end]","[start:step:end]","[start1, start 2, ...]","[start1:end1, start2:end2, ...]","[start1:step1:end1, start2:step2:end2, ...]"],description:"Create an index to get or replace a subset of a matrix",examples:["A = [1, 2, 3; 4, 5, 6]","A[1, :]","A[1, 2] = 50","A[1:2, 1:2] = 1","B = [1, 2, 3]","B[B>1 and B<3]"],seealso:["bignumber","boolean","complex","matrix,","number","range","string","unit"]};var QT={name:"matrix",category:"Construction",syntax:["[]","[a1, b1, ...; a2, b2, ...]","matrix()",'matrix("dense")',"matrix([...])"],description:"Create a matrix.",examples:["[]","[1, 2, 3]","[1, 2, 3; 4, 5, 6]","matrix()","matrix([3, 4])",'matrix([3, 4; 5, 6], "sparse")','matrix([3, 4; 5, 6], "sparse", "number")'],seealso:["bignumber","boolean","complex","index","number","string","unit","sparse"]};var XT={name:"number",category:"Construction",syntax:["x","number(x)","number(unit, valuelessUnit)"],description:"Create a number or convert a string or boolean into a number.",examples:["2","2e3","4.05","number(2)",'number("7.2")',"number(true)","number([true, false, true, true])",'number(unit("52cm"), "m")'],seealso:["bignumber","boolean","complex","fraction","index","matrix","string","unit"]};var JT={name:"sparse",category:"Construction",syntax:["sparse()","sparse([a1, b1, ...; a1, b2, ...])",'sparse([a1, b1, ...; a1, b2, ...], "number")'],description:"Create a sparse matrix.",examples:["sparse()","sparse([3, 4; 5, 6])",'sparse([3, 0; 5, 0], "number")'],seealso:["bignumber","boolean","complex","index","number","string","unit","matrix"]};var KT={name:"splitUnit",category:"Construction",syntax:["splitUnit(unit: Unit, parts: Unit[])"],description:"Split a unit in an array of units whose sum is equal to the original unit.",examples:['splitUnit(1 m, ["feet", "inch"])'],seealso:["unit","createUnit"]};var jT={name:"string",category:"Construction",syntax:['"text"',"string(x)"],description:"Create a string or convert a value to a string",examples:['"Hello World!"',"string(4.2)","string(3 + 2i)"],seealso:["bignumber","boolean","complex","index","matrix","number","unit"]};var eF={name:"unit",category:"Construction",syntax:["value unit","unit(value, unit)","unit(string)"],description:"Create a unit.",examples:["5.5 mm","3 inch",'unit(7.1, "kilogram")','unit("23 deg")'],seealso:["bignumber","boolean","complex","index","matrix","number","string"]};var rF={name:"config",category:"Core",syntax:["config()","config(options)"],description:"Get configuration or change configuration.",examples:["config()","1/3 + 1/4",'config({number: "Fraction"})',"1/3 + 1/4"],seealso:[]};var tF={name:"import",category:"Core",syntax:["import(functions)","import(functions, options)"],description:"Import functions or constants from an object.",examples:["import({myFn: f(x)=x^2, myConstant: 32 })","myFn(2)","myConstant"],seealso:[]};var nF={name:"typed",category:"Core",syntax:["typed(signatures)","typed(name, signatures)"],description:"Create a typed function.",examples:['double = typed({ "number": f(x)=x+x, "string": f(x)=concat(x,x) })',"double(2)",'double("hello")'],seealso:[]};var aF={name:"derivative",category:"Algebra",syntax:["derivative(expr, variable)","derivative(expr, variable, {simplify: boolean})"],description:"Takes the derivative of an expression expressed in parser Nodes. The derivative will be taken over the supplied variable in the second parameter. If there are multiple variables in the expression, it will return a partial derivative.",examples:['derivative("2x^3", "x")','derivative("2x^3", "x", {simplify: false})','derivative("2x^2 + 3x + 4", "x")','derivative("sin(2x)", "x")','f = parse("x^2 + x")','x = parse("x")',"df = derivative(f, x)","df.evaluate({x: 3})"],seealso:["simplify","parse","evaluate"]};var iF={name:"leafCount",category:"Algebra",syntax:["leafCount(expr)"],description:"Computes the number of leaves in the parse tree of the given expression",examples:['leafCount("e^(i*pi)-1")','leafCount(parse("{a: 22/7, b: 10^(1/2)}"))'],seealso:["simplify"]};var oF={name:"lsolve",category:"Algebra",syntax:["x=lsolve(L, b)"],description:"Finds one solution of the linear system L * x = b where L is an [n x n] lower triangular matrix and b is a [n] column vector.",examples:["a = [-2, 3; 2, 1]","b = [11, 9]","x = lsolve(a, b)"],seealso:["lsolveAll","lup","lusolve","usolve","matrix","sparse"]};var sF={name:"lsolveAll",category:"Algebra",syntax:["x=lsolveAll(L, b)"],description:"Finds all solutions of the linear system L * x = b where L is an [n x n] lower triangular matrix and b is a [n] column vector.",examples:["a = [-2, 3; 2, 1]","b = [11, 9]","x = lsolve(a, b)"],seealso:["lsolve","lup","lusolve","usolve","matrix","sparse"]};var uF={name:"lup",category:"Algebra",syntax:["lup(m)"],description:"Calculate the Matrix LU decomposition with partial pivoting. Matrix A is decomposed in three matrices (L, U, P) where P * A = L * U",examples:["lup([[2, 1], [1, 4]])","lup(matrix([[2, 1], [1, 4]]))","lup(sparse([[2, 1], [1, 4]]))"],seealso:["lusolve","lsolve","usolve","matrix","sparse","slu","qr"]};var fF={name:"lusolve",category:"Algebra",syntax:["x=lusolve(A, b)","x=lusolve(lu, b)"],description:"Solves the linear system A * x = b where A is an [n x n] matrix and b is a [n] column vector.",examples:["a = [-2, 3; 2, 1]","b = [11, 9]","x = lusolve(a, b)"],seealso:["lup","slu","lsolve","usolve","matrix","sparse"]};var cF={name:"polynomialRoot",category:"Algebra",syntax:["x=polynomialRoot(-6, 3)","x=polynomialRoot(4, -4, 1)","x=polynomialRoot(-8, 12, -6, 1)"],description:"Finds the roots of a univariate polynomial given by its coefficients starting from constant, linear, and so on, increasing in degree.",examples:["a = polynomialRoot(-6, 11, -6, 1)"],seealso:["cbrt","sqrt"]};var lF={name:"qr",category:"Algebra",syntax:["qr(A)"],description:"Calculates the Matrix QR decomposition. Matrix \`A\` is decomposed in two matrices (\`Q\`, \`R\`) where \`Q\` is an orthogonal matrix and \`R\` is an upper triangular matrix.",examples:["qr([[1, -1, 4], [1, 4, -2], [1, 4, 2], [1, -1, 0]])"],seealso:["lup","slu","matrix"]};var mF={name:"rationalize",category:"Algebra",syntax:["rationalize(expr)","rationalize(expr, scope)","rationalize(expr, scope, detailed)"],description:"Transform a rationalizable expression in a rational fraction. If rational fraction is one variable polynomial then converts the numerator and denominator in canonical form, with decreasing exponents, returning the coefficients of numerator.",examples:['rationalize("2x/y - y/(x+1)")','rationalize("2x/y - y/(x+1)", true)'],seealso:["simplify"]};var pF={name:"resolve",category:"Algebra",syntax:["resolve(node, scope)"],description:"Recursively substitute variables in an expression tree.",examples:['resolve(parse("1 + x"), { x: 7 })','resolve(parse("size(text)"), { text: "Hello World" })','resolve(parse("x + y"), { x: parse("3z") })','resolve(parse("3x"), { x: parse("y+z"), z: parse("w^y") })'],seealso:["simplify","evaluate"],mayThrow:["ReferenceError"]};var dF={name:"simplify",category:"Algebra",syntax:["simplify(expr)","simplify(expr, rules)"],description:"Simplify an expression tree.",examples:['simplify("3 + 2 / 4")','simplify("2x + x")','f = parse("x * (x + 2 + x)")',"simplified = simplify(f)","simplified.evaluate({x: 2})"],seealso:["simplifyCore","derivative","evaluate","parse","rationalize","resolve"]};var hF={name:"simplifyConstant",category:"Algebra",syntax:["simplifyConstant(expr)","simplifyConstant(expr, options)"],description:"Replace constant subexpressions of node with their values.",examples:['simplifyConstant("(3-3)*x")','simplifyConstant(parse("z-cos(tau/8)"))'],seealso:["simplify","simplifyCore","evaluate"]};var vF={name:"simplifyCore",category:"Algebra",syntax:["simplifyCore(node)"],description:"Perform simple one-pass simplifications on an expression tree.",examples:['simplifyCore(parse("0*x"))','simplifyCore(parse("(x+0)*2"))'],seealso:["simplify","simplifyConstant","evaluate"]};var gF={name:"slu",category:"Algebra",syntax:["slu(A, order, threshold)"],description:"Calculate the Matrix LU decomposition with full pivoting. Matrix A is decomposed in two matrices (L, U) and two permutation vectors (pinv, q) where P * A * Q = L * U",examples:["slu(sparse([4.5, 0, 3.2, 0; 3.1, 2.9, 0, 0.9; 0, 1.7, 3, 0; 3.5, 0.4, 0, 1]), 1, 0.001)"],seealso:["lusolve","lsolve","usolve","matrix","sparse","lup","qr"]};var xF={name:"symbolicEqual",category:"Algebra",syntax:["symbolicEqual(expr1, expr2)","symbolicEqual(expr1, expr2, options)"],description:"Returns true if the difference of the expressions simplifies to 0",examples:['symbolicEqual("x*y","y*x")','symbolicEqual("abs(x^2)", "x^2")','symbolicEqual("abs(x)", "x", {context: {abs: {trivial: true}}})'],seealso:["simplify","evaluate"]};var yF={name:"usolve",category:"Algebra",syntax:["x=usolve(U, b)"],description:"Finds one solution of the linear system U * x = b where U is an [n x n] upper triangular matrix and b is a [n] column vector.",examples:["x=usolve(sparse([1, 1, 1, 1; 0, 1, 1, 1; 0, 0, 1, 1; 0, 0, 0, 1]), [1; 2; 3; 4])"],seealso:["usolveAll","lup","lusolve","lsolve","matrix","sparse"]};var bF={name:"usolveAll",category:"Algebra",syntax:["x=usolve(U, b)"],description:"Finds all solutions of the linear system U * x = b where U is an [n x n] upper triangular matrix and b is a [n] column vector.",examples:["x=usolve(sparse([1, 1, 1, 1; 0, 1, 1, 1; 0, 0, 1, 1; 0, 0, 0, 1]), [1; 2; 3; 4])"],seealso:["usolve","lup","lusolve","lsolve","matrix","sparse"]};var wF={name:"abs",category:"Arithmetic",syntax:["abs(x)"],description:"Compute the absolute value.",examples:["abs(3.5)","abs(-4.2)"],seealso:["sign"]};var DF={name:"add",category:"Operators",syntax:["x + y","add(x, y)"],description:"Add two values.",examples:["a = 2.1 + 3.6","a - 3.6","3 + 2i","3 cm + 2 inch",'"2.3" + "4"'],seealso:["subtract"]};var SF={name:"cbrt",category:"Arithmetic",syntax:["cbrt(x)","cbrt(x, allRoots)"],description:"Compute the cubic root value. If x = y * y * y, then y is the cubic root of x. When \`x\` is a number or complex number, an optional second argument \`allRoots\` can be provided to return all three cubic roots. If not provided, the principal root is returned",examples:["cbrt(64)","cube(4)","cbrt(-8)","cbrt(2 + 3i)","cbrt(8i)","cbrt(8i, true)","cbrt(27 m^3)"],seealso:["square","sqrt","cube","multiply"]};var NF={name:"ceil",category:"Arithmetic",syntax:["ceil(x)"],description:"Round a value towards plus infinity. If x is complex, both real and imaginary part are rounded towards plus infinity.",examples:["ceil(3.2)","ceil(3.8)","ceil(-4.2)"],seealso:["floor","fix","round"]};var AF={name:"cube",category:"Arithmetic",syntax:["cube(x)"],description:"Compute the cube of a value. The cube of x is x * x * x.",examples:["cube(2)","2^3","2 * 2 * 2"],seealso:["multiply","square","pow"]};var MF={name:"divide",category:"Operators",syntax:["x / y","divide(x, y)"],description:"Divide two values.",examples:["a = 2 / 3","a * 3","4.5 / 2","3 + 4 / 2","(3 + 4) / 2","18 km / 4.5"],seealso:["multiply"]};var CF={name:"dotDivide",category:"Operators",syntax:["x ./ y","dotDivide(x, y)"],description:"Divide two values element wise.",examples:["a = [1, 2, 3; 4, 5, 6]","b = [2, 1, 1; 3, 2, 5]","a ./ b"],seealso:["multiply","dotMultiply","divide"]};var EF={name:"dotMultiply",category:"Operators",syntax:["x .* y","dotMultiply(x, y)"],description:"Multiply two values element wise.",examples:["a = [1, 2, 3; 4, 5, 6]","b = [2, 1, 1; 3, 2, 5]","a .* b"],seealso:["multiply","divide","dotDivide"]};var TF={name:"dotPow",category:"Operators",syntax:["x .^ y","dotPow(x, y)"],description:"Calculates the power of x to y element wise.",examples:["a = [1, 2, 3; 4, 5, 6]","a .^ 2"],seealso:["pow"]};var FF={name:"exp",category:"Arithmetic",syntax:["exp(x)"],description:"Calculate the exponent of a value.",examples:["exp(1.3)","e ^ 1.3","log(exp(1.3))","x = 2.4","(exp(i*x) == cos(x) + i*sin(x)) # Euler's formula"],seealso:["expm","expm1","pow","log"]};var _F={name:"expm",category:"Arithmetic",syntax:["exp(x)"],description:"Compute the matrix exponential, expm(A) = e^A. The matrix must be square. Not to be confused with exp(a), which performs element-wise exponentiation.",examples:["expm([[0,2],[0,0]])"],seealso:["exp"]};var OF={name:"expm1",category:"Arithmetic",syntax:["expm1(x)"],description:"Calculate the value of subtracting 1 from the exponential value.",examples:["expm1(2)","pow(e, 2) - 1","log(expm1(2) + 1)"],seealso:["exp","pow","log"]};var BF={name:"fix",category:"Arithmetic",syntax:["fix(x)"],description:"Round a value towards zero. If x is complex, both real and imaginary part are rounded towards zero.",examples:["fix(3.2)","fix(3.8)","fix(-4.2)","fix(-4.8)"],seealso:["ceil","floor","round"]};var PF={name:"floor",category:"Arithmetic",syntax:["floor(x)"],description:"Round a value towards minus infinity.If x is complex, both real and imaginary part are rounded towards minus infinity.",examples:["floor(3.2)","floor(3.8)","floor(-4.2)"],seealso:["ceil","fix","round"]};var IF={name:"gcd",category:"Arithmetic",syntax:["gcd(a, b)","gcd(a, b, c, ...)"],description:"Compute the greatest common divisor.",examples:["gcd(8, 12)","gcd(-4, 6)","gcd(25, 15, -10)"],seealso:["lcm","xgcd"]};var RF={name:"hypot",category:"Arithmetic",syntax:["hypot(a, b, c, ...)","hypot([a, b, c, ...])"],description:"Calculate the hypotenusa of a list with values. ",examples:["hypot(3, 4)","sqrt(3^2 + 4^2)","hypot(-2)","hypot([3, 4, 5])"],seealso:["abs","norm"]};var kF={name:"invmod",category:"Arithmetic",syntax:["invmod(a, b)"],description:"Calculate the (modular) multiplicative inverse of a modulo b. Solution to the equation ax \\u2263 1 (mod b)",examples:["invmod(8, 12)","invmod(7, 13)","invmod(15151, 15122)"],seealso:["gcd","xgcd"]};var qF={name:"lcm",category:"Arithmetic",syntax:["lcm(x, y)"],description:"Compute the least common multiple.",examples:["lcm(4, 6)","lcm(6, 21)","lcm(6, 21, 5)"],seealso:["gcd"]};var LF={name:"log",category:"Arithmetic",syntax:["log(x)","log(x, base)"],description:"Compute the logarithm of a value. If no base is provided, the natural logarithm of x is calculated. If base if provided, the logarithm is calculated for the specified base. log(x, base) is defined as log(x) / log(base).",examples:["log(3.5)","a = log(2.4)","exp(a)","10 ^ 4","log(10000, 10)","log(10000) / log(10)","b = log(1024, 2)","2 ^ b"],seealso:["exp","log1p","log2","log10"]};var zF={name:"log10",category:"Arithmetic",syntax:["log10(x)"],description:"Compute the 10-base logarithm of a value.",examples:["log10(0.00001)","log10(10000)","10 ^ 4","log(10000) / log(10)","log(10000, 10)"],seealso:["exp","log"]};var UF={name:"log1p",category:"Arithmetic",syntax:["log1p(x)","log1p(x, base)"],description:"Calculate the logarithm of a \`value+1\`",examples:["log1p(2.5)","exp(log1p(1.4))","pow(10, 4)","log1p(9999, 10)","log1p(9999) / log(10)"],seealso:["exp","log","log2","log10"]};var WF={name:"log2",category:"Arithmetic",syntax:["log2(x)"],description:"Calculate the 2-base of a value. This is the same as calculating \`log(x, 2)\`.",examples:["log2(0.03125)","log2(16)","log2(16) / log2(2)","pow(2, 4)"],seealso:["exp","log1p","log","log10"]};var YF={name:"mod",category:"Operators",syntax:["x % y","x mod y","mod(x, y)"],description:"Calculates the modulus, the remainder of an integer division.",examples:["7 % 3","11 % 2","10 mod 4","isOdd(x) = x % 2","isOdd(2)","isOdd(3)"],seealso:["divide"]};var HF={name:"multiply",category:"Operators",syntax:["x * y","multiply(x, y)"],description:"multiply two values.",examples:["a = 2.1 * 3.4","a / 3.4","2 * 3 + 4","2 * (3 + 4)","3 * 2.1 km"],seealso:["divide"]};var $F={name:"norm",category:"Arithmetic",syntax:["norm(x)","norm(x, p)"],description:"Calculate the norm of a number, vector or matrix.",examples:["abs(-3.5)","norm(-3.5)","norm(3 - 4i)","norm([1, 2, -3], Infinity)","norm([1, 2, -3], -Infinity)","norm([3, 4], 2)","norm([[1, 2], [3, 4]], 1)",'norm([[1, 2], [3, 4]], "inf")','norm([[1, 2], [3, 4]], "fro")']};var GF={name:"nthRoot",category:"Arithmetic",syntax:["nthRoot(a)","nthRoot(a, root)"],description:'Calculate the nth root of a value. The principal nth root of a positive real number A, is the positive real solution of the equation "x^root = A".',examples:["4 ^ 3","nthRoot(64, 3)","nthRoot(9, 2)","sqrt(9)"],seealso:["nthRoots","pow","sqrt"]};var VF={name:"nthRoots",category:"Arithmetic",syntax:["nthRoots(A)","nthRoots(A, root)"],description:'Calculate the nth roots of a value. An nth root of a positive real number A, is a positive real solution of the equation "x^root = A". This function returns an array of complex values.',examples:["nthRoots(1)","nthRoots(1, 3)"],seealso:["sqrt","pow","nthRoot"]};var ZF={name:"pow",category:"Operators",syntax:["x ^ y","pow(x, y)"],description:"Calculates the power of x to y, x^y.",examples:["2^3","2*2*2","1 + e ^ (pi * i)","pow([[1, 2], [4, 3]], 2)","pow([[1, 2], [4, 3]], -1)"],seealso:["multiply","nthRoot","nthRoots","sqrt"]};var QF={name:"round",category:"Arithmetic",syntax:["round(x)","round(x, n)","round(unit, valuelessUnit)","round(unit, n, valuelessUnit)"],description:"round a value towards the nearest integer.If x is complex, both real and imaginary part are rounded towards the nearest integer. When n is specified, the value is rounded to n decimals.",examples:["round(3.2)","round(3.8)","round(-4.2)","round(-4.8)","round(pi, 3)","round(123.45678, 2)","round(3.241cm, 2, cm)","round([3.2, 3.8, -4.7])"],seealso:["ceil","floor","fix"]};var XF={name:"sign",category:"Arithmetic",syntax:["sign(x)"],description:"Compute the sign of a value. The sign of a value x is 1 when x>1, -1 when x<0, and 0 when x=0.",examples:["sign(3.5)","sign(-4.2)","sign(0)"],seealso:["abs"]};var JF={name:"sqrt",category:"Arithmetic",syntax:["sqrt(x)"],description:"Compute the square root value. If x = y * y, then y is the square root of x.",examples:["sqrt(25)","5 * 5","sqrt(-1)"],seealso:["square","sqrtm","multiply","nthRoot","nthRoots","pow"]};var KF={name:"sqrtm",category:"Arithmetic",syntax:["sqrtm(x)"],description:"Calculate the principal square root of a square matrix. The principal square root matrix \`X\` of another matrix \`A\` is such that \`X * X = A\`.",examples:["sqrtm([[33, 24], [48, 57]])"],seealso:["sqrt","abs","square","multiply"]};var jF={name:"sylvester",category:"Algebra",syntax:["sylvester(A,B,C)"],description:"Solves the real-valued Sylvester equation AX+XB=C for X",examples:["sylvester([[-1, -2], [1, 1]], [[-2, 1], [-1, 2]], [[-3, 2], [3, 0]])","A = [[-1, -2], [1, 1]]; B = [[2, -1], [1, -2]]; C = [[-3, 2], [3, 0]]","sylvester(A, B, C)"],seealso:["schur","lyap"]};var e_={name:"schur",category:"Algebra",syntax:["schur(A)"],description:"Performs a real Schur decomposition of the real matrix A = UTU'",examples:["schur([[1, 0], [-4, 3]])","A = [[1, 0], [-4, 3]]","schur(A)"],seealso:["lyap","sylvester"]};var r_={name:"lyap",category:"Algebra",syntax:["lyap(A,Q)"],description:"Solves the Continuous-time Lyapunov equation AP+PA'+Q=0 for P",examples:["lyap([[-2, 0], [1, -4]], [[3, 1], [1, 3]])","A = [[-2, 0], [1, -4]]","Q = [[3, 1], [1, 3]]","lyap(A,Q)"],seealso:["schur","sylvester"]};var t_={name:"square",category:"Arithmetic",syntax:["square(x)"],description:"Compute the square of a value. The square of x is x * x.",examples:["square(3)","sqrt(9)","3^2","3 * 3"],seealso:["multiply","pow","sqrt","cube"]};var n_={name:"subtract",category:"Operators",syntax:["x - y","subtract(x, y)"],description:"subtract two values.",examples:["a = 5.3 - 2","a + 2","2/3 - 1/6","2 * 3 - 3","2.1 km - 500m"],seealso:["add"]};var a_={name:"unaryMinus",category:"Operators",syntax:["-x","unaryMinus(x)"],description:"Inverse the sign of a value. Converts booleans and strings to numbers.",examples:["-4.5","-(-5.6)",'-"22"'],seealso:["add","subtract","unaryPlus"]};var i_={name:"unaryPlus",category:"Operators",syntax:["+x","unaryPlus(x)"],description:"Converts booleans and strings to numbers.",examples:["+true",'+"2"'],seealso:["add","subtract","unaryMinus"]};var o_={name:"xgcd",category:"Arithmetic",syntax:["xgcd(a, b)"],description:"Calculate the extended greatest common divisor for two values. The result is an array [d, x, y] with 3 entries, where d is the greatest common divisor, and d = x * a + y * b.",examples:["xgcd(8, 12)","gcd(8, 12)","xgcd(36163, 21199)"],seealso:["gcd","lcm"]};var s_={name:"bitAnd",category:"Bitwise",syntax:["x & y","bitAnd(x, y)"],description:"Bitwise AND operation. Performs the logical AND operation on each pair of the corresponding bits of the two given values by multiplying them. If both bits in the compared position are 1, the bit in the resulting binary representation is 1, otherwise, the result is 0",examples:["5 & 3","bitAnd(53, 131)","[1, 12, 31] & 42"],seealso:["bitNot","bitOr","bitXor","leftShift","rightArithShift","rightLogShift"]};var u_={name:"bitNot",category:"Bitwise",syntax:["~x","bitNot(x)"],description:"Bitwise NOT operation. Performs a logical negation on each bit of the given value. Bits that are 0 become 1, and those that are 1 become 0.",examples:["~1","~2","bitNot([2, -3, 4])"],seealso:["bitAnd","bitOr","bitXor","leftShift","rightArithShift","rightLogShift"]};var f_={name:"bitOr",category:"Bitwise",syntax:["x | y","bitOr(x, y)"],description:"Bitwise OR operation. Performs the logical inclusive OR operation on each pair of corresponding bits of the two given values. The result in each position is 1 if the first bit is 1 or the second bit is 1 or both bits are 1, otherwise, the result is 0.",examples:["5 | 3","bitOr([1, 2, 3], 4)"],seealso:["bitAnd","bitNot","bitXor","leftShift","rightArithShift","rightLogShift"]};var c_={name:"bitXor",category:"Bitwise",syntax:["bitXor(x, y)"],description:"Bitwise XOR operation, exclusive OR. Performs the logical exclusive OR operation on each pair of corresponding bits of the two given values. The result in each position is 1 if only the first bit is 1 or only the second bit is 1, but will be 0 if both are 0 or both are 1.",examples:["bitOr(1, 2)","bitXor([2, 3, 4], 4)"],seealso:["bitAnd","bitNot","bitOr","leftShift","rightArithShift","rightLogShift"]};var l_={name:"leftShift",category:"Bitwise",syntax:["x << y","leftShift(x, y)"],description:"Bitwise left logical shift of a value x by y number of bits.",examples:["4 << 1","8 >> 1"],seealso:["bitAnd","bitNot","bitOr","bitXor","rightArithShift","rightLogShift"]};var m_={name:"rightArithShift",category:"Bitwise",syntax:["x >> y","rightArithShift(x, y)"],description:"Bitwise right arithmetic shift of a value x by y number of bits.",examples:["8 >> 1","4 << 1","-12 >> 2"],seealso:["bitAnd","bitNot","bitOr","bitXor","leftShift","rightLogShift"]};var p_={name:"rightLogShift",category:"Bitwise",syntax:["x >>> y","rightLogShift(x, y)"],description:"Bitwise right logical shift of a value x by y number of bits.",examples:["8 >>> 1","4 << 1","-12 >>> 2"],seealso:["bitAnd","bitNot","bitOr","bitXor","leftShift","rightArithShift"]};var d_={name:"bellNumbers",category:"Combinatorics",syntax:["bellNumbers(n)"],description:"The Bell Numbers count the number of partitions of a set. A partition is a pairwise disjoint subset of S whose union is S. \`bellNumbers\` only takes integer arguments. The following condition must be enforced: n >= 0.",examples:["bellNumbers(3)","bellNumbers(8)"],seealso:["stirlingS2"]};var h_={name:"catalan",category:"Combinatorics",syntax:["catalan(n)"],description:"The Catalan Numbers enumerate combinatorial structures of many different types. catalan only takes integer arguments. The following condition must be enforced: n >= 0.",examples:["catalan(3)","catalan(8)"],seealso:["bellNumbers"]};var v_={name:"composition",category:"Combinatorics",syntax:["composition(n, k)"],description:"The composition counts of n into k parts. composition only takes integer arguments. The following condition must be enforced: k <= n.",examples:["composition(5, 3)"],seealso:["combinations"]};var g_={name:"stirlingS2",category:"Combinatorics",syntax:["stirlingS2(n, k)"],description:"he Stirling numbers of the second kind, counts the number of ways to partition a set of n labelled objects into k nonempty unlabelled subsets. \`stirlingS2\` only takes integer arguments. The following condition must be enforced: k <= n. If n = k or k = 1, then s(n,k) = 1.",examples:["stirlingS2(5, 3)"],seealso:["bellNumbers"]};var x_={name:"arg",category:"Complex",syntax:["arg(x)"],description:"Compute the argument of a complex value. If x = a+bi, the argument is computed as atan2(b, a).",examples:["arg(2 + 2i)","atan2(3, 2)","arg(2 + 3i)"],seealso:["re","im","conj","abs"]};var y_={name:"conj",category:"Complex",syntax:["conj(x)"],description:"Compute the complex conjugate of a complex value. If x = a+bi, the complex conjugate is a-bi.",examples:["conj(2 + 3i)","conj(2 - 3i)","conj(-5.2i)"],seealso:["re","im","abs","arg"]};var b_={name:"im",category:"Complex",syntax:["im(x)"],description:"Get the imaginary part of a complex number.",examples:["im(2 + 3i)","re(2 + 3i)","im(-5.2i)","im(2.4)"],seealso:["re","conj","abs","arg"]};var w_={name:"re",category:"Complex",syntax:["re(x)"],description:"Get the real part of a complex number.",examples:["re(2 + 3i)","im(2 + 3i)","re(-5.2i)","re(2.4)"],seealso:["im","conj","abs","arg"]};var D_={name:"evaluate",category:"Expression",syntax:["evaluate(expression)","evaluate(expression, scope)","evaluate([expr1, expr2, expr3, ...])","evaluate([expr1, expr2, expr3, ...], scope)"],description:"Evaluate an expression or an array with expressions.",examples:['evaluate("2 + 3")','evaluate("sqrt(16)")','evaluate("2 inch to cm")','evaluate("sin(x * pi)", { "x": 1/2 })','evaluate(["width=2", "height=4","width*height"])'],seealso:[]};var S_={name:"help",category:"Expression",syntax:["help(object)","help(string)"],description:"Display documentation on a function or data type.",examples:["help(sqrt)",'help("complex")'],seealso:[]};var N_={name:"distance",category:"Geometry",syntax:["distance([x1, y1], [x2, y2])","distance([[x1, y1], [x2, y2]])"],description:"Calculates the Euclidean distance between two points.",examples:["distance([0,0], [4,4])","distance([[0,0], [4,4]])"],seealso:[]};var A_={name:"intersect",category:"Geometry",syntax:["intersect(expr1, expr2, expr3, expr4)","intersect(expr1, expr2, expr3)"],description:"Computes the intersection point of lines and/or planes.",examples:["intersect([0, 0], [10, 10], [10, 0], [0, 10])","intersect([1, 0, 1], [4, -2, 2], [1, 1, 1, 6])"],seealso:[]};var M_={name:"and",category:"Logical",syntax:["x and y","and(x, y)"],description:"Logical and. Test whether two values are both defined with a nonzero/nonempty value.",examples:["true and false","true and true","2 and 4"],seealso:["not","or","xor"]};var C_={name:"not",category:"Logical",syntax:["not x","not(x)"],description:"Logical not. Flips the boolean value of given argument.",examples:["not true","not false","not 2","not 0"],seealso:["and","or","xor"]};var E_={name:"or",category:"Logical",syntax:["x or y","or(x, y)"],description:"Logical or. Test if at least one value is defined with a nonzero/nonempty value.",examples:["true or false","false or false","0 or 4"],seealso:["not","and","xor"]};var T_={name:"xor",category:"Logical",syntax:["x xor y","xor(x, y)"],description:"Logical exclusive or, xor. Test whether one and only one value is defined with a nonzero/nonempty value.",examples:["true xor false","false xor false","true xor true","0 xor 4"],seealso:["not","and","or"]};var F_={name:"column",category:"Matrix",syntax:["column(x, index)"],description:"Return a column from a matrix or array.",examples:["A = [[1, 2], [3, 4]]","column(A, 1)","column(A, 2)"],seealso:["row","matrixFromColumns"]};var __={name:"concat",category:"Matrix",syntax:["concat(A, B, C, ...)","concat(A, B, C, ..., dim)"],description:"Concatenate matrices. By default, the matrices are concatenated by the last dimension. The dimension on which to concatenate can be provided as last argument.",examples:["A = [1, 2; 5, 6]","B = [3, 4; 7, 8]","concat(A, B)","concat(A, B, 1)","concat(A, B, 2)"],seealso:["det","diag","identity","inv","ones","range","size","squeeze","subset","trace","transpose","zeros"]};var O_={name:"count",category:"Matrix",syntax:["count(x)"],description:"Count the number of elements of a matrix, array or string.",examples:["a = [1, 2; 3, 4; 5, 6]","count(a)","size(a)",'count("hello world")'],seealso:["size"]};var B_={name:"cross",category:"Matrix",syntax:["cross(A, B)"],description:"Calculate the cross product for two vectors in three dimensional space.",examples:["cross([1, 1, 0], [0, 1, 1])","cross([3, -3, 1], [4, 9, 2])","cross([2, 3, 4], [5, 6, 7])"],seealso:["multiply","dot"]};var P_={name:"ctranspose",category:"Matrix",syntax:["x'","ctranspose(x)"],description:"Complex Conjugate and Transpose a matrix",examples:["a = [1, 2, 3; 4, 5, 6]","a'","ctranspose(a)"],seealso:["concat","det","diag","identity","inv","ones","range","size","squeeze","subset","trace","zeros"]};var I_={name:"det",category:"Matrix",syntax:["det(x)"],description:"Calculate the determinant of a matrix",examples:["det([1, 2; 3, 4])","det([-2, 2, 3; -1, 1, 3; 2, 0, -1])"],seealso:["concat","diag","identity","inv","ones","range","size","squeeze","subset","trace","transpose","zeros"]};var R_={name:"diag",category:"Matrix",syntax:["diag(x)","diag(x, k)"],description:"Create a diagonal matrix or retrieve the diagonal of a matrix. When x is a vector, a matrix with the vector values on the diagonal will be returned. When x is a matrix, a vector with the diagonal values of the matrix is returned. When k is provided, the k-th diagonal will be filled in or retrieved, if k is positive, the values are placed on the super diagonal. When k is negative, the values are placed on the sub diagonal.",examples:["diag(1:3)","diag(1:3, 1)","a = [1, 2, 3; 4, 5, 6; 7, 8, 9]","diag(a)"],seealso:["concat","det","identity","inv","ones","range","size","squeeze","subset","trace","transpose","zeros"]};var k_={name:"diff",category:"Matrix",syntax:["diff(arr)","diff(arr, dim)"],description:["Create a new matrix or array with the difference of the passed matrix or array.","Dim parameter is optional and used to indicant the dimension of the array/matrix to apply the difference","If no dimension parameter is passed it is assumed as dimension 0","Dimension is zero-based in javascript and one-based in the parser","Arrays must be 'rectangular' meaning arrays like [1, 2]","If something is passed as a matrix it will be returned as a matrix but other than that all matrices are converted to arrays"],examples:["A = [1, 2, 4, 7, 0]","diff(A)","diff(A, 1)","B = [[1, 2], [3, 4]]","diff(B)","diff(B, 1)","diff(B, 2)","diff(B, bignumber(2))","diff([[1, 2], matrix([3, 4])], 2)"],seealso:["subtract","partitionSelect"]};var q_={name:"dot",category:"Matrix",syntax:["dot(A, B)","A * B"],description:"Calculate the dot product of two vectors. The dot product of A = [a1, a2, a3, ..., an] and B = [b1, b2, b3, ..., bn] is defined as dot(A, B) = a1 * b1 + a2 * b2 + a3 * b3 + ... + an * bn",examples:["dot([2, 4, 1], [2, 2, 3])","[2, 4, 1] * [2, 2, 3]"],seealso:["multiply","cross"]};var L_={name:"eigs",category:"Matrix",syntax:["eigs(x)"],description:"Calculate the eigenvalues and optionally eigenvectors of a square matrix",examples:["eigs([[5, 2.3], [2.3, 1]])","eigs([[1, 2, 3], [4, 5, 6], [7, 8, 9]], { precision: 1e-6, eigenvectors: false })"],seealso:["inv"]};var z_={name:"filter",category:"Matrix",syntax:["filter(x, test)"],description:"Filter items in a matrix.",examples:["isPositive(x) = x > 0","filter([6, -2, -1, 4, 3], isPositive)","filter([6, -2, 0, 1, 0], x != 0)"],seealso:["sort","map","forEach"]};var U_={name:"flatten",category:"Matrix",syntax:["flatten(x)"],description:"Flatten a multi dimensional matrix into a single dimensional matrix.",examples:["a = [1, 2, 3; 4, 5, 6]","size(a)","b = flatten(a)","size(b)"],seealso:["concat","resize","size","squeeze"]};var W_={name:"forEach",category:"Matrix",syntax:["forEach(x, callback)"],description:"Iterates over all elements of a matrix/array, and executes the given callback function.",examples:["numberOfPets = {}","addPet(n) = numberOfPets[n] = (numberOfPets[n] ? numberOfPets[n]:0 ) + 1;",'forEach(["Dog","Cat","Cat"], addPet)',"numberOfPets"],seealso:["map","sort","filter"]};var Y_={name:"getMatrixDataType",category:"Matrix",syntax:["getMatrixDataType(x)"],description:'Find the data type of all elements in a matrix or array, for example "number" if all items are a number and "Complex" if all values are complex numbers. If a matrix contains more than one data type, it will return "mixed".',examples:["getMatrixDataType([1, 2, 3])","getMatrixDataType([[5 cm], [2 inch]])",'getMatrixDataType([1, "text"])',"getMatrixDataType([1, bignumber(4)])"],seealso:["matrix","sparse","typeOf"]};var H_={name:"identity",category:"Matrix",syntax:["identity(n)","identity(m, n)","identity([m, n])"],description:"Returns the identity matrix with size m-by-n. The matrix has ones on the diagonal and zeros elsewhere.",examples:["identity(3)","identity(3, 5)","a = [1, 2, 3; 4, 5, 6]","identity(size(a))"],seealso:["concat","det","diag","inv","ones","range","size","squeeze","subset","trace","transpose","zeros"]};var $_={name:"inv",category:"Matrix",syntax:["inv(x)"],description:"Calculate the inverse of a matrix",examples:["inv([1, 2; 3, 4])","inv(4)","1 / 4"],seealso:["concat","det","diag","identity","ones","range","size","squeeze","subset","trace","transpose","zeros"]};var G_={name:"pinv",category:"Matrix",syntax:["pinv(x)"],description:"Calculate the Moore\\u2013Penrose inverse of a matrix",examples:["pinv([1, 2; 3, 4])","pinv([[1, 0], [0, 1], [0, 1]])","pinv(4)"],seealso:["inv"]};var V_={name:"kron",category:"Matrix",syntax:["kron(x, y)"],description:"Calculates the kronecker product of 2 matrices or vectors.",examples:["kron([[1, 0], [0, 1]], [[1, 2], [3, 4]])","kron([1,1], [2,3,4])"],seealso:["multiply","dot","cross"]};var Z_={name:"map",category:"Matrix",syntax:["map(x, callback)"],description:"Create a new matrix or array with the results of the callback function executed on each entry of the matrix/array.",examples:["map([1, 2, 3], square)"],seealso:["filter","forEach"]};var Q_={name:"matrixFromColumns",category:"Matrix",syntax:["matrixFromColumns(...arr)","matrixFromColumns(row1, row2)","matrixFromColumns(row1, row2, row3)"],description:"Create a dense matrix from vectors as individual columns.",examples:["matrixFromColumns([1, 2, 3], [[4],[5],[6]])"],seealso:["matrix","matrixFromRows","matrixFromFunction","zeros"]};var X_={name:"matrixFromFunction",category:"Matrix",syntax:["matrixFromFunction(size, fn)","matrixFromFunction(size, fn, format)","matrixFromFunction(size, fn, format, datatype)","matrixFromFunction(size, format, fn)","matrixFromFunction(size, format, datatype, fn)"],description:"Create a matrix by evaluating a generating function at each index.",examples:["f(I) = I[1] - I[2]","matrixFromFunction([3,3], f)","g(I) = I[1] - I[2] == 1 ? 4 : 0",'matrixFromFunction([100, 100], "sparse", g)',"matrixFromFunction([5], random)"],seealso:["matrix","matrixFromRows","matrixFromColumns","zeros"]};var J_={name:"matrixFromRows",category:"Matrix",syntax:["matrixFromRows(...arr)","matrixFromRows(row1, row2)","matrixFromRows(row1, row2, row3)"],description:"Create a dense matrix from vectors as individual rows.",examples:["matrixFromRows([1, 2, 3], [[4],[5],[6]])"],seealso:["matrix","matrixFromColumns","matrixFromFunction","zeros"]};var K_={name:"ones",category:"Matrix",syntax:["ones(m)","ones(m, n)","ones(m, n, p, ...)","ones([m])","ones([m, n])","ones([m, n, p, ...])"],description:"Create a matrix containing ones.",examples:["ones(3)","ones(3, 5)","ones([2,3]) * 4.5","a = [1, 2, 3; 4, 5, 6]","ones(size(a))"],seealso:["concat","det","diag","identity","inv","range","size","squeeze","subset","trace","transpose","zeros"]};var j_={name:"partitionSelect",category:"Matrix",syntax:["partitionSelect(x, k)","partitionSelect(x, k, compare)"],description:"Partition-based selection of an array or 1D matrix. Will find the kth smallest value, and mutates the input array. Uses Quickselect.",examples:["partitionSelect([5, 10, 1], 2)",'partitionSelect(["C", "B", "A", "D"], 1, compareText)',"arr = [5, 2, 1]","partitionSelect(arr, 0) # returns 1, arr is now: [1, 2, 5]","arr","partitionSelect(arr, 1, 'desc') # returns 2, arr is now: [5, 2, 1]","arr"],seealso:["sort"]};var eO={name:"range",category:"Type",syntax:["start:end","start:step:end","range(start, end)","range(start, end, step)","range(string)"],description:"Create a range. Lower bound of the range is included, upper bound is excluded.",examples:["1:5","3:-1:-3","range(3, 7)","range(0, 12, 2)",'range("4:10")',"range(1m, 1m, 3m)","a = [1, 2, 3, 4; 5, 6, 7, 8]","a[1:2, 1:2]"],seealso:["concat","det","diag","identity","inv","ones","size","squeeze","subset","trace","transpose","zeros"]};var rO={name:"reshape",category:"Matrix",syntax:["reshape(x, sizes)"],description:"Reshape a multi dimensional array to fit the specified dimensions.",examples:["reshape([1, 2, 3, 4, 5, 6], [2, 3])","reshape([[1, 2], [3, 4]], [1, 4])","reshape([[1, 2], [3, 4]], [4])","reshape([1, 2, 3, 4], [-1, 2])"],seealso:["size","squeeze","resize"]};var tO={name:"resize",category:"Matrix",syntax:["resize(x, size)","resize(x, size, defaultValue)"],description:"Resize a matrix.",examples:["resize([1,2,3,4,5], [3])","resize([1,2,3], [5])","resize([1,2,3], [5], -1)","resize(2, [2, 3])",'resize("hello", [8], "!")'],seealso:["size","subset","squeeze","reshape"]};var nO={name:"rotate",category:"Matrix",syntax:["rotate(w, theta)","rotate(w, theta, v)"],description:"Returns a 2-D rotation matrix (2x2) for a given angle (in radians). Returns a 2-D rotation matrix (3x3) of a given angle (in radians) around given axis.",examples:["rotate([1, 0], pi / 2)",'rotate(matrix([1, 0]), unit("35deg"))','rotate([1, 0, 0], unit("90deg"), [0, 0, 1])','rotate(matrix([1, 0, 0]), unit("90deg"), matrix([0, 0, 1]))'],seealso:["matrix","rotationMatrix"]};var aO={name:"rotationMatrix",category:"Matrix",syntax:["rotationMatrix(theta)","rotationMatrix(theta, v)","rotationMatrix(theta, v, format)"],description:"Returns a 2-D rotation matrix (2x2) for a given angle (in radians). Returns a 2-D rotation matrix (3x3) of a given angle (in radians) around given axis.",examples:["rotationMatrix(pi / 2)",'rotationMatrix(unit("45deg"), [0, 0, 1])','rotationMatrix(1, matrix([0, 0, 1]), "sparse")'],seealso:["cos","sin"]};var iO={name:"row",category:"Matrix",syntax:["row(x, index)"],description:"Return a row from a matrix or array.",examples:["A = [[1, 2], [3, 4]]","row(A, 1)","row(A, 2)"],seealso:["column","matrixFromRows"]};var oO={name:"size",category:"Matrix",syntax:["size(x)"],description:"Calculate the size of a matrix.",examples:["size(2.3)",'size("hello world")',"a = [1, 2; 3, 4; 5, 6]","size(a)","size(1:6)"],seealso:["concat","count","det","diag","identity","inv","ones","range","squeeze","subset","trace","transpose","zeros"]};var sO={name:"sort",category:"Matrix",syntax:["sort(x)","sort(x, compare)"],description:'Sort the items in a matrix. Compare can be a string "asc", "desc", "natural", or a custom sort function.',examples:["sort([5, 10, 1])",'sort(["C", "B", "A", "D"], "natural")',"sortByLength(a, b) = size(a)[1] - size(b)[1]",'sort(["Langdon", "Tom", "Sara"], sortByLength)','sort(["10", "1", "2"], "natural")'],seealso:["map","filter","forEach"]};var uO={name:"squeeze",category:"Matrix",syntax:["squeeze(x)"],description:"Remove inner and outer singleton dimensions from a matrix.",examples:["a = zeros(3,2,1)","size(squeeze(a))","b = zeros(1,1,3)","size(squeeze(b))"],seealso:["concat","det","diag","identity","inv","ones","range","size","subset","trace","transpose","zeros"]};var fO={name:"subset",category:"Matrix",syntax:["value(index)","value(index) = replacement","subset(value, [index])","subset(value, [index], replacement)"],description:"Get or set a subset of the entries of a matrix or characters of a string. Indexes are one-based. There should be one index specification for each dimension of the target. Each specification can be a single index, a list of indices, or a range in colon notation \`l:u\`. In a range, both the lower bound l and upper bound u are included; and if a bound is omitted it defaults to the most extreme valid value. The cartesian product of the indices specified in each dimension determines the target of the operation.",examples:["d = [1, 2; 3, 4]","e = []","e[1, 1:2] = [5, 6]","e[2, :] = [7, 8]","f = d * e","f[2, 1]","f[:, 1]","f[[1,2], [1,3]] = [9, 10; 11, 12]","f"],seealso:["concat","det","diag","identity","inv","ones","range","size","squeeze","trace","transpose","zeros"]};var cO={name:"trace",category:"Matrix",syntax:["trace(A)"],description:"Calculate the trace of a matrix: the sum of the elements on the main diagonal of a square matrix.",examples:["A = [1, 2, 3; -1, 2, 3; 2, 0, 3]","trace(A)"],seealso:["concat","det","diag","identity","inv","ones","range","size","squeeze","subset","transpose","zeros"]};var lO={name:"transpose",category:"Matrix",syntax:["x'","transpose(x)"],description:"Transpose a matrix",examples:["a = [1, 2, 3; 4, 5, 6]","a'","transpose(a)"],seealso:["concat","det","diag","identity","inv","ones","range","size","squeeze","subset","trace","zeros"]};var mO={name:"zeros",category:"Matrix",syntax:["zeros(m)","zeros(m, n)","zeros(m, n, p, ...)","zeros([m])","zeros([m, n])","zeros([m, n, p, ...])"],description:"Create a matrix containing zeros.",examples:["zeros(3)","zeros(3, 5)","a = [1, 2, 3; 4, 5, 6]","zeros(size(a))"],seealso:["concat","det","diag","identity","inv","ones","range","size","squeeze","subset","trace","transpose"]};var pO={name:"fft",category:"Matrix",syntax:["fft(x)"],description:"Calculate N-dimensional fourier transform",examples:["fft([[1, 0], [1, 0]])"],seealso:["ifft"]};var dO={name:"ifft",category:"Matrix",syntax:["ifft(x)"],description:"Calculate N-dimensional inverse fourier transform",examples:["ifft([[2, 2], [0, 0]])"],seealso:["fft"]};var hO={name:"combinations",category:"Probability",syntax:["combinations(n, k)"],description:"Compute the number of combinations of n items taken k at a time",examples:["combinations(7, 5)"],seealso:["combinationsWithRep","permutations","factorial"]};var vO={name:"combinationsWithRep",category:"Probability",syntax:["combinationsWithRep(n, k)"],description:"Compute the number of combinations of n items taken k at a time with replacements.",examples:["combinationsWithRep(7, 5)"],seealso:["combinations","permutations","factorial"]};var gO={name:"factorial",category:"Probability",syntax:["n!","factorial(n)"],description:"Compute the factorial of a value",examples:["5!","5 * 4 * 3 * 2 * 1","3!"],seealso:["combinations","combinationsWithRep","permutations","gamma"]};var xO={name:"gamma",category:"Probability",syntax:["gamma(n)"],description:"Compute the gamma function. For small values, the Lanczos approximation is used, and for large values the extended Stirling approximation.",examples:["gamma(4)","3!","gamma(1/2)","sqrt(pi)"],seealso:["factorial"]};var yO={name:"lgamma",category:"Probability",syntax:["lgamma(n)"],description:"Logarithm of the gamma function for real, positive numbers and complex numbers, using Lanczos approximation for numbers and Stirling series for complex numbers.",examples:["lgamma(4)","lgamma(1/2)","lgamma(i)","lgamma(complex(1.1, 2))"],seealso:["gamma"]};var bO={name:"kldivergence",category:"Probability",syntax:["kldivergence(x, y)"],description:"Calculate the Kullback-Leibler (KL) divergence between two distributions.",examples:["kldivergence([0.7,0.5,0.4], [0.2,0.9,0.5])"],seealso:[]};var wO={name:"multinomial",category:"Probability",syntax:["multinomial(A)"],description:"Multinomial Coefficients compute the number of ways of picking a1, a2, ..., ai unordered outcomes from \`n\` possibilities. multinomial takes one array of integers as an argument. The following condition must be enforced: every ai > 0.",examples:["multinomial([1, 2, 1])"],seealso:["combinations","factorial"]};var DO={name:"permutations",category:"Probability",syntax:["permutations(n)","permutations(n, k)"],description:"Compute the number of permutations of n items taken k at a time",examples:["permutations(5)","permutations(5, 3)"],seealso:["combinations","combinationsWithRep","factorial"]};var SO={name:"pickRandom",category:"Probability",syntax:["pickRandom(array)","pickRandom(array, number)","pickRandom(array, weights)","pickRandom(array, number, weights)","pickRandom(array, weights, number)"],description:"Pick a random entry from a given array.",examples:["pickRandom(0:10)","pickRandom([1, 3, 1, 6])","pickRandom([1, 3, 1, 6], 2)","pickRandom([1, 3, 1, 6], [2, 3, 2, 1])","pickRandom([1, 3, 1, 6], 2, [2, 3, 2, 1])","pickRandom([1, 3, 1, 6], [2, 3, 2, 1], 2)"],seealso:["random","randomInt"]};var NO={name:"random",category:"Probability",syntax:["random()","random(max)","random(min, max)","random(size)","random(size, max)","random(size, min, max)"],description:"Return a random number.",examples:["random()","random(10, 20)","random([2, 3])"],seealso:["pickRandom","randomInt"]};var AO={name:"randomInt",category:"Probability",syntax:["randomInt(max)","randomInt(min, max)","randomInt(size)","randomInt(size, max)","randomInt(size, min, max)"],description:"Return a random integer number",examples:["randomInt(10, 20)","randomInt([2, 3], 10)"],seealso:["pickRandom","random"]};var MO={name:"compare",category:"Relational",syntax:["compare(x, y)"],description:"Compare two values. Returns 1 when x > y, -1 when x < y, and 0 when x == y.",examples:["compare(2, 3)","compare(3, 2)","compare(2, 2)","compare(5cm, 40mm)","compare(2, [1, 2, 3])"],seealso:["equal","unequal","smaller","smallerEq","largerEq","compareNatural","compareText"]};var CO={name:"compareNatural",category:"Relational",syntax:["compareNatural(x, y)"],description:"Compare two values of any type in a deterministic, natural way. Returns 1 when x > y, -1 when x < y, and 0 when x == y.",examples:["compareNatural(2, 3)","compareNatural(3, 2)","compareNatural(2, 2)","compareNatural(5cm, 40mm)",'compareNatural("2", "10")',"compareNatural(2 + 3i, 2 + 4i)","compareNatural([1, 2, 4], [1, 2, 3])","compareNatural([1, 5], [1, 2, 3])","compareNatural([1, 2], [1, 2])","compareNatural({a: 2}, {a: 4})"],seealso:["equal","unequal","smaller","smallerEq","largerEq","compare","compareText"]};var EO={name:"compareText",category:"Relational",syntax:["compareText(x, y)"],description:"Compare two strings lexically. Comparison is case sensitive. Returns 1 when x > y, -1 when x < y, and 0 when x == y.",examples:['compareText("B", "A")','compareText("A", "B")','compareText("A", "A")','compareText("2", "10")','compare("2", "10")',"compare(2, 10)",'compareNatural("2", "10")','compareText("B", ["A", "B", "C"])'],seealso:["compare","compareNatural"]};var TO={name:"deepEqual",category:"Relational",syntax:["deepEqual(x, y)"],description:"Check equality of two matrices element wise. Returns true if the size of both matrices is equal and when and each of the elements are equal.",examples:["deepEqual([1,3,4], [1,3,4])","deepEqual([1,3,4], [1,3])"],seealso:["equal","unequal","smaller","larger","smallerEq","largerEq","compare"]};var FO={name:"equal",category:"Relational",syntax:["x == y","equal(x, y)"],description:"Check equality of two values. Returns true if the values are equal, and false if not.",examples:["2+2 == 3","2+2 == 4","a = 3.2","b = 6-2.8","a == b","50cm == 0.5m"],seealso:["unequal","smaller","larger","smallerEq","largerEq","compare","deepEqual","equalText"]};var _O={name:"equalText",category:"Relational",syntax:["equalText(x, y)"],description:"Check equality of two strings. Comparison is case sensitive. Returns true if the values are equal, and false if not.",examples:['equalText("Hello", "Hello")','equalText("a", "A")','equal("2e3", "2000")','equalText("2e3", "2000")','equalText("B", ["A", "B", "C"])'],seealso:["compare","compareNatural","compareText","equal"]};var OO={name:"larger",category:"Relational",syntax:["x > y","larger(x, y)"],description:"Check if value x is larger than y. Returns true if x is larger than y, and false if not.",examples:["2 > 3","5 > 2*2","a = 3.3","b = 6-2.8","(a > b)","(b < a)","5 cm > 2 inch"],seealso:["equal","unequal","smaller","smallerEq","largerEq","compare"]};var BO={name:"largerEq",category:"Relational",syntax:["x >= y","largerEq(x, y)"],description:"Check if value x is larger or equal to y. Returns true if x is larger or equal to y, and false if not.",examples:["2 >= 1+1","2 > 1+1","a = 3.2","b = 6-2.8","(a >= b)"],seealso:["equal","unequal","smallerEq","smaller","compare"]};var PO={name:"smaller",category:"Relational",syntax:["x < y","smaller(x, y)"],description:"Check if value x is smaller than value y. Returns true if x is smaller than y, and false if not.",examples:["2 < 3","5 < 2*2","a = 3.3","b = 6-2.8","(a < b)","5 cm < 2 inch"],seealso:["equal","unequal","larger","smallerEq","largerEq","compare"]};var IO={name:"smallerEq",category:"Relational",syntax:["x <= y","smallerEq(x, y)"],description:"Check if value x is smaller or equal to value y. Returns true if x is smaller than y, and false if not.",examples:["2 <= 1+1","2 < 1+1","a = 3.2","b = 6-2.8","(a <= b)"],seealso:["equal","unequal","larger","smaller","largerEq","compare"]};var RO={name:"unequal",category:"Relational",syntax:["x != y","unequal(x, y)"],description:"Check unequality of two values. Returns true if the values are unequal, and false if they are equal.",examples:["2+2 != 3","2+2 != 4","a = 3.2","b = 6-2.8","a != b","50cm != 0.5m","5 cm != 2 inch"],seealso:["equal","smaller","larger","smallerEq","largerEq","compare","deepEqual"]};var kO={name:"setCartesian",category:"Set",syntax:["setCartesian(set1, set2)"],description:"Create the cartesian product of two (multi)sets. Multi-dimension arrays will be converted to single-dimension arrays and the values will be sorted in ascending order before the operation.",examples:["setCartesian([1, 2], [3, 4])"],seealso:["setUnion","setIntersect","setDifference","setPowerset"]};var qO={name:"setDifference",category:"Set",syntax:["setDifference(set1, set2)"],description:"Create the difference of two (multi)sets: every element of set1, that is not the element of set2. Multi-dimension arrays will be converted to single-dimension arrays before the operation.",examples:["setDifference([1, 2, 3, 4], [3, 4, 5, 6])","setDifference([[1, 2], [3, 4]], [[3, 4], [5, 6]])"],seealso:["setUnion","setIntersect","setSymDifference"]};var LO={name:"setDistinct",category:"Set",syntax:["setDistinct(set)"],description:"Collect the distinct elements of a multiset. A multi-dimension array will be converted to a single-dimension array before the operation.",examples:["setDistinct([1, 1, 1, 2, 2, 3])"],seealso:["setMultiplicity"]};var zO={name:"setIntersect",category:"Set",syntax:["setIntersect(set1, set2)"],description:"Create the intersection of two (multi)sets. Multi-dimension arrays will be converted to single-dimension arrays before the operation.",examples:["setIntersect([1, 2, 3, 4], [3, 4, 5, 6])","setIntersect([[1, 2], [3, 4]], [[3, 4], [5, 6]])"],seealso:["setUnion","setDifference"]};var UO={name:"setIsSubset",category:"Set",syntax:["setIsSubset(set1, set2)"],description:"Check whether a (multi)set is a subset of another (multi)set: every element of set1 is the element of set2. Multi-dimension arrays will be converted to single-dimension arrays before the operation.",examples:["setIsSubset([1, 2], [3, 4, 5, 6])","setIsSubset([3, 4], [3, 4, 5, 6])"],seealso:["setUnion","setIntersect","setDifference"]};var WO={name:"setMultiplicity",category:"Set",syntax:["setMultiplicity(element, set)"],description:"Count the multiplicity of an element in a multiset. A multi-dimension array will be converted to a single-dimension array before the operation.",examples:["setMultiplicity(1, [1, 2, 2, 4])","setMultiplicity(2, [1, 2, 2, 4])"],seealso:["setDistinct","setSize"]};var YO={name:"setPowerset",category:"Set",syntax:["setPowerset(set)"],description:"Create the powerset of a (multi)set: the powerset contains very possible subsets of a (multi)set. A multi-dimension array will be converted to a single-dimension array before the operation.",examples:["setPowerset([1, 2, 3])"],seealso:["setCartesian"]};var HO={name:"setSize",category:"Set",syntax:["setSize(set)","setSize(set, unique)"],description:'Count the number of elements of a (multi)set. When the second parameter "unique" is true, count only the unique values. A multi-dimension array will be converted to a single-dimension array before the operation.',examples:["setSize([1, 2, 2, 4])","setSize([1, 2, 2, 4], true)"],seealso:["setUnion","setIntersect","setDifference"]};var $O={name:"setSymDifference",category:"Set",syntax:["setSymDifference(set1, set2)"],description:"Create the symmetric difference of two (multi)sets. Multi-dimension arrays will be converted to single-dimension arrays before the operation.",examples:["setSymDifference([1, 2, 3, 4], [3, 4, 5, 6])","setSymDifference([[1, 2], [3, 4]], [[3, 4], [5, 6]])"],seealso:["setUnion","setIntersect","setDifference"]};var GO={name:"setUnion",category:"Set",syntax:["setUnion(set1, set2)"],description:"Create the union of two (multi)sets. Multi-dimension arrays will be converted to single-dimension arrays before the operation.",examples:["setUnion([1, 2, 3, 4], [3, 4, 5, 6])","setUnion([[1, 2], [3, 4]], [[3, 4], [5, 6]])"],seealso:["setIntersect","setDifference"]};var VO={name:"zpk2tf",category:"Signal",syntax:["zpk2tf(z, p, k)"],description:"Compute the transfer function of a zero-pole-gain model.",examples:["zpk2tf([1, 2], [-1, -2], 1)","zpk2tf([1, 2], [-1, -2])","zpk2tf([1 - 3i, 2 + 2i], [-1, -2])"],seealso:[]};var ZO={name:"freqz",category:"Signal",syntax:["freqz(b, a)","freqz(b, a, w)"],description:"Calculates the frequency response of a filter given its numerator and denominator coefficients.",examples:["freqz([1, 2], [1, 2, 3])","freqz([1, 2], [1, 2, 3], [0, 1])","freqz([1, 2], [1, 2, 3], 512)"],seealso:[]};var QO={name:"erf",category:"Special",syntax:["erf(x)"],description:"Compute the erf function of a value using a rational Chebyshev approximations for different intervals of x",examples:["erf(0.2)","erf(-0.5)","erf(4)"],seealso:[]};var XO={name:"zeta",category:"Special",syntax:["zeta(s)"],description:"Compute the Riemann Zeta Function using an infinite series and Riemanns Functional Equation for the entire complex plane",examples:["zeta(0.2)","zeta(-0.5)","zeta(4)"],seealso:[]};var JO={name:"mad",category:"Statistics",syntax:["mad(a, b, c, ...)","mad(A)"],description:"Compute the median absolute deviation of a matrix or a list with values. The median absolute deviation is defined as the median of the absolute deviations from the median.",examples:["mad(10, 20, 30)","mad([1, 2, 3])"],seealso:["mean","median","std","abs"]};var KO={name:"max",category:"Statistics",syntax:["max(a, b, c, ...)","max(A)","max(A, dimension)"],description:"Compute the maximum value of a list of values.",examples:["max(2, 3, 4, 1)","max([2, 3, 4, 1])","max([2, 5; 4, 3])","max([2, 5; 4, 3], 1)","max([2, 5; 4, 3], 2)","max(2.7, 7.1, -4.5, 2.0, 4.1)","min(2.7, 7.1, -4.5, 2.0, 4.1)"],seealso:["mean","median","min","prod","std","sum","variance"]};var jO={name:"mean",category:"Statistics",syntax:["mean(a, b, c, ...)","mean(A)","mean(A, dimension)"],description:"Compute the arithmetic mean of a list of values.",examples:["mean(2, 3, 4, 1)","mean([2, 3, 4, 1])","mean([2, 5; 4, 3])","mean([2, 5; 4, 3], 1)","mean([2, 5; 4, 3], 2)","mean([1.0, 2.7, 3.2, 4.0])"],seealso:["max","median","min","prod","std","sum","variance"]};var e3={name:"median",category:"Statistics",syntax:["median(a, b, c, ...)","median(A)"],description:"Compute the median of all values. The values are sorted and the middle value is returned. In case of an even number of values, the average of the two middle values is returned.",examples:["median(5, 2, 7)","median([3, -1, 5, 7])"],seealso:["max","mean","min","prod","std","sum","variance","quantileSeq"]};var r3={name:"min",category:"Statistics",syntax:["min(a, b, c, ...)","min(A)","min(A, dimension)"],description:"Compute the minimum value of a list of values.",examples:["min(2, 3, 4, 1)","min([2, 3, 4, 1])","min([2, 5; 4, 3])","min([2, 5; 4, 3], 1)","min([2, 5; 4, 3], 2)","min(2.7, 7.1, -4.5, 2.0, 4.1)","max(2.7, 7.1, -4.5, 2.0, 4.1)"],seealso:["max","mean","median","prod","std","sum","variance"]};var t3={name:"mode",category:"Statistics",syntax:["mode(a, b, c, ...)","mode(A)","mode(A, a, b, B, c, ...)"],description:"Computes the mode of all values as an array. In case mode being more than one, multiple values are returned in an array.",examples:["mode(2, 1, 4, 3, 1)","mode([1, 2.7, 3.2, 4, 2.7])","mode(1, 4, 6, 1, 6)"],seealso:["max","mean","min","median","prod","std","sum","variance"]};var n3={name:"prod",category:"Statistics",syntax:["prod(a, b, c, ...)","prod(A)"],description:"Compute the product of all values.",examples:["prod(2, 3, 4)","prod([2, 3, 4])","prod([2, 5; 4, 3])"],seealso:["max","mean","min","median","min","std","sum","variance"]};var a3={name:"quantileSeq",category:"Statistics",syntax:["quantileSeq(A, prob[, sorted])","quantileSeq(A, [prob1, prob2, ...][, sorted])","quantileSeq(A, N[, sorted])"],description:\`Compute the prob order quantile of a matrix or a list with values. The sequence is sorted and the middle value is returned. Supported types of sequence values are: Number, BigNumber, Unit Supported types of probablity are: Number, BigNumber. - -In case of a (multi dimensional) array or matrix, the prob order quantile of all elements will be calculated.\`,examples:["quantileSeq([3, -1, 5, 7], 0.5)","quantileSeq([3, -1, 5, 7], [1/3, 2/3])","quantileSeq([3, -1, 5, 7], 2)","quantileSeq([-1, 3, 5, 7], 0.5, true)"],seealso:["mean","median","min","max","prod","std","sum","variance"]};var i3={name:"std",category:"Statistics",syntax:["std(a, b, c, ...)","std(A)","std(A, dimension)","std(A, normalization)","std(A, dimension, normalization)"],description:'Compute the standard deviation of all values, defined as std(A) = sqrt(variance(A)). Optional parameter normalization can be "unbiased" (default), "uncorrected", or "biased".',examples:["std(2, 4, 6)","std([2, 4, 6, 8])",'std([2, 4, 6, 8], "uncorrected")','std([2, 4, 6, 8], "biased")',"std([1, 2, 3; 4, 5, 6])"],seealso:["max","mean","min","median","prod","sum","variance"]};var o3={name:"cumsum",category:"Statistics",syntax:["cumsum(a, b, c, ...)","cumsum(A)"],description:"Compute the cumulative sum of all values.",examples:["cumsum(2, 3, 4, 1)","cumsum([2, 3, 4, 1])","cumsum([1, 2; 3, 4])","cumsum([1, 2; 3, 4], 1)","cumsum([1, 2; 3, 4], 2)"],seealso:["max","mean","median","min","prod","std","sum","variance"]};var s3={name:"sum",category:"Statistics",syntax:["sum(a, b, c, ...)","sum(A)","sum(A, dimension)"],description:"Compute the sum of all values.",examples:["sum(2, 3, 4, 1)","sum([2, 3, 4, 1])","sum([2, 5; 4, 3])"],seealso:["max","mean","median","min","prod","std","sum","variance"]};var u3={name:"variance",category:"Statistics",syntax:["variance(a, b, c, ...)","variance(A)","variance(A, dimension)","variance(A, normalization)","variance(A, dimension, normalization)"],description:'Compute the variance of all values. Optional parameter normalization can be "unbiased" (default), "uncorrected", or "biased".',examples:["variance(2, 4, 6)","variance([2, 4, 6, 8])",'variance([2, 4, 6, 8], "uncorrected")','variance([2, 4, 6, 8], "biased")',"variance([1, 2, 3; 4, 5, 6])"],seealso:["max","mean","min","median","min","prod","std","sum"]};var f3={name:"corr",category:"Statistics",syntax:["corr(A,B)"],description:"Compute the correlation coefficient of a two list with values, For matrices, the matrix correlation coefficient is calculated.",examples:["corr([2, 4, 6, 8],[1, 2, 3, 6])","corr(matrix([[1, 2.2, 3, 4.8, 5], [1, 2, 3, 4, 5]]), matrix([[4, 5.3, 6.6, 7, 8], [1, 2, 3, 4, 5]]))"],seealso:["max","mean","min","median","min","prod","std","sum"]};var c3={name:"acos",category:"Trigonometry",syntax:["acos(x)"],description:"Compute the inverse cosine of a value in radians.",examples:["acos(0.5)","acos(cos(2.3))"],seealso:["cos","atan","asin"]};var l3={name:"acosh",category:"Trigonometry",syntax:["acosh(x)"],description:"Calculate the hyperbolic arccos of a value, defined as \`acosh(x) = ln(sqrt(x^2 - 1) + x)\`.",examples:["acosh(1.5)"],seealso:["cosh","asinh","atanh"]};var m3={name:"acot",category:"Trigonometry",syntax:["acot(x)"],description:"Calculate the inverse cotangent of a value.",examples:["acot(0.5)","acot(cot(0.5))","acot(2)"],seealso:["cot","atan"]};var p3={name:"acoth",category:"Trigonometry",syntax:["acoth(x)"],description:"Calculate the hyperbolic arccotangent of a value, defined as \`acoth(x) = (ln((x+1)/x) + ln(x/(x-1))) / 2\`.",examples:["acoth(2)","acoth(0.5)"],seealso:["acsch","asech"]};var d3={name:"acsc",category:"Trigonometry",syntax:["acsc(x)"],description:"Calculate the inverse cotangent of a value.",examples:["acsc(2)","acsc(csc(0.5))","acsc(0.5)"],seealso:["csc","asin","asec"]};var h3={name:"acsch",category:"Trigonometry",syntax:["acsch(x)"],description:"Calculate the hyperbolic arccosecant of a value, defined as \`acsch(x) = ln(1/x + sqrt(1/x^2 + 1))\`.",examples:["acsch(0.5)"],seealso:["asech","acoth"]};var v3={name:"asec",category:"Trigonometry",syntax:["asec(x)"],description:"Calculate the inverse secant of a value.",examples:["asec(0.5)","asec(sec(0.5))","asec(2)"],seealso:["acos","acot","acsc"]};var g3={name:"asech",category:"Trigonometry",syntax:["asech(x)"],description:"Calculate the inverse secant of a value.",examples:["asech(0.5)"],seealso:["acsch","acoth"]};var x3={name:"asin",category:"Trigonometry",syntax:["asin(x)"],description:"Compute the inverse sine of a value in radians.",examples:["asin(0.5)","asin(sin(0.5))"],seealso:["sin","acos","atan"]};var y3={name:"asinh",category:"Trigonometry",syntax:["asinh(x)"],description:"Calculate the hyperbolic arcsine of a value, defined as \`asinh(x) = ln(x + sqrt(x^2 + 1))\`.",examples:["asinh(0.5)"],seealso:["acosh","atanh"]};var b3={name:"atan",category:"Trigonometry",syntax:["atan(x)"],description:"Compute the inverse tangent of a value in radians.",examples:["atan(0.5)","atan(tan(0.5))"],seealso:["tan","acos","asin"]};var w3={name:"atan2",category:"Trigonometry",syntax:["atan2(y, x)"],description:"Computes the principal value of the arc tangent of y/x in radians.",examples:["atan2(2, 2) / pi","angle = 60 deg in rad","x = cos(angle)","y = sin(angle)","atan2(y, x)"],seealso:["sin","cos","tan"]};var D3={name:"atanh",category:"Trigonometry",syntax:["atanh(x)"],description:"Calculate the hyperbolic arctangent of a value, defined as \`atanh(x) = ln((1 + x)/(1 - x)) / 2\`.",examples:["atanh(0.5)"],seealso:["acosh","asinh"]};var S3={name:"cos",category:"Trigonometry",syntax:["cos(x)"],description:"Compute the cosine of x in radians.",examples:["cos(2)","cos(pi / 4) ^ 2","cos(180 deg)","cos(60 deg)","sin(0.2)^2 + cos(0.2)^2"],seealso:["acos","sin","tan"]};var N3={name:"cosh",category:"Trigonometry",syntax:["cosh(x)"],description:"Compute the hyperbolic cosine of x in radians.",examples:["cosh(0.5)"],seealso:["sinh","tanh","coth"]};var A3={name:"cot",category:"Trigonometry",syntax:["cot(x)"],description:"Compute the cotangent of x in radians. Defined as 1/tan(x)",examples:["cot(2)","1 / tan(2)"],seealso:["sec","csc","tan"]};var M3={name:"coth",category:"Trigonometry",syntax:["coth(x)"],description:"Compute the hyperbolic cotangent of x in radians.",examples:["coth(2)","1 / tanh(2)"],seealso:["sech","csch","tanh"]};var C3={name:"csc",category:"Trigonometry",syntax:["csc(x)"],description:"Compute the cosecant of x in radians. Defined as 1/sin(x)",examples:["csc(2)","1 / sin(2)"],seealso:["sec","cot","sin"]};var E3={name:"csch",category:"Trigonometry",syntax:["csch(x)"],description:"Compute the hyperbolic cosecant of x in radians. Defined as 1/sinh(x)",examples:["csch(2)","1 / sinh(2)"],seealso:["sech","coth","sinh"]};var T3={name:"sec",category:"Trigonometry",syntax:["sec(x)"],description:"Compute the secant of x in radians. Defined as 1/cos(x)",examples:["sec(2)","1 / cos(2)"],seealso:["cot","csc","cos"]};var F3={name:"sech",category:"Trigonometry",syntax:["sech(x)"],description:"Compute the hyperbolic secant of x in radians. Defined as 1/cosh(x)",examples:["sech(2)","1 / cosh(2)"],seealso:["coth","csch","cosh"]};var _3={name:"sin",category:"Trigonometry",syntax:["sin(x)"],description:"Compute the sine of x in radians.",examples:["sin(2)","sin(pi / 4) ^ 2","sin(90 deg)","sin(30 deg)","sin(0.2)^2 + cos(0.2)^2"],seealso:["asin","cos","tan"]};var O3={name:"sinh",category:"Trigonometry",syntax:["sinh(x)"],description:"Compute the hyperbolic sine of x in radians.",examples:["sinh(0.5)"],seealso:["cosh","tanh"]};var B3={name:"tan",category:"Trigonometry",syntax:["tan(x)"],description:"Compute the tangent of x in radians.",examples:["tan(0.5)","sin(0.5) / cos(0.5)","tan(pi / 4)","tan(45 deg)"],seealso:["atan","sin","cos"]};var P3={name:"tanh",category:"Trigonometry",syntax:["tanh(x)"],description:"Compute the hyperbolic tangent of x in radians.",examples:["tanh(0.5)","sinh(0.5) / cosh(0.5)"],seealso:["sinh","cosh"]};var I3={name:"to",category:"Units",syntax:["x to unit","to(x, unit)"],description:"Change the unit of a value.",examples:["5 inch to cm","3.2kg to g","16 bytes in bits"],seealso:[]};var R3={name:"bin",category:"Utils",syntax:["bin(value)"],description:"Format a number as binary",examples:["bin(2)"],seealso:["oct","hex"]};var k3={name:"clone",category:"Utils",syntax:["clone(x)"],description:"Clone a variable. Creates a copy of primitive variables,and a deep copy of matrices",examples:["clone(3.5)","clone(2 - 4i)","clone(45 deg)","clone([1, 2; 3, 4])",'clone("hello world")'],seealso:[]};var q3={name:"format",category:"Utils",syntax:["format(value)","format(value, precision)"],description:"Format a value of any type as string.",examples:["format(2.3)","format(3 - 4i)","format([])","format(pi, 3)"],seealso:["print"]};var L3={name:"hasNumericValue",category:"Utils",syntax:["hasNumericValue(x)"],description:"Test whether a value is an numeric value. In case of a string, true is returned if the string contains a numeric value.",examples:["hasNumericValue(2)",'hasNumericValue("2")','isNumeric("2")',"hasNumericValue(0)","hasNumericValue(bignumber(500))","hasNumericValue(fraction(0.125))","hasNumericValue(2 + 3i)",'hasNumericValue([2.3, "foo", false])'],seealso:["isInteger","isZero","isNegative","isPositive","isNaN","isNumeric"]};var z3={name:"hex",category:"Utils",syntax:["hex(value)"],description:"Format a number as hexadecimal",examples:["hex(240)"],seealso:["bin","oct"]};var U3={name:"isInteger",category:"Utils",syntax:["isInteger(x)"],description:"Test whether a value is an integer number.",examples:["isInteger(2)","isInteger(3.5)","isInteger([3, 0.5, -2])"],seealso:["isNegative","isNumeric","isPositive","isZero"]};var W3={name:"isNaN",category:"Utils",syntax:["isNaN(x)"],description:"Test whether a value is NaN (not a number)",examples:["isNaN(2)","isNaN(0 / 0)","isNaN(NaN)","isNaN(Infinity)"],seealso:["isNegative","isNumeric","isPositive","isZero"]};var Y3={name:"isNegative",category:"Utils",syntax:["isNegative(x)"],description:"Test whether a value is negative: smaller than zero.",examples:["isNegative(2)","isNegative(0)","isNegative(-4)","isNegative([3, 0.5, -2])"],seealso:["isInteger","isNumeric","isPositive","isZero"]};var H3={name:"isNumeric",category:"Utils",syntax:["isNumeric(x)"],description:"Test whether a value is a numeric value. Returns true when the input is a number, BigNumber, Fraction, or boolean.",examples:["isNumeric(2)",'isNumeric("2")','hasNumericValue("2")',"isNumeric(0)","isNumeric(bignumber(500))","isNumeric(fraction(0.125))","isNumeric(2 + 3i)",'isNumeric([2.3, "foo", false])'],seealso:["isInteger","isZero","isNegative","isPositive","isNaN","hasNumericValue"]};var $3={name:"isPositive",category:"Utils",syntax:["isPositive(x)"],description:"Test whether a value is positive: larger than zero.",examples:["isPositive(2)","isPositive(0)","isPositive(-4)","isPositive([3, 0.5, -2])"],seealso:["isInteger","isNumeric","isNegative","isZero"]};var G3={name:"isPrime",category:"Utils",syntax:["isPrime(x)"],description:"Test whether a value is prime: has no divisors other than itself and one.",examples:["isPrime(3)","isPrime(-2)","isPrime([2, 17, 100])"],seealso:["isInteger","isNumeric","isNegative","isZero"]};var V3={name:"isZero",category:"Utils",syntax:["isZero(x)"],description:"Test whether a value is zero.",examples:["isZero(2)","isZero(0)","isZero(-4)","isZero([3, 0, -2, 0])"],seealso:["isInteger","isNumeric","isNegative","isPositive"]};var Z3={name:"numeric",category:"Utils",syntax:["numeric(x)"],description:"Convert a numeric input to a specific numeric type: number, BigNumber, or Fraction.",examples:['numeric("4")','numeric("4", "number")','numeric("4", "BigNumber")','numeric("4", "Fraction")','numeric(4, "Fraction")','numeric(fraction(2, 5), "number")'],seealso:["number","fraction","bignumber","string","format"]};var Q3={name:"oct",category:"Utils",syntax:["oct(value)"],description:"Format a number as octal",examples:["oct(56)"],seealso:["bin","hex"]};var X3={name:"print",category:"Utils",syntax:["print(template, values)","print(template, values, precision)"],description:"Interpolate values into a string template.",examples:['print("Lucy is $age years old", {age: 5})','print("The value of pi is $pi", {pi: pi}, 3)','print("Hello, $user.name!", {user: {name: "John"}})','print("Values: $1, $2, $3", [6, 9, 4])'],seealso:["format"]};var J3={name:"typeOf",category:"Utils",syntax:["typeOf(x)"],description:"Get the type of a variable.",examples:["typeOf(3.5)","typeOf(2 - 4i)","typeOf(45 deg)",'typeOf("hello world")'],seealso:["getMatrixDataType"]};var K3={name:"solveODE",category:"Numeric",syntax:["solveODE(func, tspan, y0)","solveODE(func, tspan, y0, options)"],description:"Numerical Integration of Ordinary Differential Equations.",examples:["f(t,y) = y","tspan = [0, 4]","solveODE(f, tspan, 1)","solveODE(f, tspan, [1, 2])",'solveODE(f, tspan, 1, { method:"RK23", maxStep:0.1 })'],seealso:["derivative","simplifyCore"]};var j3={bignumber:YT,boolean:HT,complex:$T,createUnit:GT,fraction:VT,index:ZT,matrix:QT,number:XT,sparse:JT,splitUnit:KT,string:jT,unit:eF,e:DD,E:DD,false:ET,i:TT,Infinity:FT,LN2:OT,LN10:_T,LOG2E:PT,LOG10E:BT,NaN:IT,null:RT,pi:SD,PI:SD,phi:kT,SQRT1_2:qT,SQRT2:LT,tau:zT,true:UT,version:WT,speedOfLight:{description:"Speed of light in vacuum",examples:["speedOfLight"]},gravitationConstant:{description:"Newtonian constant of gravitation",examples:["gravitationConstant"]},planckConstant:{description:"Planck constant",examples:["planckConstant"]},reducedPlanckConstant:{description:"Reduced Planck constant",examples:["reducedPlanckConstant"]},magneticConstant:{description:"Magnetic constant (vacuum permeability)",examples:["magneticConstant"]},electricConstant:{description:"Electric constant (vacuum permeability)",examples:["electricConstant"]},vacuumImpedance:{description:"Characteristic impedance of vacuum",examples:["vacuumImpedance"]},coulomb:{description:"Coulomb's constant",examples:["coulomb"]},elementaryCharge:{description:"Elementary charge",examples:["elementaryCharge"]},bohrMagneton:{description:"Borh magneton",examples:["bohrMagneton"]},conductanceQuantum:{description:"Conductance quantum",examples:["conductanceQuantum"]},inverseConductanceQuantum:{description:"Inverse conductance quantum",examples:["inverseConductanceQuantum"]},magneticFluxQuantum:{description:"Magnetic flux quantum",examples:["magneticFluxQuantum"]},nuclearMagneton:{description:"Nuclear magneton",examples:["nuclearMagneton"]},klitzing:{description:"Von Klitzing constant",examples:["klitzing"]},bohrRadius:{description:"Borh radius",examples:["bohrRadius"]},classicalElectronRadius:{description:"Classical electron radius",examples:["classicalElectronRadius"]},electronMass:{description:"Electron mass",examples:["electronMass"]},fermiCoupling:{description:"Fermi coupling constant",examples:["fermiCoupling"]},fineStructure:{description:"Fine-structure constant",examples:["fineStructure"]},hartreeEnergy:{description:"Hartree energy",examples:["hartreeEnergy"]},protonMass:{description:"Proton mass",examples:["protonMass"]},deuteronMass:{description:"Deuteron Mass",examples:["deuteronMass"]},neutronMass:{description:"Neutron mass",examples:["neutronMass"]},quantumOfCirculation:{description:"Quantum of circulation",examples:["quantumOfCirculation"]},rydberg:{description:"Rydberg constant",examples:["rydberg"]},thomsonCrossSection:{description:"Thomson cross section",examples:["thomsonCrossSection"]},weakMixingAngle:{description:"Weak mixing angle",examples:["weakMixingAngle"]},efimovFactor:{description:"Efimov factor",examples:["efimovFactor"]},atomicMass:{description:"Atomic mass constant",examples:["atomicMass"]},avogadro:{description:"Avogadro's number",examples:["avogadro"]},boltzmann:{description:"Boltzmann constant",examples:["boltzmann"]},faraday:{description:"Faraday constant",examples:["faraday"]},firstRadiation:{description:"First radiation constant",examples:["firstRadiation"]},loschmidt:{description:"Loschmidt constant at T=273.15 K and p=101.325 kPa",examples:["loschmidt"]},gasConstant:{description:"Gas constant",examples:["gasConstant"]},molarPlanckConstant:{description:"Molar Planck constant",examples:["molarPlanckConstant"]},molarVolume:{description:"Molar volume of an ideal gas at T=273.15 K and p=101.325 kPa",examples:["molarVolume"]},sackurTetrode:{description:"Sackur-Tetrode constant at T=1 K and p=101.325 kPa",examples:["sackurTetrode"]},secondRadiation:{description:"Second radiation constant",examples:["secondRadiation"]},stefanBoltzmann:{description:"Stefan-Boltzmann constant",examples:["stefanBoltzmann"]},wienDisplacement:{description:"Wien displacement law constant",examples:["wienDisplacement"]},molarMass:{description:"Molar mass constant",examples:["molarMass"]},molarMassC12:{description:"Molar mass constant of carbon-12",examples:["molarMassC12"]},gravity:{description:"Standard acceleration of gravity (standard acceleration of free-fall on Earth)",examples:["gravity"]},planckLength:{description:"Planck length",examples:["planckLength"]},planckMass:{description:"Planck mass",examples:["planckMass"]},planckTime:{description:"Planck time",examples:["planckTime"]},planckCharge:{description:"Planck charge",examples:["planckCharge"]},planckTemperature:{description:"Planck temperature",examples:["planckTemperature"]},derivative:aF,lsolve:oF,lsolveAll:sF,lup:uF,lusolve:fF,leafCount:iF,polynomialRoot:cF,resolve:pF,simplify:dF,simplifyConstant:hF,simplifyCore:vF,symbolicEqual:xF,rationalize:mF,slu:gF,usolve:yF,usolveAll:bF,qr:lF,abs:wF,add:DF,cbrt:SF,ceil:NF,cube:AF,divide:MF,dotDivide:CF,dotMultiply:EF,dotPow:TF,exp:FF,expm:_F,expm1:OF,fix:BF,floor:PF,gcd:IF,hypot:RF,lcm:qF,log:LF,log2:WF,log1p:UF,log10:zF,mod:YF,multiply:HF,norm:$F,nthRoot:GF,nthRoots:VF,pow:ZF,round:QF,sign:XF,sqrt:JF,sqrtm:KF,square:t_,subtract:n_,unaryMinus:a_,unaryPlus:i_,xgcd:o_,invmod:kF,bitAnd:s_,bitNot:u_,bitOr:f_,bitXor:c_,leftShift:l_,rightArithShift:m_,rightLogShift:p_,bellNumbers:d_,catalan:h_,composition:v_,stirlingS2:g_,config:rF,import:tF,typed:nF,arg:x_,conj:y_,re:w_,im:b_,evaluate:D_,help:S_,distance:N_,intersect:A_,and:M_,not:C_,or:E_,xor:T_,concat:__,count:O_,cross:B_,column:F_,ctranspose:P_,det:I_,diag:R_,diff:k_,dot:q_,getMatrixDataType:Y_,identity:H_,filter:z_,flatten:U_,forEach:W_,inv:$_,pinv:G_,eigs:L_,kron:V_,matrixFromFunction:X_,matrixFromRows:J_,matrixFromColumns:Q_,map:Z_,ones:K_,partitionSelect:j_,range:eO,resize:tO,reshape:rO,rotate:nO,rotationMatrix:aO,row:iO,size:oO,sort:sO,squeeze:uO,subset:fO,trace:cO,transpose:lO,zeros:mO,fft:pO,ifft:dO,sylvester:jF,schur:e_,lyap:r_,solveODE:K3,combinations:hO,combinationsWithRep:vO,factorial:gO,gamma:xO,kldivergence:bO,lgamma:yO,multinomial:wO,permutations:DO,pickRandom:SO,random:NO,randomInt:AO,compare:MO,compareNatural:CO,compareText:EO,deepEqual:TO,equal:FO,equalText:_O,larger:OO,largerEq:BO,smaller:PO,smallerEq:IO,unequal:RO,setCartesian:kO,setDifference:qO,setDistinct:LO,setIntersect:zO,setIsSubset:UO,setMultiplicity:WO,setPowerset:YO,setSize:HO,setSymDifference:$O,setUnion:GO,zpk2tf:VO,freqz:ZO,erf:QO,zeta:XO,cumsum:o3,mad:JO,max:KO,mean:jO,median:e3,min:r3,mode:t3,prod:n3,quantileSeq:a3,std:i3,sum:s3,variance:u3,corr:f3,acos:c3,acosh:l3,acot:m3,acoth:p3,acsc:d3,acsch:h3,asec:v3,asech:g3,asin:x3,asinh:y3,atan:b3,atanh:D3,atan2:w3,cos:S3,cosh:N3,cot:A3,coth:M3,csc:C3,csch:E3,sec:T3,sech:F3,sin:_3,sinh:O3,tan:B3,tanh:P3,to:I3,clone:k3,format:q3,bin:R3,oct:Q3,hex:z3,isNaN:W3,isInteger:U3,isNegative:Y3,isNumeric:H3,hasNumericValue:L3,isPositive:$3,isPrime:G3,isZero:V3,print:X3,typeOf:J3,numeric:Z3};var eB="help",xG=["typed","mathWithTransform","Help"],hg=F(eB,xG,e=>{var{typed:r,mathWithTransform:t,Help:n}=e;return r(eB,{any:function(i){var u,l=i;if(typeof i!="string"){for(u in t)if(Xe(t,u)&&i===t[u]){l=u;break}}var c=wt(j3,l);if(!c){var o=typeof l=="function"?l.name:l;throw new Error('No documentation found on "'+o+'"')}return new n(c)}})});var rB="chain",yG=["typed","Chain"],vg=F(rB,yG,e=>{var{typed:r,Chain:t}=e;return r(rB,{"":function(){return new t},any:function(a){return new t(a)}})});var tB="det",bG=["typed","matrix","subtractScalar","multiply","divideScalar","isZero","unaryMinus"],gg=F(tB,bG,e=>{var{typed:r,matrix:t,subtractScalar:n,multiply:a,divideScalar:i,isZero:u,unaryMinus:l}=e;return r(tB,{any:function(s){return ar(s)},"Array | Matrix":function(s){var m;switch(Qe(s)?m=s.size():Array.isArray(s)?(s=t(s),m=s.size()):m=[],m.length){case 0:return ar(s);case 1:if(m[0]===1)return ar(s.valueOf()[0]);if(m[0]===0)return 1;throw new RangeError("Matrix must be square (size: "+lr(m)+")");case 2:{var d=m[0],h=m[1];if(d===h)return c(s.clone().valueOf(),d,h);if(h===0)return 1;throw new RangeError("Matrix must be square (size: "+lr(m)+")")}default:throw new RangeError("Matrix must be two dimensional (size: "+lr(m)+")")}}});function c(o,s,m){if(s===1)return ar(o[0][0]);if(s===2)return n(a(o[0][0],o[1][1]),a(o[1][0],o[0][1]));for(var d=!1,h=new Array(s).fill(0).map((O,_)=>_),x=0;x{var{typed:r,matrix:t,divideScalar:n,addScalar:a,multiply:i,unaryMinus:u,det:l,identity:c,abs:o}=e;return r(nB,{"Array | Matrix":function(d){var h=Qe(d)?d.size():ur(d);switch(h.length){case 1:if(h[0]===1)return Qe(d)?t([n(1,d.valueOf()[0])]):[n(1,d[0])];throw new RangeError("Matrix must be square (size: "+lr(h)+")");case 2:{var x=h[0],v=h[1];if(x===v)return Qe(d)?t(s(d.valueOf(),x,v),d.storage()):s(d,x,v);throw new RangeError("Matrix must be square (size: "+lr(h)+")")}default:throw new RangeError("Matrix must be two dimensional (size: "+lr(h)+")")}},any:function(d){return n(1,d)}});function s(m,d,h){var x,v,y,w,C;if(d===1){if(w=m[0][0],w===0)throw Error("Cannot calculate inverse, determinant is zero");return[[n(1,w)]]}else if(d===2){var b=l(m);if(b===0)throw Error("Cannot calculate inverse, determinant is zero");return[[n(m[1][1],b),n(u(m[0][1]),b)],[n(u(m[1][0]),b),n(m[0][0],b)]]}else{var M=m.concat();for(x=0;xO&&(O=o(M[x][S]),_=x),x++;if(O===0)throw Error("Cannot calculate inverse, determinant is zero");x=_,x!==S&&(C=M[S],M[S]=M[x],M[x]=C,C=A[S],A[S]=A[x],A[x]=C);var E=M[S],T=A[S];for(x=0;x{var{typed:r,matrix:t,inv:n,deepEqual:a,equal:i,dotDivide:u,dot:l,ctranspose:c,divideScalar:o,multiply:s,add:m,Complex:d}=e;return r(aB,{"Array | Matrix":function(b){var M=Qe(b)?b.size():ur(b);switch(M.length){case 1:return w(b)?c(b):M[0]===1?n(b):u(c(b),l(b,b));case 2:{if(w(b))return c(b);var A=M[0],S=M[1];if(A===S)try{return n(b)}catch(O){if(!(O instanceof Error&&O.message.match(/Cannot calculate inverse, determinant is zero/)))throw O}return Qe(b)?t(h(b.valueOf(),A,S),b.storage()):h(b,A,S)}default:throw new RangeError("Matrix must be two dimensional (size: "+lr(M)+")")}},any:function(b){return i(b,0)?ar(b):o(1,b)}});function h(C,b,M){var{C:A,F:S}=v(C,b,M),O=s(n(s(c(A),A)),c(A)),_=s(c(S),n(s(S,c(S))));return s(_,O)}function x(C,b,M){for(var A=ar(C),S=0,O=0;O_.filter((T,R)=>R!y(l(A[E],A[E])));return{C:S,F:O}}function y(C){return i(m(C,d(1,1)),m(0,d(1,1)))}function w(C){return a(m(C,d(1,1)),m(s(C,0),d(1,1)))}});function iB(e){var{addScalar:r,subtract:t,flatten:n,multiply:a,multiplyScalar:i,divideScalar:u,sqrt:l,abs:c,bignumber:o,diag:s,size:m,reshape:d,inv:h,qr:x,usolve:v,usolveAll:y,equal:w,complex:C,larger:b,smaller:M,matrixFromColumns:A,dot:S}=e;function O(ae,$,le,Ee){var me=arguments.length>4&&arguments[4]!==void 0?arguments[4]:!0,ge=_(ae,$,le,Ee,me);E(ae,$,le,Ee,me,ge);var{values:Se,C:xe}=T(ae,$,le,Ee,me);if(me){var be=R(ae,$,xe,ge,Se,le,Ee);return{values:Se,eigenvectors:be}}return{values:Se}}function _(ae,$,le,Ee,me){var ge=Ee==="BigNumber",Se=Ee==="Complex",xe=ge?o(0):0,be=ge?o(1):Se?C(1):1,De=ge?o(1):1,Ae=ge?o(10):2,We=i(Ae,Ae),Je;me&&(Je=Array($).fill(be));for(var J=!1;!J;){J=!0;for(var re=0;re<$;re++){for(var ye=xe,j=xe,ne=0;ne<$;ne++)re!==ne&&(ye=r(ye,c(ae[ne][re])),j=r(j,c(ae[re][ne])));if(!w(ye,0)&&!w(j,0)){for(var ue=De,Me=ye,Ce=u(j,Ae),Le=i(j,Ae);M(Me,Ce);)Me=i(Me,We),ue=i(ue,Ae);for(;b(Me,Le);)Me=u(Me,We),ue=u(ue,Ae);var Ie=M(u(r(Me,j),ue),i(r(ye,j),.95));if(Ie){J=!1;for(var fr=u(1,ue),or=0;or<$;or++)re!==or&&(ae[re][or]=i(ae[re][or],fr),ae[or][re]=i(ae[or][re],ue));me&&(Je[re]=i(Je[re],fr))}}}}return me?s(Je):null}function E(ae,$,le,Ee,me,ge){var Se=Ee==="BigNumber",xe=Ee==="Complex",be=Se?o(0):xe?C(0):0;Se&&(le=o(le));for(var De=0;De<$-2;De++){for(var Ae=0,We=be,Je=De+1;Je<$;Je++){var J=ae[Je][De];M(c(We),c(J))&&(We=J,Ae=Je)}if(!M(c(We),le)){if(Ae!==De+1){var re=ae[Ae];ae[Ae]=ae[De+1],ae[De+1]=re;for(var ye=0;ye<$;ye++){var j=ae[ye][Ae];ae[ye][Ae]=ae[ye][De+1],ae[ye][De+1]=j}if(me){var ne=ge[Ae];ge[Ae]=ge[De+1],ge[De+1]=ne}}for(var ue=De+2;ue<$;ue++){var Me=u(ae[ue][De],We);if(Me!==0){for(var Ce=0;Ce<$;Ce++)ae[ue][Ce]=t(ae[ue][Ce],i(Me,ae[De+1][Ce]));for(var Le=0;Le<$;Le++)ae[Le][De+1]=r(ae[Le][De+1],i(Me,ae[Le][ue]));if(me)for(var Ie=0;Ie<$;Ie++)ge[ue][Ie]=t(ge[ue][Ie],i(Me,ge[De+1][Ie]))}}}}return ge}function T(ae,$,le,Ee,me){var ge=Ee==="BigNumber",Se=Ee==="Complex",xe=ge?o(1):Se?C(1):1;ge&&(le=o(le));for(var be=ar(ae),De=[],Ae=$,We=[],Je=me?s(Array($).fill(xe)):void 0,J=me?s(Array(Ae).fill(xe)):void 0,re=0;re<=100;){re+=1;for(var ye=be[Ae-1][Ae-1],j=0;j1&&(J=s(Array(Ae-1).fill(xe)))),Ae-=1,be.pop();for(var Ce=0;Ce2&&(J=s(Array(Ae-2).fill(xe)))),Ae-=2,be.pop(),be.pop();for(var Ie=0;Ie+t(c(Ke),c(Pr))),re>100){var fr=Error("The eigenvalues failed to converge. Only found these eigenvalues: "+De.join(", "));throw fr.values=De,fr.vectors=[],fr}var or=me?a(Je,H(We,$)):void 0;return{values:De,C:or}}function R(ae,$,le,Ee,me,ge,Se){var xe=h(le),be=a(xe,ae,le),De=Se==="BigNumber",Ae=Se==="Complex",We=De?o(0):Ae?C(0):0,Je=De?o(1):Ae?C(1):1,J=[],re=[];for(var ye of me){var j=L(J,ye,w);j===-1?(J.push(ye),re.push(1)):re[j]+=1}for(var ne=[],ue=J.length,Me=Array($).fill(We),Ce=s(Array($).fill(Je)),Le=function(){var or=J[Ie],Ke=t(be,a(or,Ce)),Pr=y(Ke,Me);for(Pr.shift();Pr.lengtha(ce,we)),ne.push(...Pr.map(we=>({value:or,vector:n(we)})))},Ie=0;Ie=5)return null;for(xe=0;;){var be=v(ae,Se);if(M(oe(z(Se,[be])),Ee))break;if(++xe>=10)return null;Se=pe(be)}return Se}function K(ae,$,le){var Ee=le==="BigNumber",me=le==="Complex",ge=Array(ae).fill(0).map(Se=>2*Math.random()-1);return Ee&&(ge=ge.map(Se=>o(Se))),me&&(ge=ge.map(Se=>C(Se))),ge=z(ge,$),pe(ge,le)}function z(ae,$){var le=m(ae);for(var Ee of $)Ee=d(Ee,le),ae=t(ae,a(u(S(Ee,ae),S(Ee,Ee)),Ee));return ae}function oe(ae){return c(l(S(ae,ae)))}function pe(ae,$){var le=$==="BigNumber",Ee=$==="Complex",me=le?o(1):Ee?C(1):1;return a(u(me,oe(ae)),ae)}return O}function oB(e){var{config:r,addScalar:t,subtract:n,abs:a,atan:i,cos:u,sin:l,multiplyScalar:c,inv:o,bignumber:s,multiply:m,add:d}=e;function h(E,T){var R=arguments.length>2&&arguments[2]!==void 0?arguments[2]:r.epsilon,q=arguments.length>3?arguments[3]:void 0,W=arguments.length>4?arguments[4]:void 0;if(q==="number")return x(E,R,W);if(q==="BigNumber")return v(E,R,W);throw TypeError("Unsupported data type: "+q)}function x(E,T,R){var q=E.length,W=Math.abs(T/q),G,H;if(R){H=new Array(q);for(var L=0;L=Math.abs(W);){var K=k[0][0],z=k[0][1];G=y(E[K][K],E[z][z],E[K][z]),E=A(E,G,K,z),R&&(H=C(H,G,K,z)),k=S(E)}for(var oe=Array(q).fill(0),pe=0;pe=a(W);){var K=k[0][0],z=k[0][1];G=w(E[K][K],E[z][z],E[K][z]),E=M(E,G,K,z),R&&(H=b(H,G,K,z)),k=O(E)}for(var oe=Array(q).fill(0),pe=0;pe({value:W[$],vector:ae}));return{values:W,eigenvectors:pe}}return h}var SG="eigs",NG=["config","typed","matrix","addScalar","equal","subtract","abs","atan","cos","sin","multiplyScalar","divideScalar","inv","bignumber","multiply","add","larger","column","flatten","number","complex","sqrt","diag","size","reshape","qr","usolve","usolveAll","im","re","smaller","matrixFromColumns","dot"],bg=F(SG,NG,e=>{var{config:r,typed:t,matrix:n,addScalar:a,subtract:i,equal:u,abs:l,atan:c,cos:o,sin:s,multiplyScalar:m,divideScalar:d,inv:h,bignumber:x,multiply:v,add:y,larger:w,column:C,flatten:b,number:M,complex:A,sqrt:S,diag:O,size:_,reshape:E,qr:T,usolve:R,usolveAll:q,im:W,re:G,smaller:H,matrixFromColumns:L,dot:k}=e,K=oB({config:r,addScalar:a,subtract:i,column:C,flatten:b,equal:u,abs:l,atan:c,cos:o,sin:s,multiplyScalar:m,inv:h,bignumber:x,complex:A,multiply:v,add:y}),z=iB({config:r,addScalar:a,subtract:i,multiply:v,multiplyScalar:m,flatten:b,divideScalar:d,sqrt:S,abs:l,bignumber:x,diag:O,size:_,reshape:E,qr:T,inv:h,usolve:R,usolveAll:q,equal:u,complex:A,larger:w,smaller:H,matrixFromColumns:L,dot:k});return t("eigs",{Array:function(ge){return oe(n(ge))},"Array, number|BigNumber":function(ge,Se){return oe(n(ge),{precision:Se})},"Array, Object"(me,ge){return oe(n(me),ge)},Matrix:function(ge){return oe(ge,{matricize:!0})},"Matrix, number|BigNumber":function(ge,Se){return oe(ge,{precision:Se,matricize:!0})},"Matrix, Object":function(ge,Se){var xe={matricize:!0};return ht(xe,Se),oe(ge,xe)}});function oe(me){var ge,Se=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},xe="eigenvectors"in Se?Se.eigenvectors:!0,be=(ge=Se.precision)!==null&&ge!==void 0?ge:r.epsilon,De=pe(me,be,xe);return Se.matricize&&(De.values=n(De.values),xe&&(De.eigenvectors=De.eigenvectors.map(Ae=>{var{value:We,vector:Je}=Ae;return{value:We,vector:n(Je)}}))),xe&&Object.defineProperty(De,"vectors",{enumerable:!1,get:()=>{throw new Error("eigs(M).vectors replaced with eigs(M).eigenvectors")}}),De}function pe(me,ge,Se){var xe=me.toArray(),be=me.size();if(be.length!==2||be[0]!==be[1])throw new RangeError("Matrix must be square (size: ".concat(lr(be),")"));var De=be[0];if($(xe,De,ge)&&(le(xe,De),ae(xe,De,ge))){var Ae=Ee(me,xe,De);return K(xe,De,ge,Ae,Se)}var We=Ee(me,xe,De);return z(xe,De,ge,We,Se)}function ae(me,ge,Se){for(var xe=0;xe{var{typed:r,abs:t,add:n,identity:a,inv:i,multiply:u}=e;return r(sB,{Matrix:function(m){var d=m.size();if(d.length!==2||d[0]!==d[1])throw new RangeError("Matrix must be square (size: "+lr(d)+")");for(var h=d[0],x=1e-15,v=l(m),y=c(v,x),w=y.q,C=y.j,b=u(m,Math.pow(2,-C)),M=a(h),A=a(h),S=1,O=b,_=-1,E=1;E<=w;E++)E>1&&(O=u(O,b),_=-_),S=S*(w-E+1)/((2*w-E+1)*E),M=n(M,u(S,O)),A=n(A,u(S*_,O));for(var T=u(i(A),M),R=0;R{var{typed:r,abs:t,add:n,multiply:a,map:i,sqrt:u,subtract:l,inv:c,size:o,max:s,identity:m}=e,d=1e3,h=1e-6;function x(v){var y,w=0,C=v,b=m(o(v));do{var M=C;if(C=a(.5,n(M,c(b))),b=a(.5,n(b,c(M))),y=s(t(l(C,M))),y>h&&++w>d)throw new Error("computing square root of matrix: iterative method could not converge")}while(y>h);return C}return r(uB,{"Array | Matrix":function(y){var w=Qe(y)?y.size():ur(y);switch(w.length){case 1:if(w[0]===1)return i(y,u);throw new RangeError("Matrix must be square (size: "+lr(w)+")");case 2:{var C=w[0],b=w[1];if(C===b)return x(y);throw new RangeError("Matrix must be square (size: "+lr(w)+")")}default:throw new RangeError("Matrix must be at most two dimensional (size: "+lr(w)+")")}}})});var fB="sylvester",CG=["typed","schur","matrixFromColumns","matrix","multiply","range","concat","transpose","index","subset","add","subtract","identity","lusolve","abs"],Sg=F(fB,CG,e=>{var{typed:r,schur:t,matrixFromColumns:n,matrix:a,multiply:i,range:u,concat:l,transpose:c,index:o,subset:s,add:m,subtract:d,identity:h,lusolve:x,abs:v}=e;return r(fB,{"Matrix, Matrix, Matrix":y,"Array, Matrix, Matrix":function(C,b,M){return y(a(C),b,M)},"Array, Array, Matrix":function(C,b,M){return y(a(C),a(b),M)},"Array, Matrix, Array":function(C,b,M){return y(a(C),b,a(M))},"Matrix, Array, Matrix":function(C,b,M){return y(C,a(b),M)},"Matrix, Array, Array":function(C,b,M){return y(C,a(b),a(M))},"Matrix, Matrix, Array":function(C,b,M){return y(C,b,a(M))},"Array, Array, Array":function(C,b,M){return y(a(C),a(b),a(M)).toArray()}});function y(w,C,b){for(var M=C.size()[0],A=w.size()[0],S=t(w),O=S.T,_=S.U,E=t(i(-1,C)),T=E.T,R=E.U,q=i(i(c(_),b),R),W=u(0,A),G=[],H=(Ae,We)=>l(Ae,We,1),L=(Ae,We)=>l(Ae,We,0),k=0;k1e-5){for(var K=L(s(q,o(W,k)),s(q,o(W,k+1))),z=0;z{var{typed:r,matrix:t,identity:n,multiply:a,qr:i,norm:u,subtract:l}=e;return r(cB,{Array:function(s){var m=c(t(s));return{U:m.U.valueOf(),T:m.T.valueOf()}},Matrix:function(s){return c(s)}});function c(o){var s=o.size()[0],m=o,d=n(s),h=0,x;do{x=m;var v=i(m),y=v.Q,w=v.R;if(m=a(w,y),d=a(d,y),h++>100)break}while(u(l(m,x))>1e-4);return{U:d,T:m}}});var lB="lyap",TG=["typed","matrix","sylvester","multiply","transpose"],Ag=F(lB,TG,e=>{var{typed:r,matrix:t,sylvester:n,multiply:a,transpose:i}=e;return r(lB,{"Matrix, Matrix":function(l,c){return n(l,i(l),a(-1,c))},"Array, Matrix":function(l,c){return n(t(l),i(t(l)),a(-1,c))},"Matrix, Array":function(l,c){return n(l,i(t(l)),t(a(-1,c)))},"Array, Array":function(l,c){return n(t(l),i(t(l)),t(a(-1,c))).toArray()}})});var FG="divide",_G=["typed","matrix","multiply","equalScalar","divideScalar","inv"],Mg=F(FG,_G,e=>{var{typed:r,matrix:t,multiply:n,equalScalar:a,divideScalar:i,inv:u}=e,l=jr({typed:r,equalScalar:a}),c=qt({typed:r});return r("divide",Dm({"Array | Matrix, Array | Matrix":function(s,m){return n(s,u(m))},"DenseMatrix, any":function(s,m){return c(s,m,i,!1)},"SparseMatrix, any":function(s,m){return l(s,m,i,!1)},"Array, any":function(s,m){return c(t(s),m,i,!1).valueOf()},"any, Array | Matrix":function(s,m){return n(s,u(m))}},i.signatures))});var mB="distance",OG=["typed","addScalar","subtractScalar","divideScalar","multiplyScalar","deepEqual","sqrt","abs"],Cg=F(mB,OG,e=>{var{typed:r,addScalar:t,subtractScalar:n,multiplyScalar:a,divideScalar:i,deepEqual:u,sqrt:l,abs:c}=e;return r(mB,{"Array, Array, Array":function(A,S,O){if(A.length===2&&S.length===2&&O.length===2){if(!s(A))throw new TypeError("Array with 2 numbers or BigNumbers expected for first argument");if(!s(S))throw new TypeError("Array with 2 numbers or BigNumbers expected for second argument");if(!s(O))throw new TypeError("Array with 2 numbers or BigNumbers expected for third argument");if(u(S,O))throw new TypeError("LinePoint1 should not be same with LinePoint2");var _=n(O[1],S[1]),E=n(S[0],O[0]),T=n(a(O[0],S[1]),a(S[0],O[1]));return y(A[0],A[1],_,E,T)}else throw new TypeError("Invalid Arguments: Try again")},"Object, Object, Object":function(A,S,O){if(Object.keys(A).length===2&&Object.keys(S).length===2&&Object.keys(O).length===2){if(!s(A))throw new TypeError("Values of pointX and pointY should be numbers or BigNumbers");if(!s(S))throw new TypeError("Values of lineOnePtX and lineOnePtY should be numbers or BigNumbers");if(!s(O))throw new TypeError("Values of lineTwoPtX and lineTwoPtY should be numbers or BigNumbers");if(u(x(S),x(O)))throw new TypeError("LinePoint1 should not be same with LinePoint2");if("pointX"in A&&"pointY"in A&&"lineOnePtX"in S&&"lineOnePtY"in S&&"lineTwoPtX"in O&&"lineTwoPtY"in O){var _=n(O.lineTwoPtY,S.lineOnePtY),E=n(S.lineOnePtX,O.lineTwoPtX),T=n(a(O.lineTwoPtX,S.lineOnePtY),a(S.lineOnePtX,O.lineTwoPtY));return y(A.pointX,A.pointY,_,E,T)}else throw new TypeError("Key names do not match")}else throw new TypeError("Invalid Arguments: Try again")},"Array, Array":function(A,S){if(A.length===2&&S.length===3){if(!s(A))throw new TypeError("Array with 2 numbers or BigNumbers expected for first argument");if(!m(S))throw new TypeError("Array with 3 numbers or BigNumbers expected for second argument");return y(A[0],A[1],S[0],S[1],S[2])}else if(A.length===3&&S.length===6){if(!m(A))throw new TypeError("Array with 3 numbers or BigNumbers expected for first argument");if(!h(S))throw new TypeError("Array with 6 numbers or BigNumbers expected for second argument");return w(A[0],A[1],A[2],S[0],S[1],S[2],S[3],S[4],S[5])}else if(A.length===S.length&&A.length>0){if(!d(A))throw new TypeError("All values of an array should be numbers or BigNumbers");if(!d(S))throw new TypeError("All values of an array should be numbers or BigNumbers");return C(A,S)}else throw new TypeError("Invalid Arguments: Try again")},"Object, Object":function(A,S){if(Object.keys(A).length===2&&Object.keys(S).length===3){if(!s(A))throw new TypeError("Values of pointX and pointY should be numbers or BigNumbers");if(!m(S))throw new TypeError("Values of xCoeffLine, yCoeffLine and constant should be numbers or BigNumbers");if("pointX"in A&&"pointY"in A&&"xCoeffLine"in S&&"yCoeffLine"in S&&"constant"in S)return y(A.pointX,A.pointY,S.xCoeffLine,S.yCoeffLine,S.constant);throw new TypeError("Key names do not match")}else if(Object.keys(A).length===3&&Object.keys(S).length===6){if(!m(A))throw new TypeError("Values of pointX, pointY and pointZ should be numbers or BigNumbers");if(!h(S))throw new TypeError("Values of x0, y0, z0, a, b and c should be numbers or BigNumbers");if("pointX"in A&&"pointY"in A&&"x0"in S&&"y0"in S&&"z0"in S&&"a"in S&&"b"in S&&"c"in S)return w(A.pointX,A.pointY,A.pointZ,S.x0,S.y0,S.z0,S.a,S.b,S.c);throw new TypeError("Key names do not match")}else if(Object.keys(A).length===2&&Object.keys(S).length===2){if(!s(A))throw new TypeError("Values of pointOneX and pointOneY should be numbers or BigNumbers");if(!s(S))throw new TypeError("Values of pointTwoX and pointTwoY should be numbers or BigNumbers");if("pointOneX"in A&&"pointOneY"in A&&"pointTwoX"in S&&"pointTwoY"in S)return C([A.pointOneX,A.pointOneY],[S.pointTwoX,S.pointTwoY]);throw new TypeError("Key names do not match")}else if(Object.keys(A).length===3&&Object.keys(S).length===3){if(!m(A))throw new TypeError("Values of pointOneX, pointOneY and pointOneZ should be numbers or BigNumbers");if(!m(S))throw new TypeError("Values of pointTwoX, pointTwoY and pointTwoZ should be numbers or BigNumbers");if("pointOneX"in A&&"pointOneY"in A&&"pointOneZ"in A&&"pointTwoX"in S&&"pointTwoY"in S&&"pointTwoZ"in S)return C([A.pointOneX,A.pointOneY,A.pointOneZ],[S.pointTwoX,S.pointTwoY,S.pointTwoZ]);throw new TypeError("Key names do not match")}else throw new TypeError("Invalid Arguments: Try again")},Array:function(A){if(!v(A))throw new TypeError("Incorrect array format entered for pairwise distance calculation");return b(A)}});function o(M){return typeof M=="number"||rr(M)}function s(M){return M.constructor!==Array&&(M=x(M)),o(M[0])&&o(M[1])}function m(M){return M.constructor!==Array&&(M=x(M)),o(M[0])&&o(M[1])&&o(M[2])}function d(M){return Array.isArray(M)||(M=x(M)),M.every(o)}function h(M){return M.constructor!==Array&&(M=x(M)),o(M[0])&&o(M[1])&&o(M[2])&&o(M[3])&&o(M[4])&&o(M[5])}function x(M){for(var A=Object.keys(M),S=[],O=0;OA.length!==2||!o(A[0])||!o(A[1])))return!1}else if(M[0].length===3&&o(M[0][0])&&o(M[0][1])&&o(M[0][2])){if(M.some(A=>A.length!==3||!o(A[0])||!o(A[1])||!o(A[2])))return!1}else return!1;return!0}function y(M,A,S,O,_){var E=c(t(t(a(S,M),a(O,A)),_)),T=l(t(a(S,S),a(O,O)));return i(E,T)}function w(M,A,S,O,_,E,T,R,q){var W=[n(a(n(_,A),q),a(n(E,S),R)),n(a(n(E,S),T),a(n(O,M),q)),n(a(n(O,M),R),a(n(_,A),T))];W=l(t(t(a(W[0],W[0]),a(W[1],W[1])),a(W[2],W[2])));var G=l(t(t(a(T,T),a(R,R)),a(q,q)));return i(W,G)}function C(M,A){for(var S=M.length,O=0,_=0,E=0;E{var{typed:r,config:t,abs:n,add:a,addScalar:i,matrix:u,multiply:l,multiplyScalar:c,divideScalar:o,subtract:s,smaller:m,equalScalar:d,flatten:h,isZero:x,isNumeric:v}=e;return r("intersect",{"Array, Array, Array":y,"Array, Array, Array, Array":w,"Matrix, Matrix, Matrix":function(R,q,W){var G=y(R.valueOf(),q.valueOf(),W.valueOf());return G===null?null:u(G)},"Matrix, Matrix, Matrix, Matrix":function(R,q,W,G){var H=w(R.valueOf(),q.valueOf(),W.valueOf(),G.valueOf());return H===null?null:u(H)}});function y(T,R,q){if(T=C(T),R=C(R),q=C(q),!M(T))throw new TypeError("Array with 3 numbers or BigNumbers expected for first argument");if(!M(R))throw new TypeError("Array with 3 numbers or BigNumbers expected for second argument");if(!A(q))throw new TypeError("Array with 4 numbers expected as third argument");return E(T[0],T[1],T[2],R[0],R[1],R[2],q[0],q[1],q[2],q[3])}function w(T,R,q,W){if(T=C(T),R=C(R),q=C(q),W=C(W),T.length===2){if(!b(T))throw new TypeError("Array with 2 numbers or BigNumbers expected for first argument");if(!b(R))throw new TypeError("Array with 2 numbers or BigNumbers expected for second argument");if(!b(q))throw new TypeError("Array with 2 numbers or BigNumbers expected for third argument");if(!b(W))throw new TypeError("Array with 2 numbers or BigNumbers expected for fourth argument");return S(T,R,q,W)}else if(T.length===3){if(!M(T))throw new TypeError("Array with 3 numbers or BigNumbers expected for first argument");if(!M(R))throw new TypeError("Array with 3 numbers or BigNumbers expected for second argument");if(!M(q))throw new TypeError("Array with 3 numbers or BigNumbers expected for third argument");if(!M(W))throw new TypeError("Array with 3 numbers or BigNumbers expected for fourth argument");return _(T[0],T[1],T[2],R[0],R[1],R[2],q[0],q[1],q[2],W[0],W[1],W[2])}else throw new TypeError("Arrays with two or thee dimensional points expected")}function C(T){return T.length===1?T[0]:T.length>1&&Array.isArray(T[0])&&T.every(R=>Array.isArray(R)&&R.length===1)?h(T):T}function b(T){return T.length===2&&v(T[0])&&v(T[1])}function M(T){return T.length===3&&v(T[0])&&v(T[1])&&v(T[2])}function A(T){return T.length===4&&v(T[0])&&v(T[1])&&v(T[2])&&v(T[3])}function S(T,R,q,W){var G=T,H=q,L=s(G,R),k=s(H,W),K=s(c(L[0],k[1]),c(k[0],L[1]));if(x(K)||m(n(K),t.epsilon))return null;var z=c(k[0],G[1]),oe=c(k[1],G[0]),pe=c(k[0],H[1]),ae=c(k[1],H[0]),$=o(i(s(s(z,oe),pe),ae),K);return a(l(L,$),G)}function O(T,R,q,W,G,H,L,k,K,z,oe,pe){var ae=c(s(T,R),s(q,W)),$=c(s(G,H),s(L,k)),le=c(s(K,z),s(oe,pe));return i(i(ae,$),le)}function _(T,R,q,W,G,H,L,k,K,z,oe,pe){var ae=O(T,L,z,L,R,k,oe,k,q,K,pe,K),$=O(z,L,W,T,oe,k,G,R,pe,K,H,q),le=O(T,L,W,T,R,k,G,R,q,K,H,q),Ee=O(z,L,z,L,oe,k,oe,k,pe,K,pe,K),me=O(W,T,W,T,G,R,G,R,H,q,H,q),ge=s(c(ae,$),c(le,Ee)),Se=s(c(me,Ee),c($,$));if(x(Se))return null;var xe=o(ge,Se),be=o(i(ae,c(xe,$)),Ee),De=i(T,c(xe,s(W,T))),Ae=i(R,c(xe,s(G,R))),We=i(q,c(xe,s(H,q))),Je=i(L,c(be,s(z,L))),J=i(k,c(be,s(oe,k))),re=i(K,c(be,s(pe,K)));return d(De,Je)&&d(Ae,J)&&d(We,re)?[De,Ae,We]:null}function E(T,R,q,W,G,H,L,k,K,z){var oe=c(T,L),pe=c(W,L),ae=c(R,k),$=c(G,k),le=c(q,K),Ee=c(H,K),me=s(s(s(z,oe),ae),le),ge=s(s(s(i(i(pe,$),Ee),oe),ae),le),Se=o(me,ge),xe=i(T,c(Se,s(W,T))),be=i(R,c(Se,s(G,R))),De=i(q,c(Se,s(H,q)));return[xe,be,De]}});var pB="sum",IG=["typed","config","add","numeric"],nf=F(pB,IG,e=>{var{typed:r,config:t,add:n,numeric:a}=e;return r(pB,{"Array | Matrix":i,"Array | Matrix, number | BigNumber":u,"...":function(c){if(Ba(c))throw new TypeError("Scalar values expected in function sum");return i(c)}});function i(l){var c;return An(l,function(o){try{c=c===void 0?o:n(c,o)}catch(s){throw Et(s,"sum",o)}}),c===void 0&&(c=a(0,t.number)),typeof c=="string"&&(c=a(c,t.number)),c}function u(l,c){try{var o=ko(l,c,n);return o}catch(s){throw Et(s,"sum")}}});var Tg="cumsum",RG=["typed","add","unaryPlus"],af=F(Tg,RG,e=>{var{typed:r,add:t,unaryPlus:n}=e;return r(Tg,{Array:a,Matrix:function(o){return o.create(a(o.valueOf()))},"Array, number | BigNumber":u,"Matrix, number | BigNumber":function(o,s){return o.create(u(o.valueOf(),s))},"...":function(o){if(Ba(o))throw new TypeError("All values expected to be scalar in function cumsum");return a(o)}});function a(c){try{return i(c)}catch(o){throw Et(o,Tg)}}function i(c){if(c.length===0)return[];for(var o=[n(c[0])],s=1;s=s.length)throw new tn(o,s.length);try{return l(c,o)}catch(m){throw Et(m,Tg)}}function l(c,o){var s,m,d;if(o<=0){var h=c[0][0];if(Array.isArray(h)){for(d=Km(c),m=[],s=0;s{var{typed:r,add:t,divide:n}=e;return r(dB,{"Array | Matrix":i,"Array | Matrix, number | BigNumber":a,"...":function(l){if(Ba(l))throw new TypeError("Scalar values expected in function mean");return i(l)}});function a(u,l){try{var c=ko(u,l,t),o=Array.isArray(u)?ur(u):u.size();return n(c,o[l])}catch(s){throw Et(s,"mean")}}function i(u){var l,c=0;if(An(u,function(o){try{l=l===void 0?o:t(l,o),c++}catch(s){throw Et(s,"mean",o)}}),c===0)throw new Error("Cannot calculate the mean of an empty array");return n(l,c)}});var hB="median",qG=["typed","add","divide","compare","partitionSelect"],Fg=F(hB,qG,e=>{var{typed:r,add:t,divide:n,compare:a,partitionSelect:i}=e;function u(o){try{o=gr(o.valueOf());var s=o.length;if(s===0)throw new Error("Cannot calculate median of an empty array");if(s%2===0){for(var m=s/2-1,d=i(o,m+1),h=o[m],x=0;x0&&(h=o[x]);return c(h,d)}else{var v=i(o,(s-1)/2);return l(v)}}catch(y){throw Et(y,"median")}}var l=r({"number | BigNumber | Complex | Unit":function(s){return s}}),c=r({"number | BigNumber | Complex | Unit, number | BigNumber | Complex | Unit":function(s,m){return n(t(s,m),2)}});return r(hB,{"Array | Matrix":u,"Array | Matrix, number | BigNumber":function(s,m){throw new Error("median(A, dim) is not yet supported")},"...":function(s){if(Ba(s))throw new TypeError("Scalar values expected in function median");return u(s)}})});var vB="mad",LG=["typed","abs","map","median","subtract"],_g=F(vB,LG,e=>{var{typed:r,abs:t,map:n,median:a,subtract:i}=e;return r(vB,{"Array | Matrix":u,"...":function(c){return u(c)}});function u(l){if(l=gr(l.valueOf()),l.length===0)throw new Error("Cannot calculate median absolute deviation (mad) of an empty array");try{var c=a(l);return a(n(l,function(o){return t(i(o,c))}))}catch(o){throw o instanceof TypeError&&o.message.indexOf("median")!==-1?new TypeError(o.message.replace("median","mad")):Et(o,"mad")}}});var ND="unbiased",gB="variance",zG=["typed","add","subtract","multiply","divide","apply","isNaN"],sf=F(gB,zG,e=>{var{typed:r,add:t,subtract:n,multiply:a,divide:i,apply:u,isNaN:l}=e;return r(gB,{"Array | Matrix":function(m){return c(m,ND)},"Array | Matrix, string":c,"Array | Matrix, number | BigNumber":function(m,d){return o(m,d,ND)},"Array | Matrix, number | BigNumber, string":o,"...":function(m){return c(m,ND)}});function c(s,m){var d,h=0;if(s.length===0)throw new SyntaxError("Function variance requires one or more parameters (0 provided)");if(An(s,function(y){try{d=d===void 0?y:t(d,y),h++}catch(w){throw Et(w,"variance",y)}}),h===0)throw new Error("Cannot calculate variance of an empty array");var x=i(d,h);if(d=void 0,An(s,function(y){var w=n(y,x);d=d===void 0?a(w,w):t(d,a(w,w))}),l(d))return d;switch(m){case"uncorrected":return i(d,h);case"biased":return i(d,h+1);case"unbiased":{var v=rr(d)?d.mul(0):0;return h===1?v:i(d,h-1)}default:throw new Error('Unknown normalization "'+m+'". Choose "unbiased" (default), "uncorrected", or "biased".')}}function o(s,m,d){try{if(s.length===0)throw new SyntaxError("Function variance requires one or more parameters (0 provided)");return u(s,m,h=>c(h,d))}catch(h){throw Et(h,"variance")}}});var xB="quantileSeq",UG=["typed","?bignumber","add","subtract","divide","multiply","partitionSelect","compare","isInteger","smaller","smallerEq","larger"],uf=F(xB,UG,e=>{var{typed:r,bignumber:t,add:n,subtract:a,divide:i,multiply:u,partitionSelect:l,compare:c,isInteger:o,smaller:s,smallerEq:m,larger:d}=e,h=qo({typed:r,isInteger:o});return r(xB,{"Array | Matrix, number | BigNumber":(C,b)=>v(C,b,!1),"Array | Matrix, number | BigNumber, number":(C,b,M)=>x(C,b,!1,M,v),"Array | Matrix, number | BigNumber, boolean":v,"Array | Matrix, number | BigNumber, boolean, number":(C,b,M,A)=>x(C,b,M,A,v),"Array | Matrix, Array | Matrix":(C,b)=>y(C,b,!1),"Array | Matrix, Array | Matrix, number":(C,b,M)=>x(C,b,!1,M,y),"Array | Matrix, Array | Matrix, boolean":y,"Array | Matrix, Array | Matrix, boolean, number":(C,b,M,A)=>x(C,b,M,A,y)});function x(C,b,M,A,S){return h(C,A,O=>S(O,b,M))}function v(C,b,M){var A,S=C.valueOf();if(s(b,0))throw new Error("N/prob must be non-negative");if(m(b,1))return sr(b)?w(S,b,M):t(w(S,b,M));if(d(b,1)){if(!o(b))throw new Error("N must be a positive integer");if(d(b,4294967295))throw new Error("N must be less than or equal to 2^32-1, as that is the maximum length of an Array");var O=n(b,1);A=[];for(var _=0;s(_,b);_++){var E=i(_+1,O);A.push(w(S,E,M))}return sr(b)?A:t(A)}}function y(C,b,M){for(var A=C.valueOf(),S=b.valueOf(),O=[],_=0;_0&&(T=A[q])}return n(u(T,a(1,E)),u(R,E))}});var yB="std",WG=["typed","map","sqrt","variance"],ff=F(yB,WG,e=>{var{typed:r,map:t,sqrt:n,variance:a}=e;return r(yB,{"Array | Matrix":i,"Array | Matrix, string":i,"Array | Matrix, number | BigNumber":i,"Array | Matrix, number | BigNumber, string":i,"...":function(l){return i(l)}});function i(u,l){if(u.length===0)throw new SyntaxError("Function std requires one or more parameters (0 provided)");try{var c=a.apply(null,arguments);return Nt(c)?t(c,n):n(c)}catch(o){throw o instanceof TypeError&&o.message.indexOf(" variance")!==-1?new TypeError(o.message.replace(" variance"," std")):o}}});var bB="corr",YG=["typed","matrix","mean","sqrt","sum","add","subtract","multiply","pow","divide"],Og=F(bB,YG,e=>{var{typed:r,matrix:t,sqrt:n,sum:a,add:i,subtract:u,multiply:l,pow:c,divide:o}=e;return r(bB,{"Array, Array":function(h,x){return s(h,x)},"Matrix, Matrix":function(h,x){var v=s(h.toArray(),x.toArray());return Array.isArray(v)?t(v):v}});function s(d,h){var x=[];if(Array.isArray(d[0])&&Array.isArray(h[0])){if(d.length!==h.length)throw new SyntaxError("Dimension mismatch. Array A and B must have the same length.");for(var v=0;vi(S,l(O,h[_])),0),C=a(d.map(S=>c(S,2))),b=a(h.map(S=>c(S,2))),M=u(l(x,w),l(v,y)),A=n(l(u(l(x,C),c(v,2)),u(l(x,b),c(y,2))));return o(M,A)}});var wB="combinations",HG=["typed"],Bg=F(wB,HG,e=>{var{typed:r}=e;return r(wB,{"number, number":kw,"BigNumber, BigNumber":function(n,a){var i=n.constructor,u,l,c=n.minus(a),o=new i(1);if(!DB(n)||!DB(a))throw new TypeError("Positive integer value expected in function combinations");if(a.gt(n))throw new TypeError("k must be less than n in function combinations");if(u=o,a.lt(c))for(l=o;l.lte(c);l=l.plus(o))u=u.times(a.plus(l)).dividedBy(l);else for(l=o;l.lte(a);l=l.plus(o))u=u.times(c.plus(l)).dividedBy(l);return u}})});function DB(e){return e.isInteger()&&e.gte(0)}var SB="combinationsWithRep",$G=["typed"],Pg=F(SB,$G,e=>{var{typed:r}=e;return r(SB,{"number, number":function(n,a){if(!Ze(n)||n<0)throw new TypeError("Positive integer value expected in function combinationsWithRep");if(!Ze(a)||a<0)throw new TypeError("Positive integer value expected in function combinationsWithRep");if(n<1)throw new TypeError("k must be less than or equal to n + k - 1");if(a{var{typed:r,config:t,multiplyScalar:n,pow:a,BigNumber:i,Complex:u}=e;function l(o){if(o.im===0)return _c(o.re);if(o.re<.5){var s=new u(1-o.re,-o.im),m=new u(Math.PI*o.re,Math.PI*o.im);return new u(Math.PI).div(m.sin()).div(l(s))}o=new u(o.re-1,o.im);for(var d=new u(Ts[0],0),h=1;h2;)d-=2,x+=d,h=h.times(x);return new i(h.toPrecision(i.precision))}});var MB="lgamma",VG=["Complex","typed"],Rg=F(MB,VG,e=>{var{Complex:r,typed:t}=e,n=7,a=7,i=[-.029550653594771242,.00641025641025641,-.0019175269175269176,.0008417508417508417,-.0005952380952380953,.0007936507936507937,-.002777777777777778,.08333333333333333];return t(MB,{number:Oc,Complex:u,BigNumber:function(){throw new Error("mathjs doesn't yet provide an implementation of the algorithm lgamma for BigNumber")}});function u(o){var s=6.283185307179586,m=1.1447298858494002,d=.1;if(o.isNaN())return new r(NaN,NaN);if(o.im===0)return new r(Oc(o.re),0);if(o.re>=n||Math.abs(o.im)>=a)return l(o);if(o.re<=d){var h=nM(s,o.im)*Math.floor(.5*o.re+.25),x=o.mul(Math.PI).sin().log(),v=u(new r(1-o.re,-o.im));return new r(m,h).sub(x).sub(v)}else return o.im>=0?c(o):c(o.conjugate()).conjugate()}function l(o){for(var s=o.sub(.5).mul(o.log()).sub(o).add(Hw),m=new r(1,0).div(o),d=m.div(o),h=i[0],x=i[1],v=2*d.re,y=d.re*d.re+d.im*d.im,w=2;w<8;w++){var C=x;x=-y*h+i[w],h=v*h+C}var b=m.mul(d.mul(h).add(x));return s.add(b)}function c(o){var s=0,m=0,d=o;for(o=o.add(1);o.re<=n;){d=d.mul(o);var h=d.im<0?1:0;h!==0&&m===0&&s++,m=h,o=o.add(1)}return l(o).sub(d.log()).sub(new r(0,s*2*Math.PI*1))}});var CB="factorial",ZG=["typed","gamma"],kg=F(CB,ZG,e=>{var{typed:r,gamma:t}=e;return r(CB,{number:function(a){if(a<0)throw new Error("Value must be non-negative");return t(a+1)},BigNumber:function(a){if(a.isNegative())throw new Error("Value must be non-negative");return t(a.plus(1))},"Array | Matrix":r.referToSelf(n=>a=>je(a,n))})});var EB="kldivergence",QG=["typed","matrix","divide","sum","multiply","map","dotDivide","log","isNumeric"],qg=F(EB,QG,e=>{var{typed:r,matrix:t,divide:n,sum:a,multiply:i,map:u,dotDivide:l,log:c,isNumeric:o}=e;return r(EB,{"Array, Array":function(d,h){return s(t(d),t(h))},"Matrix, Array":function(d,h){return s(d,t(h))},"Array, Matrix":function(d,h){return s(t(d),h)},"Matrix, Matrix":function(d,h){return s(d,h)}});function s(m,d){var h=d.size().length,x=m.size().length;if(h>1)throw new Error("first object must be one dimensional");if(x>1)throw new Error("second object must be one dimensional");if(h!==x)throw new Error("Length of two vectors must be equal");var v=a(m);if(v===0)throw new Error("Sum of elements in first object must be non zero");var y=a(d);if(y===0)throw new Error("Sum of elements in second object must be non zero");var w=n(m,a(m)),C=n(d,a(d)),b=a(i(w,u(l(w,C),M=>c(M))));return o(b)?b:Number.NaN}});var TB="multinomial",XG=["typed","add","divide","multiply","factorial","isInteger","isPositive"],Lg=F(TB,XG,e=>{var{typed:r,add:t,divide:n,multiply:a,factorial:i,isInteger:u,isPositive:l}=e;return r(TB,{"Array | Matrix":function(o){var s=0,m=1;return An(o,function(d){if(!u(d)||!l(d))throw new TypeError("Positive integer value expected in function multinomial");s=t(s,d),m=a(m,i(d))}),n(i(s),m)}})});var FB="permutations",JG=["typed","factorial"],zg=F(FB,JG,e=>{var{typed:r,factorial:t}=e;return r(FB,{"number | BigNumber":t,"number, number":function(a,i){if(!Ze(a)||a<0)throw new TypeError("Positive integer value expected in function permutations");if(!Ze(i)||i<0)throw new TypeError("Positive integer value expected in function permutations");if(i>a)throw new TypeError("second argument k must be less than or equal to first argument n");return da(a-i+1,a)},"BigNumber, BigNumber":function(a,i){var u,l;if(!_B(a)||!_B(i))throw new TypeError("Positive integer value expected in function permutations");if(i.gt(a))throw new TypeError("second argument k must be less than or equal to first argument n");var c=a.mul(0).add(1);for(u=c,l=a.minus(i).plus(1);l.lte(a);l=l.plus(1))u=u.times(l);return u}})});function _B(e){return e.isInteger()&&e.gte(0)}var _D=ca(ZB(),1),aV=(0,_D.default)(Date.now());function to(e){var r;function t(a){r=a===null?aV:(0,_D.default)(String(a))}t(e);function n(){return r()}return n}var QB="pickRandom",iV=["typed","config","?on"],Wg=F(QB,iV,e=>{var{typed:r,config:t,on:n}=e,a=to(t.randomSeed);return n&&n("config",function(u,l){u.randomSeed!==l.randomSeed&&(a=to(u.randomSeed))}),r(QB,{"Array | Matrix":function(l){return i(l,{})},"Array | Matrix, Object":function(l,c){return i(l,c)},"Array | Matrix, number":function(l,c){return i(l,{number:c})},"Array | Matrix, Array | Matrix":function(l,c){return i(l,{weights:c})},"Array | Matrix, Array | Matrix, number":function(l,c,o){return i(l,{number:o,weights:c})},"Array | Matrix, number, Array | Matrix":function(l,c,o){return i(l,{number:c,weights:o})}});function i(u,l){var{number:c,weights:o,elementWise:s=!0}=l,m=typeof c>"u";m&&(c=1);var d=Qe(u)?u.create:Qe(o)?o.create:null;u=u.valueOf(),o&&(o=o.valueOf()),s===!0&&(u=gr(u),o=gr(o));var h=0;if(typeof o<"u"){if(o.length!==u.length)throw new Error("Weights must have the same length as possibles");for(var x=0,v=o.length;x"u")C=u[Math.floor(a()*y)];else for(var b=a()*h,M=0,A=u.length;M1)for(var n=0,a=e.shift();n{var{typed:r,config:t,on:n}=e,a=to(t.randomSeed);return n&&n("config",function(l,c){l.randomSeed!==c.randomSeed&&(a=to(l.randomSeed))}),r(XB,{"":()=>u(0,1),number:l=>u(0,l),"number, number":(l,c)=>u(l,c),"Array | Matrix":l=>i(l,0,1),"Array | Matrix, number":(l,c)=>i(l,0,c),"Array | Matrix, number, number":(l,c,o)=>i(l,c,o)});function i(l,c,o){var s=kc(l.valueOf(),()=>u(c,o));return Qe(l)?l.create(s):s}function u(l,c){return l+a()*(c-l)}});var JB="randomInt",sV=["typed","config","?on"],Hg=F(JB,sV,e=>{var{typed:r,config:t,on:n}=e,a=to(t.randomSeed);return n&&n("config",function(l,c){l.randomSeed!==c.randomSeed&&(a=to(l.randomSeed))}),r(JB,{"":()=>u(0,1),number:l=>u(0,l),"number, number":(l,c)=>u(l,c),"Array | Matrix":l=>i(l,0,1),"Array | Matrix, number":(l,c)=>i(l,0,c),"Array | Matrix, number, number":(l,c,o)=>i(l,c,o)});function i(l,c,o){var s=kc(l.valueOf(),()=>u(c,o));return Qe(l)?l.create(s):s}function u(l,c){return Math.floor(l+a()*(c-l))}});var KB="stirlingS2",uV=["typed","addScalar","subtractScalar","multiplyScalar","divideScalar","pow","factorial","combinations","isNegative","isInteger","number","?bignumber","larger"],$g=F(KB,uV,e=>{var{typed:r,addScalar:t,subtractScalar:n,multiplyScalar:a,divideScalar:i,pow:u,factorial:l,combinations:c,isNegative:o,isInteger:s,number:m,bignumber:d,larger:h}=e,x=[],v=[];return r(KB,{"number | BigNumber, number | BigNumber":function(w,C){if(!s(w)||o(w)||!s(C)||o(C))throw new TypeError("Non-negative integer value expected in function stirlingS2");if(h(C,w))throw new TypeError("k must be less than or equal to n in function stirlingS2");var b=!(sr(w)&&sr(C)),M=b?v:x,A=b?d:m,S=m(w),O=m(C);if(M[S]&&M[S].length>O)return M[S][O];for(var _=0;_<=S;++_)if(M[_]||(M[_]=[A(_===0?1:0)]),_!==0)for(var E=M[_],T=M[_-1],R=E.length;R<=_&&R<=O;++R)R===_?E[R]=1:E[R]=t(a(A(R),T[R]),T[R-1]);return M[S][O]}})});var jB="bellNumbers",fV=["typed","addScalar","isNegative","isInteger","stirlingS2"],Gg=F(jB,fV,e=>{var{typed:r,addScalar:t,isNegative:n,isInteger:a,stirlingS2:i}=e;return r(jB,{"number | BigNumber":function(l){if(!a(l)||n(l))throw new TypeError("Non-negative integer value expected in function bellNumbers");for(var c=0,o=0;o<=l;o++)c=t(c,i(l,o));return c}})});var eP="catalan",cV=["typed","addScalar","divideScalar","multiplyScalar","combinations","isNegative","isInteger"],Vg=F(eP,cV,e=>{var{typed:r,addScalar:t,divideScalar:n,multiplyScalar:a,combinations:i,isNegative:u,isInteger:l}=e;return r(eP,{"number | BigNumber":function(o){if(!l(o)||u(o))throw new TypeError("Non-negative integer value expected in function catalan");return n(i(a(o,2),o),t(o,1))}})});var rP="composition",lV=["typed","addScalar","combinations","isNegative","isPositive","isInteger","larger"],Zg=F(rP,lV,e=>{var{typed:r,addScalar:t,combinations:n,isPositive:a,isNegative:i,isInteger:u,larger:l}=e;return r(rP,{"number | BigNumber, number | BigNumber":function(o,s){if(!u(o)||!a(o)||!u(s)||!a(s))throw new TypeError("Positive integer value expected in function composition");if(l(s,o))throw new TypeError("k must be less than or equal to n in function composition");return n(t(o,-1),t(s,-1))}})});var tP="leafCount",mV=["parse","typed"],Qg=F(tP,mV,e=>{var{parse:r,typed:t}=e;function n(a){var i=0;return a.forEach(u=>{i+=n(u)}),i||1}return t(tP,{Node:function(i){return n(i)}})});function OD(e){return yr(e)||ct(e)&&e.isUnary()&&yr(e.args[0])}function qc(e){return!!(yr(e)||(gn(e)||ct(e))&&e.args.every(qc)||en(e)&&qc(e.content))}function nP(e,r){var t=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);r&&(n=n.filter(function(a){return Object.getOwnPropertyDescriptor(e,a).enumerable})),t.push.apply(t,n)}return t}function BD(e){for(var r=1;r{var{FunctionNode:r,OperatorNode:t,SymbolNode:n}=e,a=!0,i=!1,u="defaultF",l={add:{trivial:a,total:a,commutative:a,associative:a},unaryPlus:{trivial:a,total:a,commutative:a,associative:a},subtract:{trivial:i,total:a,commutative:i,associative:i},multiply:{trivial:a,total:a,commutative:a,associative:a},divide:{trivial:i,total:a,commutative:i,associative:i},paren:{trivial:a,total:a,commutative:a,associative:i},defaultF:{trivial:i,total:a,commutative:i,associative:i}},c={divide:{total:i},log:{total:i}},o={subtract:{total:i},abs:{trivial:a},log:{total:a}};function s(b,M){var A=arguments.length>2&&arguments[2]!==void 0?arguments[2]:l,S=u;if(typeof b=="string"?S=b:ct(b)?S=b.fn.toString():gn(b)?S=b.name:en(b)&&(S="paren"),Xe(A,S)){var O=A[S];if(Xe(O,M))return O[M];if(Xe(l,S))return l[S][M]}if(Xe(A,u)){var _=A[u];return Xe(_,M)?_[M]:l[u][M]}if(Xe(l,S)){var E=l[S];if(Xe(E,M))return E[M]}return l[u][M]}function m(b){var M=arguments.length>1&&arguments[1]!==void 0?arguments[1]:l;return s(b,"commutative",M)}function d(b){var M=arguments.length>1&&arguments[1]!==void 0?arguments[1]:l;return s(b,"associative",M)}function h(b,M){var A=BD({},b);for(var S in M)Xe(b,S)?A[S]=BD(BD({},M[S]),b[S]):A[S]=M[S];return A}function x(b,M){if(!b.args||b.args.length===0)return b;b.args=v(b,M);for(var A=0;A2&&d(b,M)){for(var _=b.args.pop();b.args.length>0;)_=A([b.args.pop(),_]);b.args=_.args}}}function w(b,M){if(!(!b.args||b.args.length===0)){for(var A=C(b),S=b.args.length,O=0;O2&&d(b,M)){for(var _=b.args.shift();b.args.length>0;)_=A([_,b.args.shift()]);b.args=_.args}}}function C(b){return ct(b)?function(M){try{return new t(b.op,b.fn,M,b.implicit)}catch(A){return console.error(A),[]}}:function(M){return new r(new n(b.name),M)}}return{createMakeNodeFunction:C,hasProperty:s,isCommutative:m,isAssociative:d,mergeContext:h,flatten:x,allChildren:v,unflattenr:y,unflattenl:w,defaultContext:l,realContext:c,positiveContext:o}});var hV="simplify",vV=["config","typed","parse","add","subtract","multiply","divide","pow","isZero","equal","resolve","simplifyConstant","simplifyCore","?fraction","?bignumber","mathWithTransform","matrix","AccessorNode","ArrayNode","ConstantNode","FunctionNode","IndexNode","ObjectNode","OperatorNode","ParenthesisNode","SymbolNode"],Xg=F(hV,vV,e=>{var{config:r,typed:t,parse:n,add:a,subtract:i,multiply:u,divide:l,pow:c,isZero:o,equal:s,resolve:m,simplifyConstant:d,simplifyCore:h,fraction:x,bignumber:v,mathWithTransform:y,matrix:w,AccessorNode:C,ArrayNode:b,ConstantNode:M,FunctionNode:A,IndexNode:S,ObjectNode:O,OperatorNode:_,ParenthesisNode:E,SymbolNode:T}=e,{hasProperty:R,isCommutative:q,isAssociative:W,mergeContext:G,flatten:H,unflattenr:L,unflattenl:k,createMakeNodeFunction:K,defaultContext:z,realContext:oe,positiveContext:pe}=cf({FunctionNode:A,OperatorNode:_,SymbolNode:T});t.addConversion({from:"Object",to:"Map",convert:Ki});var ae=t("simplify",{Node:xe,"Node, Map":(j,ne)=>xe(j,!1,ne),"Node, Map, Object":(j,ne,ue)=>xe(j,!1,ne,ue),"Node, Array":xe,"Node, Array, Map":xe,"Node, Array, Map, Object":xe});t.removeConversion({from:"Object",to:"Map",convert:Ki}),ae.defaultContext=z,ae.realContext=oe,ae.positiveContext=pe;function $(j){return j.transform(function(ne,ue,Me){return en(ne)?$(ne.content):ne})}var le={true:!0,false:!0,e:!0,i:!0,Infinity:!0,LN2:!0,LN10:!0,LOG2E:!0,LOG10E:!0,NaN:!0,phi:!0,pi:!0,SQRT1_2:!0,SQRT2:!0,tau:!0};ae.rules=[h,{l:"log(e)",r:"1"},{s:"n-n1 -> n+-n1",assuming:{subtract:{total:!0}}},{s:"n-n -> 0",assuming:{subtract:{total:!1}}},{s:"-(cl*v) -> v * (-cl)",assuming:{multiply:{commutative:!0},subtract:{total:!0}}},{s:"-(cl*v) -> (-cl) * v",assuming:{multiply:{commutative:!1},subtract:{total:!0}}},{s:"-(v*cl) -> v * (-cl)",assuming:{multiply:{commutative:!1},subtract:{total:!0}}},{l:"-(n1/n2)",r:"-n1/n2"},{l:"-v",r:"v * (-1)"},{l:"(n1 + n2)*(-1)",r:"n1*(-1) + n2*(-1)",repeat:!0},{l:"n/n1^n2",r:"n*n1^-n2"},{l:"n/n1",r:"n*n1^-1"},{s:"(n1*n2)^n3 -> n1^n3 * n2^n3",assuming:{multiply:{commutative:!0}}},{s:"(n1*n2)^(-1) -> n2^(-1) * n1^(-1)",assuming:{multiply:{commutative:!1}}},{s:"(n ^ n1) ^ n2 -> n ^ (n1 * n2)",assuming:{divide:{total:!0}}},{l:" vd * ( vd * n1 + n2)",r:"vd^2 * n1 + vd * n2"},{s:" vd * (vd^n4 * n1 + n2) -> vd^(1+n4) * n1 + vd * n2",assuming:{divide:{total:!0}}},{s:"vd^n3 * ( vd * n1 + n2) -> vd^(n3+1) * n1 + vd^n3 * n2",assuming:{divide:{total:!0}}},{s:"vd^n3 * (vd^n4 * n1 + n2) -> vd^(n3+n4) * n1 + vd^n3 * n2",assuming:{divide:{total:!0}}},{l:"n*n",r:"n^2"},{s:"n * n^n1 -> n^(n1+1)",assuming:{divide:{total:!0}}},{s:"n^n1 * n^n2 -> n^(n1+n2)",assuming:{divide:{total:!0}}},d,{s:"n+n -> 2*n",assuming:{add:{total:!0}}},{l:"n+-n",r:"0"},{l:"vd*n + vd",r:"vd*(n+1)"},{l:"n3*n1 + n3*n2",r:"n3*(n1+n2)"},{l:"n3^(-n4)*n1 + n3 * n2",r:"n3^(-n4)*(n1 + n3^(n4+1) *n2)"},{l:"n3^(-n4)*n1 + n3^n5 * n2",r:"n3^(-n4)*(n1 + n3^(n4+n5)*n2)"},{s:"n*vd + vd -> (n+1)*vd",assuming:{multiply:{commutative:!1}}},{s:"vd + n*vd -> (1+n)*vd",assuming:{multiply:{commutative:!1}}},{s:"n1*n3 + n2*n3 -> (n1+n2)*n3",assuming:{multiply:{commutative:!1}}},{s:"n^n1 * n -> n^(n1+1)",assuming:{divide:{total:!0},multiply:{commutative:!1}}},{s:"n1*n3^(-n4) + n2 * n3 -> (n1 + n2*n3^(n4 + 1))*n3^(-n4)",assuming:{multiply:{commutative:!1}}},{s:"n1*n3^(-n4) + n2 * n3^n5 -> (n1 + n2*n3^(n4 + n5))*n3^(-n4)",assuming:{multiply:{commutative:!1}}},{l:"n*cd + cd",r:"(n+1)*cd"},{s:"cd*n + cd -> cd*(n+1)",assuming:{multiply:{commutative:!1}}},{s:"cd + cd*n -> cd*(1+n)",assuming:{multiply:{commutative:!1}}},d,{s:"(-n)*n1 -> -(n*n1)",assuming:{subtract:{total:!0}}},{s:"n1*(-n) -> -(n1*n)",assuming:{subtract:{total:!0},multiply:{commutative:!1}}},{s:"ce+ve -> ve+ce",assuming:{add:{commutative:!0}},imposeContext:{add:{commutative:!1}}},{s:"vd*cd -> cd*vd",assuming:{multiply:{commutative:!0}},imposeContext:{multiply:{commutative:!1}}},{l:"n+-n1",r:"n-n1"},{l:"n+-(n1)",r:"n-(n1)"},{s:"n*(n1^-1) -> n/n1",assuming:{multiply:{commutative:!0}}},{s:"n*n1^-n2 -> n/n1^n2",assuming:{multiply:{commutative:!0}}},{s:"n^-1 -> 1/n",assuming:{multiply:{commutative:!0}}},{l:"n^1",r:"n"},{s:"n*(n1/n2) -> (n*n1)/n2",assuming:{multiply:{associative:!0}}},{s:"n-(n1+n2) -> n-n1-n2",assuming:{addition:{associative:!0,commutative:!0}}},{l:"1*n",r:"n",imposeContext:{multiply:{commutative:!0}}},{s:"n1/(n2/n3) -> (n1*n3)/n2",assuming:{multiply:{associative:!0}}},{l:"n1/(-n2)",r:"-n1/n2"}];function Ee(j,ne){var ue={};if(j.s){var Me=j.s.split("->");if(Me.length===2)ue.l=Me[0],ue.r=Me[1];else throw SyntaxError("Could not parse rule: "+j.s)}else ue.l=j.l,ue.r=j.r;ue.l=$(n(ue.l)),ue.r=$(n(ue.r));for(var Ce of["imposeContext","repeat","assuming"])Ce in j&&(ue[Ce]=j[Ce]);if(j.evaluate&&(ue.evaluate=n(j.evaluate)),W(ue.l,ne)){var Le=!q(ue.l,ne),Ie;Le&&(Ie=Se());var fr=K(ue.l),or=Se();ue.expanded={},ue.expanded.l=fr([ue.l,or]),H(ue.expanded.l,ne),L(ue.expanded.l,ne),ue.expanded.r=fr([ue.r,or]),Le&&(ue.expandedNC1={},ue.expandedNC1.l=fr([Ie,ue.l]),ue.expandedNC1.r=fr([Ie,ue.r]),ue.expandedNC2={},ue.expandedNC2.l=fr([Ie,ue.expanded.l]),ue.expandedNC2.r=fr([Ie,ue.expanded.r]))}return ue}function me(j,ne){for(var ue=[],Me=0;Me2&&arguments[2]!==void 0?arguments[2]:Oo(),Me=arguments.length>3&&arguments[3]!==void 0?arguments[3]:{},Ce=Me.consoleDebug;ne=me(ne||ae.rules,Me.context);var Le=m(j,ue);Le=$(Le);for(var Ie={},fr=Le.toString({parenthesis:"all"});!Ie[fr];){Ie[fr]=!0,ge=0;var or=fr;Ce&&console.log("Working on: ",fr);for(var Ke=0;Ke ").concat(ne[Ke].r.toString()))),Ce){var ee=Le.toString({parenthesis:"all"});ee!==or&&(console.log("Applying",Pr,"produced",ee),or=ee)}k(Le,Me.context)}fr=Le.toString({parenthesis:"all"})}return Le}function be(j,ne,ue){var Me=j;if(j)for(var Ce=0;Ce1&&(or=Le(j.args.slice(0,fr))),Ce=j.args.slice(fr),Me=Ce.length===1?Ce[0]:Le(Ce),ue.push(Le([or,Me]))}return ue}function We(j,ne){var ue={placeholders:{}};if(!j.placeholders&&!ne.placeholders)return ue;if(j.placeholders){if(!ne.placeholders)return j}else return ne;for(var Me in j.placeholders)if(Xe(j.placeholders,Me)&&(ue.placeholders[Me]=j.placeholders[Me],Xe(ne.placeholders,Me)&&!ye(j.placeholders[Me],ne.placeholders[Me])))return null;for(var Ce in ne.placeholders)Xe(ne.placeholders,Ce)&&(ue.placeholders[Ce]=ne.placeholders[Ce]);return ue}function Je(j,ne){var ue=[];if(j.length===0||ne.length===0)return ue;for(var Me,Ce=0;Ce2)throw new Error("permuting >2 commutative non-associative rule arguments not yet implemented");var or=re(j.args[0],ne.args[1],ue);if(or.length===0)return[];var Ke=re(j.args[1],ne.args[0],ue);if(Ke.length===0)return[];Le=[or,Ke]}Ce=J(Le)}else if(ne.args.length>=2&&j.args.length===2){for(var Pr=Ae(ne,ue),ee=[],ce=0;ce2)throw Error("Unexpected non-binary associative function: "+j.toString());return[]}}else if(j instanceof T){if(j.name.length===0)throw new Error("Symbol in rule has 0 length...!?");if(le[j.name]){if(j.name!==ne.name)return[]}else switch(j.name[1]>="a"&&j.name[1]<="z"?j.name.substring(0,2):j.name[0]){case"n":case"_p":Ce[0].placeholders[j.name]=ne;break;case"c":case"cl":if(yr(ne))Ce[0].placeholders[j.name]=ne;else return[];break;case"v":if(!yr(ne))Ce[0].placeholders[j.name]=ne;else return[];break;case"vl":if(at(ne))Ce[0].placeholders[j.name]=ne;else return[];break;case"cd":if(OD(ne))Ce[0].placeholders[j.name]=ne;else return[];break;case"vd":if(!OD(ne))Ce[0].placeholders[j.name]=ne;else return[];break;case"ce":if(qc(ne))Ce[0].placeholders[j.name]=ne;else return[];break;case"ve":if(!qc(ne))Ce[0].placeholders[j.name]=ne;else return[];break;default:throw new Error("Invalid symbol in rule: "+j.name)}}else if(j instanceof M){if(!s(j.value,ne.value))return[]}else return[];return Ce}function ye(j,ne){if(j instanceof M&&ne instanceof M){if(!s(j.value,ne.value))return!1}else if(j instanceof T&&ne instanceof T){if(j.name!==ne.name)return!1}else if(j instanceof _&&ne instanceof _||j instanceof A&&ne instanceof A){if(j instanceof _){if(j.op!==ne.op||j.fn!==ne.fn)return!1}else if(j instanceof A&&j.name!==ne.name)return!1;if(j.args.length!==ne.args.length)return!1;for(var ue=0;ue{var{typed:r,config:t,mathWithTransform:n,matrix:a,fraction:i,bignumber:u,AccessorNode:l,ArrayNode:c,ConstantNode:o,FunctionNode:s,IndexNode:m,ObjectNode:d,OperatorNode:h,SymbolNode:x}=e,{isCommutative:v,isAssociative:y,allChildren:w,createMakeNodeFunction:C}=cf({FunctionNode:s,OperatorNode:h,SymbolNode:x}),b=r("simplifyConstant",{Node:H=>O(G(H,{})),"Node, Object":function(L,k){return O(G(L,k))}});function M(H){return ma(H)?H.valueOf():H instanceof Array?H.map(M):Qe(H)?a(M(H.valueOf())):H}function A(H,L,k){try{return n[H].apply(null,L)}catch{return L=L.map(M),E(n[H].apply(null,L),k)}}var S=r({Fraction:R,number:function(L){return L<0?T(new o(-L)):new o(L)},BigNumber:function(L){return L<0?T(new o(-L)):new o(L)},Complex:function(L){throw new Error("Cannot convert Complex number to Node")},string:function(L){return new o(L)},Matrix:function(L){return new c(L.valueOf().map(k=>S(k)))}});function O(H){return Nr(H)?H:S(H)}function _(H,L){var k=L&&L.exactFractions!==!1;if(k&&isFinite(H)&&i){var K=i(H),z=L&&typeof L.fractionsLimit=="number"?L.fractionsLimit:1/0;if(K.valueOf()===H&&K.n0;)if(yr(K[0])&&typeof K[0].value!="string"){var z=E(K.shift().value,k);jt(H)?H=H.items[z-1]:(H=H.valueOf()[z-1],H instanceof Array&&(H=a(H)))}else if(K.length>1&&yr(K[1])&&typeof K[1].value!="string"){var oe=E(K[1].value,k),pe=[],ae=jt(H)?H.items:H.valueOf();for(var $ of ae)if(jt($))pe.push($.items[oe-1]);else if(Qe(H))pe.push($[oe-1]);else break;if(pe.length===ae.length)jt(H)?H=new c(pe):H=a(pe),K.splice(1,1);else break}else break;return K.length===L.dimensions.length?new l(O(H),L):K.length>0?(L=new m(K),new l(O(H),L)):H}if(Ci(H)&&L.dimensions.length===1&&yr(L.dimensions[0])){var le=L.dimensions[0].value;return le in H.properties?H.properties[le]:new o}return new l(O(H),L)}function W(H,L,k,K){var z=L.shift(),oe=L.reduce((pe,ae)=>{if(!Nr(ae)){var $=pe.pop();if(Nr($))return[$,ae];try{return pe.push(A(H,[$,ae],K)),pe}catch{pe.push($)}}pe.push(O(pe.pop()));var le=pe.length===1?pe[0]:k(pe);return[k([le,O(ae)])]},[z]);return oe.length===1?oe[0]:k([oe[0],S(oe[1])])}function G(H,L){switch(H.type){case"SymbolNode":return H;case"ConstantNode":switch(typeof H.value){case"number":return E(H.value,L);case"string":return H.value;default:if(!isNaN(H.value))return E(H.value,L)}return H;case"FunctionNode":if(n[H.name]&&n[H.name].rawArgs)return H;{var k=["add","multiply"];if(k.indexOf(H.name)===-1){var K=H.args.map(De=>G(De,L));if(!K.some(Nr))try{return A(H.name,K,L)}catch{}if(H.name==="size"&&K.length===1&&jt(K[0])){for(var z=[],oe=K[0];jt(oe);)z.push(oe.items.length),oe=oe.items[0];return a(z)}return new s(H.name,K.map(O))}}case"OperatorNode":{var pe=H.fn.toString(),ae,$,le=C(H);if(ct(H)&&H.isUnary())ae=[G(H.args[0],L)],Nr(ae[0])?$=le(ae):$=A(pe,ae,L);else if(y(H,L.context))if(ae=w(H,L.context),ae=ae.map(De=>G(De,L)),v(pe,L.context)){for(var Ee=[],me=[],ge=0;ge1?($=W(pe,Ee,le,L),me.unshift($),$=W(pe,me,le,L)):$=W(pe,ae,le,L)}else $=W(pe,ae,le,L);else ae=H.args.map(De=>G(De,L)),$=W(pe,ae,le,L);return $}case"ParenthesisNode":return G(H.content,L);case"AccessorNode":return q(G(H.object,L),G(H.index,L),L);case"ArrayNode":{var Se=H.items.map(De=>G(De,L));return Se.some(Nr)?new c(Se.map(O)):a(Se)}case"IndexNode":return new m(H.dimensions.map(De=>b(De,L)));case"ObjectNode":{var xe={};for(var be in H.properties)xe[be]=b(H.properties[be],L);return new d(xe)}case"AssignmentNode":case"BlockNode":case"FunctionAssignmentNode":case"RangeNode":case"ConditionalNode":default:throw new Error("Unimplemented node type in simplifyConstant: ".concat(H.type))}}return b});var aP="simplifyCore",yV=["typed","parse","equal","isZero","add","subtract","multiply","divide","pow","AccessorNode","ArrayNode","ConstantNode","FunctionNode","IndexNode","ObjectNode","OperatorNode","ParenthesisNode","SymbolNode"],Kg=F(aP,yV,e=>{var{typed:r,parse:t,equal:n,isZero:a,add:i,subtract:u,multiply:l,divide:c,pow:o,AccessorNode:s,ArrayNode:m,ConstantNode:d,FunctionNode:h,IndexNode:x,ObjectNode:v,OperatorNode:y,ParenthesisNode:w,SymbolNode:C}=e,b=new d(0),M=new d(1),A=new d(!0),S=new d(!1);function O(R){return ct(R)&&["and","not","or"].includes(R.op)}var{hasProperty:_,isCommutative:E}=cf({FunctionNode:h,OperatorNode:y,SymbolNode:C});function T(R){var q=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},W=q?q.context:void 0;if(_(R,"trivial",W)){if(gn(R)&&R.args.length===1)return T(R.args[0],q);var G=!1,H=0;if(R.forEach(me=>{++H,H===1&&(G=T(me,q))}),H===1)return G}var L=R;if(gn(L)){var k=rT(L.name);if(k){if(L.args.length>2&&_(L,"associative",W))for(;L.args.length>2;){var K=L.args.pop(),z=L.args.pop();L.args.push(new y(k,L.name,[K,z]))}L=new y(k,L.name,L.args)}else return new h(T(L.fn),L.args.map(me=>T(me,q)))}if(ct(L)&&L.isUnary()){var oe=T(L.args[0],q);if(L.op==="~"&&ct(oe)&&oe.isUnary()&&oe.op==="~"||L.op==="not"&&ct(oe)&&oe.isUnary()&&oe.op==="not"&&O(oe.args[0]))return oe.args[0];var pe=!0;if(L.op==="-"&&ct(oe)&&(oe.isBinary()&&oe.fn==="subtract"&&(L=new y("-","subtract",[oe.args[1],oe.args[0]]),pe=!1),oe.isUnary()&&oe.op==="-"))return oe.args[0];if(pe)return new y(L.op,L.fn,[oe])}if(ct(L)&&L.isBinary()){var ae=T(L.args[0],q),$=T(L.args[1],q);if(L.op==="+"){if(yr(ae)&&a(ae.value))return $;if(yr($)&&a($.value))return ae;ct($)&&$.isUnary()&&$.op==="-"&&($=$.args[0],L=new y("-","subtract",[ae,$]))}if(L.op==="-")return ct($)&&$.isUnary()&&$.op==="-"?T(new y("+","add",[ae,$.args[0]]),q):yr(ae)&&a(ae.value)?T(new y("-","unaryMinus",[$])):yr($)&&a($.value)?ae:new y(L.op,L.fn,[ae,$]);if(L.op==="*"){if(yr(ae)){if(a(ae.value))return b;if(n(ae.value,1))return $}if(yr($)){if(a($.value))return b;if(n($.value,1))return ae;if(E(L,W))return new y(L.op,L.fn,[$,ae],L.implicit)}return new y(L.op,L.fn,[ae,$],L.implicit)}if(L.op==="/")return yr(ae)&&a(ae.value)?b:yr($)&&n($.value,1)?ae:new y(L.op,L.fn,[ae,$]);if(L.op==="^"&&yr($)){if(a($.value))return M;if(n($.value,1))return ae}if(L.op==="and"){if(yr(ae))if(ae.value){if(O($))return $;if(yr($))return $.value?A:S}else return S;if(yr($))if($.value){if(O(ae))return ae}else return S}if(L.op==="or"){if(yr(ae)){if(ae.value)return A;if(O($))return $}if(yr($)){if($.value)return A;if(O(ae))return ae}}return new y(L.op,L.fn,[ae,$])}if(ct(L))return new y(L.op,L.fn,L.args.map(me=>T(me,q)));if(jt(L))return new m(L.items.map(me=>T(me,q)));if(qn(L))return new s(T(L.object,q),T(L.index,q));if(Qn(L))return new x(L.dimensions.map(me=>T(me,q)));if(Ci(L)){var le={};for(var Ee in L.properties)le[Ee]=T(L.properties[Ee],q);return new v(le)}return L}return r(aP,{Node:T,"Node,Object":T})});var bV="resolve",wV=["typed","parse","ConstantNode","FunctionNode","OperatorNode","ParenthesisNode"],jg=F(bV,wV,e=>{var{typed:r,parse:t,ConstantNode:n,FunctionNode:a,OperatorNode:i,ParenthesisNode:u}=e;function l(c,o){var s=arguments.length>2&&arguments[2]!==void 0?arguments[2]:new Set;if(!o)return c;if(at(c)){if(s.has(c.name)){var m=Array.from(s).join(", ");throw new ReferenceError("recursive loop of variable definitions among {".concat(m,"}"))}var d=o.get(c.name);if(Nr(d)){var h=new Set(s);return h.add(c.name),l(d,o,h)}else return typeof d=="number"?t(String(d)):d!==void 0?new n(d):c}else if(ct(c)){var x=c.args.map(function(y){return l(y,o,s)});return new i(c.op,c.fn,x,c.implicit)}else{if(en(c))return new u(l(c.content,o,s));if(gn(c)){var v=c.args.map(function(y){return l(y,o,s)});return new a(c.name,v)}}return c.map(y=>l(y,o,s))}return r("resolve",{Node:l,"Node, Map | null | undefined":l,"Node, Object":(c,o)=>l(c,Ki(o)),"Array | Matrix":r.referToSelf(c=>o=>o.map(s=>c(s))),"Array | Matrix, null | undefined":r.referToSelf(c=>o=>o.map(s=>c(s))),"Array, Object":r.referTo("Array,Map",c=>(o,s)=>c(o,Ki(s))),"Matrix, Object":r.referTo("Matrix,Map",c=>(o,s)=>c(o,Ki(s))),"Array | Matrix, Map":r.referToSelf(c=>(o,s)=>o.map(m=>c(m,s)))})});var iP="symbolicEqual",DV=["parse","simplify","typed","OperatorNode"],e0=F(iP,DV,e=>{var{parse:r,simplify:t,typed:n,OperatorNode:a}=e;function i(u,l){var c=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{},o=new a("-","subtract",[u,l]),s=t(o,{},c);return yr(s)&&!s.value}return n(iP,{"Node, Node":i,"Node, Node, Object":i})});var oP="derivative",SV=["typed","config","parse","simplify","equal","isZero","numeric","ConstantNode","FunctionNode","OperatorNode","ParenthesisNode","SymbolNode"],r0=F(oP,SV,e=>{var{typed:r,config:t,parse:n,simplify:a,equal:i,isZero:u,numeric:l,ConstantNode:c,FunctionNode:o,OperatorNode:s,ParenthesisNode:m,SymbolNode:d}=e;function h(b,M){var A=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{simplify:!0},S={};y(S,b,M.name);var O=w(b,S);return A.simplify?a(O):O}r.addConversion({from:"identifier",to:"SymbolNode",convert:n});var x=r(oP,{"Node, SymbolNode":h,"Node, SymbolNode, Object":h});r.removeConversion({from:"identifier",to:"SymbolNode",convert:n}),x._simplify=!0,x.toTex=function(b){return v.apply(null,b.args)};var v=r("_derivTex",{"Node, SymbolNode":function(M,A){return yr(M)&&Fr(M.value)==="string"?v(n(M.value).toString(),A.toString(),1):v(M.toTex(),A.toString(),1)},"Node, ConstantNode":function(M,A){if(Fr(A.value)==="string")return v(M,n(A.value));throw new Error("The second parameter to 'derivative' is a non-string constant")},"Node, SymbolNode, ConstantNode":function(M,A,S){return v(M.toString(),A.name,S.value)},"string, string, number":function(M,A,S){var O;return S===1?O="{d\\\\over d"+A+"}":O="{d^{"+S+"}\\\\over d"+A+"^{"+S+"}}",O+"\\\\left[".concat(M,"\\\\right]")}}),y=r("constTag",{"Object, ConstantNode, string":function(M,A){return M[A]=!0,!0},"Object, SymbolNode, string":function(M,A,S){return A.name!==S?(M[A]=!0,!0):!1},"Object, ParenthesisNode, string":function(M,A,S){return y(M,A.content,S)},"Object, FunctionAssignmentNode, string":function(M,A,S){return A.params.indexOf(S)===-1?(M[A]=!0,!0):y(M,A.expr,S)},"Object, FunctionNode | OperatorNode, string":function(M,A,S){if(A.args.length>0){for(var O=y(M,A.args[0],S),_=1;_0){var O=M.args.filter(function(H){return A[H]===void 0}),_=O.length===1?O[0]:new s("*","multiply",O),E=S.concat(w(_,A));return new s("*","multiply",E)}return new s("+","add",M.args.map(function(H){return new s("*","multiply",M.args.map(function(L){return L===H?w(L,A):L.clone()}))}))}if(M.op==="/"&&M.isBinary()){var T=M.args[0],R=M.args[1];return A[R]!==void 0?new s("/","divide",[w(T,A),R]):A[T]!==void 0?new s("*","multiply",[new s("-","unaryMinus",[T]),new s("/","divide",[w(R,A),new s("^","pow",[R.clone(),C(2)])])]):new s("/","divide",[new s("-","subtract",[new s("*","multiply",[w(T,A),R.clone()]),new s("*","multiply",[T.clone(),w(R,A)])]),new s("^","pow",[R.clone(),C(2)])])}if(M.op==="^"&&M.isBinary()){var q=M.args[0],W=M.args[1];if(A[q]!==void 0)return yr(q)&&(u(q.value)||i(q.value,1))?C(0):new s("*","multiply",[M,new s("*","multiply",[new o("log",[q.clone()]),w(W.clone(),A)])]);if(A[W]!==void 0){if(yr(W)){if(u(W.value))return C(0);if(i(W.value,1))return w(q,A)}var G=new s("^","pow",[q.clone(),new s("-","subtract",[W,C(1)])]);return new s("*","multiply",[W.clone(),new s("*","multiply",[w(q,A),G])])}return new s("*","multiply",[new s("^","pow",[q.clone(),W.clone()]),new s("+","add",[new s("*","multiply",[w(q,A),new s("/","divide",[W.clone(),q.clone()])]),new s("*","multiply",[w(W,A),new o("log",[q.clone()])])])])}throw new Error('Cannot process operator "'+M.op+'" in derivative: the operator is not supported, undefined, or the number of arguments passed to it are not supported')}});function C(b,M){return new c(l(b,M||t.number))}return x});var sP="rationalize",NV=["config","typed","equal","isZero","add","subtract","multiply","divide","pow","parse","simplifyConstant","simplifyCore","simplify","?bignumber","?fraction","mathWithTransform","matrix","AccessorNode","ArrayNode","ConstantNode","FunctionNode","IndexNode","ObjectNode","OperatorNode","SymbolNode","ParenthesisNode"],t0=F(sP,NV,e=>{var{config:r,typed:t,equal:n,isZero:a,add:i,subtract:u,multiply:l,divide:c,pow:o,parse:s,simplifyConstant:m,simplifyCore:d,simplify:h,fraction:x,bignumber:v,mathWithTransform:y,matrix:w,AccessorNode:C,ArrayNode:b,ConstantNode:M,FunctionNode:A,IndexNode:S,ObjectNode:O,OperatorNode:_,SymbolNode:E,ParenthesisNode:T}=e;function R(L){var k=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},K=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!1,z=W(),oe=q(L,k,!0,z.firstRules),pe=oe.variables.length,ae={exactFractions:!1},$={exactFractions:!0};if(L=oe.expression,pe>=1){L=G(L);var le,Ee,me=!0,ge=!1;L=h(L,z.firstRules,{},ae);for(var Se;Ee=me?z.distrDivRules:z.sucDivRules,L=h(L,Ee,{},$),me=!me,Se=L.toString(),Se!==le;)ge=!0,le=Se;ge&&(L=h(L,z.firstRulesAgain,{},ae)),L=h(L,z.finalRules,{},ae)}var xe=[],be={};return L.type==="OperatorNode"&&L.isBinary()&&L.op==="/"?(pe===1&&(L.args[0]=H(L.args[0],xe),L.args[1]=H(L.args[1])),K&&(be.numerator=L.args[0],be.denominator=L.args[1])):(pe===1&&(L=H(L,xe)),K&&(be.numerator=L,be.denominator=null)),K?(be.coefficients=xe,be.variables=oe.variables,be.expression=L,be):L}return t(sP,{Node:R,"Node, boolean":(L,k)=>R(L,{},k),"Node, Object":R,"Node, Object, boolean":R});function q(L,k,K,z){var oe=[],pe=h(L,z,k,{exactFractions:!1});K=!!K;var ae="+-*"+(K?"/":"");le(pe);var $={};return $.expression=pe,$.variables=oe,$;function le(Ee){var me=Ee.type;if(me==="FunctionNode")throw new Error("There is an unsolved function call");if(me==="OperatorNode")if(Ee.op==="^"){if(Ee.args[1].type!=="ConstantNode"||!Ze(parseFloat(Ee.args[1].value)))throw new Error("There is a non-integer exponent");le(Ee.args[0])}else{if(ae.indexOf(Ee.op)===-1)throw new Error("Operator "+Ee.op+" invalid in polynomial expression");for(var ge=0;ge1;if(z==="OperatorNode"&&L.isBinary()){var pe=!1,ae;if(L.op==="^"&&(L.args[0].type==="ParenthesisNode"||L.args[0].type==="OperatorNode")&&L.args[1].type==="ConstantNode"&&(ae=parseFloat(L.args[1].value),pe=ae>=2&&Ze(ae)),pe){if(ae>2){var $=L.args[0],le=new _("^","pow",[L.args[0].cloneDeep(),new M(ae-1)]);L=new _("*","multiply",[$,le])}else L=new _("*","multiply",[L.args[0],L.args[0].cloneDeep()]);oe&&(K==="content"?k.content=L:k.args[K]=L)}}if(z==="ParenthesisNode")G(L.content,L,"content");else if(z!=="ConstantNode"&&z!=="SymbolNode")for(var Ee=0;Ee=0;$--)if(k[$]!==0){var le=new M(pe?k[$]:Math.abs(k[$])),Ee=k[$]<0?"-":"+";if($>0){var me=new E(oe);if($>1){var ge=new M($);me=new _("^","pow",[me,ge])}k[$]===-1&&pe?le=new _("-","unaryMinus",[me]):Math.abs(k[$])===1?le=me:le=new _("*","multiply",[le,me])}pe?ae=le:Ee==="+"?ae=new _("+","add",[ae,le]):ae=new _("-","subtract",[ae,le]),pe=!1}if(pe)return new M(0);return ae;function Se(xe,be,De){var Ae=xe.type;if(Ae==="FunctionNode")throw new Error("There is an unsolved function call");if(Ae==="OperatorNode"){if("+-*^".indexOf(xe.op)===-1)throw new Error("Operator "+xe.op+" invalid");if(be!==null){if((xe.fn==="unaryMinus"||xe.fn==="pow")&&be.fn!=="add"&&be.fn!=="subtract"&&be.fn!=="multiply")throw new Error("Invalid "+xe.op+" placing");if((xe.fn==="subtract"||xe.fn==="add"||xe.fn==="multiply")&&be.fn!=="add"&&be.fn!=="subtract")throw new Error("Invalid "+xe.op+" placing");if((xe.fn==="subtract"||xe.fn==="add"||xe.fn==="unaryMinus")&&De.noFil!==0)throw new Error("Invalid "+xe.op+" placing")}(xe.op==="^"||xe.op==="*")&&(De.fire=xe.op);for(var We=0;Wez&&(k[Je]=0),k[Je]+=De.cte*(De.oper==="+"?1:-1),z=Math.max(Je,z);return}De.cte=Je,De.fire===""&&(k[0]+=De.cte*(De.oper==="+"?1:-1))}else throw new Error("Type "+Ae+" is not allowed")}}});var uP="zpk2tf",AV=["typed","add","multiply","Complex","number"],n0=F(uP,AV,e=>{var{typed:r,add:t,multiply:n,Complex:a,number:i}=e;return r(uP,{"Array,Array,number":function(o,s,m){return u(o,s,m)},"Array,Array":function(o,s){return u(o,s,1)},"Matrix,Matrix,number":function(o,s,m){return u(o.valueOf(),s.valueOf(),m)},"Matrix,Matrix":function(o,s){return u(o.valueOf(),s.valueOf(),1)}});function u(c,o,s){c.some(C=>C.type==="BigNumber")&&(c=c.map(C=>i(C))),o.some(C=>C.type==="BigNumber")&&(o=o.map(C=>i(C)));for(var m=[a(1,0)],d=[a(1,0)],h=0;h=0&&m-d{var{typed:r,add:t,multiply:n,Complex:a,divide:i,matrix:u}=e;return r(fP,{"Array, Array":function(s,m){var d=c(512);return l(s,m,d)},"Array, Array, Array":function(s,m,d){return l(s,m,d)},"Array, Array, number":function(s,m,d){if(d<0)throw new Error("w must be a positive number");var h=c(d);return l(s,m,h)},"Matrix, Matrix":function(s,m){var d=c(512),{w:h,h:x}=l(s.valueOf(),m.valueOf(),d);return{w:u(h),h:u(x)}},"Matrix, Matrix, Matrix":function(s,m,d){var{h}=l(s.valueOf(),m.valueOf(),d.valueOf());return{h:u(h),w:u(d)}},"Matrix, Matrix, number":function(s,m,d){if(d<0)throw new Error("w must be a positive number");var h=c(d),{h:x}=l(s.valueOf(),m.valueOf(),h);return{h:u(x),w:u(h)}}});function l(o,s,m){for(var d=[],h=[],x=0;x{var{classes:r}=e;return function(n,a){var i=r[a&&a.mathjs];return i&&typeof i.fromJSON=="function"?i.fromJSON(a):a}});var TV="replacer",FV=[],o0=F(TV,FV,()=>function(r,t){return typeof t=="number"&&(!isFinite(t)||isNaN(t))?{mathjs:"number",value:String(t)}:t});var cP="12.4.1";var s0=F("true",[],()=>!0),u0=F("false",[],()=>!1),f0=F("null",[],()=>null),c0=va("Infinity",["config","?BigNumber"],e=>{var{config:r,BigNumber:t}=e;return r.number==="BigNumber"?new t(1/0):1/0}),l0=va("NaN",["config","?BigNumber"],e=>{var{config:r,BigNumber:t}=e;return r.number==="BigNumber"?new t(NaN):NaN}),m0=va("pi",["config","?BigNumber"],e=>{var{config:r,BigNumber:t}=e;return r.number==="BigNumber"?Ic(t):HM}),p0=va("tau",["config","?BigNumber"],e=>{var{config:r,BigNumber:t}=e;return r.number==="BigNumber"?mE(t):$M}),d0=va("e",["config","?BigNumber"],e=>{var{config:r,BigNumber:t}=e;return r.number==="BigNumber"?cE(t):GM}),h0=va("phi",["config","?BigNumber"],e=>{var{config:r,BigNumber:t}=e;return r.number==="BigNumber"?lE(t):VM}),v0=va("LN2",["config","?BigNumber"],e=>{var{config:r,BigNumber:t}=e;return r.number==="BigNumber"?new t(2).ln():Math.LN2}),g0=va("LN10",["config","?BigNumber"],e=>{var{config:r,BigNumber:t}=e;return r.number==="BigNumber"?new t(10).ln():Math.LN10}),x0=va("LOG2E",["config","?BigNumber"],e=>{var{config:r,BigNumber:t}=e;return r.number==="BigNumber"?new t(1).div(new t(2).ln()):Math.LOG2E}),y0=va("LOG10E",["config","?BigNumber"],e=>{var{config:r,BigNumber:t}=e;return r.number==="BigNumber"?new t(1).div(new t(10).ln()):Math.LOG10E}),b0=va("SQRT1_2",["config","?BigNumber"],e=>{var{config:r,BigNumber:t}=e;return r.number==="BigNumber"?new t("0.5").sqrt():Math.SQRT1_2}),w0=va("SQRT2",["config","?BigNumber"],e=>{var{config:r,BigNumber:t}=e;return r.number==="BigNumber"?new t(2).sqrt():Math.SQRT2}),D0=va("i",["Complex"],e=>{var{Complex:r}=e;return r.I}),lP=F("PI",["pi"],e=>{var{pi:r}=e;return r}),mP=F("E",["e"],e=>{var{e:r}=e;return r}),S0=F("version",[],()=>cP);function va(e,r,t){return F(e,r,t,{recreateOnConfigChange:!0})}var N0=Er("speedOfLight","299792458","m s^-1"),A0=Er("gravitationConstant","6.67430e-11","m^3 kg^-1 s^-2"),M0=Er("planckConstant","6.62607015e-34","J s"),C0=Er("reducedPlanckConstant","1.0545718176461565e-34","J s"),E0=Er("magneticConstant","1.25663706212e-6","N A^-2"),T0=Er("electricConstant","8.8541878128e-12","F m^-1"),F0=Er("vacuumImpedance","376.730313667","ohm"),_0=Er("coulomb","8.987551792261171e9","N m^2 C^-2"),O0=Er("elementaryCharge","1.602176634e-19","C"),B0=Er("bohrMagneton","9.2740100783e-24","J T^-1"),P0=Er("conductanceQuantum","7.748091729863649e-5","S"),I0=Er("inverseConductanceQuantum","12906.403729652257","ohm"),R0=Er("magneticFluxQuantum","2.0678338484619295e-15","Wb"),k0=Er("nuclearMagneton","5.0507837461e-27","J T^-1"),q0=Er("klitzing","25812.807459304513","ohm");var L0=Er("bohrRadius","5.29177210903e-11","m"),z0=Er("classicalElectronRadius","2.8179403262e-15","m"),U0=Er("electronMass","9.1093837015e-31","kg"),W0=Er("fermiCoupling","1.1663787e-5","GeV^-2"),Y0=bx("fineStructure",.0072973525693),H0=Er("hartreeEnergy","4.3597447222071e-18","J"),$0=Er("protonMass","1.67262192369e-27","kg"),G0=Er("deuteronMass","3.3435830926e-27","kg"),V0=Er("neutronMass","1.6749271613e-27","kg"),Z0=Er("quantumOfCirculation","3.6369475516e-4","m^2 s^-1"),Q0=Er("rydberg","10973731.568160","m^-1"),X0=Er("thomsonCrossSection","6.6524587321e-29","m^2"),J0=bx("weakMixingAngle",.2229),K0=bx("efimovFactor",22.7),j0=Er("atomicMass","1.66053906660e-27","kg"),ex=Er("avogadro","6.02214076e23","mol^-1"),rx=Er("boltzmann","1.380649e-23","J K^-1"),tx=Er("faraday","96485.33212331001","C mol^-1"),nx=Er("firstRadiation","3.7417718521927573e-16","W m^2"),ax=Er("loschmidt","2.686780111798444e25","m^-3"),ix=Er("gasConstant","8.31446261815324","J K^-1 mol^-1"),ox=Er("molarPlanckConstant","3.990312712893431e-10","J s mol^-1"),sx=Er("molarVolume","0.022413969545014137","m^3 mol^-1"),ux=bx("sackurTetrode",-1.16487052358),fx=Er("secondRadiation","0.014387768775039337","m K"),cx=Er("stefanBoltzmann","5.67037441918443e-8","W m^-2 K^-4"),lx=Er("wienDisplacement","2.897771955e-3","m K"),mx=Er("molarMass","0.99999999965e-3","kg mol^-1"),px=Er("molarMassC12","11.9999999958e-3","kg mol^-1"),dx=Er("gravity","9.80665","m s^-2"),hx=Er("planckLength","1.616255e-35","m"),vx=Er("planckMass","2.176435e-8","kg"),gx=Er("planckTime","5.391245e-44","s"),xx=Er("planckCharge","1.87554603778e-18","C"),yx=Er("planckTemperature","1.416785e+32","K");function Er(e,r,t){var n=["config","Unit","BigNumber"];return F(e,n,a=>{var{config:i,Unit:u,BigNumber:l}=a,c=i.number==="BigNumber"?new l(r):parseFloat(r),o=new u(c,t);return o.fixPrefix=!0,o})}function bx(e,r){var t=["config","BigNumber"];return F(e,t,n=>{var{config:a,BigNumber:i}=n;return a.number==="BigNumber"?new i(r):r})}var _V="apply",OV=["typed","isInteger"],wx=F(_V,OV,e=>{var{typed:r,isInteger:t}=e,n=qo({typed:r,isInteger:t});return r("apply",{"...any":function(i){var u=i[1];sr(u)?i[1]=u-1:rr(u)&&(i[1]=u.minus(1));try{return n.apply(null,i)}catch(l){throw mt(l)}}})},{isTransformFunction:!0});var BV="column",PV=["typed","Index","matrix","range"],Dx=F(BV,PV,e=>{var{typed:r,Index:t,matrix:n,range:a}=e,i=Wu({typed:r,Index:t,matrix:n,range:a});return r("column",{"...any":function(l){var c=l.length-1,o=l[c];sr(o)&&(l[c]=o-1);try{return i.apply(null,l)}catch(s){throw mt(s)}}})},{isTransformFunction:!0});function lf(e,r,t){var n=e.filter(function(c){return at(c)&&!(c.name in r)&&!t.has(c.name)})[0];if(!n)throw new Error('No undefined variable found in inline expression "'+e+'"');var a=n.name,i=new Map,u=new Eu(t,i,new Set([a])),l=e.compile();return function(o){return i.set(a,o),l.evaluate(u)}}var IV="filter",RV=["typed"],Sx=F(IV,RV,e=>{var{typed:r}=e;function t(a,i,u){var l,c;return a[0]&&(l=a[0].compile().evaluate(u)),a[1]&&(at(a[1])||_a(a[1])?c=a[1].compile().evaluate(u):c=lf(a[1],i,u)),n(l,c)}t.rawArgs=!0;var n=r("filter",{"Array, function":pP,"Matrix, function":function(i,u){return i.create(pP(i.toArray(),u))},"Array, RegExp":Mu,"Matrix, RegExp":function(i,u){return i.create(Mu(i.toArray(),u))}});return t},{isTransformFunction:!0});function pP(e,r){return Om(e,function(t,n,a){return Ia(r,t,[n+1],a,"filter")})}var kV="forEach",qV=["typed"],Nx=F(kV,qV,e=>{var{typed:r}=e;function t(a,i,u){var l,c;return a[0]&&(l=a[0].compile().evaluate(u)),a[1]&&(at(a[1])||_a(a[1])?c=a[1].compile().evaluate(u):c=lf(a[1],i,u)),n(l,c)}t.rawArgs=!0;var n=r("forEach",{"Array | Matrix, function":function(i,u){var l=function c(o,s){if(Array.isArray(o))Fo(o,function(m,d){c(m,s.concat(d+1))});else return Ia(u,o,s,i,"forEach")};l(i.valueOf(),[])}});return t},{isTransformFunction:!0});var LV="index",zV=["Index","getMatrixDataType"],Ax=F(LV,zV,e=>{var{Index:r,getMatrixDataType:t}=e;return function(){for(var a=[],i=0,u=arguments.length;i0?0:2;else if(l&&l.isSet===!0)l=l.map(function(o){return o-1});else if(Mr(l)||Qe(l))t(l)!=="boolean"&&(l=l.map(function(o){return o-1}));else if(sr(l))l--;else if(rr(l))l=l.toNumber()-1;else if(typeof l!="string")throw new TypeError("Dimension must be an Array, Matrix, number, string, or Range");a[i]=l}var c=new r;return r.apply(c,a),c}},{isTransformFunction:!0});var UV="map",WV=["typed"],Mx=F(UV,WV,e=>{var{typed:r}=e;function t(a,i,u){var l,c;return a[0]&&(l=a[0].compile().evaluate(u)),a[1]&&(at(a[1])||_a(a[1])?c=a[1].compile().evaluate(u):c=lf(a[1],i,u)),n(l,c)}t.rawArgs=!0;var n=r("map",{"Array, function":function(i,u){return dP(i,u,i)},"Matrix, function":function(i,u){return i.create(dP(i.valueOf(),u,i))}});return t},{isTransformFunction:!0});function dP(e,r,t){function n(a,i){return Array.isArray(a)?Xn(a,function(u,l){return n(u,i.concat(l+1))}):Ia(r,a,i,t,"map")}return n(e,[])}function Cn(e){if(e.length===2&&Nt(e[0])){e=e.slice();var r=e[1];sr(r)?e[1]=r-1:rr(r)&&(e[1]=r.minus(1))}return e}var YV="max",HV=["typed","config","numeric","larger"],Cx=F(YV,HV,e=>{var{typed:r,config:t,numeric:n,larger:a}=e,i=ef({typed:r,config:t,numeric:n,larger:a});return r("max",{"...any":function(l){l=Cn(l);try{return i.apply(null,l)}catch(c){throw mt(c)}}})},{isTransformFunction:!0});var $V="mean",GV=["typed","add","divide"],Ex=F($V,GV,e=>{var{typed:r,add:t,divide:n}=e,a=of({typed:r,add:t,divide:n});return r("mean",{"...any":function(u){u=Cn(u);try{return a.apply(null,u)}catch(l){throw mt(l)}}})},{isTransformFunction:!0});var VV="min",ZV=["typed","config","numeric","smaller"],Tx=F(VV,ZV,e=>{var{typed:r,config:t,numeric:n,smaller:a}=e,i=rf({typed:r,config:t,numeric:n,smaller:a});return r("min",{"...any":function(l){l=Cn(l);try{return i.apply(null,l)}catch(c){throw mt(c)}}})},{isTransformFunction:!0});var QV="range",XV=["typed","config","?matrix","?bignumber","smaller","smallerEq","larger","largerEq","add","isPositive"],Fx=F(QV,XV,e=>{var{typed:r,config:t,matrix:n,bignumber:a,smaller:i,smallerEq:u,larger:l,largerEq:c,add:o,isPositive:s}=e,m=$u({typed:r,config:t,matrix:n,bignumber:a,smaller:i,smallerEq:u,larger:l,largerEq:c,add:o,isPositive:s});return r("range",{"...any":function(h){var x=h.length-1,v=h[x];return typeof v!="boolean"&&h.push(!0),m.apply(null,h)}})},{isTransformFunction:!0});var JV="row",KV=["typed","Index","matrix","range"],_x=F(JV,KV,e=>{var{typed:r,Index:t,matrix:n,range:a}=e,i=Gu({typed:r,Index:t,matrix:n,range:a});return r("row",{"...any":function(l){var c=l.length-1,o=l[c];sr(o)&&(l[c]=o-1);try{return i.apply(null,l)}catch(s){throw mt(s)}}})},{isTransformFunction:!0});var jV="subset",eZ=["typed","matrix","zeros","add"],Ox=F(jV,eZ,e=>{var{typed:r,matrix:t,zeros:n,add:a}=e,i=Vu({typed:r,matrix:t,zeros:n,add:a});return r("subset",{"...any":function(l){try{return i.apply(null,l)}catch(c){throw mt(c)}}})},{isTransformFunction:!0});var rZ="concat",tZ=["typed","matrix","isInteger"],Bx=F(rZ,tZ,e=>{var{typed:r,matrix:t,isInteger:n}=e,a=Uu({typed:r,matrix:t,isInteger:n});return r("concat",{"...any":function(u){var l=u.length-1,c=u[l];sr(c)?u[l]=c-1:rr(c)&&(u[l]=c.minus(1));try{return a.apply(null,u)}catch(o){throw mt(o)}}})},{isTransformFunction:!0});var hP="diff",nZ=["typed","matrix","subtract","number","bignumber"],Px=F(hP,nZ,e=>{var{typed:r,matrix:t,subtract:n,number:a,bignumber:i}=e,u=Yu({typed:r,matrix:t,subtract:n,number:a,bignumber:i});return r(hP,{"...any":function(c){c=Cn(c);try{return u.apply(null,c)}catch(o){throw mt(o)}}})},{isTransformFunction:!0});var aZ="std",iZ=["typed","map","sqrt","variance"],Ix=F(aZ,iZ,e=>{var{typed:r,map:t,sqrt:n,variance:a}=e,i=ff({typed:r,map:t,sqrt:n,variance:a});return r("std",{"...any":function(l){l=Cn(l);try{return i.apply(null,l)}catch(c){throw mt(c)}}})},{isTransformFunction:!0});var vP="sum",oZ=["typed","config","add","numeric"],Rx=F(vP,oZ,e=>{var{typed:r,config:t,add:n,numeric:a}=e,i=nf({typed:r,config:t,add:n,numeric:a});return r(vP,{"...any":function(l){l=Cn(l);try{return i.apply(null,l)}catch(c){throw mt(c)}}})},{isTransformFunction:!0});var sZ="quantileSeq",uZ=["typed","bignumber","add","subtract","divide","multiply","partitionSelect","compare","isInteger","smaller","smallerEq","larger"],kx=F(sZ,uZ,e=>{var{typed:r,bignumber:t,add:n,subtract:a,divide:i,multiply:u,partitionSelect:l,compare:c,isInteger:o,smaller:s,smallerEq:m,larger:d}=e,h=uf({typed:r,bignumber:t,add:n,subtract:a,divide:i,multiply:u,partitionSelect:l,compare:c,isInteger:o,smaller:s,smallerEq:m,larger:d});return r("quantileSeq",{"Array | Matrix, number | BigNumber":h,"Array | Matrix, number | BigNumber, number":(v,y,w)=>h(v,y,x(w)),"Array | Matrix, number | BigNumber, boolean":h,"Array | Matrix, number | BigNumber, boolean, number":(v,y,w,C)=>h(v,y,w,x(C)),"Array | Matrix, Array | Matrix":h,"Array | Matrix, Array | Matrix, number":(v,y,w)=>h(v,y,x(w)),"Array | Matrix, Array | Matrix, boolean":h,"Array | Matrix, Array | Matrix, boolean, number":(v,y,w,C)=>h(v,y,w,x(C))});function x(v){return Cn([[],v])[1]}},{isTransformFunction:!0});var gP="cumsum",fZ=["typed","add","unaryPlus"],qx=F(gP,fZ,e=>{var{typed:r,add:t,unaryPlus:n}=e,a=af({typed:r,add:t,unaryPlus:n});return r(gP,{"...any":function(u){if(u.length===2&&Nt(u[0])){var l=u[1];sr(l)?u[1]=l-1:rr(l)&&(u[1]=l.minus(1))}try{return a.apply(null,u)}catch(c){throw mt(c)}}})},{isTransformFunction:!0});var xP="variance",cZ=["typed","add","subtract","multiply","divide","apply","isNaN"],Lx=F(xP,cZ,e=>{var{typed:r,add:t,subtract:n,multiply:a,divide:i,apply:u,isNaN:l}=e,c=sf({typed:r,add:t,subtract:n,multiply:a,divide:i,apply:u,isNaN:l});return r(xP,{"...any":function(s){s=Cn(s);try{return c.apply(null,s)}catch(m){throw mt(m)}}})},{isTransformFunction:!0});var yP="print",lZ=["typed","matrix","zeros","add"],zx=F(yP,lZ,e=>{var{typed:r,matrix:t,zeros:n,add:a}=e,i=Qu({typed:r,matrix:t,zeros:n,add:a});return r(yP,{"string, Object | Array":function(c,o){return i(u(c),o)},"string, Object | Array, number | Object":function(c,o,s){return i(u(c),o,s)}});function u(l){return l.replace(qd,c=>{var o=c.slice(1).split("."),s=o.map(function(m){return!isNaN(m)&&m.length>0?parseInt(m)-1:m});return"$"+s.join(".")})}},{isTransformFunction:!0});var mZ="and",pZ=["typed","matrix","zeros","add","equalScalar","not","concat"],Ux=F(mZ,pZ,e=>{var{typed:r,matrix:t,equalScalar:n,zeros:a,not:i,concat:u}=e,l=ju({typed:r,matrix:t,equalScalar:n,zeros:a,not:i,concat:u});function c(o,s,m){var d=o[0].compile().evaluate(m);if(!Nt(d)&&!l(d,!0))return!1;var h=o[1].compile().evaluate(m);return l(d,h)}return c.rawArgs=!0,c},{isTransformFunction:!0});var dZ="or",hZ=["typed","matrix","equalScalar","DenseMatrix","concat"],Wx=F(dZ,hZ,e=>{var{typed:r,matrix:t,equalScalar:n,DenseMatrix:a,concat:i}=e,u=zu({typed:r,matrix:t,equalScalar:n,DenseMatrix:a,concat:i});function l(c,o,s){var m=c[0].compile().evaluate(s);if(!Nt(m)&&u(m,!1))return!0;var d=c[1].compile().evaluate(s);return u(m,d)}return l.rawArgs=!0,l},{isTransformFunction:!0});var vZ="bitAnd",gZ=["typed","matrix","zeros","add","equalScalar","not","concat"],Yx=F(vZ,gZ,e=>{var{typed:r,matrix:t,equalScalar:n,zeros:a,not:i,concat:u}=e,l=qu({typed:r,matrix:t,equalScalar:n,zeros:a,not:i,concat:u});function c(o,s,m){var d=o[0].compile().evaluate(m);if(!Nt(d)){if(isNaN(d))return NaN;if(d===0||d===!1)return 0}var h=o[1].compile().evaluate(m);return l(d,h)}return c.rawArgs=!0,c},{isTransformFunction:!0});var xZ="bitOr",yZ=["typed","matrix","equalScalar","DenseMatrix","concat"],Hx=F(xZ,yZ,e=>{var{typed:r,matrix:t,equalScalar:n,DenseMatrix:a,concat:i}=e,u=Lu({typed:r,matrix:t,equalScalar:n,DenseMatrix:a,concat:i});function l(c,o,s){var m=c[0].compile().evaluate(s);if(!Nt(m)){if(isNaN(m))return NaN;if(m===-1)return-1;if(m===!0)return 1}var d=c[1].compile().evaluate(s);return u(m,d)}return l.rawArgs=!0,l},{isTransformFunction:!0});var Ge=Hm({config:Oe}),pt=$m({}),ID=d0({BigNumber:Ge,config:Oe}),bP=u0({}),wP=Y0({BigNumber:Ge,config:Oe}),Uo=Gm({}),RD=D0({Complex:pt}),DP=c0({BigNumber:Ge,config:Oe}),SP=g0({BigNumber:Ge,config:Oe}),NP=y0({BigNumber:Ge,config:Oe}),Lc=Zm({}),AP=l0({BigNumber:Ge,config:Oe}),MP=f0({}),CP=h0({BigNumber:Ge,config:Oe}),EP=Vm({}),kD=Rm({}),TP=b0({BigNumber:Ge,config:Oe}),FP=ux({BigNumber:Ge,config:Oe}),qD=p0({BigNumber:Ge,config:Oe}),_P=s0({}),OP=S0({}),_r=Xm({Matrix:Lc}),BP=K0({BigNumber:Ge,config:Oe}),PP=v0({BigNumber:Ge,config:Oe}),$x=m0({BigNumber:Ge,config:Oe}),IP=o0({}),RP=w0({BigNumber:Ge,config:Oe}),te=Im({BigNumber:Ge,Complex:pt,DenseMatrix:_r,Fraction:Uo}),Gx=Np({BigNumber:Ge,config:Oe,typed:te}),kP=J0({BigNumber:Ge,config:Oe}),En=Ap({typed:te}),qP=Oh({Complex:pt,config:Oe,typed:te}),LP=Ph({BigNumber:Ge,typed:te}),zP=Rh({BigNumber:Ge,Complex:pt,config:Oe,typed:te}),Qt=Cp({typed:te}),UP=jp({typed:te}),WP=Lh({BigNumber:Ge,Complex:pt,config:Oe,typed:te}),YP=Uh({typed:te}),LD=Wh({typed:te}),HP=Hh({Complex:pt,config:Oe,typed:te}),ea=hp({BigNumber:Ge,typed:te}),$P=Jp({typed:te}),GP=dp({typed:te}),VP=Jm({typed:te}),zc=Bg({typed:te}),Uc=vp({Complex:pt,typed:te}),Wo=ed({typed:te}),Vx=$h({typed:te}),ZP=Vh({BigNumber:Ge,typed:te}),QP=Qh({BigNumber:Ge,typed:te}),XP=_p({typed:te}),Ir=cp({config:Oe,typed:te}),JP=Fd({typed:te}),zD=Op({typed:te}),KP=Bp({Complex:pt,typed:te}),jP=ud({typed:te}),eI=cd({typed:te}),mf=Pd({typed:te}),Zx=ld({typed:te}),rI=kd({format:mf,typed:te}),Qx=rd({typed:te}),Ln=ep({typed:te}),no=tp({typed:te}),Yo=ip({typed:te}),qa=op({typed:te}),tI=x0({BigNumber:Ge,config:Oe}),nI=Rg({Complex:pt,typed:te}),aI=kp({Complex:pt,config:Oe,typed:te}),UD=qp({Complex:pt,config:Oe,typed:te}),Ho=dd({typed:te}),Ot=Lp({typed:te}),Wc=nd({typed:te}),Oi=mp({typed:te}),iI=Rd({format:mf,typed:te}),oI=Wg({config:Oe,typed:te}),sI=Qu({typed:te}),uI=Yg({config:Oe,typed:te}),Xx=td({typed:te}),fI=Jh({BigNumber:Ge,typed:te}),WD=Wp({BigNumber:Ge,Fraction:Uo,complex:Uc,typed:te}),Yc=jh({typed:te}),Bi=lp({Matrix:Lc,equalScalar:Ir,typed:te}),cI=Dp({typed:te}),lI=Hp({typed:te}),mI=pp({typed:te}),ga=Ep({typed:te}),pI=rv({typed:te}),YD=up({typed:te}),dI=Bh({Complex:pt,config:Oe,typed:te}),hI=kh({BigNumber:Ge,typed:te}),Jx=qo({isInteger:Ln,typed:te}),vI=qh({BigNumber:Ge,Complex:pt,config:Oe,typed:te}),gI=Id({format:mf,typed:te}),xI=Pg({typed:te}),yI=Gh({typed:te}),bI=Xh({BigNumber:Ge,typed:te}),pf=sp({typed:te}),wI=zd({typed:te}),DI=Hg({config:Oe,typed:te}),SI=Kh({BigNumber:Ge,typed:te}),NI=ev({typed:te}),AI=Fh({SparseMatrix:Bi,typed:te}),La=Yp({Complex:pt,config:Oe,typed:te}),MI=tv({typed:te}),fi=Sp({typed:te}),CI=Ih({BigNumber:Ge,Complex:pt,config:Oe,typed:te}),EI=Zh({BigNumber:Ge,typed:te}),Bs=gp({Fraction:Uo,typed:te}),$o=np({typed:te}),$e=xp({DenseMatrix:_r,Matrix:Lc,SparseMatrix:Bi,typed:te}),TI=yp({isZero:qa,matrix:$e,typed:te}),FI=Od({isNaN:pf,isNumeric:$o,typed:te}),za=Ud({bignumber:ea,fraction:Bs,number:Oi}),HD=Bd({config:Oe,multiplyScalar:Ot,numeric:za,typed:te}),$D=xd({isInteger:Ln,matrix:$e,typed:te}),cn=Dd({matrix:$e,config:Oe,typed:te}),_I=Sd({matrix:$e,typed:te}),df=Nd({matrix:$e,typed:te}),GD=Gp({BigNumber:Ge,config:Oe,matrix:$e,typed:te}),ln=Md({BigNumber:Ge,config:Oe,matrix:$e,typed:te}),OI=zh({Complex:pt,config:Oe,typed:te}),VD=Tp({BigNumber:Ge,Complex:pt,Fraction:Uo,config:Oe,isNegative:no,matrix:$e,typed:te,unaryMinus:fi}),Gr=Uu({isInteger:Ln,matrix:$e,typed:te}),BI=id({prod:HD,size:cn,typed:te}),Kx=Ad({conj:Wo,transpose:df,typed:te}),ZD=sd({DenseMatrix:_r,SparseMatrix:Bi,matrix:$e,typed:te}),Mt=Wd({numeric:za,typed:te}),hf=Qd({DenseMatrix:_r,concat:Gr,divideScalar:Mt,equalScalar:Ir,matrix:$e,typed:te}),xa=uh({DenseMatrix:_r,concat:Gr,equalScalar:Ir,matrix:$e,typed:te}),vf=fd({matrix:$e,typed:te}),PI=ap({isNumeric:$o,typed:te}),ao=md({BigNumber:Ge,DenseMatrix:_r,SparseMatrix:Bi,config:Oe,matrix:$e,typed:te}),II=pd({matrix:$e,multiplyScalar:Ot,typed:te}),Hc=gh({DenseMatrix:_r,concat:Gr,config:Oe,matrix:$e,typed:te}),RI=eh({DenseMatrix:_r,concat:Gr,equalScalar:Ir,matrix:$e,typed:te,zeros:ln}),QD=Xd({DenseMatrix:_r,divideScalar:Mt,equalScalar:Ir,matrix:$e,multiplyScalar:Ot,subtractScalar:ga,typed:te}),jx=wp({flatten:vf,matrix:$e,size:cn,typed:te}),kI=Up({BigNumber:Ge,concat:Gr,equalScalar:Ir,matrix:$e,typed:te}),qI=hd({BigNumber:Ge,config:Oe,matrix:$e,typed:te}),ey=sg({addScalar:Qt,complex:Uc,conj:Wo,divideScalar:Mt,equal:xa,identity:ao,isZero:qa,matrix:$e,multiplyScalar:Ot,sign:WD,sqrt:La,subtractScalar:ga,typed:te,unaryMinus:fi,zeros:ln}),LI=yd({config:Oe,matrix:$e}),zI=rh({DenseMatrix:_r,concat:Gr,equalScalar:Ir,matrix:$e,typed:te,zeros:ln}),Ps=Hd({BigNumber:Ge,DenseMatrix:_r,config:Oe,equalScalar:Ir,matrix:$e,typed:te,zeros:ln}),Tn=lh({DenseMatrix:_r,concat:Gr,config:Oe,matrix:$e,typed:te}),Bt=$p({DenseMatrix:_r,concat:Gr,equalScalar:Ir,matrix:$e,subtractScalar:ga,typed:te,unaryMinus:fi}),UI=Ld({concat:Gr,matrix:$e,typed:te}),WI=bh({DenseMatrix:_r,concat:Gr,config:Oe,equalScalar:Ir,matrix:$e,typed:te}),ry=Jd({DenseMatrix:_r,divideScalar:Mt,equalScalar:Ir,matrix:$e,multiplyScalar:Ot,subtractScalar:ga,typed:te}),YI=ad({DenseMatrix:_r,concat:Gr,matrix:$e,typed:te}),Lr=pv({DenseMatrix:_r,SparseMatrix:Bi,addScalar:Qt,concat:Gr,equalScalar:Ir,matrix:$e,typed:te}),HI=Yh({BigNumber:Ge,DenseMatrix:_r,concat:Gr,equalScalar:Ir,matrix:$e,typed:te}),$I=qu({concat:Gr,equalScalar:Ir,matrix:$e,typed:te}),GI=Lu({DenseMatrix:_r,concat:Gr,equalScalar:Ir,matrix:$e,typed:te}),VI=Kp({DenseMatrix:_r,concat:Gr,matrix:$e,typed:te}),ZI=Vg({addScalar:Qt,combinations:zc,divideScalar:Mt,isInteger:Ln,isNegative:no,multiplyScalar:Ot,typed:te}),Go=ah({BigNumber:Ge,DenseMatrix:_r,Fraction:Uo,concat:Gr,config:Oe,equalScalar:Ir,matrix:$e,typed:te}),XD=oh({concat:Gr,matrix:$e,typed:te}),QI=af({add:Lr,typed:te,unaryPlus:Gx}),ty=xh({equal:xa,typed:te}),XI=Yu({matrix:$e,number:Oi,subtract:Bt,typed:te}),JI=Cg({abs:En,addScalar:Qt,deepEqual:ty,divideScalar:Mt,multiplyScalar:Ot,sqrt:La,subtractScalar:ga,typed:te}),$c=vv({addScalar:Qt,conj:Wo,multiplyScalar:Ot,size:cn,typed:te}),KI=fh({compareText:XD,isZero:qa,typed:te}),JD=Pu({DenseMatrix:_r,config:Oe,equalScalar:Ir,matrix:$e,round:Ps,typed:te,zeros:ln}),jI=Ip({BigNumber:Ge,DenseMatrix:_r,concat:Gr,config:Oe,equalScalar:Ir,matrix:$e,round:Ps,typed:te,zeros:ln}),e4=dv({abs:En,addScalar:Qt,divideScalar:Mt,isPositive:Yo,multiplyScalar:Ot,smaller:Tn,sqrt:La,typed:te}),KD=Sh({DenseMatrix:_r,smaller:Tn}),yn=Nh({ImmutableDenseMatrix:KD,getMatrixDataType:Zx}),Fn=hh({DenseMatrix:_r,concat:Gr,config:Oe,matrix:$e,typed:te}),ny=$d({Complex:pt,config:Oe,divideScalar:Mt,typed:te}),r4=Kd({DenseMatrix:_r,divideScalar:Mt,equalScalar:Ir,matrix:$e,multiplyScalar:Ot,subtractScalar:ga,typed:te}),t4=bp({flatten:vf,matrix:$e,size:cn,typed:te}),n4=rf({config:Oe,numeric:za,smaller:Tn,typed:te}),jD=Iu({DenseMatrix:_r,concat:Gr,config:Oe,equalScalar:Ir,matrix:$e,round:Ps,typed:te,zeros:ln}),it=zp({addScalar:Qt,dot:$c,equalScalar:Ir,matrix:$e,multiplyScalar:Ot,typed:te}),a4=Vd({Complex:pt,config:Oe,divideScalar:Mt,typed:te}),i4=zu({DenseMatrix:_r,concat:Gr,equalScalar:Ir,matrix:$e,typed:te}),Gc=wh({compare:Go,isNaN:pf,isNumeric:$o,typed:te}),o4=th({DenseMatrix:_r,concat:Gr,equalScalar:Ir,matrix:$e,typed:te,zeros:ln}),eS=cg({SparseMatrix:Bi,abs:En,add:Lr,divideScalar:Mt,larger:Fn,largerEq:Hc,multiply:it,subtract:Bt,transpose:df,typed:te}),ra=Vu({add:Lr,matrix:$e,typed:te,zeros:ln}),ay=nf({add:Lr,config:Oe,numeric:za,typed:te}),s4=gv({add:Lr,matrix:$e,typed:te}),rS=jd({DenseMatrix:_r,divideScalar:Mt,equalScalar:Ir,matrix:$e,multiplyScalar:Ot,subtractScalar:ga,typed:te}),u4=n0({Complex:pt,add:Lr,multiply:it,number:Oi,typed:te}),iy=Fp({DenseMatrix:_r,config:Oe,equalScalar:Ir,matrix:$e,round:Ps,typed:te,zeros:ln}),ci=ih({compare:Go,typed:te}),f4=Zg({addScalar:Qt,combinations:zc,isInteger:Ln,isNegative:no,isPositive:Yo,larger:Fn,typed:te}),c4=od({matrix:$e,multiply:it,subtract:Bt,typed:te}),tS=gg({divideScalar:Mt,isZero:qa,matrix:$e,multiply:it,subtractScalar:ga,typed:te,unaryMinus:fi}),l4=Qp({concat:Gr,equalScalar:Ir,matrix:$e,multiplyScalar:Ot,typed:te}),nS=Ah({larger:Fn,smaller:Tn}),aS=Pp({Complex:pt,DenseMatrix:_r,ceil:iy,equalScalar:Ir,floor:JD,matrix:$e,typed:te,zeros:ln}),iS=xv({Index:yn,typed:te}),m4=Eg({abs:En,add:Lr,addScalar:Qt,config:Oe,divideScalar:Mt,equalScalar:Ir,flatten:vf,isNumeric:$o,isZero:qa,matrix:$e,multiply:it,multiplyScalar:Ot,smaller:Tn,subtract:Bt,typed:te}),p4=Vp({BigNumber:Ge,add:Lr,config:Oe,equal:xa,isInteger:Ln,mod:jD,smaller:Tn,typed:te,xgcd:GD}),d4=Rp({concat:Gr,equalScalar:Ir,matrix:$e,typed:te}),h4=Gd({Complex:pt,config:Oe,divideScalar:Mt,log:ny,typed:te}),oy=ef({config:Oe,larger:Fn,numeric:za,typed:te}),v4=nv({DenseMatrix:_r,Index:yn,compareNatural:ci,size:cn,subset:ra,typed:te}),g4=iv({DenseMatrix:_r,Index:yn,compareNatural:ci,size:cn,subset:ra,typed:te}),x4=sv({Index:yn,compareNatural:ci,size:cn,subset:ra,typed:te}),y4=fv({Index:yn,compareNatural:ci,size:cn,subset:ra,typed:te}),Is=ph({DenseMatrix:_r,concat:Gr,config:Oe,matrix:$e,typed:te}),b4=Dh({compare:Go,compareNatural:ci,matrix:$e,typed:te}),w4=ju({concat:Gr,equalScalar:Ir,matrix:$e,not:Wc,typed:te,zeros:ln}),Rs=$u({bignumber:ea,matrix:$e,add:Lr,config:Oe,isPositive:Yo,larger:Fn,largerEq:Hc,smaller:Tn,smallerEq:Is,typed:te}),D4=Gu({Index:yn,matrix:$e,range:Rs,typed:te}),oS=av({DenseMatrix:_r,Index:yn,compareNatural:ci,size:cn,subset:ra,typed:te}),S4=uv({Index:yn,compareNatural:ci,size:cn,subset:ra,typed:te}),sS=lv({Index:yn,concat:Gr,setDifference:oS,size:cn,subset:ra,typed:te}),uS=Mh({FibonacciHeap:nS,addScalar:Qt,equalScalar:Ir}),fS=Wu({Index:yn,matrix:$e,range:Rs,typed:te}),Vo=xg({abs:En,addScalar:Qt,det:tS,divideScalar:Mt,identity:ao,matrix:$e,multiply:it,typed:te,unaryMinus:fi}),cS=og({DenseMatrix:_r,Spa:uS,SparseMatrix:Bi,abs:En,addScalar:Qt,divideScalar:Mt,equalScalar:Ir,larger:Fn,matrix:$e,multiplyScalar:Ot,subtractScalar:ga,typed:te,unaryMinus:fi}),N4=yg({Complex:pt,add:Lr,ctranspose:Kx,deepEqual:ty,divideScalar:Mt,dot:$c,dotDivide:hf,equal:xa,inv:Vo,matrix:$e,multiply:it,typed:te}),ya=Yd({Complex:pt,config:Oe,fraction:Bs,identity:ao,inv:Vo,matrix:$e,multiply:it,number:Oi,typed:te}),lS=ov({DenseMatrix:_r,Index:yn,compareNatural:ci,size:cn,subset:ra,typed:te}),A4=mv({Index:yn,concat:Gr,setIntersect:lS,setSymDifference:sS,size:cn,subset:ra,typed:te}),M4=Dg({abs:En,add:Lr,identity:ao,inv:Vo,map:Ho,max:oy,multiply:it,size:cn,sqrt:La,subtract:Bt,typed:te}),wr=Eh({BigNumber:Ge,Complex:pt,Fraction:Uo,abs:En,addScalar:Qt,config:Oe,divideScalar:Mt,equal:xa,fix:aS,format:mf,isNumeric:$o,multiplyScalar:Ot,number:Oi,pow:ya,round:Ps,subtractScalar:ga}),C4=F0({BigNumber:Ge,Unit:wr,config:Oe}),E4=lx({BigNumber:Ge,Unit:wr,config:Oe}),T4=j0({BigNumber:Ge,Unit:wr,config:Oe}),F4=B0({BigNumber:Ge,Unit:wr,config:Oe}),_4=rx({BigNumber:Ge,Unit:wr,config:Oe}),O4=P0({BigNumber:Ge,Unit:wr,config:Oe}),B4=_0({BigNumber:Ge,Unit:wr,config:Oe}),P4=G0({BigNumber:Ge,Unit:wr,config:Oe}),I4=Zd({DenseMatrix:_r,concat:Gr,equalScalar:Ir,matrix:$e,pow:ya,typed:te}),R4=T0({BigNumber:Ge,Unit:wr,config:Oe}),k4=O0({BigNumber:Ge,Unit:wr,config:Oe}),q4=wg({abs:En,add:Lr,identity:ao,inv:Vo,multiply:it,typed:te}),L4=tx({BigNumber:Ge,Unit:wr,config:Oe}),mS=Cd({addScalar:Qt,ceil:iy,conj:Wo,divideScalar:Mt,dotDivide:hf,exp:zD,i:RD,log2:UD,matrix:$e,multiplyScalar:Ot,pow:ya,tau:qD,typed:te}),sy=Ig({BigNumber:Ge,Complex:pt,config:Oe,multiplyScalar:Ot,pow:ya,typed:te}),z4=A0({BigNumber:Ge,Unit:wr,config:Oe}),U4=H0({BigNumber:Ge,Unit:wr,config:Oe}),W4=Ed({conj:Wo,dotDivide:hf,fft:mS,typed:te}),Y4=q0({BigNumber:Ge,Unit:wr,config:Oe}),H4=ax({BigNumber:Ge,Unit:wr,config:Oe}),$4=E0({BigNumber:Ge,Unit:wr,config:Oe}),G4=mx({BigNumber:Ge,Unit:wr,config:Oe}),V4=ox({BigNumber:Ge,Unit:wr,config:Oe}),Z4=V0({BigNumber:Ge,Unit:wr,config:Oe}),Q4=k0({BigNumber:Ge,Unit:wr,config:Oe}),X4=xx({BigNumber:Ge,Unit:wr,config:Oe}),J4=hx({BigNumber:Ge,Unit:wr,config:Oe}),K4=yx({BigNumber:Ge,Unit:wr,config:Oe}),j4=$0({BigNumber:Ge,Unit:wr,config:Oe}),eR=Z0({BigNumber:Ge,Unit:wr,config:Oe}),rR=C0({BigNumber:Ge,Unit:wr,config:Oe}),tR=Q0({BigNumber:Ge,Unit:wr,config:Oe}),nR=fx({BigNumber:Ge,Unit:wr,config:Oe}),aR=N0({BigNumber:Ge,Unit:wr,config:Oe}),iR=cx({BigNumber:Ge,Unit:wr,config:Oe}),oR=X0({BigNumber:Ge,Unit:wr,config:Oe}),sR=ex({BigNumber:Ge,Unit:wr,config:Oe}),uR=L0({BigNumber:Ge,Unit:wr,config:Oe}),fR=_h({Unit:wr,typed:te}),an=Mg({divideScalar:Mt,equalScalar:Ir,inv:Vo,matrix:$e,multiply:it,typed:te}),cR=U0({BigNumber:Ge,Unit:wr,config:Oe}),gf=kg({gamma:sy,typed:te}),lR=nx({BigNumber:Ge,Unit:wr,config:Oe}),mR=dx({BigNumber:Ge,Unit:wr,config:Oe}),pR=I0({BigNumber:Ge,Unit:wr,config:Oe}),pS=lg({DenseMatrix:_r,lsolve:QD,lup:cS,matrix:$e,slu:eS,typed:te,usolve:ry}),dR=R0({BigNumber:Ge,Unit:wr,config:Oe}),hR=px({BigNumber:Ge,Unit:wr,config:Oe}),vR=Lg({add:Lr,divide:an,factorial:gf,isInteger:Ln,isPositive:Yo,multiply:it,typed:te}),gR=zg({factorial:gf,typed:te}),xR=vx({BigNumber:Ge,Unit:wr,config:Oe}),yR=mg({add:Lr,cbrt:VD,divide:an,equalScalar:Ir,im:Qx,isZero:qa,multiply:it,re:Xx,sqrt:La,subtract:Bt,typeOf:YD,typed:te,unaryMinus:fi}),bR=cv({compareNatural:ci,typed:te}),wR=Td({abs:En,add:Lr,bignumber:ea,divide:an,isNegative:no,isPositive:Yo,larger:Fn,map:Ho,matrix:$e,max:oy,multiply:it,smaller:Tn,subtract:Bt,typed:te,unaryMinus:fi}),dS=$g({bignumber:ea,addScalar:Qt,combinations:zc,divideScalar:Mt,factorial:gf,isInteger:Ln,isNegative:no,larger:Fn,multiplyScalar:Ot,number:Oi,pow:ya,subtractScalar:ga,typed:te}),DR=Th({Unit:wr,typed:te}),SR=Gg({addScalar:Qt,isInteger:Ln,isNegative:no,stirlingS2:dS,typed:te}),hS=bg({abs:En,add:Lr,addScalar:Qt,atan:LD,bignumber:ea,column:fS,complex:Uc,config:Oe,cos:Vx,diag:ZD,divideScalar:Mt,dot:$c,equal:xa,flatten:vf,im:Qx,inv:Vo,larger:Fn,matrix:$e,matrixFromColumns:jx,multiply:it,multiplyScalar:Ot,number:Oi,qr:ey,re:Xx,reshape:$D,sin:Yc,size:cn,smaller:Tn,sqrt:La,subtract:Bt,typed:te,usolve:ry,usolveAll:rS}),NR=W0({BigNumber:Ge,Unit:wr,config:Oe}),AR=ix({BigNumber:Ge,Unit:wr,config:Oe}),MR=qg({divide:an,dotDivide:hf,isNumeric:$o,log:ny,map:Ho,matrix:$e,multiply:it,sum:ay,typed:te}),vS=of({add:Lr,divide:an,typed:te}),CR=sx({BigNumber:Ge,Unit:wr,config:Oe}),ER=M0({BigNumber:Ge,Unit:wr,config:Oe}),TR=uf({bignumber:ea,add:Lr,compare:Go,divide:an,isInteger:Ln,larger:Fn,multiply:it,partitionSelect:Gc,smaller:Tn,smallerEq:Is,subtract:Bt,typed:te}),uy=sf({add:Lr,apply:Jx,divide:an,isNaN:pf,multiply:it,subtract:Bt,typed:te}),FR=z0({BigNumber:Ge,Unit:wr,config:Oe}),gS=Fg({add:Lr,compare:Go,divide:an,partitionSelect:Gc,typed:te}),_R=Og({add:Lr,divide:an,matrix:$e,mean:vS,multiply:it,pow:ya,sqrt:La,subtract:Bt,sum:ay,typed:te}),OR=a0({Complex:pt,add:Lr,divide:an,matrix:$e,multiply:it,typed:te}),BR=_g({abs:En,map:Ho,median:gS,subtract:Bt,typed:te}),PR=ff({map:Ho,sqrt:La,typed:te,variance:uy}),IR=_d({BigNumber:Ge,Complex:pt,add:Lr,config:Oe,divide:an,equal:xa,factorial:gf,gamma:sy,isNegative:no,multiply:it,pi:$x,pow:ya,sin:Yc,smallerEq:Is,subtract:Bt,typed:te}),fy=hv({abs:En,add:Lr,conj:Wo,ctranspose:Kx,eigs:hS,equalScalar:Ir,larger:Fn,matrix:$e,multiply:it,pow:ya,smaller:Tn,sqrt:La,typed:te}),xS=wd({BigNumber:Ge,DenseMatrix:_r,SparseMatrix:Bi,addScalar:Qt,config:Oe,cos:Vx,matrix:$e,multiplyScalar:Ot,norm:fy,sin:Yc,typed:te,unaryMinus:fi}),RR=gx({BigNumber:Ge,Unit:wr,config:Oe}),yS=Ng({identity:ao,matrix:$e,multiply:it,norm:fy,qr:ey,subtract:Bt,typed:te}),kR=bd({multiply:it,rotationMatrix:xS,typed:te}),bS=Sg({abs:En,add:Lr,concat:Gr,identity:ao,index:iS,lusolve:pS,matrix:$e,matrixFromColumns:jx,multiply:it,range:Rs,schur:yS,subset:ra,subtract:Bt,transpose:df,typed:te}),qR=Ag({matrix:$e,multiply:it,sylvester:bS,transpose:df,typed:te});var xf={},yf={},LR={},_n=bv({mathWithTransform:yf}),bf=Yv({Node:_n}),io=$v({Node:_n}),ks=Vv({Node:_n}),zR=Jv({Node:_n}),wf=Av({Node:_n}),UR=_v({Node:_n,ResultSet:kD}),WR=Bv({Node:_n}),Zo=kv({Node:_n}),YR=Qv({Node:_n}),bZ=i0({classes:LR}),wS=dg({math:xf,typed:te}),HR=Lv({Node:_n,typed:te}),wZ=vg({Chain:wS,typed:te}),Df=Uv({Node:_n,size:cn}),Sf=Sv({Node:_n,subset:ra}),$R=Tv({matrix:$e,Node:_n,subset:ra}),Qo=Kv({Unit:wr,Node:_n,math:xf}),Xo=eg({Node:_n,SymbolNode:Qo,math:xf}),Ua=rg({AccessorNode:Sf,ArrayNode:wf,AssignmentNode:$R,BlockNode:UR,ConditionalNode:WR,ConstantNode:Zo,FunctionAssignmentNode:HR,FunctionNode:Xo,IndexNode:Df,ObjectNode:bf,OperatorNode:io,ParenthesisNode:ks,RangeNode:YR,RelationalNode:zR,SymbolNode:Qo,config:Oe,numeric:za,typed:te}),GR=jg({ConstantNode:Zo,FunctionNode:Xo,OperatorNode:io,ParenthesisNode:ks,parse:Ua,typed:te}),DS=Jg({bignumber:ea,fraction:Bs,AccessorNode:Sf,ArrayNode:wf,ConstantNode:Zo,FunctionNode:Xo,IndexNode:Df,ObjectNode:bf,OperatorNode:io,SymbolNode:Qo,config:Oe,mathWithTransform:yf,matrix:$e,typed:te}),DZ=tg({parse:Ua,typed:te}),SS=Kg({AccessorNode:Sf,ArrayNode:wf,ConstantNode:Zo,FunctionNode:Xo,IndexNode:Df,ObjectNode:bf,OperatorNode:io,ParenthesisNode:ks,SymbolNode:Qo,add:Lr,divide:an,equal:xa,isZero:qa,multiply:it,parse:Ua,pow:ya,subtract:Bt,typed:te}),NS=ng({parse:Ua,typed:te}),VR=pg({evaluate:NS}),ZR=ag({evaluate:NS}),cy=Xg({bignumber:ea,fraction:Bs,AccessorNode:Sf,ArrayNode:wf,ConstantNode:Zo,FunctionNode:Xo,IndexNode:Df,ObjectNode:bf,OperatorNode:io,ParenthesisNode:ks,SymbolNode:Qo,add:Lr,config:Oe,divide:an,equal:xa,isZero:qa,mathWithTransform:yf,matrix:$e,multiply:it,parse:Ua,pow:ya,resolve:GR,simplifyConstant:DS,simplifyCore:SS,subtract:Bt,typed:te}),SZ=e0({OperatorNode:io,parse:Ua,simplify:cy,typed:te}),NZ=Qg({parse:Ua,typed:te}),AZ=ig({Parser:ZR,typed:te}),MZ=t0({bignumber:ea,fraction:Bs,AccessorNode:Sf,ArrayNode:wf,ConstantNode:Zo,FunctionNode:Xo,IndexNode:Df,ObjectNode:bf,OperatorNode:io,ParenthesisNode:ks,SymbolNode:Qo,add:Lr,config:Oe,divide:an,equal:xa,isZero:qa,mathWithTransform:yf,matrix:$e,multiply:it,parse:Ua,pow:ya,simplify:cy,simplifyConstant:DS,simplifyCore:SS,subtract:Bt,typed:te}),CZ=r0({ConstantNode:Zo,FunctionNode:Xo,OperatorNode:io,ParenthesisNode:ks,SymbolNode:Qo,config:Oe,equal:xa,isZero:qa,numeric:za,parse:Ua,simplify:cy,typed:te}),EZ=hg({Help:VR,mathWithTransform:yf,typed:te});ht(xf,{e:ID,false:bP,fineStructure:wP,i:RD,Infinity:DP,LN10:SP,LOG10E:NP,NaN:AP,null:MP,phi:CP,SQRT1_2:TP,sackurTetrode:FP,tau:qD,true:_P,E:ID,version:OP,efimovFactor:BP,LN2:PP,pi:$x,replacer:IP,reviver:bZ,SQRT2:RP,typed:te,unaryPlus:Gx,PI:$x,weakMixingAngle:kP,abs:En,acos:qP,acot:LP,acsc:zP,addScalar:Qt,arg:UP,asech:WP,asinh:YP,atan:LD,atanh:HP,bignumber:ea,bitNot:$P,boolean:GP,clone:VP,combinations:zc,complex:Uc,conj:Wo,cos:Vx,cot:ZP,csc:QP,cube:XP,equalScalar:Ir,erf:JP,exp:zD,expm1:KP,filter:jP,forEach:eI,format:mf,getMatrixDataType:Zx,hex:rI,im:Qx,isInteger:Ln,isNegative:no,isPositive:Yo,isZero:qa,LOG2E:tI,lgamma:nI,log10:aI,log2:UD,map:Ho,multiplyScalar:Ot,not:Wc,number:Oi,oct:iI,pickRandom:oI,print:sI,random:uI,re:Xx,sec:fI,sign:WD,sin:Yc,splitUnit:cI,square:lI,string:mI,subtractScalar:ga,tan:pI,typeOf:YD,acosh:dI,acsch:hI,apply:Jx,asec:vI,bin:gI,chain:wZ,combinationsWithRep:xI,cosh:yI,csch:bI,isNaN:pf,isPrime:wI,randomInt:DI,sech:SI,sinh:NI,sparse:AI,sqrt:La,tanh:MI,unaryMinus:fi,acoth:CI,coth:EI,fraction:Bs,isNumeric:$o,matrix:$e,matrixFromFunction:TI,mode:FI,numeric:za,prod:HD,reshape:$D,size:cn,squeeze:_I,transpose:df,xgcd:GD,zeros:ln,asin:OI,cbrt:VD,concat:Gr,count:BI,ctranspose:Kx,diag:ZD,divideScalar:Mt,dotDivide:hf,equal:xa,flatten:vf,hasNumericValue:PI,identity:ao,kron:II,largerEq:Hc,leftShift:RI,lsolve:QD,matrixFromColumns:jx,nthRoot:kI,ones:qI,qr:ey,resize:LI,rightArithShift:zI,round:Ps,smaller:Tn,subtract:Bt,to:UI,unequal:WI,usolve:ry,xor:YI,add:Lr,atan2:HI,bitAnd:$I,bitOr:GI,bitXor:VI,catalan:ZI,compare:Go,compareText:XD,cumsum:QI,deepEqual:ty,diff:XI,distance:JI,dot:$c,equalText:KI,floor:JD,gcd:jI,hypot:e4,larger:Fn,log:ny,lsolveAll:r4,matrixFromRows:t4,min:n4,mod:jD,multiply:it,nthRoots:a4,or:i4,partitionSelect:Gc,rightLogShift:o4,slu:eS,subset:ra,sum:ay,trace:s4,usolveAll:rS,zpk2tf:u4,ceil:iy,compareNatural:ci,composition:f4,cross:c4,det:tS,dotMultiply:l4,fix:aS,index:iS,intersect:m4,invmod:p4,lcm:d4,log1p:h4,max:oy,setCartesian:v4,setDistinct:g4,setIsSubset:x4,setPowerset:y4,smallerEq:Is,sort:b4,and:w4,range:Rs,row:D4,setDifference:oS,setMultiplicity:S4,setSymDifference:sS,column:fS,inv:Vo,lup:cS,pinv:N4,pow:ya,setIntersect:lS,setUnion:A4,sqrtm:M4,vacuumImpedance:C4,wienDisplacement:E4,atomicMass:T4,bohrMagneton:F4,boltzmann:_4,conductanceQuantum:O4,coulomb:B4,deuteronMass:P4,dotPow:I4,electricConstant:R4,elementaryCharge:k4,expm:q4,faraday:L4,fft:mS,gamma:sy,gravitationConstant:z4,hartreeEnergy:U4,ifft:W4,klitzing:Y4,loschmidt:H4,magneticConstant:$4,molarMass:G4,molarPlanckConstant:V4,neutronMass:Z4,nuclearMagneton:Q4,planckCharge:X4,planckLength:J4,planckTemperature:K4,protonMass:j4,quantumOfCirculation:eR,reducedPlanckConstant:rR,rydberg:tR,secondRadiation:nR,speedOfLight:aR,stefanBoltzmann:iR,thomsonCrossSection:oR,avogadro:sR,bohrRadius:uR,createUnit:fR,divide:an,electronMass:cR,factorial:gf,firstRadiation:lR,gravity:mR,inverseConductanceQuantum:pR,lusolve:pS,magneticFluxQuantum:dR,molarMassC12:hR,multinomial:vR,parse:Ua,permutations:gR,planckMass:xR,polynomialRoot:yR,resolve:GR,setSize:bR,simplifyConstant:DS,solveODE:wR,stirlingS2:dS,unit:DR,bellNumbers:SR,compile:DZ,eigs:hS,fermiCoupling:NR,gasConstant:AR,kldivergence:MR,mean:vS,molarVolume:CR,planckConstant:ER,quantileSeq:TR,simplifyCore:SS,variance:uy,classicalElectronRadius:FR,evaluate:NS,median:gS,simplify:cy,symbolicEqual:SZ,corr:_R,freqz:OR,leafCount:NZ,mad:BR,parser:AZ,rationalize:MZ,std:PR,zeta:IR,derivative:CZ,norm:fy,rotationMatrix:xS,help:EZ,planckTime:RR,schur:yS,rotate:kR,sylvester:bS,lyap:qR,config:Oe});ht(yf,xf,{filter:Sx({typed:te}),forEach:Nx({typed:te}),map:Mx({typed:te}),apply:wx({isInteger:Ln,typed:te}),or:Wx({DenseMatrix:_r,concat:Gr,equalScalar:Ir,matrix:$e,typed:te}),and:Ux({add:Lr,concat:Gr,equalScalar:Ir,matrix:$e,not:Wc,typed:te,zeros:ln}),concat:Bx({isInteger:Ln,matrix:$e,typed:te}),max:Cx({config:Oe,larger:Fn,numeric:za,typed:te}),print:zx({add:Lr,matrix:$e,typed:te,zeros:ln}),bitAnd:Yx({add:Lr,concat:Gr,equalScalar:Ir,matrix:$e,not:Wc,typed:te,zeros:ln}),diff:Px({bignumber:ea,matrix:$e,number:Oi,subtract:Bt,typed:te}),min:Tx({config:Oe,numeric:za,smaller:Tn,typed:te}),subset:Ox({add:Lr,matrix:$e,typed:te,zeros:ln}),bitOr:Hx({DenseMatrix:_r,concat:Gr,equalScalar:Ir,matrix:$e,typed:te}),cumsum:qx({add:Lr,typed:te,unaryPlus:Gx}),index:Ax({Index:yn,getMatrixDataType:Zx}),sum:Rx({add:Lr,config:Oe,numeric:za,typed:te}),range:Fx({bignumber:ea,matrix:$e,add:Lr,config:Oe,isPositive:Yo,larger:Fn,largerEq:Hc,smaller:Tn,smallerEq:Is,typed:te}),row:_x({Index:yn,matrix:$e,range:Rs,typed:te}),column:Dx({Index:yn,matrix:$e,range:Rs,typed:te}),mean:Ex({add:Lr,divide:an,typed:te}),quantileSeq:kx({add:Lr,bignumber:ea,compare:Go,divide:an,isInteger:Ln,larger:Fn,multiply:it,partitionSelect:Gc,smaller:Tn,smallerEq:Is,subtract:Bt,typed:te}),variance:Lx({add:Lr,apply:Jx,divide:an,isNaN:pf,multiply:it,subtract:Bt,typed:te}),std:Ix({map:Ho,sqrt:La,typed:te,variance:uy})});ht(LR,{BigNumber:Ge,Complex:pt,Fraction:Uo,Matrix:Lc,Node:_n,ObjectNode:bf,OperatorNode:io,ParenthesisNode:ks,Range:EP,RelationalNode:zR,ResultSet:kD,ArrayNode:wf,BlockNode:UR,ConditionalNode:WR,ConstantNode:Zo,DenseMatrix:_r,RangeNode:YR,Chain:wS,FunctionAssignmentNode:HR,SparseMatrix:Bi,IndexNode:Df,ImmutableDenseMatrix:KD,Index:yn,AccessorNode:Sf,AssignmentNode:$R,FibonacciHeap:nS,Spa:uS,Unit:wr,SymbolNode:Qo,FunctionNode:Xo,Help:VR,Parser:ZR});wS.createProxy(xf);var AS=PD;var jR=ca(Am(),1);var XR=ca(QR(),1);function JR(e){var r=new XR.default;return e.on=r.on.bind(r),e.off=r.off.bind(r),e.once=r.once.bind(r),e.emit=r.emit.bind(r),e}function KR(e,r,t,n){function a(y,w){var C=arguments.length;if(C!==1&&C!==2)throw new ha("import",C,1,2);w||(w={});function b(O,_,E){if(Array.isArray(_))_.forEach(q=>b(O,q));else if(typeof _=="object")for(var T in _)Xe(_,T)&&b(O,_[T],T);else if(As(_)||E!==void 0){var R=As(_)?x(_)?_.fn+".transform":_.fn:E;if(Xe(O,R)&&O[R]!==_&&!w.silent)throw new Error('Cannot import "'+R+'" twice');O[R]=_}else if(!w.silent)throw new TypeError("Factory, Object, or Array expected")}var M={};b(M,y);for(var A in M)if(Xe(M,A)){var S=M[A];if(As(S))o(S,w);else if(s(S))i(A,S,w);else if(!w.silent)throw new TypeError("Factory, Object, or Array expected")}}function i(y,w,C){if(C.wrap&&typeof w=="function"&&(w=c(w)),m(w)&&(w=e(y,{[w.signature]:w})),e.isTypedFunction(t[y])&&e.isTypedFunction(w)){C.override?w=e(y,w.signatures):w=e(t[y],w),t[y]=w,delete n[y],u(y,w),t.emit("import",y,function(){return w});return}if(t[y]===void 0||C.override){t[y]=w,delete n[y],u(y,w),t.emit("import",y,function(){return w});return}if(!C.silent)throw new Error('Cannot import "'+y+'": already exists')}function u(y,w){w&&typeof w.transform=="function"?(t.expression.transform[y]=w.transform,d(y)&&(t.expression.mathWithTransform[y]=w.transform)):(delete t.expression.transform[y],d(y)&&(t.expression.mathWithTransform[y]=w))}function l(y){delete t.expression.transform[y],d(y)?t.expression.mathWithTransform[y]=t[y]:delete t.expression.mathWithTransform[y]}function c(y){var w=function(){for(var b=[],M=0,A=arguments.length;M2&&arguments[2]!==void 0?arguments[2]:y.fn;if(Jb(C,"."))throw new Error("Factory name should not contain a nested path. Name: "+JSON.stringify(C));var b=x(y)?t.expression.transform:t,M=C in t.expression.transform,A=Xe(b,C)?b[C]:void 0,S=function(){var _={};y.dependencies.map(ew).forEach(T=>{if(Jb(T,"."))throw new Error("Factory dependency should not contain a nested path. Name: "+JSON.stringify(T));T==="math"?_.math=t:T==="mathWithTransform"?_.mathWithTransform=t.expression.mathWithTransform:T==="classes"?_.classes=t:_[T]=t[T]});var E=y(_);if(E&&typeof E.transform=="function")throw new Error('Transforms cannot be attached to factory functions. Please create a separate function for it with exports.path="expression.transform"');if(A===void 0||w.override)return E;if(e.isTypedFunction(A)&&e.isTypedFunction(E))return e(A,E);if(w.silent)return A;throw new Error('Cannot import "'+C+'": already exists')};!y.meta||y.meta.lazy!==!1?(Du(b,C,S),A&&M?l(C):(x(y)||h(y))&&Du(t.expression.mathWithTransform,C,()=>b[C])):(b[C]=S(),A&&M?l(C):(x(y)||h(y))&&Du(t.expression.mathWithTransform,C,()=>b[C])),n[C]=y,t.emit("import",C,S)}function s(y){return typeof y=="function"||typeof y=="number"||typeof y=="string"||typeof y=="boolean"||y===null||Ht(y)||Kt(y)||rr(y)||ma(y)||Qe(y)||Array.isArray(y)}function m(y){return typeof y=="function"&&typeof y.signature=="string"}function d(y){return!Xe(v,y)}function h(y){return y.fn.indexOf(".")===-1&&!Xe(v,y.fn)&&(!y.meta||!y.meta.isClass)}function x(y){return y!==void 0&&y.meta!==void 0&&y.meta.isTransformFunction===!0||!1}var v={expression:!0,type:!0,docs:!0,error:!0,json:!0,chain:!0};return a}function ly(e,r){var t=ht({},Ds,r);if(typeof Object.create!="function")throw new Error("ES5 not supported by this JavaScript engine. Please load the es5-shim and es5-sham library for compatibility.");var n=JR({isNumber:sr,isComplex:Kt,isBigNumber:rr,isFraction:ma,isUnit:Ht,isString:St,isArray:Mr,isMatrix:Qe,isCollection:Nt,isDenseMatrix:Xi,isSparseMatrix:pa,isRange:To,isIndex:Ai,isBoolean:cm,isResultSet:lm,isHelp:yu,isFunction:mm,isDate:pm,isRegExp:dm,isObject:Mi,isNull:hm,isUndefined:vm,isAccessorNode:qn,isArrayNode:jt,isAssignmentNode:gm,isBlockNode:xm,isConditionalNode:ym,isConstantNode:yr,isFunctionAssignmentNode:_a,isFunctionNode:gn,isIndexNode:Qn,isNode:Nr,isObjectNode:Ci,isOperatorNode:ct,isParenthesisNode:en,isRangeNode:bm,isRelationalNode:wm,isSymbolNode:at,isChain:bu});n.config=HA(t,n.emit),n.expression={transform:{},mathWithTransform:{config:n.config}};var a=[],i=[];function u(s){if(As(s))return s(n);var m=s[Object.keys(s)[0]];if(As(m))return m(n);if(!UA(s))throw console.warn("Factory object with properties \`type\`, \`name\`, and \`factory\` expected",s),new Error("Factory object with properties \`type\`, \`name\`, and \`factory\` expected");var d=a.indexOf(s),h;return d===-1?(s.math===!0?h=s.factory(n.type,t,u,n.typed,n):h=s.factory(n.type,t,u,n.typed),a.push(s),i.push(h)):h=i[d],h}var l={};function c(){for(var s=arguments.length,m=new Array(s),d=0;d{Ub(l).forEach(s=>{s&&s.meta&&s.meta.recreateOnConfigChange&&o(s,{override:!0})})}),n.create=ly.bind(null,e),n.factory=F,n.import(Ub(LA(e))),n.ArgumentsError=ha,n.DimensionError=pr,n.IndexError=tn,n}var vy=ca(fm());var r5=ca(e5()),TS=class{constructor(){this.lang="en";this.all={en:{hintText:{dragDropModifierKeys:"Hold \${1} to Pin and \${2} to Copy",createListItem:"Select/Create List Item Frame",dragDropProperties:"Drag and drop properties to link them into the list",newItem:"+ New",selectNote:"Select Note...",newFrame:"New"},defaults:{spaceNote:"Current Note",spaceContext:"Current Space"},commands:{h1:"Heading 1",h2:"Heading 2",h3:"Heading 3",h4:"Heading 4",h5:"Heading 5",h6:"Heading 6",columns:"Columns",tabs:"Tabs",button:"Button",label:"Label",column:"Column",idea:"New",group:"Group",paragraph:"Text",card:"Card",progress:"Progress",rating:"Rating",circularProgress:"Circular Progress",list:"Bullet List","ordered-list":"Numbered List",todo:"To-do List",quote:"Quote",divider:"Divider",note:"Link to Note",link:"Link",callout:"Callout",bookmark:"Bookmark",table:"Table",codeblock:"Code Block",toggle:"Toggle",emoji:"Emoji",image:"Image",flow:"Linked Note",newNote:"New Note",tag:"Tag",makeMenu:"Flow Menu",selectStyle:"Style",toggleKeyboard:"Toggle Keyboard",rows:"Rows",masonry:"Gallery"},styles:{bold:"Bold",italics:"Italics",strikethrough:"Strikethrough",code:"Code",link:"Web Link",blocklink:"Link to Note",textColor:"Text Color",highlight:"Highlight"},commandsSuggest:{noResult:"No result"},commandPalette:{enable:"Enable",disabled:"Disable",openFlow:"Open Flow Blocks in Selection",closeFlow:"Close Flow Blocks in Selection",toggleBold:"Toggle Bold",toggleItalics:"Toggle Italics",openSpaces:"Open Spaces",migrateData:"Migrate Spaces From 0.7",blink:"Blink",openFileContext:"Open Explorer",convertPathToSpace:"Convert to Space",revealFile:"Reveal File in Spaces",releaseNotes:"Release Notes",toggleBacklinks:"Toggle Backlinks",collapseAllFolders:"Collapse All Folders",addFileSpace:"Add File to Space",removeFileSpace:"Remove File from Space"},frames:{sections:{kit:"Kit",paths:"Paths"},label:{label:"Label",description:"Label"},note:{label:"Note",description:"Link to a note"},table:{label:"Table",description:"Table"},context:{label:"Context",description:"Display a context view from another space"},calendar:{label:"Calendar View"},field:{label:"Field",description:"Dynamic node that displays a value based on property type"},event:{label:"Event"},divider:{label:"Divider",description:"Divider to separate your content"},button:{label:"Button",description:"Buttons can perform actions and open links"},callout:{label:"Callout",description:"Callout to highlight important information"},toggle:{label:"Toggle",description:"Toggle to show/hide content"}},menu:{newView:"New View",closeSpace:"Close Space",customView:"Custom View",detailsView:"Details View",catalogView:"Catalog View",galleryView:"Gallery View",deleteContext:"Delete Context",openSpace:"Open Space",revealInDefault:"Reveal in Finder",setNone:"None",fileMetadataDescription:"This note only",openFilePane:"Open in a new pane",rename:"Rename",changeToFolderNote:"New Space from Note",moveFile:"Move file to...",moveFolder:"Move folder to...",duplicate:"Make a copy",edit:"Edit",delete:"Delete",getHelp:"Make.md Community",vault:"Vault",openVault:"Open Another Vault",openVaultInFolder:"Open Vault Folder",obSettings:"Obsidian Settings",commandPalette:"Command Palette",backToSpace:"Back to Spaces",collapseAllSections:"Collapse All Spaces",expandAllSections:"Expand All Spaces",collapseAllFolders:"Collapse All Folders",expandAllFolders:"Expand All Folders",spaceTitle:"Add/Remove in Space",home:"Home",waypoints:"Waypoints",none:"None",tableView:"Table View",cardView:"Card View",boardView:"Board View",listView:"List View",flowView:"Flow View",groupBy:"Group By",sortBy:"Sort By",newFilter:"New Filter",clearFilters:"Clear Filters",hide:"Hide",unhideFields:"Unhide All Properties",importDataview:"Import All Dataview Properties",saveAllProperties:"Save All Properties to Files",mergeProperties:"Merge Properties",removeFromSpace:"Unpin from Space",removeFromWaypoints:"Unpin from Waypoints",editCode:"Edit Code",deleteProperty:"Delete Property",hideProperty:"Hide Property",unhideProperty:"Unhide Property",saveProperty:"Save Property",sortAscending:"Sort Ascending",sortDescending:"Sort Descending",deleteRow:"Delete Item",collapseAll:"Collapse All",customSort:"Custom Sort",groupSpaces:"Group Spaces",fileNameSortAlphaAsc:"File Name (A to Z)",fileNameSortAlphaDesc:"File Name (Z to A)",fileNameSortNumericalAsc:"File Name (1 to 9)",fileNameSortNumericalDesc:"File Name (9 to 1)",createdTimeSortAsc:"Created Time (new to old)",createdTimeSortDesc:"Created Time (old to new)",modifiedTimeSortAsc:"Modified Time (new to old)",modifiedTimeSortDesc:"Modified Time (old to new)",sizeSortAsc:"Size (smallest to largest)",sizeSortDesc:"Size (largest to smallest)",spaces:"Spaces",tags:"Tags",manageHiddenFiles:"Manage Hidden Files",manageActions:"Manage Actions",deleteSpace:"Delete",changeColor:"Change Color",changePropertyType:"Change Type",deleteFiles:"Delete Files",createFolderSpace:"Create Space from Folder",folder:"Folder",syncToContext:"Add Property to Context",setIcon:"Set Icon",copyEmbedLink:"Copy Embed Link",moveUp:"Move Up",moveDown:"Move Down",moveTo:"Move To",groupNodes:"Group Nodes",moveFrame:"Move Frame",renameFrame:"Rename Frame",deleteFrame:"Delete Frame",insertAbove:"Insert Above",insertBelow:"Insert Below"},editor:{rows:"Rows",columns:"Columns",catalog:"Catalog",gallery:"Gallery",grid:"Grid",scaleToFit:"Change to Fit",scaleToFill:"Change to Fill",fit:"Fit",strokeNone:"None",strokeSolid:"Solid",strokeDotted:"Dotted",strokeDashed:"Dashed",size:"Size",gap:"Gap",marginLeft:"Left",marginTop:"Top",marginRight:"Right",marginBottom:"Bottom",minimize:"Minimize",paddingLeft:"Left",paddingTop:"Top",paddingRight:"Right",paddingBottom:"Bottom",unlinkProperty:"Unlink Property",linkedProperty:"Linked Property",linkProperty:"Link Property",currentSpace:"Current Space",linkName:"\${1} Link",linkThumbnail:"\${1} Thumbnail",linkSticker:"\${1} Sticker",opacity:"Opacity",shadowSpread:"Spread",shadowBlur:"Blur",width:"Width",height:"Height",margin:"Margin",padding:"Padding",bold:"Bold",italic:"Italic",underline:"Underline",alignLeft:"Align Left",alignCenter:"Align Center",alignRight:"Align Right",alignJustify:"Align Justify",numberOfLines:"Lines",createVerticalSection:"Create Vertical Section",createHorizontalSection:"Create Horizontal Section",themeColors:"Theme Colors",uiColors:"UI Colors",hex:"Hex"},buttons:{add:"Add",addFilter:"Add Filter",addCondition:"Add Condition",customize:"Customize",moreOptions:"More Options",saveProperty:"Save Property",newNote:"New Note",changeIcon:"Change Sticker",removeIcon:"Remove Sticker",addIcon:"Add Sticker",addCover:"Add Cover",changeBanner:"Change Cover",changeBannerShort:"Cover",saveChanges:"Save Changes",removeBanner:"Remove Cover",rename:"Change Name",editFrame:"Edit Frame",saveSpace:"Save Space",createSpace:"New Space",createFolder:"New Folder",createNote:"New Note",createCanvas:"New Canvas",addIntoSpace:"New Pin",addSmartSearch:"Add Live Search",addItem:"Add Item",addProperty:"Add Property",editProperty:"Edit Property",addContext:"Add Context",cancel:"Cancel",search:"Search",delete:"Delete",toggleFlow:"Toggle Flow",openFlow:"Open Flow",hideFlow:"Hide Flow",openLink:"Open Link",addToSpace:"Add to Space",addToSpaceShort:"Pin",addTag:"Add Tag",tag:"Tag",syncFields:"Sync Properties",convertTable:"Convert to Markdown",cutTable:"Cut Table",deleteTable:"Delete Table",blink:"Blink",addFile:"Add Item",merge:"Merge",saveView:"Save View",saveTable:"Save Table",renameView:"Rename View",deleteView:"Delete View",renameTable:"Rename Table",renameTag:"Rename Tag",createTag:"Create Tag",currentFolder:"Current Folder",sync:"Sync",pasteCSS:"Paste CSS",save:"Save",run:"Run"},metadataTypes:{fileName:"File Name",contexts:"Contexts",path:"Path",folder:"Folder",sticker:"Sticker",color:"Color",created:"Created",lastModified:"Last Modified",extension:"Extension",size:"Size",tags:"Tags",inlinks:"Linked Mentions",outlinks:"Links",label:"Label",fileMetadata:"File Metadata",frontmatter:"Frontmatter"},filterTypes:{contains:"contains",notContains:"does not contain",is:"is",isNot:"is not",before:"before",after:"on or after",anyOf:"is any of",noneOf:"is none of",checked:"is checked",unchecked:"is unchecked",isEmpty:"is empty",isNotEmpty:"is not empty",isSameDate:"is same date",isSameDateAsToday:"today"},sortTypes:{alphaAsc:"A to Z",alphaDesc:"Z to A",earliest:"Earliest",latest:"Latest",checkAsc:"Checked \\u2192 Unchecked",checkDesc:"Unchecked \\u2192 Checked",itemsAsc:"Least Items",itemsDesc:"Most Items"},properties:{defaultField:"Name",audio:{label:"Audio",description:"Audio"},text:{label:"Text",description:"Text field"},number:{label:"Number",description:"Number field with optional unit"},boolean:{label:"Yes/No",description:"Yes or No toggle to indicate the status"},date:{label:"Date",description:"Select a date from a calendar"},option:{label:"Option",description:"Select one or multiple option from a list"},file:{label:"File"},link:{label:"Link",description:"Link to another note or a website"},tags:{label:"Tags",description:"Use tags to quickly organize your items"},object:{label:"Object",description:"Store any complex objects"},context:{label:"Relation",description:"Connect to another context property and create a relation"},image:{label:"Image",description:"Select any image from your system or from the internet"},color:{label:"Color",description:"Use colors to label your items or status"},space:{label:"Context",description:"Link to a context"},icon:{label:"Sticker",description:"Use stickers to uniquely label your items or status"},super:{label:"Super Property",links:"Open Link",properties:"Update Property",api:"API",obsidianCommands:"Run Command",runCommand:"Run Command",performAction:"Perform Action",whenClicked:"When Clicked"},fileProperty:{name:"Name",label:"Formula",createdTime:"Created",modifiedTime:"Last Edited",sticker:"Sticker",links:"Links",tags:"Tags",spaces:"Spaces",extension:"Extension",size:"Size",preview:"Note Preview",parentFolder:"Folder",description:"Use a formula to dynamically display a property"}},views:{navigator:"Navigator",explorer:"Explorer",space:"Space"},subViews:{spaceItems:"Items",spaceContext:"Context",spaceLists:"Lists",spaceActions:"Actions",spaceTemplates:"Templates",smartSearch:"Live Searches",filesAndFolders:"Files and Folders"},labels:{duplicateTable:"Duplicate Table",moveTable:"Move Table",editFormula:"Edit Formula",editObject:"Edit Object",properties:"Properties",newAction:"New Action",newTable:"New Table",createFolder:"New Folder Name",rename:"Rename",createNew:"New",default:"Default",done:"Done",tables:"Tables",selectDateFormat:"Select/Type Date Format",renameSection:"Edit Space",createSection:"New Folder",createNote:"New Note",contextMaker:"Context Maker",select:"Select",pinnedItems:"Pinned Items",collapse:"Collapse",expand:"Expand",all:"All",none:"None",view:"View",findStickers:"Find Sticker",mergeProperties:"Merge Properties",placeholder:"Type '\${1}' for commands",notePlaceholder:"New Note for \${1}",itemsSelected:"\${1} Selected",selectNote:"Select Note",selectIcon:"Select Icon",selectImage:"Select Image",selectSpace:"Select Space",styleSmall:"Small",styleMedium:"Medium",styleLarge:"Large",hiddenFilePattern:"Name, Suffixes and Extension",hiddenFileSpecific:"Exclude specific files and folders",textPlaceholder:"Enter Text",noFile:"is not created yet. Click to create.",navigatorSearchPlaceholder:"Search by Text or Filters",blinkPlaceholder:"Quickly Search a File, Folder, Tag... Press Tab to Edit",searchPlaceholder:"Type to search...",contextItemSelectPlaceholder:"Find Item",linkItemSelectPlaceholder:"Find or Create Note",pinNotePlaceholder:"Select a Note or Space to Pin",optionItemSelectPlaceholder:"Select Option",viewItemSelectPlaceholder:"Select View",tagItemSelectPlaceholder:"Find Tag",spaceSelectPlaceholder:"Select any Folder or Tag",propertyItemSelectPlaceholder:"Select Property",sortItemSelectPlaceholder:"Select Sort",filterItemSelectPlaceholder:"Select Filter",imageSelectPlaceholder:"Select an image or paste a URL",imageNotFoundPlaceholder:"No Images Found",syncFrontmatterProperty:"Sync Frontmatter Property",newProperty:"New Property",newPropertyShort:"New Property",propertyType:"Type",propertyDynamic:"Dyanmic",propertyValueSpace:"Space",propertyValueProperty:"Property",propertyLookup:"Edit Formula",dateFormat:"Date Format",propertyFileProp:"Property",multiple:"Multiple",filesCount:"{$1} Files",hiddenFiles:"Hidden Files",addExtension:"Add Rule",saveView:"Save View",saveTable:"Save Table",renameView:"Rename View",renameTable:"Rename Table",syncMetadata:"Sync Metadata",syncProperties:"Sync Properties",selectContext:"Select Context",metadata:"Metadata",backlinks:"Backlinks",spaces:"Spaces",context:"Context",content:"Content",deleteSpace:"Delete Space",deleteFiles:"Delete Files",outgoingLinks:"Outgoing Links",moveTo:"Move to",addTo:"Pin to",copyTo:"Copy to",reorderIn:"Reorder in",border:"Border",corners:"Corners",color:"Color",backgroundColor:"Background",cornerRadius:"Radius",onClick:"On Click",layout:"Layout",element:"Element",name:"Name",display:"Display",alignment:"Alignment",margin:"Margin",padding:"Padding",gap:"Gap",width:"Width",height:"Height",opacity:"Opacity",shadow:"Shadow",shadowBlur:"Blur",shadowSpread:"Spread",typography:"Typography",layers:"Layers",fontSize:"Size",props:"Props",styles:"Styles",events:"Events",code:"Code",selectedLayers:"\${1} Layers"},descriptions:{spaceActions:"Create actions that runs when you press a button",spaceLists:"Create lists to track data and organize them in your space",spaceItems:"Add new items to the space or pin items to the space",spaceTemplates:"Create templates to quickly add items to your space",smartSearch:"Automatically pin notes to this space based on a set of searches",hiddenFileOptions:"Exclude any files and folders by name, suffix or extension.",deleteSpace:"Deleting the space will also delete the folder and its contents.",deleteFiles:"Delete \${1} files/folders and their contents?",addContext:"Contexts lets you connect properties from your tags",spaceProperties:"Define Properties for your Space Items",syncMetadata:"Select which fields from your notes to start syncing with the context.",syncProperties:"Contexts defines and syncs the same fields across your notes depending on their folder or tag.",selectContext:"Select which folder or tag context you want to sync the fields."},flowView:{emptyDoc:"Empty Document",itemsCount:" Items",emptyFolder:"This Folder is Empty"},notice:{duplicateFile:"Folder already contains note with same name",addedToSection:"Added to Space",fileExists:"File Already Exists",folderExists:"Folder Already Exists",noPropertyName:"Property Name is Required",duplicatePropertyName:"Duplicate Property Name",newSpaceName:"Enter a name for your space",duplicateSpaceName:"Space name already exists",cantConvertNoteToSpace:"The view is not a note",templateSaved:"Template saved to space: "},settings:{layoutVertical:"Vertical",layoutHorizontal:"Horizontal",sectionSidebar:"Spaces",sectionEditor:"Maker Mode",sectionFlow:"Flow",sectionAdvanced:"Advanced",sectionDataview:"Dataview",sectionContext:"Context",sectionStickers:"Stickers",sectionNavigator:"Navigator",sectionDefault:"Default Spaces",sectionSpaceView:"Space View",sectionBlink:"Blink",sectionInlineContext:"Inline Context",sectionFlowBlock:"Flow Block",sectionFlowMenu:"Flow Menu",sectionFlowStyler:"Flow Styler",experimental:{name:"Experimental",desc:"Experimental features that are subject to change and may not be optimized for performance"},generateThumbnails:{name:"Generate Thumbnails",desc:"Create thumbnails for images to speed up performance"},minimalThemeFix:{name:"Minimal Theme Fix",description:"Apply fixes for the popular theme Minimal"},inlineStickerMenu:{name:"Inline Stickers",desc:"Add inline stickers by typing :"},openSpacesOnLaunch:{name:"Open Spaces as Default Tab",desc:"Open the Spaces tab when Obsidian launches"},defaultSpaceTemplate:{name:"Default Space Template",desc:"Select the default template for new spaces"},defaultDateFormat:{name:"Default Date Format",desc:"Set the default date format, example: yyyy-MM-dd (see https://date-fns.org/v2.30.0/docs/format)"},newNotePlaceholder:{name:"New Note Placeholder",desc:"Default name for new notes"},folderIndentationLines:{name:"Show Folder Indentation Lines",desc:"Turn on to show a line on the left of folders to indicate indentation"},folderNoteLocation:{name:"Folder Note Location Inside Folder",desc:"Turn on to have folder notes inside the folder, turn off to have it outside"},folderViewDefault:{name:"Show Folder Note by Default",desc:"Show the folder note by default when opening a folder"},internalLinkFlowEditor:{name:"Open Flow Blocks on Internal Link Click",desc:"Turn on to toggle Flow Blocks directly by clicking on internal links, otherwise a tooltip will be shown"},syncContextToFrontmatter:{name:"Sync Context Fields to Frontmatter",desc:"Turn on to automatically save all context fields to frontmatter fields, not just existing frontmatter fields."},syncFormulaToFrontmatter:{name:"Sync Formula Fields to Frontmatter",desc:"Turn on to save calculated formula values to frontmatter fields."},inlineBacklinks:{name:"Show Inline Backlinks (Inline Context required)",desc:"Show editable backlinks at the bottom of your notes"},dataviewInlineContext:{name:"Show Dataview in Inline Context",desc:"Show dataview when inline context is enabled"},inlineContextExplorer:{name:"Inline Context",desc:"Display the context and a banner at the top of your notes"},inlineContextExpanded:{name:"Auto Expand Inline Context",desc:"Expand the inline context sections when opening a note"},inlineContextHorizontal:{name:"Inline Title and Sticker Layout",desc:"Layout for inline title and sticker in Inline Context"},hideFrontmatter:{name:"Hide Frontmatter Properties",desc:"Hide the frontmatter properties in inline context"},openFileContext:{name:"Auto Open Explorer",desc:"Automatically open explorer panel in the right panel"},folderNote:{name:"Enable Folder Note",desc:"Access the folder note in the folder page and hide the folder note from spaces"},expandFolder:{name:"Auto Expand Folder",desc:"Auto expand folders on click"},hoverPreview:{name:"Preview on Hover",desc:"Preview on Hover while holding Control/Command key"},activeFile:{name:"Reveal Active File",desc:"Automatically reveal the active file in Spaces"},contexts:{name:"Contexts",desc:"Contexts allows you to have full control over the metadata of your files"},spaces:{name:"Navigator",desc:"The navigator lets you create and organize your spaces"},spacesStickers:{name:"Stickers",desc:"Use Emojis to make it easier to find your notes"},spacesAlias:{name:"Alias",desc:"Use the alias metadata to show in Spaces"},spacesFileExplorerDual:{name:"Compatibility Mode",desc:"This will improve the compatibility of plugins while using Spaces"},spacesDeleteOption:{name:"Delete File Option",desc:"Select how you want files to be deleted"},spacesDeleteOptions:{permanant:"Delete Permanently",trash:"Move to Obsidian Trash","system-trash":"Move to System Trash"},hideRibbon:{name:"App Ribbon",desc:"Show/hide the left menu aka. ribbon"},spaceView:{name:"Space View",desc:"Open the space view when you click on a space"},defaultSpaces:{name:"Default Spaces",desc:"Recommended spaces for quickly organizing your vault"},homeSpace:{name:"Home Space",desc:"An easy-to-access space where you can add/organize your other spaces"},tagSpaces:{name:"Tag Spaces",desc:"Automatically create spaces for each of your tags"},readableLineWidth:{name:"Readable Line Width",desc:"Use Readable Line Width"},sidebarTabs:{name:"Sidebar Tabs",desc:"Show/hide other sidebar tabs"},spacesPerformance:{name:"Performance Mode",desc:"Turn on performance mode for Spaces, may affect scrolling appearance. Requires Restart"},indexSVG:{name:"Use SVGs as Stickers",desc:"Use any svg file in your vault as a sticker"},inlineStyler:{name:"Flow Styler",desc:"Select text to add styling"},inlineStylerColor:{name:"Text and Highlight Colors \\u{1F9EA}",desc:"Select text color and highlight color, (this may change in the future because of the limitations with HTML and Obsidian)"},spaceRowHeight:{name:"Row Height",desc:"The height for each row in spaces (in pixels), default is 28"},coverHeight:{name:"Cover Height",desc:"The height for the cover of the note or space, default is 200"},makeChar:{name:"Flow Menu Trigger",desc:"Character to open the Flow Menu"},mobileMakeBar:{name:"Flow Styler (Mobile)",desc:"Replaces the mobile toolbar"},editorMarkSans:{name:"Mark Sans \\u{1F9EA}",desc:"Use the editor without Markdown."},editorMakerMode:{name:"Flow (Beta)",desc:"An integrated and intuitive editor experience"},editorMakePlacholder:{name:"Flow Menu Hint Text",desc:"Show a hint text on how to open the Flow Menu Shortcut"},blink:{name:"Blink",desc:"A faster way to search and edit your notes"},editorMakeMenu:{name:"Flow Menu",desc:"Open the Flow menu to quickly add content"},editorMakeMenuTrigger:{name:"Flow Menu Shortcut",desc:"Trigger key to use flow menu"},editorFlowReplace:{name:"Flow Block",desc:"Open your internal links or toggle your embeds in the flow block."},editorFlowStyle:{name:"Flow Block Style",desc:"Select a theme for your flow block",seamless:"Seamless",classic:"Classic",minimal:"Minimal"}}}};this.lang="en";let r=r5.default.locale();["en"].includes(r)&&(this.lang=r)}get texts(){return this.all.en}},Tr=new TS().texts;var RZ=ca(fm());var _Z=(e,r)=>{let t=n=>n=="builtin"?"Builtin":n=="api"?"Spaces":"Action";return[...(e.actionsIndex.get(r)??[]).map(n=>({name:n.schema.name,description:"Action",value:\`\${r}/#;\${n.schema.id}\`,section:"Action"}))??[],...[...e.cli.allCommands()].map(n=>({name:n.schema.name,description:t(n.schema.type),value:n.path,section:t(n.schema.type)}))]};var t5=({field:e,value:r})=>r=="ctime"?{value:\`parseDate(prop('\${e}')['metadata']['file']['\${r}'])\`,type:"date"}:{value:\`prop('\${e}')['metadata']['file']['\${r}']\`,type:"string"},my=(e,r,t,n)=>{let a=wc(e);if(a)return r=="fileprop"&&a.field?t5(a):(r=="option"&&a.source?.length>0&&(a.source=="$commands"?a.options=t.cli.allCommands():a.source=="$links"?a.options=t.spaceManager.allPaths().map(i=>({name:i,value:i})):a.source=="$super"?a.options=_Z(t,n):a.source=="$properties"&&(a.options=t.contextsIndex.get(n)?.cols?.map(i=>({name:i.name,value:i.name}))??[])),[...n5(r).configKeys??[],"alias","default"].reduce((i,u)=>({...i,[u]:a[u]}),{}));if(!r)return{};if(!a)if(r=="context")e?.length>0?a={space:e}:a={};else if(r.startsWith("date"))e?.length>0?a={format:e}:a={};else if(r.startsWith("fileprop"))if(e?.length>0){let[i,u]=e.split(".");a=t5({field:i,value:u})}else a={};else r.startsWith("option")&&(e?.length>0?a={options:Sn(e).map(u=>({name:u,value:u}))}:a={});return a??{}};var n5=(e,r)=>r==Fa?Af.find(t=>t.type=="file"):r=="tags"?Af.find(t=>t.type=="tags-multi"):r=="aliases"?Af.find(t=>t.type=="option-multi"):r=="sticker"?Af.find(t=>e=="icon"):Af.find(t=>e==t.type)||Af.find(t=>e==t.multiType),Af=[{type:"unknown",label:"",restricted:!0,icon:"ui//file-question"},{type:"text",label:Tr.properties.text.label,metadata:!0,icon:"ui//text",primative:!0,description:Tr.properties.text.description},{type:"number",label:Tr.properties.number.label,metadata:!0,icon:"ui//binary",configKeys:["unit"],primative:!0,description:Tr.properties.number.description},{type:"boolean",label:Tr.properties.boolean.label,metadata:!0,icon:"ui//check-square",primative:!0,description:Tr.properties.boolean.description},{type:"date",label:Tr.properties.date.label,metadata:!0,icon:"ui//calendar",configKeys:["format"],primative:!0,description:Tr.properties.date.description},{type:"option",label:Tr.properties.option.label,multi:!0,multiType:"option-multi",icon:"ui//list",configKeys:["options","source"],description:Tr.properties.option.description},{type:"tags-multi",label:Tr.properties.tags.label,icon:"ui//tags",description:Tr.properties.tags.description},{type:"file",label:Tr.properties.file.label,restricted:!0,icon:"ui//mk-make-h3"},{type:"fileprop",label:Tr.properties.fileProperty.label,icon:"ui//formula",configKeys:["field","value","type"],description:Tr.properties.fileProperty.description},{type:"link",label:Tr.properties.link.label,multi:!0,multiType:"link-multi",metadata:!0,icon:"ui//file-text",primative:!0,description:Tr.properties.link.description},{type:"context",label:Tr.properties.context.label,icon:"ui//mk-make-note",multi:!0,multiType:"context-multi",configKeys:["space"],description:Tr.properties.context.description},{type:"object",label:Tr.properties.object.label,multi:!0,multiType:"object-multi",metadata:!0,icon:"ui//list-tree",configKeys:["type","typeName"],description:Tr.properties.object.description},{type:"icon",label:Tr.properties.icon.label,multi:!0,multiType:"icon-multi",icon:"ui//gem",restricted:!0,primative:!0,description:Tr.properties.icon.description},{type:"image",label:Tr.properties.image.label,multi:!0,multiType:"image-multi",metadata:!0,icon:"ui//mk-make-image",primative:!0,description:Tr.properties.image.description},{type:"color",label:Tr.properties.color.label,icon:"ui//mk-make-image",restricted:!0,description:Tr.properties.color.description},{type:"space",label:Tr.properties.space.label,icon:"ui//layout-grid",restricted:!0,description:Tr.properties.space.description},{type:"table",label:Tr.properties.space.label,icon:"ui//layout-grid",restricted:!0,description:Tr.properties.space.description},{type:"super",label:Tr.properties.super.label,icon:"ui//zap",restricted:!0,configKeys:["dynamic","field"]},{type:"input",label:Tr.properties.super.label,icon:"ui//input",restricted:!0}];var qs="files",hy={id:qs,name:"Files",type:"db",primary:"true"},OZ="filesView",BZ={id:OZ,name:"All",type:"view",def:JSON.stringify({db:qs,icon:"ui//file-stack"})},PZ="main",IZ=e=>({id:e,name:e,type:"frame",def:"",predicate:"",primary:"true"}),N4e={uniques:[],cols:["id","name","type","def","predicate","primary"],rows:[IZ(PZ),BZ]},py={uniques:[],cols:["id","name","type","def","predicate","primary"],rows:[hy]},a5={uniques:["name,schemaId"],cols:["name","schemaId","type","value","attrs","hidden","unique","primary"]},dy={...a5,rows:[{name:Fa,schemaId:qs,type:"file",primary:"true",hidden:"",unique:"",attrs:"",value:""},{name:Tr.properties.fileProperty.createdTime,schemaId:qs,type:"fileprop",value:Fa+".ctime",hidden:"",unique:"",attrs:"",primary:"true"}]};var A4e=[{name:Tr.properties.defaultField,schemaId:"",type:"text",primary:"true"}],FS={...a5,rows:[{name:Fa,schemaId:qs,type:"file",primary:"true",hidden:"",unique:"",attrs:"",value:""}]};var M4e={schema:hy,cols:dy.rows,rows:[]},C4e={schema:hy,cols:dy.rows,rows:[]},E4e={schema:hy,cols:FS.rows,rows:[]},i5=(e,r)=>e.filter(t=>r.find(n=>n.id==t.schemaId&&n.type=="db")).reduce((t,n)=>({...t,...t[n.schemaId]?{[n.schemaId]:{uniques:n.unique=="true"?[...t[n.schemaId].uniques,n.name]:t[n.schemaId].uniques,cols:[...t[n.schemaId].cols,n.name],rows:[]}}:{[n.schemaId]:{uniques:n.unique=="true"?[n.name]:[],cols:[n.name],rows:[]}}}),{});var T4e={m_schema:py,m_fields:dy,...i5(dy.rows,py.rows)},F4e={m_schema:py,m_fields:FS,...i5(FS.rows,py.rows)};var _S="spaces://$tags";var fRe={name:Tr.menu.waypoints,displayName:Tr.menu.waypoints,path:"spaces://$waypoints",label:{name:Tr.menu.waypoints,thumbnail:"",sticker:"ui//tags",color:""},type:"default"},cRe={name:Tr.menu.tags,displayName:Tr.menu.tags,path:"spaces://$tags",label:{thumbnail:"",name:Tr.menu.tags,sticker:"ui//tags",color:""},type:"default"},lRe={name:Tr.menu.vault,displayName:Tr.menu.vault,path:"/",label:{thumbnail:"",name:Tr.menu.vault,sticker:"ui//vault",color:""},type:"default"};var o5=(e,r,t,n,a,i,u)=>{if(!t)return"";let l=new Map;Object.keys(a).forEach(o=>l.set(o,a[o])),l.set("$properties",n),l.set("$paths",r),i&&l.set("$current",i);let c;try{e.evaluate("current = current()",l),c=e.evaluate(t,l),c=ws("",c)}catch(o){if(u)throw o}return c};var OS=e=>{let r=new Map;e.filter(u=>u.type=="fileprop"||u.name.startsWith("tags")).forEach(u=>{let{value:l}=my(u.value,u.type),c=[];try{let s=Ua(l).filter(m=>m.type=="FunctionNode").filter(m=>m.fn.name=="prop"&&m.args[0].type=="ConstantNode").map(m=>m.args[0]?.value);c.push(...s)}catch{}let o=u.name;r.has(o)||r.set(o,new Set);for(let s of c){let m=s;m!==o&&r.get(o).add(m)}});let t=new Set,n=[],a=new Set,i=u=>{if(a.has(u))throw new Error("Circular dependency detected");if(!t.has(u)){a.add(u);let l=r.get(u)||new Set;for(let c of l)i(c);t.add(u),a.delete(u),n.push(u)}};for(let u of e)t.has(u.name)||i(u.name);return n},s5=(e,r,t,n,a,i)=>{if(!t)return{};let u=i??OS(n),l=r.get(t[Fa])?.metadata?.property??{},c=Object.keys(l).filter(m=>n.some(d=>d.name==m)).reduce((m,d)=>({...m,[d]:ws(d,l[d])}),{}),o=u.map(m=>n.find(d=>d.name==m)).filter(m=>m&&(m.type=="fileprop"||m.name=="tags")),s=n.reduce((m,d)=>({...m,[d.name]:d}),{});return{...t,...c,...o.reduce((m,d)=>{let{value:h}=my(d.value,d.type);return{...m,[d.name]:o5(e,r,h,s,{...t,...m},a)}},{})}};var u5=(e,r)=>{let t=e?Sn(e):[],n=r?Sn(r):[];return n.every(a=>t.some(i=>i==a))&&t.every(a=>n.some(i=>i==a))},Mf=(e,r)=>e==r,BS=(e,r)=>(e??"").length==0,PS=(e,r)=>(e??"").toLowerCase().includes((r??"").toLowerCase()),IS=(e,r)=>parseFloat(e)>parseFloat(r),RS=(e,r)=>parseInt(e){let t=isNaN(Date.parse(e))?new Date(parseInt(e)):new Date(e),n=isNaN(Date.parse(r))?new Date(parseInt(r)):new Date(r);return t.valueOf()>=n.valueOf()},c5=(e,r)=>{let t=isNaN(Date.parse(e))?new Date(parseInt(e)):new Date(e),n=isNaN(Date.parse(r))?new Date(parseInt(r)):new Date(r);return t.valueOf(){let t=e?Sn(e):[],n=r?Sn(r):[];return t.length==0?!1:n.some(a=>t.some(i=>i==a))},l5=(e,r)=>{if(!e)return!1;let t=new Date(\`\${e.toString().replace(".",":")}\`),n=new Date(\`\${r}\`);return t.getMonth()===n.getMonth()&&t.getDate()===n.getDate()},m5=e=>{if(!e)return!1;let r=new Date(\`\${e.toString()}T00:00\`),t=new Date;return r.getMonth()===t.getMonth()&&r.getDate()===t.getDate()};var Cf={isNotEmpty:{type:["text","file","number","option","option-multi","link","link-multi","image"],fn:(e,r)=>!BS(e,""),valueType:"none"},isEmpty:{type:["text","file","number","option","option-multi","link","link-multi","image"],fn:(e,r)=>BS(e,""),valueType:"none"},include:{fn:(e,r)=>PS(e,r),type:["text","file","link","image"],valueType:"text"},notInclude:{type:["text","file","link","image"],fn:(e,r)=>!PS(e,r),valueType:"text"},is:{type:["text"],fn:(e,r)=>Mf(e,r),valueType:"text"},isNot:{type:["text"],fn:(e,r)=>!Mf(e,r),valueType:"text"},equal:{type:["number"],fn:(e,r)=>Mf(e,r),valueType:"number"},isLink:{type:["link","context"],fn:(e,r)=>Mf(e,r),valueType:"link"},isNotLink:{type:["link","context"],fn:(e,r)=>!Mf(e,r),valueType:"link"},isGreatThan:{type:["number"],fn:(e,r)=>IS(e,r),valueType:"number"},isLessThan:{type:["number"],fn:(e,r)=>RS(e,r),valueType:"number"},isLessThanOrEqual:{type:["number"],fn:(e,r)=>!IS(e,r),valueType:"number"},isGreatThanOrEqual:{type:["number"],fn:(e,r)=>!RS(e,r),valueType:"number"},dateBefore:{type:["date"],fn:(e,r)=>c5(e,r),valueType:"date"},dateAfter:{type:["date"],fn:(e,r)=>f5(e,r),valueType:"date"},isSameDate:{type:["date"],fn:(e,r)=>l5(e,r),valueType:"date"},isSameDateAsToday:{type:["date"],fn:(e,r)=>m5(e,r),valueType:"none"},isExactList:{type:["option","option-multi","link-multi","context-multi","tags-multi"],fn:(e,r)=>u5(e,r),valueType:"list"},isAnyInList:{type:["option","context","link","option-multi","link-multi","context-multi","tags-multi"],fn:(e,r)=>kS(e,r),valueType:"list"},isNoneInList:{type:["option","context","link","option-multi","link-multi","context-multi","tags-multi"],fn:(e,r)=>!kS(e,r),valueType:"list"},isTrue:{type:["boolean"],fn:(e,r)=>e=="true",valueType:"none"},isFalse:{type:["boolean"],fn:(e,r)=>e!="true",valueType:"none"}};var qZ=(e,r,t)=>r.reduce((a,i)=>{let[u,l]=a,c=i.type=="context"?p5(l,i,t):i.type=="path"?h5(l,i,t):i.type=="frontmatter"?d5(l,i,t):v5(l,i,t),o=l.filter(s=>!c.includes(s));return[[...u,...c],o]},[[],e])[0],LZ=(e,r,t)=>r.reduce((n,a)=>a.type=="context"?p5(n,a,t):a.type=="path"?h5(n,a,t):a.type=="frontmatter"?d5(n,a,t):v5(n,a,t),e),p5=(e,r,t)=>{let n=Cf[r.fn];return!n||n.valueType!="none"&&r.value.length==0?[]:e.filter(a=>{let[i,u]=r.field.split("."),l=a.metadata?.property;if(!a.spaces?.includes(i)||!l||!l[u])return!1;let c=!0;if(n){let o=r.fType=="property"?t[r.value]:r.value;c=n.fn(ws(u,l[u]),o)}return c})},d5=(e,r,t)=>{let n=Cf[r.fn];return!n||n.valueType!="none"&&r.value.length==0?[]:e.filter(a=>{let i=a.metadata?.property;if(!i||i[r.field]===void 0)return!1;let u=!0;if(n){let l=r.fType=="property"?t[r.value]:r.value;u=n.fn(ws(r.field,i[r.field]),l)}return u})},h5=(e,r,t)=>{let n=Cf[r.fn];return!n||n.valueType!="none"&&r.value.length==0?[]:e.filter(a=>{let i="";r.field=="outlinks"?i=bs(a.outlinks??[]):r.field=="inlinks"?i=bs(a.inlinks??[]):r.field=="tags"&&(i=bs(a.tags??[]));let u=!0;if(n){let l=r.fType=="property"?t[r.value]:r.value;u=n.fn(i,l)}return u})},v5=(e,r,t)=>{let n=Cf[r.fn];return!n||n.valueType!="none"&&r.value.length==0?[]:e.filter(a=>{let i=!0;if(n){let u=r.fType=="property"?t[r.value]:r.value;i=n.fn(a.metadata?.[r.type]?.[r.field],u)}return i})},g5=(e,r,t)=>e.reduce((a,i)=>!a||i.filters.length==0?!1:i.type=="any"?qZ([r],i.filters,t).length>0:LZ([r],i.filters,t).length>0,!0);var x5=(e,r)=>e.hiddenExtensions.some(t=>r.endsWith(t))||r.startsWith(e.spacesFolder+"/#")||e.hiddenFiles.some(t=>t==r);var y5=(e,r,t)=>{if(!e)return{changed:!1,cache:null};if(!r)return{changed:!1,cache:{path:e.path,frames:{},schemas:[]}};let n=Object.values(r).map(l=>l.schema),a=n.filter(l=>l.type=="frame").reduce((l,c)=>({...l,[c.id]:r[c.id]}),{}),i={path:e.path,frames:a,schemas:n},u=!0;return t&&vy.default.isEqual(i,t)&&(u=!1),{changed:u,cache:i}},b5=(e,r,t,n,a,i,u)=>{let l={};if(!e)return{changed:!1,cache:null};if(!r)return{changed:!1,cache:{cols:[],path:e.path,schemas:[],outlinks:[],contexts:[],paths:[],tables:{},space:e,spaceMap:l,dbExists:!1}};let c=Object.values(r).map(A=>A.schema),o=c.find(A=>A.primary=="true"),s=OS(r[o.id].cols),m={...r[o.id],rows:r[o.id].rows.map(A=>s5(u,i,A,r[o.id].cols,i.get(e.path),s))},d={...r,[o.id]:m},h=m.cols?.filter(A=>A.type.startsWith("context"))??[],x=m.cols?.filter(A=>A.type.startsWith("link"))??[],v=ti(h.map(A=>A.value));h.forEach(A=>{l[A.name]={},m.rows.forEach(S=>{Sn(S[A.name]).forEach(O=>l[A.name][O]=[...l[A.name][O]??[],S[Fa]])})});let y=d[qs]?.rows?.map(A=>A[Fa])??[],w=NA(t??[],y),C=ti(m.rows.reduce((A,S)=>ti([...A,...[...h,...x].flatMap(O=>Sn(S[O.name]).map(_=>Dc(_)))]),[])),b={cols:m.cols,path:e.path,contexts:v,outlinks:C,paths:w,tables:d,schemas:c,space:e,spaceMap:l,dbExists:a},M=!0;return n&&vy.default.isEqual(b,n)&&(M=!0),{changed:M,cache:b}},w5=(e,r,t,n)=>{let a={};for(let[i,u]of e){let l=t.get(i)?.defPath??i,c=e.get(l)??u,o=u?.parent??"",s=u?.type??"",m=u?.subtype??"",d=c?.label,h=n?.get(i),{changed:x,cache:v}=qS(i,r,t,c,d,s,m,o,h);a[i]={changed:x,cache:v}}return a},qS=(e,r,t,n,a,i,u,l,c)=>{let o=(W,G,H)=>W?.length>0||W?.length>0?W:G=="space"?H=="Spaces/Home"?"ui//home":H=="/"?"ui//vault":H.startsWith("spaces://")?"ui//tags":"ui//folder":"ui//file",s={label:n?.label,path:e,name:yc(e),displayName:yc(e)},m=[],d=n?.tags?.map(W=>W)??[],h=x5(r,e),x=(W,G,H=new Set)=>{let L=[];for(let k of G){let K=W.get(k)?.contexts??[];for(let z of K)H.has(z)||(L.push(z),H.add(z),L.push(...x(W,[bc(z)],H)))}return L};if(t.has(l))for(let W of t.get(l).contexts??[])m.push(W);m.push(...d);let v=a?.name,y=n?.properties?um(n.properties[r.fmKeyAlias]):[],w=o(a?.sticker,i,e),C=a?.color??"",b=n?.inlinks??[],M=n?.links??[],A=r.spacesUseAlias?y[0]??v:v,S={...s,name:v,tags:ti(m),type:i,subtype:u,displayName:A,parent:l,label:{name:v,sticker:w,color:C,thumbnail:a?.thumbnail??"",preview:a?.preview??""},metadata:{...n},inlinks:b,outlinks:M},O=[];u=="tag"&&O.push(_S);for(let W of m)O.push(bc(W));let _=new Set,E=(W,G)=>{if(!_.has(W)){if(_.add(W),G.dependencies?.length>0)for(let H of G.dependencies)t.has(H)&&E(H,t.get(H));if(G.defPath==e&&(h=!0),u!="tag"&&u!="default"&&G.space&&G.space.path==l){O.push(W);return}if(G.metadata?.filters?.length>0&&g5(G.metadata.filters,{...S,spaces:O},G.properties)){O.push(W);return}if(G.metadata?.links?.length>0&&(G.metadata?.links??[]).find(L=>L==S.path)){O.push(W);return}}};for(let[W,G]of t)E(W,G);let T=x(t,O);O.push(...T.map(W=>bc(W))),S.tags.push(...T);let R=h?{...S,spaces:[],hidden:h}:{...S,spaces:ti(O),hidden:h},q=!0;return c&&vy.default.isEqual(R,c)&&(q=!1),{changed:q,cache:R}};function D5(e){let{path:r,settings:t,spacesCache:n,pathMetadata:a,label:i,type:u,subtype:l,parent:c,oldMetadata:o}=e;return qS(r,t,n,a,i,u,l,c,o)}function LS(e,r){let{space:t,mdb:n,paths:a,oldCache:i,dbExists:u,pathsIndex:l}=e;return b5(t,n,a,i,u,l,r)}function S5(e,r){let{map:t,pathsIndex:n}=e,a=new Map;for(let[i,u]of t)a.set(i,LS({...u,pathsIndex:n},r));return a}function N5(e){let{pathCache:r,settings:t,spacesCache:n,oldMetadata:a}=e;return w5(r,t,n,a)}function A5(e){let{space:r,mdb:t,oldCache:n}=e;return y5(r,t,n)}var zZ=self,UZ={...AS,createAdd:F("add",[],()=>function(r,t){return r+t})},zS=ly(UZ);zS.import(Lb,{override:!0});zZ.onmessage=async e=>{let{payload:r,job:t}=e.data,n;t.type=="path"?n=D5(r):t.type=="context"?n=LS(r,zS):t.type=="contexts"?n=S5(r,zS):t.type=="frames"?n=A5(r):t.type=="paths"&&(n=N5(r));try{postMessage({job:t,result:n})}catch(a){console.log(a),postMessage({job:t,result:{$error:\`Failed to index \${t.type} \${t.path}: \${a}\`}})}}; -/*! - * decimal.js v10.4.3 - * An arbitrary-precision Decimal type for JavaScript. - * https://github.com/MikeMcl/decimal.js - * Copyright (c) 2022 Michael Mclaughlin - * MIT Licence - */ -/** - * @license - * Lodash - * Copyright OpenJS Foundation and other contributors - * Released under MIT license - * Based on Underscore.js 1.8.3 - * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors - */ -/** - * @license Complex.js v2.1.1 12/05/2020 - * - * Copyright (c) 2020, Robert Eisele (robert@xarg.org) - * Dual licensed under the MIT or GPL Version 2 licenses. - **/ -/** - * @license Fraction.js v4.3.0 20/08/2023 - * https://www.xarg.org/2014/03/rational-numbers-in-javascript/ - * - * Copyright (c) 2023, Robert Eisele (robert@raw.org) - * Dual licensed under the MIT or GPL Version 2 licenses. - **/ -//! authors : Tim Wood, Iskren Chernev, Moment.js contributors -//! license : MIT -//! moment.js -//! momentjs.com -//! version : 2.29.4 -`, { "name": "Superstate Indexer" }); +function findFinished(stacks) { + let best = null; + for (let stack of stacks) { + let stopped = stack.p.stoppedAt; + if ((stack.pos == stack.p.stream.end || stopped != null && stack.pos > stopped) && stack.p.parser.stateFlag(stack.state, 2) && (!best || best.score < stack.score)) + best = stack; + } + return best; } -// src/core/superstate/workers/indexer/indexer.ts -var Indexer = class { - constructor(numWorkers, cache2) { - this.numWorkers = numWorkers; - this.cache = cache2; - this.workers = []; - this.busy = []; - this.reloadQueue = []; - this.reloadSet = /* @__PURE__ */ new Set(); - this.callbacks = /* @__PURE__ */ new Map(); - for (let index2 = 0; index2 < numWorkers; index2++) { - const worker = new Worker2({ name: "Make.md Superstate Indexer " + (index2 + 1) }); - worker.onmessage = (evt) => this.finish(evt.data.job, evt.data.result, index2); - this.workers.push(worker); - this.busy.push(false); - } - } - reload(jerb) { - const jobKey = stringifyJob(jerb); - const promise = new Promise((resolve2, reject) => { - if (this.callbacks.has(jobKey)) - this.callbacks.get(jobKey)?.push([resolve2, reject]); - else - this.callbacks.set(jobKey, [[resolve2, reject]]); - }); - if (this.reloadSet.has(jobKey)) - return promise; - this.reloadSet.add(jobKey); - const workerId = this.nextAvailableWorker(); - if (workerId !== void 0) { - this.send(jerb, workerId); - } else { - this.reloadQueue.push(jerb); - } - return promise; +// node_modules/@lezer/javascript/node_modules/@lezer/highlight/dist/index.js +var nextTagID = 0; +var Tag = class { + constructor(set, base2, modified) { + this.set = set; + this.base = base2; + this.modified = modified; + this.id = nextTagID++; } - finish(jerb, data2, index2) { - const jobKey = stringifyJob(jerb); - const calls = [].concat(this.callbacks.get(jobKey) ?? []); - this.reloadSet.delete(jobKey); - this.callbacks.delete(jobKey); - this.busy[index2] = false; - const job = this.reloadQueue.shift(); - if (job !== void 0) - this.send(job, index2); - if ("$error" in data2) { - for (const [_15, reject] of calls) - reject(data2["$error"]); - } else { - for (const [callback, _15] of calls) - callback(data2); - } + static define(parent) { + if (parent === null || parent === void 0 ? void 0 : parent.base) + throw new Error("Can not derive from a modified tag"); + let tag2 = new Tag([], null, []); + tag2.set.push(tag2); + if (parent) + for (let t5 of parent.set) + tag2.set.push(t5); + return tag2; } - async send(job, workerId) { - if (job.type == "paths") { - const payload = { - settings: this.cache.settings, - spacesCache: this.cache.spacesIndex, - pathCache: this.cache.spaceManager.allCaches(), - oldMetadata: this.cache.pathsIndex - }; - this.message(workerId, { - job, - payload - }); - this.busy[workerId] = true; - return; - } - if (job.type == "path") { - const spaceState = this.cache.spacesIndex.get(job.path); - const cachePath = spaceState?.defPath ? spaceState?.defPath : job.path; - const pathMetadata = await this.cache.spaceManager.readPathCache(cachePath) ?? await this.cache.spaceManager.readPathCache(job.path); - const label = pathMetadata?.label; - const parent = await this.cache.spaceManager.parentPathForPath(job.path); - const type = spaceState ? "space" : "file"; - const subtype = spaceState ? spaceState.type : pathMetadata?.subtype; - const payload = { - path: job.path, - settings: this.cache.settings, - spacesCache: this.cache.spacesIndex, - pathMetadata, - label, - parent, - type, - subtype, - oldMetadata: this.cache.pathsIndex.get(job.path) - }; - this.message(workerId, { - job, - payload - }); - this.busy[workerId] = true; - return; - } - if (job.type == "context") { - const space2 = this.cache.spacesIndex.get(job.path)?.space; - if (!space2 || !space2.path) { - this.message(workerId, { - job, - payload: { - space: space2, - mdb: null, - paths: [...this.cache.spacesMap.getInverse(job.path)], - oldCache: this.cache.contextsIndex.get(job.path), - pathsIndex: this.cache.pathsIndex - } - }); - this.busy[workerId] = true; - return; - } - const dbExists = await this.cache.spaceManager.spaceInitiated(space2.path); - this.cache.spaceManager.readAllTables(space2.path).then((mdb) => { - this.message(workerId, { - job, - payload: { - space: space2, - mdb, - paths: [...this.cache.spacesMap.getInverse(job.path)], - oldCache: this.cache.contextsIndex.get(job.path), - dbExists, - pathsIndex: this.cache.pathsIndex - } - }); - this.busy[workerId] = true; - }); - return; - } - if (job.type == "contexts") { - const spaces2 = this.cache.allSpaces().filter((f2) => f2.type != "default").map((f2) => f2.space); - const payloads = /* @__PURE__ */ new Map(); - for (const space2 of spaces2) { - const dbExists = await this.cache.spaceManager.spaceInitiated(space2.path); - await this.cache.spaceManager.readAllTables(space2.path).then((mdb) => { - payloads.set( - space2.path, - { - space: space2, - mdb, - paths: [...this.cache.spacesMap.getInverse(space2.path)], - oldCache: this.cache.contextsIndex.get(space2.path), - dbExists - } - ); - }); - } - this.message(workerId, { - job, - payload: { - map: payloads, - pathsIndex: this.cache.pathsIndex - } - }); - this.busy[workerId] = true; - } - if (job.type == "frames") { - const space2 = this.cache.spacesIndex.get(job.path)?.space; - if (!space2) { - this.message(workerId, { - job, - payload: { - space: space2, - mdb: null, - oldCache: this.cache.framesIndex.get(job.path) - } - }); - this.busy[workerId] = true; - return; - } - this.cache.spaceManager.readAllFrames(space2.path).then((mdb) => { - this.message(workerId, { - job, - payload: { - space: space2, - mdb, - oldCache: this.cache.framesIndex.get(job.path) - } - }); - this.busy[workerId] = true; - }); - return; - } + static defineModifier() { + let mod3 = new Modifier(); + return (tag2) => { + if (tag2.modified.indexOf(mod3) > -1) + return tag2; + return Modifier.get(tag2.base || tag2, tag2.modified.concat(mod3).sort((a4, b2) => a4.id - b2.id)); + }; } - message(workerId, message) { - this.workers[workerId].postMessage( - message - ); +}; +var nextModifierID = 0; +var Modifier = class { + constructor() { + this.instances = []; + this.id = nextModifierID++; } - nextAvailableWorker() { - const index2 = this.busy.indexOf(false); - return index2 == -1 ? void 0 : index2; + static get(base2, mods) { + if (!mods.length) + return base2; + let exists = mods[0].instances.find((t5) => t5.base == base2 && sameArray(mods, t5.modified)); + if (exists) + return exists; + let set = [], tag2 = new Tag(set, base2, mods); + for (let m4 of mods) + m4.instances.push(tag2); + let configs = permute(mods); + for (let parent of base2.set) + for (let config4 of configs) + set.push(Modifier.get(parent, config4)); + return tag2; } }; - -// src/core/superstate/workers/search/search.worker.ts -function Worker3() { - return inlineWorker('"use strict";function he(t){return Array.isArray(t)?t:typeof t=="string"?[t]:[]}var xe=(t,e)=>e.indexOf(t)>0?e.indexOf(t):e.length;function k(t){return k=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(e){return typeof e}:function(e){return e&&typeof Symbol=="function"&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},k(t)}function x(t){if(t===null||t===!0||t===!1)return NaN;var e=Number(t);return isNaN(e)?e:e<0?Math.ceil(e):Math.floor(e)}function f(t,e){if(e.length1?"s":"")+" required, but only "+e.length+" present")}function m(t){f(1,arguments);var e=Object.prototype.toString.call(t);return t instanceof Date||k(t)==="object"&&e==="[object Date]"?new Date(t.getTime()):typeof t=="number"||e==="[object Number]"?new Date(t):((typeof t=="string"||e==="[object String]")&&typeof console<"u"&&(console.warn("Starting with v2.0.0-beta.1 date-fns doesn\'t accept strings as date arguments. Please use `parseISO` to parse strings. See: https://github.com/date-fns/date-fns/blob/master/docs/upgradeGuide.md#string-arguments"),console.warn(new Error().stack)),new Date(NaN))}function J(t,e){f(2,arguments);var r=m(t).getTime(),a=x(e);return new Date(r+a)}var Ke={};function T(){return Ke}function z(t){var e=new Date(Date.UTC(t.getFullYear(),t.getMonth(),t.getDate(),t.getHours(),t.getMinutes(),t.getSeconds(),t.getMilliseconds()));return e.setUTCFullYear(t.getFullYear()),t.getTime()-e.getTime()}function K(t){return f(1,arguments),t instanceof Date||k(t)==="object"&&Object.prototype.toString.call(t)==="[object Date]"}function Z(t){if(f(1,arguments),!K(t)&&typeof t!="number")return!1;var e=m(t);return!isNaN(Number(e))}function ee(t,e){f(2,arguments);var r=x(e);return J(t,-r)}var Ze=864e5;function te(t){f(1,arguments);var e=m(t),r=e.getTime();e.setUTCMonth(0,1),e.setUTCHours(0,0,0,0);var a=e.getTime(),n=r-a;return Math.floor(n/Ze)+1}function O(t){f(1,arguments);var e=1,r=m(t),a=r.getUTCDay(),n=(a=n.getTime()?r+1:e.getTime()>=i.getTime()?r:r-1}function re(t){f(1,arguments);var e=_(t),r=new Date(0);r.setUTCFullYear(e,0,4),r.setUTCHours(0,0,0,0);var a=O(r);return a}var et=6048e5;function ae(t){f(1,arguments);var e=m(t),r=O(e).getTime()-re(e).getTime();return Math.round(r/et)+1}function S(t,e){var r,a,n,o,i,s,d,l;f(1,arguments);var p=T(),c=x((r=(a=(n=(o=e?.weekStartsOn)!==null&&o!==void 0?o:e==null||(i=e.locale)===null||i===void 0||(s=i.options)===null||s===void 0?void 0:s.weekStartsOn)!==null&&n!==void 0?n:p.weekStartsOn)!==null&&a!==void 0?a:(d=p.locale)===null||d===void 0||(l=d.options)===null||l===void 0?void 0:l.weekStartsOn)!==null&&r!==void 0?r:0);if(!(c>=0&&c<=6))throw new RangeError("weekStartsOn must be between 0 and 6 inclusively");var h=m(t),g=h.getUTCDay(),v=(g=1&&g<=7))throw new RangeError("firstWeekContainsDate must be between 1 and 7 inclusively");var v=new Date(0);v.setUTCFullYear(c+1,0,g),v.setUTCHours(0,0,0,0);var N=S(v,e),D=new Date(0);D.setUTCFullYear(c,0,g),D.setUTCHours(0,0,0,0);var E=S(D,e);return p.getTime()>=N.getTime()?c+1:p.getTime()>=E.getTime()?c:c-1}function ne(t,e){var r,a,n,o,i,s,d,l;f(1,arguments);var p=T(),c=x((r=(a=(n=(o=e?.firstWeekContainsDate)!==null&&o!==void 0?o:e==null||(i=e.locale)===null||i===void 0||(s=i.options)===null||s===void 0?void 0:s.firstWeekContainsDate)!==null&&n!==void 0?n:p.firstWeekContainsDate)!==null&&a!==void 0?a:(d=p.locale)===null||d===void 0||(l=d.options)===null||l===void 0?void 0:l.firstWeekContainsDate)!==null&&r!==void 0?r:1),h=L(t,e),g=new Date(0);g.setUTCFullYear(h,0,c),g.setUTCHours(0,0,0,0);var v=S(g,e);return v}var tt=6048e5;function oe(t,e){f(1,arguments);var r=m(t),a=S(r,e).getTime()-ne(r,e).getTime();return Math.round(a/tt)+1}function u(t,e){for(var r=t<0?"-":"",a=Math.abs(t).toString();a.length0?a:1-a;return u(r==="yy"?n%100:n,r.length)},M:function(e,r){var a=e.getUTCMonth();return r==="M"?String(a+1):u(a+1,2)},d:function(e,r){return u(e.getUTCDate(),r.length)},a:function(e,r){var a=e.getUTCHours()/12>=1?"pm":"am";switch(r){case"a":case"aa":return a.toUpperCase();case"aaa":return a;case"aaaaa":return a[0];case"aaaa":default:return a==="am"?"a.m.":"p.m."}},h:function(e,r){return u(e.getUTCHours()%12||12,r.length)},H:function(e,r){return u(e.getUTCHours(),r.length)},m:function(e,r){return u(e.getUTCMinutes(),r.length)},s:function(e,r){return u(e.getUTCSeconds(),r.length)},S:function(e,r){var a=r.length,n=e.getUTCMilliseconds(),o=Math.floor(n*Math.pow(10,a-3));return u(o,r.length)}},b=rt;var F={am:"am",pm:"pm",midnight:"midnight",noon:"noon",morning:"morning",afternoon:"afternoon",evening:"evening",night:"night"},at={G:function(e,r,a){var n=e.getUTCFullYear()>0?1:0;switch(r){case"G":case"GG":case"GGG":return a.era(n,{width:"abbreviated"});case"GGGGG":return a.era(n,{width:"narrow"});case"GGGG":default:return a.era(n,{width:"wide"})}},y:function(e,r,a){if(r==="yo"){var n=e.getUTCFullYear(),o=n>0?n:1-n;return a.ordinalNumber(o,{unit:"year"})}return b.y(e,r)},Y:function(e,r,a,n){var o=L(e,n),i=o>0?o:1-o;if(r==="YY"){var s=i%100;return u(s,2)}return r==="Yo"?a.ordinalNumber(i,{unit:"year"}):u(i,r.length)},R:function(e,r){var a=_(e);return u(a,r.length)},u:function(e,r){var a=e.getUTCFullYear();return u(a,r.length)},Q:function(e,r,a){var n=Math.ceil((e.getUTCMonth()+1)/3);switch(r){case"Q":return String(n);case"QQ":return u(n,2);case"Qo":return a.ordinalNumber(n,{unit:"quarter"});case"QQQ":return a.quarter(n,{width:"abbreviated",context:"formatting"});case"QQQQQ":return a.quarter(n,{width:"narrow",context:"formatting"});case"QQQQ":default:return a.quarter(n,{width:"wide",context:"formatting"})}},q:function(e,r,a){var n=Math.ceil((e.getUTCMonth()+1)/3);switch(r){case"q":return String(n);case"qq":return u(n,2);case"qo":return a.ordinalNumber(n,{unit:"quarter"});case"qqq":return a.quarter(n,{width:"abbreviated",context:"standalone"});case"qqqqq":return a.quarter(n,{width:"narrow",context:"standalone"});case"qqqq":default:return a.quarter(n,{width:"wide",context:"standalone"})}},M:function(e,r,a){var n=e.getUTCMonth();switch(r){case"M":case"MM":return b.M(e,r);case"Mo":return a.ordinalNumber(n+1,{unit:"month"});case"MMM":return a.month(n,{width:"abbreviated",context:"formatting"});case"MMMMM":return a.month(n,{width:"narrow",context:"formatting"});case"MMMM":default:return a.month(n,{width:"wide",context:"formatting"})}},L:function(e,r,a){var n=e.getUTCMonth();switch(r){case"L":return String(n+1);case"LL":return u(n+1,2);case"Lo":return a.ordinalNumber(n+1,{unit:"month"});case"LLL":return a.month(n,{width:"abbreviated",context:"standalone"});case"LLLLL":return a.month(n,{width:"narrow",context:"standalone"});case"LLLL":default:return a.month(n,{width:"wide",context:"standalone"})}},w:function(e,r,a,n){var o=oe(e,n);return r==="wo"?a.ordinalNumber(o,{unit:"week"}):u(o,r.length)},I:function(e,r,a){var n=ae(e);return r==="Io"?a.ordinalNumber(n,{unit:"week"}):u(n,r.length)},d:function(e,r,a){return r==="do"?a.ordinalNumber(e.getUTCDate(),{unit:"date"}):b.d(e,r)},D:function(e,r,a){var n=te(e);return r==="Do"?a.ordinalNumber(n,{unit:"dayOfYear"}):u(n,r.length)},E:function(e,r,a){var n=e.getUTCDay();switch(r){case"E":case"EE":case"EEE":return a.day(n,{width:"abbreviated",context:"formatting"});case"EEEEE":return a.day(n,{width:"narrow",context:"formatting"});case"EEEEEE":return a.day(n,{width:"short",context:"formatting"});case"EEEE":default:return a.day(n,{width:"wide",context:"formatting"})}},e:function(e,r,a,n){var o=e.getUTCDay(),i=(o-n.weekStartsOn+8)%7||7;switch(r){case"e":return String(i);case"ee":return u(i,2);case"eo":return a.ordinalNumber(i,{unit:"day"});case"eee":return a.day(o,{width:"abbreviated",context:"formatting"});case"eeeee":return a.day(o,{width:"narrow",context:"formatting"});case"eeeeee":return a.day(o,{width:"short",context:"formatting"});case"eeee":default:return a.day(o,{width:"wide",context:"formatting"})}},c:function(e,r,a,n){var o=e.getUTCDay(),i=(o-n.weekStartsOn+8)%7||7;switch(r){case"c":return String(i);case"cc":return u(i,r.length);case"co":return a.ordinalNumber(i,{unit:"day"});case"ccc":return a.day(o,{width:"abbreviated",context:"standalone"});case"ccccc":return a.day(o,{width:"narrow",context:"standalone"});case"cccccc":return a.day(o,{width:"short",context:"standalone"});case"cccc":default:return a.day(o,{width:"wide",context:"standalone"})}},i:function(e,r,a){var n=e.getUTCDay(),o=n===0?7:n;switch(r){case"i":return String(o);case"ii":return u(o,r.length);case"io":return a.ordinalNumber(o,{unit:"day"});case"iii":return a.day(n,{width:"abbreviated",context:"formatting"});case"iiiii":return a.day(n,{width:"narrow",context:"formatting"});case"iiiiii":return a.day(n,{width:"short",context:"formatting"});case"iiii":default:return a.day(n,{width:"wide",context:"formatting"})}},a:function(e,r,a){var n=e.getUTCHours(),o=n/12>=1?"pm":"am";switch(r){case"a":case"aa":return a.dayPeriod(o,{width:"abbreviated",context:"formatting"});case"aaa":return a.dayPeriod(o,{width:"abbreviated",context:"formatting"}).toLowerCase();case"aaaaa":return a.dayPeriod(o,{width:"narrow",context:"formatting"});case"aaaa":default:return a.dayPeriod(o,{width:"wide",context:"formatting"})}},b:function(e,r,a){var n=e.getUTCHours(),o;switch(n===12?o=F.noon:n===0?o=F.midnight:o=n/12>=1?"pm":"am",r){case"b":case"bb":return a.dayPeriod(o,{width:"abbreviated",context:"formatting"});case"bbb":return a.dayPeriod(o,{width:"abbreviated",context:"formatting"}).toLowerCase();case"bbbbb":return a.dayPeriod(o,{width:"narrow",context:"formatting"});case"bbbb":default:return a.dayPeriod(o,{width:"wide",context:"formatting"})}},B:function(e,r,a){var n=e.getUTCHours(),o;switch(n>=17?o=F.evening:n>=12?o=F.afternoon:n>=4?o=F.morning:o=F.night,r){case"B":case"BB":case"BBB":return a.dayPeriod(o,{width:"abbreviated",context:"formatting"});case"BBBBB":return a.dayPeriod(o,{width:"narrow",context:"formatting"});case"BBBB":default:return a.dayPeriod(o,{width:"wide",context:"formatting"})}},h:function(e,r,a){if(r==="ho"){var n=e.getUTCHours()%12;return n===0&&(n=12),a.ordinalNumber(n,{unit:"hour"})}return b.h(e,r)},H:function(e,r,a){return r==="Ho"?a.ordinalNumber(e.getUTCHours(),{unit:"hour"}):b.H(e,r)},K:function(e,r,a){var n=e.getUTCHours()%12;return r==="Ko"?a.ordinalNumber(n,{unit:"hour"}):u(n,r.length)},k:function(e,r,a){var n=e.getUTCHours();return n===0&&(n=24),r==="ko"?a.ordinalNumber(n,{unit:"hour"}):u(n,r.length)},m:function(e,r,a){return r==="mo"?a.ordinalNumber(e.getUTCMinutes(),{unit:"minute"}):b.m(e,r)},s:function(e,r,a){return r==="so"?a.ordinalNumber(e.getUTCSeconds(),{unit:"second"}):b.s(e,r)},S:function(e,r){return b.S(e,r)},X:function(e,r,a,n){var o=n._originalDate||e,i=o.getTimezoneOffset();if(i===0)return"Z";switch(r){case"X":return be(i);case"XXXX":case"XX":return M(i);case"XXXXX":case"XXX":default:return M(i,":")}},x:function(e,r,a,n){var o=n._originalDate||e,i=o.getTimezoneOffset();switch(r){case"x":return be(i);case"xxxx":case"xx":return M(i);case"xxxxx":case"xxx":default:return M(i,":")}},O:function(e,r,a,n){var o=n._originalDate||e,i=o.getTimezoneOffset();switch(r){case"O":case"OO":case"OOO":return"GMT"+ve(i,":");case"OOOO":default:return"GMT"+M(i,":")}},z:function(e,r,a,n){var o=n._originalDate||e,i=o.getTimezoneOffset();switch(r){case"z":case"zz":case"zzz":return"GMT"+ve(i,":");case"zzzz":default:return"GMT"+M(i,":")}},t:function(e,r,a,n){var o=n._originalDate||e,i=Math.floor(o.getTime()/1e3);return u(i,r.length)},T:function(e,r,a,n){var o=n._originalDate||e,i=o.getTime();return u(i,r.length)}};function ve(t,e){var r=t>0?"-":"+",a=Math.abs(t),n=Math.floor(a/60),o=a%60;if(o===0)return r+String(n);var i=e||"";return r+String(n)+i+u(o,2)}function be(t,e){if(t%60===0){var r=t>0?"-":"+";return r+u(Math.abs(t)/60,2)}return M(t,e)}function M(t,e){var r=e||"",a=t>0?"-":"+",n=Math.abs(t),o=u(Math.floor(n/60),2),i=u(n%60,2);return a+o+r+i}var we=at;var Te=function(e,r){switch(e){case"P":return r.date({width:"short"});case"PP":return r.date({width:"medium"});case"PPP":return r.date({width:"long"});case"PPPP":default:return r.date({width:"full"})}},Oe=function(e,r){switch(e){case"p":return r.time({width:"short"});case"pp":return r.time({width:"medium"});case"ppp":return r.time({width:"long"});case"pppp":default:return r.time({width:"full"})}},nt=function(e,r){var a=e.match(/(P+)(p+)?/)||[],n=a[1],o=a[2];if(!o)return Te(e,r);var i;switch(n){case"P":i=r.dateTime({width:"short"});break;case"PP":i=r.dateTime({width:"medium"});break;case"PPP":i=r.dateTime({width:"long"});break;case"PPPP":default:i=r.dateTime({width:"full"});break}return i.replace("{{date}}",Te(n,r)).replace("{{time}}",Oe(o,r))},ot={p:Oe,P:nt},Se=ot;var it=["D","DD"],st=["YY","YYYY"];function De(t){return it.indexOf(t)!==-1}function ke(t){return st.indexOf(t)!==-1}function ie(t,e,r){if(t==="YYYY")throw new RangeError("Use `yyyy` instead of `YYYY` (in `".concat(e,"`) for formatting years to the input `").concat(r,"`; see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md"));if(t==="YY")throw new RangeError("Use `yy` instead of `YY` (in `".concat(e,"`) for formatting years to the input `").concat(r,"`; see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md"));if(t==="D")throw new RangeError("Use `d` instead of `D` (in `".concat(e,"`) for formatting days of the month to the input `").concat(r,"`; see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md"));if(t==="DD")throw new RangeError("Use `dd` instead of `DD` (in `".concat(e,"`) for formatting days of the month to the input `").concat(r,"`; see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md"))}var ut={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"}},ft=function(e,r,a){var n,o=ut[e];return typeof o=="string"?n=o:r===1?n=o.one:n=o.other.replace("{{count}}",r.toString()),a!=null&&a.addSuffix?a.comparison&&a.comparison>0?"in "+n:n+" ago":n},Me=ft;function $(t){return function(){var e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},r=e.width?String(e.width):t.defaultWidth,a=t.formats[r]||t.formats[t.defaultWidth];return a}}var lt={full:"EEEE, MMMM do, y",long:"MMMM do, y",medium:"MMM d, y",short:"MM/dd/yyyy"},dt={full:"h:mm:ss a zzzz",long:"h:mm:ss a z",medium:"h:mm:ss a",short:"h:mm a"},mt={full:"{{date}} \'at\' {{time}}",long:"{{date}} \'at\' {{time}}",medium:"{{date}}, {{time}}",short:"{{date}}, {{time}}"},ct={date:$({formats:lt,defaultWidth:"full"}),time:$({formats:dt,defaultWidth:"full"}),dateTime:$({formats:mt,defaultWidth:"full"})},We=ct;var pt={lastWeek:"\'last\' eeee \'at\' p",yesterday:"\'yesterday at\' p",today:"\'today at\' p",tomorrow:"\'tomorrow at\' p",nextWeek:"eeee \'at\' p",other:"P"},gt=function(e,r,a,n){return pt[e]},Ce=gt;function W(t){return function(e,r){var a=r!=null&&r.context?String(r.context):"standalone",n;if(a==="formatting"&&t.formattingValues){var o=t.defaultFormattingWidth||t.defaultWidth,i=r!=null&&r.width?String(r.width):o;n=t.formattingValues[i]||t.formattingValues[o]}else{var s=t.defaultWidth,d=r!=null&&r.width?String(r.width):t.defaultWidth;n=t.values[d]||t.values[s]}var l=t.argumentCallback?t.argumentCallback(e):e;return n[l]}}var ht={narrow:["B","A"],abbreviated:["BC","AD"],wide:["Before Christ","Anno Domini"]},xt={narrow:["1","2","3","4"],abbreviated:["Q1","Q2","Q3","Q4"],wide:["1st quarter","2nd quarter","3rd quarter","4th quarter"]},yt={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"]},vt={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"]},bt={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"}},wt={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"}},Tt=function(e,r){var a=Number(e),n=a%100;if(n>20||n<10)switch(n%10){case 1:return a+"st";case 2:return a+"nd";case 3:return a+"rd"}return a+"th"},Ot={ordinalNumber:Tt,era:W({values:ht,defaultWidth:"wide"}),quarter:W({values:xt,defaultWidth:"wide",argumentCallback:function(e){return e-1}}),month:W({values:yt,defaultWidth:"wide"}),day:W({values:vt,defaultWidth:"wide"}),dayPeriod:W({values:bt,defaultWidth:"wide",formattingValues:wt,defaultFormattingWidth:"wide"})},Pe=Ot;function C(t){return function(e){var r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},a=r.width,n=a&&t.matchPatterns[a]||t.matchPatterns[t.defaultMatchWidth],o=e.match(n);if(!o)return null;var i=o[0],s=a&&t.parsePatterns[a]||t.parsePatterns[t.defaultParseWidth],d=Array.isArray(s)?Dt(s,function(c){return c.test(i)}):St(s,function(c){return c.test(i)}),l;l=t.valueCallback?t.valueCallback(d):d,l=r.valueCallback?r.valueCallback(l):l;var p=e.slice(i.length);return{value:l,rest:p}}}function St(t,e){for(var r in t)if(t.hasOwnProperty(r)&&e(t[r]))return r}function Dt(t,e){for(var r=0;r1&&arguments[1]!==void 0?arguments[1]:{},a=e.match(t.matchPattern);if(!a)return null;var n=a[0],o=e.match(t.parsePattern);if(!o)return null;var i=t.valueCallback?t.valueCallback(o[0]):o[0];i=r.valueCallback?r.valueCallback(i):i;var s=e.slice(n.length);return{value:i,rest:s}}}var kt=/^(\\d+)(th|st|nd|rd)?/i,Mt=/\\d+/i,Wt={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},Ct={any:[/^b/i,/^(a|c)/i]},Pt={narrow:/^[1234]/i,abbreviated:/^q[1234]/i,wide:/^[1234](th|st|nd|rd)? quarter/i},Ft={any:[/1/i,/2/i,/3/i,/4/i]},It={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},Yt={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]},Ut={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},Nt={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]},Et={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},At={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}},qt={ordinalNumber:se({matchPattern:kt,parsePattern:Mt,valueCallback:function(e){return parseInt(e,10)}}),era:C({matchPatterns:Wt,defaultMatchWidth:"wide",parsePatterns:Ct,defaultParseWidth:"any"}),quarter:C({matchPatterns:Pt,defaultMatchWidth:"wide",parsePatterns:Ft,defaultParseWidth:"any",valueCallback:function(e){return e+1}}),month:C({matchPatterns:It,defaultMatchWidth:"wide",parsePatterns:Yt,defaultParseWidth:"any"}),day:C({matchPatterns:Ut,defaultMatchWidth:"wide",parsePatterns:Nt,defaultParseWidth:"any"}),dayPeriod:C({matchPatterns:Et,defaultMatchWidth:"any",parsePatterns:At,defaultParseWidth:"any"})},Fe=qt;var _t={code:"en-US",formatDistance:Me,formatLong:We,formatRelative:Ce,localize:Pe,match:Fe,options:{weekStartsOn:0,firstWeekContainsDate:1}},Ie=_t;var Ye=Ie;var Lt=/[yYQqMLwIdDecihHKkms]o|(\\w)\\1*|\'\'|\'(\'\'|[^\'])+(\'|$)|./g,$t=/P+p+|P+|p+|\'\'|\'(\'\'|[^\'])+(\'|$)|./g,Qt=/^\'([^]*?)\'?$/,jt=/\'\'/g,Ht=/[a-zA-Z]/;function H(t,e,r){var a,n,o,i,s,d,l,p,c,h,g,v,N,D,E,R,B,G;f(2,arguments);var Ge=String(e),A=T(),q=(a=(n=r?.locale)!==null&&n!==void 0?n:A.locale)!==null&&a!==void 0?a:Ye,V=x((o=(i=(s=(d=r?.firstWeekContainsDate)!==null&&d!==void 0?d:r==null||(l=r.locale)===null||l===void 0||(p=l.options)===null||p===void 0?void 0:p.firstWeekContainsDate)!==null&&s!==void 0?s:A.firstWeekContainsDate)!==null&&i!==void 0?i:(c=A.locale)===null||c===void 0||(h=c.options)===null||h===void 0?void 0:h.firstWeekContainsDate)!==null&&o!==void 0?o:1);if(!(V>=1&&V<=7))throw new RangeError("firstWeekContainsDate must be between 1 and 7 inclusively");var X=x((g=(v=(N=(D=r?.weekStartsOn)!==null&&D!==void 0?D:r==null||(E=r.locale)===null||E===void 0||(R=E.options)===null||R===void 0?void 0:R.weekStartsOn)!==null&&N!==void 0?N:A.weekStartsOn)!==null&&v!==void 0?v:(B=A.locale)===null||B===void 0||(G=B.options)===null||G===void 0?void 0:G.weekStartsOn)!==null&&g!==void 0?g:0);if(!(X>=0&&X<=6))throw new RangeError("weekStartsOn must be between 0 and 6 inclusively");if(!q.localize)throw new RangeError("locale must contain localize property");if(!q.formatLong)throw new RangeError("locale must contain formatLong property");var Q=m(t);if(!Z(Q))throw new RangeError("Invalid time value");var Ve=z(Q),Xe=ee(Q,Ve),Je={firstWeekContainsDate:V,weekStartsOn:X,locale:q,_originalDate:Q},ze=Ge.match($t).map(function(y){var w=y[0];if(w==="p"||w==="P"){var j=Se[w];return j(y,q.formatLong)}return y}).join("").match(Lt).map(function(y){if(y==="\'\'")return"\'";var w=y[0];if(w==="\'")return Rt(y);var j=we[w];if(j)return!(r!=null&&r.useAdditionalWeekYearTokens)&&ke(y)&&ie(y,e,String(t)),!(r!=null&&r.useAdditionalDayOfYearTokens)&&De(y)&&ie(y,e,String(t)),j(Xe,y,q.localize,Je);if(w.match(Ht))throw new RangeError("Format string contains an unescaped latin alphabet character `"+w+"`");return y}).join("");return ze}function Rt(t){var e=t.match(Qt);return e?e[1].replace(jt,"\'"):t}var Ue=t=>[...new Set(t)];var ue=(t,e)=>{if(t instanceof Date)return"date";if(typeof t=="string"){if(/\\/\\/(\\S+?(?:jpe?g|png|gif|svg))/gi.test(t)||t.includes("unsplash"))return"image";if(/^\\d{4}-\\d{2}-\\d{2}$/.test(t))return"date";if(e=="tag"||e=="tags")return"tags-multi";if(/\\[\\[.*?\\]\\]/.test(t))return"link"}else{if(typeof t=="number")return"number";if(typeof t=="boolean")return"boolean";if(t)if(Array.isArray(t)||typeof t=="string"&&t.indexOf(",")>-1){let r=Array.isArray(t)?t:[];if(typeof t=="string"&&t.indexOf(",")>-1&&(r=P(t)),e=="tag"||e=="tags")return"tags-multi";if(r.length==1&&Array.isArray(r[0])&&r[0].length==1&&typeof r[0][0]=="string")return"link";let a=Ue(r.map(n=>ue(n,e)));return a.length==1&&a[0]=="link"?"link-multi":a.some(n=>n=="object")?"object-multi":"option-multi"}else{if(t.isLuxonDateTime)return"date";if(t.isLuxonDuration)return"duration";if(t.type=="file")return"link";if(typeof t=="object"&&!Array.isArray(t)&&t!==null)return"object"}else return"unknown"}return"text"};var Ne=t=>t.map(e=>e.replace(",","\\\\,")).join(", "),I=t=>JSON.stringify(t);var P=t=>t?.startsWith("[")?he(ye(t)):Bt(t),Bt=t=>(t?.replace("\\\\,",",")?.match(/(\\\\.|[^,])+/g)??[]).map(e=>e.trim()),le=(t,e)=>{switch(ue(e,t)){case"tags-multi":return e;case"object":case"object-multi":return JSON.stringify(e);case"number":return e.toString();case"boolean":return e?"true":"false";case"date":{if(e instanceof Date){let a=H(e,"yyyy-MM-dd");return typeof a=="string"?a:""}return typeof e!="string"?"":e}break;case"duration":return Ne(Object.keys(e.values).reduce((a,n)=>[...a,...e.values[n]>0?[e.values[n]+" "+n]:[]],[]));case"option-multi":case"link-multi":return typeof e=="string"?fe(e):I(e.map(a=>a?typeof a=="string"?fe(a):a.path?a.path:Array.isArray(e)&&a.length==1&&Array.isArray(a[0])&&a[0].length==1&&typeof a[0][0]=="string"?a[0][0]:JSON.stringify(a):""));case"link":return Array.isArray(e)&&e.length==1&&Array.isArray(e[0])&&e[0].length==1&&typeof e[0][0]=="string"?e[0][0]:typeof e=="string"?fe(e):e.path;case"text":case"tag":case"image":return e}return""};var ye=t=>{let e;try{e=JSON.parse(t)}catch{}return e};var fe=t=>{if(!t)return"";let e=/\\[\\[(.*?)\\]\\]/g.exec(t),r=e?.length>1?e[1].substring(0,xe("|",e[1])):t;return r||t};var Ee=(t,e)=>{let r=t?P(t):[],a=e?P(e):[];return a.every(n=>r.some(o=>o==n))&&r.every(n=>a.some(o=>o==n))},Y=(t,e)=>t==e,de=(t,e)=>(t??"").length==0,me=(t,e)=>(t??"").toLowerCase().includes((e??"").toLowerCase()),ce=(t,e)=>parseFloat(t)>parseFloat(e),pe=(t,e)=>parseInt(t){let r=isNaN(Date.parse(t))?new Date(parseInt(t)):new Date(t),a=isNaN(Date.parse(e))?new Date(parseInt(e)):new Date(e);return r.valueOf()>=a.valueOf()},qe=(t,e)=>{let r=isNaN(Date.parse(t))?new Date(parseInt(t)):new Date(t),a=isNaN(Date.parse(e))?new Date(parseInt(e)):new Date(e);return r.valueOf(){let r=t?P(t):[],a=e?P(e):[];return r.length==0?!1:a.some(n=>r.some(o=>o==n))},_e=(t,e)=>{if(!t)return!1;let r=new Date(`${t.toString().replace(".",":")}`),a=new Date(`${e}`);return r.getMonth()===a.getMonth()&&r.getDate()===a.getDate()},Le=t=>{if(!t)return!1;let e=new Date(`${t.toString()}T00:00`),r=new Date;return e.getMonth()===r.getMonth()&&e.getDate()===r.getDate()};var U={isNotEmpty:{type:["text","file","number","option","option-multi","link","link-multi","image"],fn:(t,e)=>!de(t,""),valueType:"none"},isEmpty:{type:["text","file","number","option","option-multi","link","link-multi","image"],fn:(t,e)=>de(t,""),valueType:"none"},include:{fn:(t,e)=>me(t,e),type:["text","file","link","image"],valueType:"text"},notInclude:{type:["text","file","link","image"],fn:(t,e)=>!me(t,e),valueType:"text"},is:{type:["text"],fn:(t,e)=>Y(t,e),valueType:"text"},isNot:{type:["text"],fn:(t,e)=>!Y(t,e),valueType:"text"},equal:{type:["number"],fn:(t,e)=>Y(t,e),valueType:"number"},isLink:{type:["link","context"],fn:(t,e)=>Y(t,e),valueType:"link"},isNotLink:{type:["link","context"],fn:(t,e)=>!Y(t,e),valueType:"link"},isGreatThan:{type:["number"],fn:(t,e)=>ce(t,e),valueType:"number"},isLessThan:{type:["number"],fn:(t,e)=>pe(t,e),valueType:"number"},isLessThanOrEqual:{type:["number"],fn:(t,e)=>!ce(t,e),valueType:"number"},isGreatThanOrEqual:{type:["number"],fn:(t,e)=>!pe(t,e),valueType:"number"},dateBefore:{type:["date"],fn:(t,e)=>qe(t,e),valueType:"date"},dateAfter:{type:["date"],fn:(t,e)=>Ae(t,e),valueType:"date"},isSameDate:{type:["date"],fn:(t,e)=>_e(t,e),valueType:"date"},isSameDateAsToday:{type:["date"],fn:(t,e)=>Le(t,e),valueType:"none"},isExactList:{type:["option","option-multi","link-multi","context-multi","tags-multi"],fn:(t,e)=>Ee(t,e),valueType:"list"},isAnyInList:{type:["option","context","link","option-multi","link-multi","context-multi","tags-multi"],fn:(t,e)=>ge(t,e),valueType:"list"},isNoneInList:{type:["option","context","link","option-multi","link-multi","context-multi","tags-multi"],fn:(t,e)=>!ge(t,e),valueType:"list"},isTrue:{type:["boolean"],fn:(t,e)=>t=="true",valueType:"none"},isFalse:{type:["boolean"],fn:(t,e)=>t!="true",valueType:"none"}};var Gt=(t,e,r)=>e.reduce((n,o)=>{let[i,s]=n,d=o.type=="context"?$e(s,o,r):o.type=="path"?je(s,o,r):o.type=="frontmatter"?Qe(s,o,r):He(s,o,r),l=s.filter(p=>!d.includes(p));return[[...i,...d],l]},[[],t])[0],Vt=(t,e,r)=>e.reduce((a,n)=>n.type=="context"?$e(a,n,r):n.type=="path"?je(a,n,r):n.type=="frontmatter"?Qe(a,n,r):He(a,n,r),t),$e=(t,e,r)=>{let a=U[e.fn];return!a||a.valueType!="none"&&e.value.length==0?[]:t.filter(n=>{let[o,i]=e.field.split("."),s=n.metadata?.property;if(!n.spaces?.includes(o)||!s||!s[i])return!1;let d=!0;if(a){let l=e.fType=="property"?r[e.value]:e.value;d=a.fn(le(i,s[i]),l)}return d})},Qe=(t,e,r)=>{let a=U[e.fn];return!a||a.valueType!="none"&&e.value.length==0?[]:t.filter(n=>{let o=n.metadata?.property;if(!o||o[e.field]===void 0)return!1;let i=!0;if(a){let s=e.fType=="property"?r[e.value]:e.value;i=a.fn(le(e.field,o[e.field]),s)}return i})},je=(t,e,r)=>{let a=U[e.fn];return!a||a.valueType!="none"&&e.value.length==0?[]:t.filter(n=>{let o="";e.field=="outlinks"?o=I(n.outlinks??[]):e.field=="inlinks"?o=I(n.inlinks??[]):e.field=="tags"&&(o=I(n.tags??[]));let i=!0;if(a){let s=e.fType=="property"?r[e.value]:e.value;i=a.fn(o,s)}return i})},He=(t,e,r)=>{let a=U[e.fn];return!a||a.valueType!="none"&&e.value.length==0?[]:t.filter(n=>{let o=!0;if(a){let i=e.fType=="property"?r[e.value]:e.value;o=a.fn(n.metadata?.[e.type]?.[e.field],i)}return o})},Re=(t,e,r)=>t.reduce((n,o)=>!n||o.filters.length==0?!1:o.type=="any"?Gt([e],o.filters,r).length>0:Vt([e],o.filters,r).length>0,!0);function Be(t){let{queries:e,pathsIndex:r,count:a}=t,n=[];for(let[o,i]of r)!i.hidden&&Re(e,i,{})&&n.push(i);return n.slice(0,a)}var Xt=self;Xt.onmessage=async t=>{let{payload:e,job:r}=t.data,a;r.type=="search"&&(a=Be(e));try{postMessage({job:r,result:a})}catch(n){console.log(n),postMessage({job:r,result:{$error:`Failed to run ${r.type} ${r.path}: ${n}`}})}};\n', { "name": "Superstate Search" }); +function sameArray(a4, b2) { + return a4.length == b2.length && a4.every((x2, i4) => x2 == b2[i4]); } - -// src/core/superstate/workers/search/search.ts -var Searcher = class { - constructor(numWorkers, cache2) { - this.numWorkers = numWorkers; - this.cache = cache2; - this.workers = []; - this.busy = []; - this.reloadQueue = []; - this.reloadSet = /* @__PURE__ */ new Set(); - this.callbacks = /* @__PURE__ */ new Map(); - for (let index2 = 0; index2 < numWorkers; index2++) { - const worker = new Worker3({ name: "Make.md Superstate Indexer " + (index2 + 1) }); - worker.onmessage = (evt) => this.finish(evt.data.job, evt.data.result, index2); - this.workers.push(worker); - this.busy.push(false); - } +function permute(array) { + let result = [array]; + for (let i4 = 0; i4 < array.length; i4++) { + for (let a4 of permute(array.slice(0, i4).concat(array.slice(i4 + 1)))) + result.push(a4); } - run(jerb) { - const jobKey = stringifyJob(jerb); - const promise = new Promise((resolve2, reject) => { - if (this.callbacks.has(jobKey)) - this.callbacks.get(jobKey)?.push([resolve2, reject]); - else - this.callbacks.set(jobKey, [[resolve2, reject]]); - }); - if (this.reloadSet.has(jobKey)) - return promise; - this.reloadSet.add(jobKey); - const workerId = this.nextAvailableWorker(); - if (workerId !== void 0) { - this.send(jerb, workerId); - } else { - this.reloadQueue.push(jerb); - } - return promise; + return result; +} +function styleTags(spec) { + let byName = /* @__PURE__ */ Object.create(null); + for (let prop2 in spec) { + let tags3 = spec[prop2]; + if (!Array.isArray(tags3)) + tags3 = [tags3]; + for (let part of prop2.split(" ")) + if (part) { + let pieces = [], mode2 = 2, rest = part; + for (let pos = 0; ; ) { + if (rest == "..." && pos > 0 && pos + 3 == part.length) { + mode2 = 1; + break; + } + let m4 = /^"(?:[^"\\]|\\.)*?"|[^\/!]+/.exec(rest); + if (!m4) + throw new RangeError("Invalid path: " + part); + pieces.push(m4[0] == "*" ? "" : m4[0][0] == '"' ? JSON.parse(m4[0]) : m4[0]); + pos += m4[0].length; + if (pos == part.length) + break; + let next = part[pos++]; + if (pos == part.length && next == "!") { + mode2 = 0; + break; + } + if (next != "/") + throw new RangeError("Invalid path: " + part); + rest = part.slice(pos); + } + let last = pieces.length - 1, inner = pieces[last]; + if (!inner) + throw new RangeError("Invalid path: " + part); + let rule = new Rule(tags3, mode2, last > 0 ? pieces.slice(0, last) : null); + byName[inner] = rule.sort(byName[inner]); + } } - finish(jerb, data2, index2) { - const jobKey = stringifyJob(jerb); - const calls = [].concat(this.callbacks.get(jobKey) ?? []); - this.reloadSet.delete(jobKey); - this.callbacks.delete(jobKey); - this.busy[index2] = false; - const job = this.reloadQueue.shift(); - if (job !== void 0) - this.send(job, index2); - if ("$error" in data2) { - for (const [_15, reject] of calls) - reject(data2["$error"]); - } else { - for (const [callback, _15] of calls) - callback(data2); - } + return ruleNodeProp.add(byName); +} +var ruleNodeProp = new NodeProp(); +var Rule = class { + constructor(tags3, mode2, context, next) { + this.tags = tags3; + this.mode = mode2; + this.context = context; + this.next = next; } - async send(job, workerId) { - if (job.type == "search") { - this.message(workerId, { - job, - payload: { - queries: job.payload.queries, - pathsIndex: this.cache.pathsIndex, - count: job.payload.count - } - }); - this.busy[workerId] = true; + sort(other) { + if (!other || other.depth < this.depth) { + this.next = other; + return this; } + other.next = this.sort(other.next); + return other; } - message(workerId, message) { - this.workers[workerId].postMessage( - message - ); - } - nextAvailableWorker() { - const index2 = this.busy.indexOf(false); - return index2 == -1 ? void 0 : index2; + get depth() { + return this.context ? this.context.length : 0; } }; - -// src/core/superstate/superstate.ts -var Superstate2 = class { - constructor(indexVersion, onChange, spaceManager, uiManager, commandsManager) { - this.indexVersion = indexVersion; - this.onChange = onChange; - this.loadouts = []; - this.kit = [ - buttonNode, - dividerNode, - progressNode, - callout, - toggleNode, - eventItem, - circularProgressNode, - previewNode, - linkNode, - imageListItem, - detailItem, - flowListItem, - cardListItem, - cardsListItem, - listItem, - listGroup, - columnGroup, - masonryGroup, - listView, - calendarView, - dateGroup, - tabsNode, - fieldNode, - gridGroup, - newItemNode, - ratingNode, - fieldsView, - rowGroup, - coverListItem, - columnView - ]; - this.eventsDispatcher = new EventDispatcher(); - const all2 = { - ...all, - createAdd: factory("add", [], () => function add4(a4, b2) { - return a4 + b2; - }) - }; - const runContext = create(all2); - runContext.import(formulas, { override: true }); - this.formulaContext = runContext; - this.initialized = false; - this.spaceManager = spaceManager; - this.spaceManager.superstate = this; - this.ui = uiManager; - this.cli = commandsManager; - const spaceCommands = new SpacesCommandsAdapter(this.cli, this); - this.cli.superstate = this; - this.cli.terminals.splice(0, 0, spaceCommands); - this.cli.mainTerminal = spaceCommands; - this.allMetadata = {}; - this.api = new API(this); - this.pathsIndex = /* @__PURE__ */ new Map(); - this.spacesIndex = /* @__PURE__ */ new Map(); - this.contextsIndex = /* @__PURE__ */ new Map(); - this.framesIndex = /* @__PURE__ */ new Map(); - this.actionsIndex = /* @__PURE__ */ new Map(); - this.kitFrames = /* @__PURE__ */ new Map(); - this.kits = /* @__PURE__ */ new Map(); - this.actions = /* @__PURE__ */ new Map(); - this.templateCache = /* @__PURE__ */ new Map(); - this.waypoints = []; - this.spacesMap = new IndexMap(); - this.linksMap = new IndexMap(); - this.tagsMap = new IndexMap(); - this.iconsCache = /* @__PURE__ */ new Map(); - this.imagesCache = /* @__PURE__ */ new Map(); - this.contextStateQueue = Promise.resolve(); - this.vaultDBCache = []; - this.indexer = new Indexer(2, this); - this.searcher = new Searcher(1, this); - } - static create(indexVersion, onChange, spaceManager, uiManager, commandsManager) { - return new Superstate2(indexVersion, onChange, spaceManager, uiManager, commandsManager); +function tagHighlighter(tags3, options) { + let map4 = /* @__PURE__ */ Object.create(null); + for (let style of tags3) { + if (!Array.isArray(style.tag)) + map4[style.tag.id] = style.class; + else + for (let tag2 of style.tag) + map4[tag2.id] = style.class; } - refreshMetadata() { - this.allMetadata = allMetadata(this); + let { scope, all: all2 = null } = options || {}; + return { + style: (tags4) => { + let cls = all2; + for (let tag2 of tags4) { + for (let sub2 of tag2.set) { + let tagClass = map4[sub2.id]; + if (tagClass) { + cls = cls ? cls + " " + tagClass : tagClass; + break; + } + } + } + return cls; + }, + scope + }; +} +var t2 = Tag.define; +var comment = t2(); +var name315 = t2(); +var typeName2 = t2(name315); +var propertyName = t2(name315); +var literal2 = t2(); +var string2 = t2(literal2); +var number2 = t2(literal2); +var content = t2(); +var heading = t2(content); +var keyword = t2(); +var operator = t2(); +var punctuation = t2(); +var bracket = t2(punctuation); +var meta = t2(); +var tags = { + comment, + lineComment: t2(comment), + blockComment: t2(comment), + docComment: t2(comment), + name: name315, + variableName: t2(name315), + typeName: typeName2, + tagName: t2(typeName2), + propertyName, + attributeName: t2(propertyName), + className: t2(name315), + labelName: t2(name315), + namespace: t2(name315), + macroName: t2(name315), + literal: literal2, + string: string2, + docString: t2(string2), + character: t2(string2), + attributeValue: t2(string2), + number: number2, + integer: t2(number2), + float: t2(number2), + bool: t2(literal2), + regexp: t2(literal2), + escape: t2(literal2), + color: t2(literal2), + url: t2(literal2), + keyword, + self: t2(keyword), + null: t2(keyword), + atom: t2(keyword), + unit: t2(keyword), + modifier: t2(keyword), + operatorKeyword: t2(keyword), + controlKeyword: t2(keyword), + definitionKeyword: t2(keyword), + moduleKeyword: t2(keyword), + operator, + derefOperator: t2(operator), + arithmeticOperator: t2(operator), + logicOperator: t2(operator), + bitwiseOperator: t2(operator), + compareOperator: t2(operator), + updateOperator: t2(operator), + definitionOperator: t2(operator), + typeOperator: t2(operator), + controlOperator: t2(operator), + punctuation, + separator: t2(punctuation), + bracket, + angleBracket: t2(bracket), + squareBracket: t2(bracket), + paren: t2(bracket), + brace: t2(bracket), + content, + heading, + heading1: t2(heading), + heading2: t2(heading), + heading3: t2(heading), + heading4: t2(heading), + heading5: t2(heading), + heading6: t2(heading), + contentSeparator: t2(content), + list: t2(content), + quote: t2(content), + emphasis: t2(content), + strong: t2(content), + link: t2(content), + monospace: t2(content), + strikethrough: t2(content), + inserted: t2(), + deleted: t2(), + changed: t2(), + invalid: t2(), + meta, + documentMeta: t2(meta), + annotation: t2(meta), + processingInstruction: t2(meta), + definition: Tag.defineModifier(), + constant: Tag.defineModifier(), + function: Tag.defineModifier(), + standard: Tag.defineModifier(), + local: Tag.defineModifier(), + special: Tag.defineModifier() +}; +var classHighlighter = tagHighlighter([ + { tag: tags.link, class: "tok-link" }, + { tag: tags.heading, class: "tok-heading" }, + { tag: tags.emphasis, class: "tok-emphasis" }, + { tag: tags.strong, class: "tok-strong" }, + { tag: tags.keyword, class: "tok-keyword" }, + { tag: tags.atom, class: "tok-atom" }, + { tag: tags.bool, class: "tok-bool" }, + { tag: tags.url, class: "tok-url" }, + { tag: tags.labelName, class: "tok-labelName" }, + { tag: tags.inserted, class: "tok-inserted" }, + { tag: tags.deleted, class: "tok-deleted" }, + { tag: tags.literal, class: "tok-literal" }, + { tag: tags.string, class: "tok-string" }, + { tag: tags.number, class: "tok-number" }, + { tag: [tags.regexp, tags.escape, tags.special(tags.string)], class: "tok-string2" }, + { tag: tags.variableName, class: "tok-variableName" }, + { tag: tags.local(tags.variableName), class: "tok-variableName tok-local" }, + { tag: tags.definition(tags.variableName), class: "tok-variableName tok-definition" }, + { tag: tags.special(tags.variableName), class: "tok-variableName2" }, + { tag: tags.definition(tags.propertyName), class: "tok-propertyName tok-definition" }, + { tag: tags.typeName, class: "tok-typeName" }, + { tag: tags.namespace, class: "tok-namespace" }, + { tag: tags.className, class: "tok-className" }, + { tag: tags.macroName, class: "tok-macroName" }, + { tag: tags.propertyName, class: "tok-propertyName" }, + { tag: tags.operator, class: "tok-operator" }, + { tag: tags.comment, class: "tok-comment" }, + { tag: tags.meta, class: "tok-meta" }, + { tag: tags.invalid, class: "tok-invalid" }, + { tag: tags.punctuation, class: "tok-punctuation" } +]); + +// node_modules/@lezer/javascript/dist/index.es.js +var noSemi = 281; +var incdec = 1; +var incdecPrefix = 2; +var templateContent = 282; +var InterpolationStart = 3; +var templateEnd = 283; +var insertSemi = 284; +var TSExtends = 4; +var spaces = 286; +var newline = 287; +var LineComment = 5; +var BlockComment = 6; +var Dialect_ts = 1; +var space = [ + 9, + 10, + 11, + 12, + 13, + 32, + 133, + 160, + 5760, + 8192, + 8193, + 8194, + 8195, + 8196, + 8197, + 8198, + 8199, + 8200, + 8201, + 8202, + 8232, + 8233, + 8239, + 8287, + 12288 +]; +var braceR = 125; +var braceL = 123; +var semicolon = 59; +var slash = 47; +var star = 42; +var plus = 43; +var minus = 45; +var dollar = 36; +var backtick = 96; +var backslash = 92; +var trackNewline = new ContextTracker({ + start: false, + shift(context, term) { + return term == LineComment || term == BlockComment || term == spaces ? context : term == newline; + }, + strict: false +}); +var insertSemicolon = new ExternalTokenizer((input, stack) => { + let { next } = input; + if ((next == braceR || next == -1 || stack.context) && stack.canShift(insertSemi)) + input.acceptToken(insertSemi); +}, { contextual: true, fallback: true }); +var noSemicolon = new ExternalTokenizer((input, stack) => { + let { next } = input, after; + if (space.indexOf(next) > -1) + return; + if (next == slash && ((after = input.peek(1)) == slash || after == star)) + return; + if (next != braceR && next != semicolon && next != -1 && !stack.context && stack.canShift(noSemi)) + input.acceptToken(noSemi); +}, { contextual: true }); +var incdecToken = new ExternalTokenizer((input, stack) => { + let { next } = input; + if (next == plus || next == minus) { + input.advance(); + if (next == input.next) { + input.advance(); + let mayPostfix = !stack.context && stack.canShift(incdec); + input.acceptToken(mayPostfix ? incdec : incdecPrefix); + } } - async initializeIndex() { - await this.loadFromCache(); +}, { contextual: true }); +var template = new ExternalTokenizer((input) => { + for (let afterDollar = false, i4 = 0; ; i4++) { + let { next } = input; + if (next < 0) { + if (i4) + input.acceptToken(templateContent); + break; + } else if (next == backtick) { + if (i4) + input.acceptToken(templateContent); + else + input.acceptToken(templateEnd, 1); + break; + } else if (next == braceL && afterDollar) { + if (i4 == 1) + input.acceptToken(InterpolationStart, 1); + else + input.acceptToken(templateContent, -1); + break; + } else if (next == 10 && i4) { + input.advance(); + input.acceptToken(templateContent); + break; + } else if (next == backslash) { + input.advance(); + } + afterDollar = next == dollar; + input.advance(); } - addToContextStateQueue(operation) { - this.contextStateQueue = this.contextStateQueue.then(operation).catch(() => { +}); +function tsExtends(value, stack) { + return value == "extends" && stack.dialectEnabled(Dialect_ts) ? TSExtends : -1; +} +var jsHighlight = styleTags({ + "get set async static": tags.modifier, + "for while do if else switch try catch finally return throw break continue default case": tags.controlKeyword, + "in of await yield void typeof delete instanceof": tags.operatorKeyword, + "let var const function class extends": tags.definitionKeyword, + "import export from": tags.moduleKeyword, + "with debugger as new": tags.keyword, + TemplateString: tags.special(tags.string), + Super: tags.atom, + BooleanLiteral: tags.bool, + this: tags.self, + null: tags.null, + Star: tags.modifier, + VariableName: tags.variableName, + "CallExpression/VariableName TaggedTemplateExpression/VariableName": tags.function(tags.variableName), + VariableDefinition: tags.definition(tags.variableName), + Label: tags.labelName, + PropertyName: tags.propertyName, + PrivatePropertyName: tags.special(tags.propertyName), + "CallExpression/MemberExpression/PropertyName": tags.function(tags.propertyName), + "FunctionDeclaration/VariableDefinition": tags.function(tags.definition(tags.variableName)), + "ClassDeclaration/VariableDefinition": tags.definition(tags.className), + PropertyDefinition: tags.definition(tags.propertyName), + PrivatePropertyDefinition: tags.definition(tags.special(tags.propertyName)), + UpdateOp: tags.updateOperator, + LineComment: tags.lineComment, + BlockComment: tags.blockComment, + Number: tags.number, + String: tags.string, + ArithOp: tags.arithmeticOperator, + LogicOp: tags.logicOperator, + BitOp: tags.bitwiseOperator, + CompareOp: tags.compareOperator, + RegExp: tags.regexp, + Equals: tags.definitionOperator, + "Arrow : Spread": tags.punctuation, + "( )": tags.paren, + "[ ]": tags.squareBracket, + "{ }": tags.brace, + "InterpolationStart InterpolationEnd": tags.special(tags.brace), + ".": tags.derefOperator, + ", ;": tags.separator, + TypeName: tags.typeName, + TypeDefinition: tags.definition(tags.typeName), + "type enum interface implements namespace module declare": tags.definitionKeyword, + "abstract global Privacy readonly override": tags.modifier, + "is keyof unique infer": tags.operatorKeyword, + JSXAttributeValue: tags.attributeValue, + JSXText: tags.content, + "JSXStartTag JSXStartCloseTag JSXSelfCloseEndTag JSXEndTag": tags.angleBracket, + "JSXIdentifier JSXNameSpacedName": tags.tagName, + "JSXAttribute/JSXIdentifier JSXAttribute/JSXNameSpacedName": tags.attributeName +}); +var spec_identifier = { __proto__: null, export: 18, as: 23, from: 29, default: 32, async: 37, function: 38, this: 48, true: 56, false: 56, void: 66, typeof: 70, null: 86, super: 88, new: 122, await: 139, yield: 141, delete: 142, class: 152, extends: 154, public: 197, private: 197, protected: 197, readonly: 199, instanceof: 220, in: 222, const: 224, import: 256, keyof: 307, unique: 311, infer: 317, is: 351, abstract: 371, implements: 373, type: 375, let: 378, var: 380, interface: 387, enum: 391, namespace: 397, module: 399, declare: 403, global: 407, for: 428, of: 437, while: 440, with: 444, do: 448, if: 452, else: 454, switch: 458, case: 464, try: 470, catch: 474, finally: 478, return: 482, throw: 486, break: 490, continue: 494, debugger: 498 }; +var spec_word = { __proto__: null, async: 109, get: 111, set: 113, public: 161, private: 161, protected: 161, static: 163, abstract: 165, override: 167, readonly: 173, new: 355 }; +var spec_LessThan = { __proto__: null, "<": 129 }; +var parser2 = LRParser.deserialize({ + version: 14, + states: "$4|O`QYOOO'QQ$IfO'#ChO'XOSO'#DVO)dQYO'#D]O)tQYO'#DhO){QYO'#DrO-xQYO'#DxOOQO'#E]'#E]O.]QWO'#E[O.bQWO'#E[OOQ$IU'#Ef'#EfO0aQ$IfO'#ItO2wQ$IfO'#IuO3eQWO'#EzO3jQpO'#FaOOQ$IU'#FS'#FSO3rO!bO'#FSO4QQWO'#FhO5_QWO'#FgOOQ$IU'#Iu'#IuOOQ$IS'#It'#ItOOQQ'#J^'#J^O5dQWO'#HpO5iQ$I[O'#HqOOQQ'#Ih'#IhOOQQ'#Hr'#HrQ`QYOOO){QYO'#DjO5qQWO'#G[O5vQ#tO'#CmO6UQWO'#EZO6aQWO'#EgO6fQ#tO'#FRO7QQWO'#G[O7VQWO'#G`O7bQWO'#G`O7pQWO'#GcO7pQWO'#GdO7pQWO'#GfO5qQWO'#GiO8aQWO'#GlO9oQWO'#CdO:PQWO'#GyO:XQWO'#HPO:XQWO'#HRO`QYO'#HTO:XQWO'#HVO:XQWO'#HYO:^QWO'#H`O:cQ$I]O'#HfO){QYO'#HhO:nQ$I]O'#HjO:yQ$I]O'#HlO5iQ$I[O'#HnO){QYO'#DWOOOS'#Ht'#HtO;UOSO,59qOOQ$IU,59q,59qO=gQbO'#ChO=qQYO'#HuO>UQWO'#IvO@TQbO'#IvO'dQYO'#IvO@[QWO,59wO@rQ&jO'#DbOAkQWO'#E]OAxQWO'#JROBTQWO'#JQOBTQWO'#JQOB]QWO,5:yOBbQWO'#JPOBiQWO'#DyO5vQ#tO'#EZOBwQWO'#EZOCSQ`O'#FROOQ$IU,5:S,5:SOC[QYO,5:SOEYQ$IfO,5:^OEvQWO,5:dOFaQ$I[O'#JOO7VQWO'#I}OFhQWO'#I}OFpQWO,5:xOFuQWO'#I}OGTQYO,5:vOITQWO'#EWOJ_QWO,5:vOKnQWO'#DlOKuQYO'#DqOLPQ&jO,5;PO){QYO,5;POOQQ'#Er'#ErOOQQ'#Et'#EtO){QYO,5;RO){QYO,5;RO){QYO,5;RO){QYO,5;RO){QYO,5;RO){QYO,5;RO){QYO,5;RO){QYO,5;RO){QYO,5;RO){QYO,5;RO){QYO,5;ROOQQ'#Ex'#ExOLXQYO,5;cOOQ$IU,5;h,5;hOOQ$IU,5;i,5;iONXQWO,5;iOOQ$IU,5;j,5;jO){QYO'#IPON^Q$I[O,5[OOQQ'#Ik'#IkOOQQ,5>],5>]OOQQ-E;p-E;pO!+VQ$IfO,5:UOOQ$IS'#Cp'#CpO!+vQ#tO,5Q,5>QO){QYO,5>QO5iQ$I[O,5>SOOQQ,5>U,5>UO!8VQWO,5>UOOQQ,5>W,5>WO!8VQWO,5>WOOQQ,5>Y,5>YO!8[Q`O,59rOOOS-E;r-E;rOOQ$IU1G/]1G/]O!8aQbO,5>aO'dQYO,5>aOOQO,5>f,5>fO!8kQYO'#HuOOQO-E;s-E;sO!8xQWO,5?bO!9QQbO,5?bO!9XQWO,5?lOOQ$IU1G/c1G/cO!9aQpO'#DTOOQO'#Ix'#IxO){QYO'#IxO!:OQpO'#IxO!:mQpO'#DcO!;OQ&jO'#DcO!=ZQYO'#DcO!=bQWO'#IwO!=jQWO,59|O!=oQWO'#EaO!=}QWO'#JSO!>VQWO,5:zO!>mQ&jO'#DcO){QYO,5?mO!>wQWO'#HzOOQO-E;x-E;xO!9XQWO,5?lOOQ$IS1G0e1G0eO!@TQ&jO'#D|OOQ$IU,5:e,5:eO){QYO,5:eOITQWO,5:eO!@[QWO,5:eO:^QWO,5:uO!,rQpO,5:uO!,zQ#tO,5:uO5vQ#tO,5:uOOQ$IU1G/n1G/nOOQ$IU1G0O1G0OOOQ$IS'#EV'#EVO){QYO,5?jO!@gQ$I[O,5?jO!@xQ$I[O,5?jO!APQWO,5?iO!AXQWO'#H|O!APQWO,5?iOOQ$IS1G0d1G0dO7VQWO,5?iOOQ$IU1G0b1G0bO!AsQ$IfO1G0bO!BdQ$IdO,5:rOOQ$IU'#Fq'#FqO!CQQ$IfO'#IqOGTQYO1G0bO!EPQ#tO'#IyO!EZQWO,5:WO!E`QbO'#IzO){QYO'#IzO!EjQWO,5:]OOQ$IU'#DT'#DTOOQ$IU1G0k1G0kO!EoQWO1G0kO!HQQ$IfO1G0mO!HXQ$IfO1G0mO!JlQ$IfO1G0mO!JsQ$IfO1G0mO!LzQ$IfO1G0mO!M_Q$IfO1G0mO#!OQ$IfO1G0mO#!VQ$IfO1G0mO#$jQ$IfO1G0mO#$qQ$IfO1G0mO#&fQ$IfO1G0mO#)`Q7^O'#ChO#+ZQ7^O1G0}O#-UQ7^O'#IuOOQ$IU1G1T1G1TO#-iQ$IfO,5>kOOQ$IS-E;}-E;}O#.YQ$IfO1G0mOOQ$IU1G0m1G0mO#0[Q$IfO1G1QO#0{QpO,5;sO#1QQpO,5;tO#1VQpO'#F[O#1kQWO'#FZOOQO'#JW'#JWOOQO'#H}'#H}O#1pQpO1G1]OOQ$IU1G1]1G1]OOOO1G1f1G1fO#2OQ7^O'#ItO#2YQWO,5;}OLXQYO,5;}OOOO-E;|-E;|OOQ$IU1G1Y1G1YOOQ$IU,5WQWO1G2iOOQQ1G2j1G2jOITQWO1G2jO#>]QWO1G2jO#>eQ&jO'#GhOOQQ1G2l1G2lO!&tQ&jO'#IYO!0OQ`O1G2oOOQQ1G2o1G2oOOQQ,5=Y,5=YO#>mQ#tO,5=[O5qQWO,5=[O#5YQWO,5=_O5_QWO,5=_O!,rQpO,5=_O!,zQ#tO,5=_O5vQ#tO,5=_O#?OQWO'#JaO#?ZQWO,5=`OOQQ1G.j1G.jO#?`Q$I[O1G.jO#?kQWO1G.jO#?pQWO1G.jO5iQ$I[O1G.jO#?xQbO,5@OO#@SQWO,5@OO#@_QYO,5=gO#@fQWO,5=gO7VQWO,5@OOOQQ1G3P1G3PO`QYO1G3POOQQ1G3V1G3VOOQQ1G3X1G3XO:XQWO1G3ZO#@kQYO1G3]O#DfQYO'#H[OOQQ1G3`1G3`O#DsQWO'#HbO:^QWO'#HdOOQQ1G3f1G3fO#D{QYO1G3fO5iQ$I[O1G3lOOQQ1G3n1G3nOOQ$IS'#Fx'#FxO5iQ$I[O1G3pO5iQ$I[O1G3rOOOS1G/^1G/^O#HyQ`O,5aO#I]QWO1G4|O#IeQWO1G5WO#ImQWO,5?dOLXQYO,5:{O7VQWO,5:{O:^QWO,59}OLXQYO,59}O!,rQpO,59}O#IrQ7^O,59}OOQO,5:{,5:{O#I|Q&jO'#HvO#JdQWO,5?cOOQ$IU1G/h1G/hO#JlQ&jO'#H{O#KQQWO,5?nOOQ$IS1G0f1G0fO!;OQ&jO,59}O#KYQbO1G5XO7VQWO,5>fOOQ$IS'#ES'#ESO#KdQ$ItO'#ETO!?{Q&jO'#D}OOQO'#Hy'#HyO#LOQ&jO,5:hOOQ$IU,5:h,5:hO#LVQ&jO'#D}O#LhQ&jO'#D}O#LoQ&jO'#EYO#LrQ&jO'#ETO#MPQ&jO'#ETO!?{Q&jO'#ETO#MdQWO1G0PO#MiQ`O1G0POOQ$IU1G0P1G0PO){QYO1G0POITQWO1G0POOQ$IU1G0a1G0aO:^QWO1G0aO!,rQpO1G0aO!,zQ#tO1G0aO#MpQ$IfO1G5UO){QYO1G5UO#NQQ$I[O1G5UO#NcQWO1G5TO7VQWO,5>hOOQO,5>h,5>hO#NkQWO,5>hOOQO-E;z-E;zO#NcQWO1G5TO#NyQ$IfO,59jO$!xQ$IfO,5m,5>mO$,iQWO,5>mOOQ$IU1G2P1G2PP$,nQWO'#IRPOQ$IU-Eo,5>oOOQO-Ep,5>pOOQO-Ex,5>xOOQO-E<[-E<[OOQ$IU7+&q7+&qO$4uQWO7+(iO5iQ$I[O7+(iO5qQWO7+(iO$4zQWO7+(iO$5PQWO7+'|OOQ$IS,5>r,5>rOOQ$IS-Et,5>tOOQO-EO,5>OOOQQ7+)Q7+)QOOQQ7+)W7+)WOOQQ7+)[7+)[OOQQ7+)^7+)^OOQO1G5O1G5OO$9eQ7^O1G0gO$9oQWO1G0gOOQO1G/i1G/iO$9zQ7^O1G/iO:^QWO1G/iOLXQYO'#DcOOQO,5>b,5>bOOQO-E;t-E;tOOQO,5>g,5>gOOQO-E;y-E;yO!,rQpO1G/iO:^QWO,5:iOOQO,5:o,5:oO){QYO,5:oO$:UQ$I[O,5:oO$:aQ$I[O,5:oO!,rQpO,5:iOOQO-E;w-E;wOOQ$IU1G0S1G0SO!?{Q&jO,5:iO$:oQ&jO,5:iO$;QQ$ItO,5:oO$;lQ&jO,5:iO!?{Q&jO,5:oOOQO,5:t,5:tO$;sQ&jO,5:oO$cOOQO-E;u-E;uO$CfQbO,5>dO){QYO,5>dOOQO-E;v-E;vO$CpQWO1G5QO$CxQ7^O1G0bO$FPQ7^O1G0mO$FWQ7^O1G0mO$HXQ7^O1G0mO$H`Q7^O1G0mO$JTQ7^O1G0mO$JhQ7^O1G0mO$LuQ7^O1G0mO$L|Q7^O1G0mO$N}Q7^O1G0mO% UQ7^O1G0mO%!yQ7^O1G0mO%#^Q$IfO<kOOOO7+'T7+'TOOOS1G/R1G/ROOQ$IU1G4X1G4XOJdQWO7+'zO%([QWO,5>lO5qQWO,5>lOOQO-EnO%)XQWO,5>nOITQWO,5>nOOQO-Ew,5>wO%,kQWO,5>wO%,pQWO,5>wOOQO-EvOOQO-EWQ7^O7+'WO%>eQ7^O7+'XO%>rQWO,5;xOOQO7+&{7+&{O%>wQ#tO<qOOQO-EsOOQO-E{AN>{OOQOAN>uAN>uO%1gQ$IfOAN>{O:^QWOAN>uO){QYOAN>{O!,rQpOAN>uO&%SQ$I[OAN>{O&%_Q7^O<^O!O&OO~Ox&RO!W&]O!X&UO!Y&UO'^$bO~O]&SOk&SO!Q&VO'g&PO!S'kP!S'vP~P@aO!O'sX!R'sX!]'sX!c'sX'p'sX~O!{'sX#W#PX!S'sX~PAYO!{&^O!O'uX!R'uX~O!R&_O!O'tX~O!O&bO~O!{#eO~PAYOS&fO!T&cO!o&eO']$`O~Oc&kO!d$XO']$`O~Ou$nO!d$mO~O!S&lO~P`Ou!{Ov!{Ox!|O!b!yO!d!zO'fQOP!faZ!faj!fa!R!fa!a!fa!j!fa#[!fa#]!fa#^!fa#_!fa#`!fa#a!fa#b!fa#c!fa#e!fa#g!fa#i!fa#j!fa'p!fa'w!fa'x!fa~O_!fa'W!fa!O!fa!c!fan!fa!T!fa%Q!fa!]!fa~PCcO!c&mO~O!]!wO!{&oO'p&nO!R'rX_'rX'W'rX~O!c'rX~PE{O!R&sO!c'qX~O!c&uO~Ox$tO!T$uO#V&vO']$`O~OPTOQTO]cOb!kOc!jOhcOjTOkcOlcOqTOsTOxRO{cO|cO}cO!TSO!_kO!dUO!gTO!hTO!iTO!jTO!kTO!n!iO#t!lO#x^O']9WO'fQO'oYO'|aO~O]#qOh$OOj#rOk#qOl#qOq$POs9kOx#xO!T#yO!_;RO!d#vO#V9tO#t$TO$_9nO$a9qO$d$UO']&zO'f#sO~O#W&|O~O]#qOh$OOj#rOk#qOl#qOq$POs$QOx#xO!T#yO!_$VO!d#vO#V$WO#t$TO$_$RO$a$SO$d$UO']&zO'f#sO~O'a'mP~PJdO!Q'QO!c'nP~P){O'g'SO'oYO~OP9TOQ9TO]cOb;POc!jOhcOj9TOkcOlcOq9TOs9TOxRO{cO|cO}cO!T!bO!_9VO!dUO!g9TO!h9TO!i9TO!j9TO!k9TO!n!iO#t!lO#x^O']'bO'fQO'oYO'|:}O~O!d!zO~O!R#bO_$]a'W$]a!c$]a!O$]a!T$]a%Q$]a!]$]a~O#d'iO~PITO!]'kO!T'yX#w'yX#z'yX$R'yX~Ou'lO~P! POu'lO!T'yX#w'yX#z'yX$R'yX~O!T'nO#w'rO#z'mO$R'sO~O!Q'vO~PLXO#z#fO$R'yO~Ou$eXx$eX!b$eX'p$eX'w$eX'x$eX~OSfX!RfX!{fX'afX'a$eX~P!!iOk'{O~OR'|O'U'}O'V(PO~Ou(ROx(SO'p#[O'w(UO'x(WO~O'a(QO~P!#rO'a(ZO~O]#qOh$OOj#rOk#qOl#qOq$POs9kOx#xO!T#yO!_;RO!d#vO#V9tO#t$TO$_9nO$a9qO$d$UO'f#sO~O!Q(_O']([O!c'}P~P!$aO#W(aO~O!Q(eO'](bO!O(OP~P!$aOj(sOx(kO!W(qO!X(jO!Y(jO!d(hO!x(rO$w(mO'^$bO'g(gO~O!S(pO~P!&XO!b!yOu'eXx'eX'p'eX'w'eX'x'eX!R'eX!{'eX~O'a'eX#m'eX~P!'QOS(vO!{(uO!R'dX'a'dX~O!R(wO'a'cX~O'](yO~O!d)OO~O']&zO~O!d(hO~Ox$tO!Q!rO!T$uO#U!uO#V!rO']$`O!c'qP~O!]!wO#W)SO~OP#^OZ#dOj#ROu!{Ov!{Ox!|O!a#TO!b!yO!d!zO!j#^O#[#PO#]#QO#^#QO#_#QO#`#SO#a#TO#b#TO#c#TO#e#UO#g#WO#i#YO#j#ZO'fQO'p#[O'w!}O'x#OO~O_!^a!R!^a'W!^a!O!^a!c!^an!^a!T!^a%Q!^a!]!^a~P!)cOS)[O!T&cO!o)ZO%Q)YO'b$cO~O']$zO'a'cP~O!])_O!T'`X_'`X!R'`X'W'`X~O!d$XO'b$cO~O!d$XO']$`O'b$cO~O!]!wO#W&|O~O])jO%R)kO'])gO!S(VP~O!R)lO^(UX~O'g'SO~OZ)pO~O^)qO~O!T$kO']$`O'^$bO^(UP~Ox$tO!Q)vO!R&_O!T$uO']$`O!O'tP~O]&YOk&YO!Q)wO'g'SO!S'vP~O!R)xO_(RX'W(RX~O!{)|O'b$cO~OS*PO!T#yO'b$cO~O!T*RO~Ou*TO!TSO~O!n*YO~Oc*_O~O'](yO!S(TP~Oc$iO~O%RtO']$zO~P8tOZ*eO^*dO~OPTOQTO]cObnOcmOhcOjTOkcOlcOqTOsTOxRO{cO|cO}cO!_kO!dUO!gTO!hTO!iTO!jTO!kTO!nlO#x^O%PqO'fQO'oYO'|aO~O!T!bO#t!lO']9WO~P!1RO^*dO_$[O'W$[O~O_*iO#d*kO%T*kO%U*kO~P){O!d%_O~O%t*pO~O!T*rO~O&V*tO&X*uOP&SaQ&SaX&Sa]&Sa_&Sab&Sac&Sah&Saj&Sak&Sal&Saq&Sas&Sax&Sa{&Sa|&Sa}&Sa!T&Sa!_&Sa!d&Sa!g&Sa!h&Sa!i&Sa!j&Sa!k&Sa!n&Sa#d&Sa#t&Sa#x&Sa%P&Sa%R&Sa%T&Sa%U&Sa%X&Sa%Z&Sa%^&Sa%_&Sa%a&Sa%n&Sa%t&Sa%v&Sa%x&Sa%z&Sa%}&Sa&T&Sa&Z&Sa&]&Sa&_&Sa&a&Sa&c&Sa'S&Sa']&Sa'f&Sa'o&Sa'|&Sa!S&Sa%{&Sa`&Sa&Q&Sa~O']*zO~On*}O~O!O&ia!R&ia~P!)cO!Q+RO!O&iX!R&iX~P){O!R%yO!O'ja~O!O'ja~P>^O!R&_O!O'ta~O!RwX!R!ZX!SwX!S!ZX!]wX!]!ZX!d!ZX!{wX'b!ZX~O!]+WO!{+VO!R#TX!R'lX!S#TX!S'lX!]'lX!d'lX'b'lX~O!]+YO!d$XO'b$cO!R!VX!S!VX~O]&QOk&QOx&RO'g(gO~OP9TOQ9TO]cOb;POc!jOhcOj9TOkcOlcOq9TOs9TOxRO{cO|cO}cO!T!bO!_9VO!dUO!g9TO!h9TO!i9TO!j9TO!k9TO!n!iO#t!lO#x^O'fQO'oYO'|:}O~O']9yO~P!;^O!R+^O!S'kX~O!S+`O~O!]+WO!{+VO!R#TX!S#TX~O!R+aO!S'vX~O!S+cO~O]&QOk&QOx&RO'^$bO'g(gO~O!X+dO!Y+dO~P!>[Ox$tO!Q+fO!T$uO']$`O!O&nX!R&nX~O_+jO!W+mO!X+iO!Y+iO!r+qO!s+oO!t+pO!u+nO!x+rO'^$bO'g(gO'o+gO~O!S+lO~P!?]OS+wO!T&cO!o+vO~O!{+}O!R'ra!c'ra_'ra'W'ra~O!]!wO~P!@gO!R&sO!c'qa~Ox$tO!Q,QO!T$uO#U,SO#V,QO']$`O!R&pX!c&pX~O_#Oi!R#Oi'W#Oi!O#Oi!c#Oin#Oi!T#Oi%Q#Oi!]#Oi~P!)cO#W!za!R!za!c!za!{!za!T!za_!za'W!za!O!za~P!#rO#W'eXP'eXZ'eX_'eXj'eXv'eX!a'eX!d'eX!j'eX#['eX#]'eX#^'eX#_'eX#`'eX#a'eX#b'eX#c'eX#e'eX#g'eX#i'eX#j'eX'W'eX'f'eX!c'eX!O'eX!T'eXn'eX%Q'eX!]'eX~P!'QO!R,]O'a'mX~P!#rO'a,_O~O!R,`O!c'nX~P!)cO!c,cO~O!O,dO~OP#^Ou!{Ov!{Ox!|O!b!yO!d!zO!j#^O'fQOZ#Zi_#Zij#Zi!R#Zi!a#Zi#]#Zi#^#Zi#_#Zi#`#Zi#a#Zi#b#Zi#c#Zi#e#Zi#g#Zi#i#Zi#j#Zi'W#Zi'p#Zi'w#Zi'x#Zi!O#Zi!c#Zin#Zi!T#Zi%Q#Zi!]#Zi~O#[#Zi~P!EtO#[#PO~P!EtOP#^Ou!{Ov!{Ox!|O!b!yO!d!zO!j#^O#[#PO#]#QO#^#QO#_#QO'fQOZ#Zi_#Zi!R#Zi!a#Zi#`#Zi#a#Zi#b#Zi#c#Zi#e#Zi#g#Zi#i#Zi#j#Zi'W#Zi'p#Zi'w#Zi'x#Zi!O#Zi!c#Zin#Zi!T#Zi%Q#Zi!]#Zi~Oj#Zi~P!H`Oj#RO~P!H`OP#^Oj#ROu!{Ov!{Ox!|O!b!yO!d!zO!j#^O#[#PO#]#QO#^#QO#_#QO#`#SO'fQO_#Zi!R#Zi#e#Zi#g#Zi#i#Zi#j#Zi'W#Zi'p#Zi'w#Zi'x#Zi!O#Zi!c#Zin#Zi!T#Zi%Q#Zi!]#Zi~OZ#Zi!a#Zi#a#Zi#b#Zi#c#Zi~P!JzOZ#dO!a#TO#a#TO#b#TO#c#TO~P!JzOP#^OZ#dOj#ROu!{Ov!{Ox!|O!a#TO!b!yO!d!zO!j#^O#[#PO#]#QO#^#QO#_#QO#`#SO#a#TO#b#TO#c#TO#e#UO'fQO_#Zi!R#Zi#g#Zi#i#Zi#j#Zi'W#Zi'p#Zi'x#Zi!O#Zi!c#Zin#Zi!T#Zi%Q#Zi!]#Zi~O'w#Zi~P!MrO'w!}O~P!MrOP#^OZ#dOj#ROu!{Ov!{Ox!|O!a#TO!b!yO!d!zO!j#^O#[#PO#]#QO#^#QO#_#QO#`#SO#a#TO#b#TO#c#TO#e#UO#g#WO'fQO'w!}O_#Zi!R#Zi#i#Zi#j#Zi'W#Zi'p#Zi!O#Zi!c#Zin#Zi!T#Zi%Q#Zi!]#Zi~O'x#Zi~P#!^O'x#OO~P#!^OP#^OZ#dOj#ROu!{Ov!{Ox!|O!a#TO!b!yO!d!zO!j#^O#[#PO#]#QO#^#QO#_#QO#`#SO#a#TO#b#TO#c#TO#e#UO#g#WO#i#YO'fQO'w!}O'x#OO~O_#Zi!R#Zi#j#Zi'W#Zi'p#Zi!O#Zi!c#Zin#Zi!T#Zi%Q#Zi!]#Zi~P#$xOP[XZ[Xj[Xu[Xv[Xx[X!a[X!b[X!d[X!j[X!{[X#WdX#[[X#][X#^[X#_[X#`[X#a[X#b[X#c[X#e[X#g[X#i[X#j[X#o[X'f[X'p[X'w[X'x[X!R[X!S[X~O#m[X~P#']OP#^OZ9iOj9^Ou!{Ov!{Ox!|O!a9`O!b!yO!d!zO!j#^O#[9[O#]9]O#^9]O#_9]O#`9_O#a9`O#b9`O#c9`O#e9aO#g9cO#i9eO#j9fO'fQO'p#[O'w!}O'x#OO~O#m,fO~P#)gOP'iXZ'iXj'iXu'iXv'iXx'iX!a'iX!b'iX!d'iX!j'iX#['iX#]'iX#^'iX#_'iX#`'iX#a'iX#b'iX#e'iX#g'iX#i'iX#j'iX'f'iX'p'iX'w'iX'x'iX!R'iX~O!{9jO#o9jO#c'iX#m'iX!S'iX~P#+bO_&sa!R&sa'W&sa!c&san&sa!O&sa!T&sa%Q&sa!]&sa~P!)cOP#ZiZ#Zi_#Zij#Ziv#Zi!R#Zi!a#Zi!b#Zi!d#Zi!j#Zi#[#Zi#]#Zi#^#Zi#_#Zi#`#Zi#a#Zi#b#Zi#c#Zi#e#Zi#g#Zi#i#Zi#j#Zi'W#Zi'f#Zi!O#Zi!c#Zin#Zi!T#Zi%Q#Zi!]#Zi~P!#rO_#ni!R#ni'W#ni!O#ni!c#nin#ni!T#ni%Q#ni!]#ni~P!)cO#z,hO~O#z,iO~O!]'kO!{,jO!T$OX#w$OX#z$OX$R$OX~O!Q,kO~O!T'nO#w,mO#z'mO$R,nO~O!R9gO!S'hX~P#)gO!S,oO~O$R,qO~OR'|O'U'}O'V,tO~O],wOk,wO!O,xO~O!RdX!]dX!cdX!c$eX'pdX~P!!iO!c-OO~P!#rO!R-PO!]!wO'p&nO!c'}X~O!c-UO~O!O$eX!R$eX!]$lX~P!!iO!R-WO!O(OX~P!#rO!]-YO~O!O-[O~O!Q(_O']$`O!c'}P~Oj-`O!]!wO!d$XO'b$cO'p&nO~O!])_O~O_$[O!R-eO'W$[O~O!S-gO~P!&XO!X-hO!Y-hO'^$bO'g(gO~Ox-jO'g(gO~O!x-kO~O']$zO!R&xX'a&xX~O!R(wO'a'ca~Ou-pOv-pOx-qO'pra'wra'xra!Rra!{ra~O'ara#mra~P#6qOu(ROx(SO'p$^a'w$^a'x$^a!R$^a!{$^a~O'a$^a#m$^a~P#7gOu(ROx(SO'p$`a'w$`a'x$`a!R$`a!{$`a~O'a$`a#m$`a~P#8YO]-rO~O#W-sO~O'a$na!R$na#m$na!{$na~P!#rO#W-vO~OS.PO!T&cO!o.OO%Q-}O~O'a.QO~O]#qOj#rOk#qOl#qOq$POs9kOx#xO!T#yO!_;RO!d#vO#V9tO#t$TO$_9nO$a9qO$d$UO'f#sO~Oh.SO'].RO~P#:PO!])_O!T'`a_'`a!R'`a'W'`a~O#W.YO~OZ[X!RdX!SdX~O!R.ZO!S(VX~O!S.]O~OZ.^O~O].`O'])gO~O!T$kO']$`O^'QX!R'QX~O!R)lO^(Ua~O!c.cO~P!)cO].eO~OZ.fO~O^.gO~OS.PO!T&cO!o.OO%Q-}O'b$cO~O!R)xO_(Ra'W(Ra~O!{.mO~OS.pO!T#yO~O'g'SO!S(SP~OS.zO!T.vO!o.yO%Q.xO'b$cO~OZ/UO!R/SO!S(TX~O!S/VO~O^/XO_$[O'W$[O~O]/YO~O]/ZO'](yO~O#c/[O%r/]O~P0zO!{#eO#c/[O%r/]O~O_/^O~P){O_/`O~O%{/dOP%yiQ%yiX%yi]%yi_%yib%yic%yih%yij%yik%yil%yiq%yis%yix%yi{%yi|%yi}%yi!T%yi!_%yi!d%yi!g%yi!h%yi!i%yi!j%yi!k%yi!n%yi#d%yi#t%yi#x%yi%P%yi%R%yi%T%yi%U%yi%X%yi%Z%yi%^%yi%_%yi%a%yi%n%yi%t%yi%v%yi%x%yi%z%yi%}%yi&T%yi&Z%yi&]%yi&_%yi&a%yi&c%yi'S%yi']%yi'f%yi'o%yi'|%yi!S%yi`%yi&Q%yi~O`/jO!S/hO&Q/iO~P`O!TSO!d/lO~O&X*uOP&SiQ&SiX&Si]&Si_&Sib&Sic&Sih&Sij&Sik&Sil&Siq&Sis&Six&Si{&Si|&Si}&Si!T&Si!_&Si!d&Si!g&Si!h&Si!i&Si!j&Si!k&Si!n&Si#d&Si#t&Si#x&Si%P&Si%R&Si%T&Si%U&Si%X&Si%Z&Si%^&Si%_&Si%a&Si%n&Si%t&Si%v&Si%x&Si%z&Si%}&Si&T&Si&Z&Si&]&Si&_&Si&a&Si&c&Si'S&Si']&Si'f&Si'o&Si'|&Si!S&Si%{&Si`&Si&Q&Si~O!R#bOn$]a~O!O&ii!R&ii~P!)cO!R%yO!O'ji~O!R&_O!O'ti~O!O/rO~O!R!Va!S!Va~P#)gO]&QOk&QO!Q/xO'g(gO!R&jX!S&jX~P@aO!R+^O!S'ka~O]&YOk&YO!Q)wO'g'SO!R&oX!S&oX~O!R+aO!S'va~O!O'ui!R'ui~P!)cO_$[O!]!wO!d$XO!j0SO!{0QO'W$[O'b$cO'p&nO~O!S0VO~P!?]O!X0WO!Y0WO'^$bO'g(gO'o+gO~O!W0XO~P#LVO!TSO!W0XO!u0ZO!x0[O~P#LVO!W0XO!s0^O!t0^O!u0ZO!x0[O~P#LVO!T&cO~O!T&cO~P!#rO!R'ri!c'ri_'ri'W'ri~P!)cO!{0gO!R'ri!c'ri_'ri'W'ri~O!R&sO!c'qi~Ox$tO!T$uO#V0iO']$`O~O#WraPraZra_rajra!ara!bra!dra!jra#[ra#]ra#^ra#_ra#`ra#ara#bra#cra#era#gra#ira#jra'Wra'fra!cra!Ora!Tranra%Qra!]ra~P#6qO#W$^aP$^aZ$^a_$^aj$^av$^a!a$^a!b$^a!d$^a!j$^a#[$^a#]$^a#^$^a#_$^a#`$^a#a$^a#b$^a#c$^a#e$^a#g$^a#i$^a#j$^a'W$^a'f$^a!c$^a!O$^a!T$^an$^a%Q$^a!]$^a~P#7gO#W$`aP$`aZ$`a_$`aj$`av$`a!a$`a!b$`a!d$`a!j$`a#[$`a#]$`a#^$`a#_$`a#`$`a#a$`a#b$`a#c$`a#e$`a#g$`a#i$`a#j$`a'W$`a'f$`a!c$`a!O$`a!T$`an$`a%Q$`a!]$`a~P#8YO#W$naP$naZ$na_$naj$nav$na!R$na!a$na!b$na!d$na!j$na#[$na#]$na#^$na#_$na#`$na#a$na#b$na#c$na#e$na#g$na#i$na#j$na'W$na'f$na!c$na!O$na!T$na!{$nan$na%Q$na!]$na~P!#rO_#Oq!R#Oq'W#Oq!O#Oq!c#Oqn#Oq!T#Oq%Q#Oq!]#Oq~P!)cO!R&kX'a&kX~PJdO!R,]O'a'ma~O!Q0qO!R&lX!c&lX~P){O!R,`O!c'na~O!R,`O!c'na~P!)cO#m!fa!S!fa~PCcO#m!^a!R!^a!S!^a~P#)gO!T1UO#x^O$P1VO~O!S1ZO~On1[O~P!#rO_$Yq!R$Yq'W$Yq!O$Yq!c$Yqn$Yq!T$Yq%Q$Yq!]$Yq~P!)cO!O1]O~O],wOk,wO~Ou(ROx(SO'x(WO'p$xi'w$xi!R$xi!{$xi~O'a$xi#m$xi~P$,vOu(ROx(SO'p$zi'w$zi'x$zi!R$zi!{$zi~O'a$zi#m$zi~P$-iO#m1^O~P!#rO!Q1`O']$`O!R&tX!c&tX~O!R-PO!c'}a~O!R-PO!]!wO!c'}a~O!R-PO!]!wO'p&nO!c'}a~O'a$gi!R$gi#m$gi!{$gi~P!#rO!Q1gO'](bO!O&vX!R&vX~P!$aO!R-WO!O(Oa~O!R-WO!O(Oa~P!#rO!]!wO~O!]!wO#c1oO~Oj1rO!]!wO'p&nO~O!R'di'a'di~P!#rO!{1uO!R'di'a'di~P!#rO!c1xO~O_$Zq!R$Zq'W$Zq!O$Zq!c$Zqn$Zq!T$Zq%Q$Zq!]$Zq~P!)cO!R1|O!T(PX~P!#rO!T&cO%Q2PO~O!T&cO%Q2PO~P!#rO!T$eX$u[X_$eX!R$eX'W$eX~P!!iO$u2TOugXxgX!TgX'pgX'wgX'xgX_gX!RgX'WgX~O$u2TO~O]2ZO%R2[O'])gO!R'PX!S'PX~O!R.ZO!S(Va~OZ2`O~O^2aO~O]2dO~OS2fO!T&cO!o2eO%Q2PO~O_$[O'W$[O~P!#rO!T#yO~P!#rO!R2kO!{2mO!S(SX~O!S2nO~Ox;]O!W2wO!X2pO!Y2pO!r2vO!s2uO!t2uO!x2tO'^$bO'g(gO'o+gO~O!S2sO~P$6QOS3OO!T.vO!o2}O%Q2|O~OS3OO!T.vO!o2}O%Q2|O'b$cO~O'](yO!R'OX!S'OX~O!R/SO!S(Ta~O]3YO'g3XO~O]3ZO~O^3]O~O!c3`O~P){O_3bO~O_3bO~P){O#c3dO%r3eO~PE{O`/jO!S3iO&Q/iO~P`O!]3kO~O!R#Ti!S#Ti~P#)gO!{3mO!R#Ti!S#Ti~O!R!Vi!S!Vi~P#)gO_$[O!{3tO'W$[O~O_$[O!]!wO!{3tO'W$[O~O!X3xO!Y3xO'^$bO'g(gO'o+gO~O_$[O!]!wO!d$XO!j3yO!{3tO'W$[O'b$cO'p&nO~O!W3zO~P$:oO!W3zO!u3}O!x4OO~P$:oO_$[O!]!wO!j3yO!{3tO'W$[O'p&nO~O!R'rq!c'rq_'rq'W'rq~P!)cO!R&sO!c'qq~O#W$xiP$xiZ$xi_$xij$xiv$xi!a$xi!b$xi!d$xi!j$xi#[$xi#]$xi#^$xi#_$xi#`$xi#a$xi#b$xi#c$xi#e$xi#g$xi#i$xi#j$xi'W$xi'f$xi!c$xi!O$xi!T$xin$xi%Q$xi!]$xi~P$,vO#W$ziP$ziZ$zi_$zij$ziv$zi!a$zi!b$zi!d$zi!j$zi#[$zi#]$zi#^$zi#_$zi#`$zi#a$zi#b$zi#c$zi#e$zi#g$zi#i$zi#j$zi'W$zi'f$zi!c$zi!O$zi!T$zin$zi%Q$zi!]$zi~P$-iO#W$giP$giZ$gi_$gij$giv$gi!R$gi!a$gi!b$gi!d$gi!j$gi#[$gi#]$gi#^$gi#_$gi#`$gi#a$gi#b$gi#c$gi#e$gi#g$gi#i$gi#j$gi'W$gi'f$gi!c$gi!O$gi!T$gi!{$gin$gi%Q$gi!]$gi~P!#rO!R&ka'a&ka~P!#rO!R&la!c&la~P!)cO!R,`O!c'ni~O#m#Oi!R#Oi!S#Oi~P#)gOP#^Ou!{Ov!{Ox!|O!b!yO!d!zO!j#^O'fQOZ#Zij#Zi!a#Zi#]#Zi#^#Zi#_#Zi#`#Zi#a#Zi#b#Zi#c#Zi#e#Zi#g#Zi#i#Zi#j#Zi#m#Zi'p#Zi'w#Zi'x#Zi!R#Zi!S#Zi~O#[#Zi~P$DVO#[9[O~P$DVOP#^Ou!{Ov!{Ox!|O!b!yO!d!zO!j#^O#[9[O#]9]O#^9]O#_9]O'fQOZ#Zi!a#Zi#`#Zi#a#Zi#b#Zi#c#Zi#e#Zi#g#Zi#i#Zi#j#Zi#m#Zi'p#Zi'w#Zi'x#Zi!R#Zi!S#Zi~Oj#Zi~P$F_Oj9^O~P$F_OP#^Oj9^Ou!{Ov!{Ox!|O!b!yO!d!zO!j#^O#[9[O#]9]O#^9]O#_9]O#`9_O'fQO#e#Zi#g#Zi#i#Zi#j#Zi#m#Zi'p#Zi'w#Zi'x#Zi!R#Zi!S#Zi~OZ#Zi!a#Zi#a#Zi#b#Zi#c#Zi~P$HgOZ9iO!a9`O#a9`O#b9`O#c9`O~P$HgOP#^OZ9iOj9^Ou!{Ov!{Ox!|O!a9`O!b!yO!d!zO!j#^O#[9[O#]9]O#^9]O#_9]O#`9_O#a9`O#b9`O#c9`O#e9aO'fQO#g#Zi#i#Zi#j#Zi#m#Zi'p#Zi'x#Zi!R#Zi!S#Zi~O'w#Zi~P$J{O'w!}O~P$J{OP#^OZ9iOj9^Ou!{Ov!{Ox!|O!a9`O!b!yO!d!zO!j#^O#[9[O#]9]O#^9]O#_9]O#`9_O#a9`O#b9`O#c9`O#e9aO#g9cO'fQO'w!}O#i#Zi#j#Zi#m#Zi'p#Zi!R#Zi!S#Zi~O'x#Zi~P$MTO'x#OO~P$MTOP#^OZ9iOj9^Ou!{Ov!{Ox!|O!a9`O!b!yO!d!zO!j#^O#[9[O#]9]O#^9]O#_9]O#`9_O#a9`O#b9`O#c9`O#e9aO#g9cO#i9eO'fQO'w!}O'x#OO~O#j#Zi#m#Zi'p#Zi!R#Zi!S#Zi~P% ]O_#ky!R#ky'W#ky!O#ky!c#kyn#ky!T#ky%Q#ky!]#ky~P!)cOP#ZiZ#Zij#Ziv#Zi!a#Zi!b#Zi!d#Zi!j#Zi#[#Zi#]#Zi#^#Zi#_#Zi#`#Zi#a#Zi#b#Zi#c#Zi#e#Zi#g#Zi#i#Zi#j#Zi#m#Zi'f#Zi!R#Zi!S#Zi~P!#rO!b!yOu'eXx'eX'p'eX'w'eX'x'eX!S'eX~OP'eXZ'eXj'eXv'eX!a'eX!d'eX!j'eX#['eX#]'eX#^'eX#_'eX#`'eX#a'eX#b'eX#c'eX#e'eX#g'eX#i'eX#j'eX#m'eX'f'eX!R'eX~P%%mO#m#ni!R#ni!S#ni~P#)gO!S4`O~O!R&sa!S&sa~P#)gO!]!wO'p&nO!R&ta!c&ta~O!R-PO!c'}i~O!R-PO!]!wO!c'}i~O!O&va!R&va~P!#rO!]4gO~O!R-WO!O(Oi~P!#rO!R-WO!O(Oi~O!O4kO~O!]!wO#c4pO~Oj4qO!]!wO'p&nO~O!O4sO~O'a$iq!R$iq#m$iq!{$iq~P!#rO_$Zy!R$Zy'W$Zy!O$Zy!c$Zyn$Zy!T$Zy%Q$Zy!]$Zy~P!)cO!R1|O!T(Pa~O!T&cO%Q4xO~O!T&cO%Q4xO~P!#rO_#Oy!R#Oy'W#Oy!O#Oy!c#Oyn#Oy!T#Oy%Q#Oy!]#Oy~P!)cOZ4{O~O]4}O'])gO~O!R.ZO!S(Vi~O]5QO~O^5RO~O'g'SO!R&{X!S&{X~O!R2kO!S(Sa~O!S5`O~P$6QOx;^O'g(gO'o+gO~O!W5cO!X5bO!Y5bO!x0[O'^$bO'g(gO'o+gO~O!s5dO!t5dO~P%.RO!X5bO!Y5bO'^$bO'g(gO'o+gO~O!T.vO~O!T.vO%Q5fO~O!T.vO%Q5fO~P!#rOS5kO!T.vO!o5jO%Q5fO~OZ5pO!R'Oa!S'Oa~O!R/SO!S(Ti~O]5sO~O!c5tO~O!c5uO~O!c5vO~O!c5vO~P){O_5xO~O!]5{O~O!c5|O~O!R'ui!S'ui~P#)gO_$[O'W$[O~P!)cO_$[O!{6RO'W$[O~O_$[O!]!wO!{6RO'W$[O~O!X6WO!Y6WO'^$bO'g(gO'o+gO~O_$[O!]!wO!j6XO!{6RO'W$[O'p&nO~O!d$XO'b$cO~P%2mO!W6YO~P%2[O!R'ry!c'ry_'ry'W'ry~P!)cO#W$iqP$iqZ$iq_$iqj$iqv$iq!R$iq!a$iq!b$iq!d$iq!j$iq#[$iq#]$iq#^$iq#_$iq#`$iq#a$iq#b$iq#c$iq#e$iq#g$iq#i$iq#j$iq'W$iq'f$iq!c$iq!O$iq!T$iq!{$iqn$iq%Q$iq!]$iq~P!#rO!R&li!c&li~P!)cO#m#Oq!R#Oq!S#Oq~P#)gOu-pOv-pOx-qO'pra'wra'xra!Sra~OPraZrajra!ara!bra!dra!jra#[ra#]ra#^ra#_ra#`ra#ara#bra#cra#era#gra#ira#jra#mra'fra!Rra~P%6eOu(ROx(SO'p$^a'w$^a'x$^a!S$^a~OP$^aZ$^aj$^av$^a!a$^a!b$^a!d$^a!j$^a#[$^a#]$^a#^$^a#_$^a#`$^a#a$^a#b$^a#c$^a#e$^a#g$^a#i$^a#j$^a#m$^a'f$^a!R$^a~P%8fOu(ROx(SO'p$`a'w$`a'x$`a!S$`a~OP$`aZ$`aj$`av$`a!a$`a!b$`a!d$`a!j$`a#[$`a#]$`a#^$`a#_$`a#`$`a#a$`a#b$`a#c$`a#e$`a#g$`a#i$`a#j$`a#m$`a'f$`a!R$`a~P%:gOP$naZ$naj$nav$na!a$na!b$na!d$na!j$na#[$na#]$na#^$na#_$na#`$na#a$na#b$na#c$na#e$na#g$na#i$na#j$na#m$na'f$na!R$na!S$na~P!#rO#m$Yq!R$Yq!S$Yq~P#)gO#m$Zq!R$Zq!S$Zq~P#)gO!S6dO~O'a$|y!R$|y#m$|y!{$|y~P!#rO!]!wO!R&ti!c&ti~O!]!wO'p&nO!R&ti!c&ti~O!R-PO!c'}q~O!O&vi!R&vi~P!#rO!R-WO!O(Oq~O!O6jO~P!#rO!O6jO~O!R'dy'a'dy~P!#rO!R&ya!T&ya~P!#rO!T$tq_$tq!R$tq'W$tq~P!#rOZ6qO~O!R.ZO!S(Vq~O]6tO~O!T&cO%Q6uO~O!T&cO%Q6uO~P!#rO!{6vO!R&{a!S&{a~O!R2kO!S(Si~P#)gO!X6|O!Y6|O'^$bO'g(gO'o+gO~O!W7OO!x4OO~P%BkO!T.vO%Q7RO~O!T.vO%Q7RO~P!#rO]7YO'g7XO~O!R/SO!S(Tq~O!c7[O~O!c7[O~P){O!c7^O~O!c7_O~O!R#Ty!S#Ty~P#)gO_$[O!{7eO'W$[O~O_$[O!]!wO!{7eO'W$[O~O!X7hO!Y7hO'^$bO'g(gO'o+gO~O_$[O!]!wO!j7iO!{7eO'W$[O'p&nO~O#W$|yP$|yZ$|y_$|yj$|yv$|y!R$|y!a$|y!b$|y!d$|y!j$|y#[$|y#]$|y#^$|y#_$|y#`$|y#a$|y#b$|y#c$|y#e$|y#g$|y#i$|y#j$|y'W$|y'f$|y!c$|y!O$|y!T$|y!{$|yn$|y%Q$|y!]$|y~P!#rO#m#ky!R#ky!S#ky~P#)gOP$giZ$gij$giv$gi!a$gi!b$gi!d$gi!j$gi#[$gi#]$gi#^$gi#_$gi#`$gi#a$gi#b$gi#c$gi#e$gi#g$gi#i$gi#j$gi#m$gi'f$gi!R$gi!S$gi~P!#rOu(ROx(SO'x(WO'p$xi'w$xi!S$xi~OP$xiZ$xij$xiv$xi!a$xi!b$xi!d$xi!j$xi#[$xi#]$xi#^$xi#_$xi#`$xi#a$xi#b$xi#c$xi#e$xi#g$xi#i$xi#j$xi#m$xi'f$xi!R$xi~P%JROu(ROx(SO'p$zi'w$zi'x$zi!S$zi~OP$ziZ$zij$ziv$zi!a$zi!b$zi!d$zi!j$zi#[$zi#]$zi#^$zi#_$zi#`$zi#a$zi#b$zi#c$zi#e$zi#g$zi#i$zi#j$zi#m$zi'f$zi!R$zi~P%LSO#m$Zy!R$Zy!S$Zy~P#)gO#m#Oy!R#Oy!S#Oy~P#)gO!]!wO!R&tq!c&tq~O!R-PO!c'}y~O!O&vq!R&vq~P!#rO!O7mO~P!#rO!R.ZO!S(Vy~O!R2kO!S(Sq~O!X7yO!Y7yO'^$bO'g(gO'o+gO~O!T.vO%Q7|O~O!T.vO%Q7|O~P!#rO!c8PO~O_$[O!{8UO'W$[O~O_$[O!]!wO!{8UO'W$[O~OP$iqZ$iqj$iqv$iq!a$iq!b$iq!d$iq!j$iq#[$iq#]$iq#^$iq#_$iq#`$iq#a$iq#b$iq#c$iq#e$iq#g$iq#i$iq#j$iq#m$iq'f$iq!R$iq!S$iq~P!#rO!R&{q!S&{q~P#)gO_$[O!{8hO'W$[O~OP$|yZ$|yj$|yv$|y!a$|y!b$|y!d$|y!j$|y#[$|y#]$|y#^$|y#_$|y#`$|y#a$|y#b$|y#c$|y#e$|y#g$|y#i$|y#j$|y#m$|y'f$|y!R$|y!S$|y~P!#rO!S!za!W!za!X!za!Y!za!r!za!s!za!t!za!x!za'^!za'g!za'o!za~P!#rO!W'eX!X'eX!Y'eX!r'eX!s'eX!t'eX!x'eX'^'eX'g'eX'o'eX~P%%mO!Wra!Xra!Yra!rra!sra!tra!xra'^ra'gra'ora~P%6eO!W$^a!X$^a!Y$^a!r$^a!s$^a!t$^a!x$^a'^$^a'g$^a'o$^a~P%8fO!W$`a!X$`a!Y$`a!r$`a!s$`a!t$`a!x$`a'^$`a'g$`a'o$`a~P%:gO!S$na!W$na!X$na!Y$na!r$na!s$na!t$na!x$na'^$na'g$na'o$na~P!#rO!W$xi!X$xi!Y$xi!r$xi!s$xi!t$xi!x$xi'^$xi'g$xi'o$xi~P%JRO!W$zi!X$zi!Y$zi!r$zi!s$zi!t$zi!x$zi'^$zi'g$zi'o$zi~P%LSO!S$gi!W$gi!X$gi!Y$gi!r$gi!s$gi!t$gi!x$gi'^$gi'g$gi'o$gi~P!#rO!S$iq!W$iq!X$iq!Y$iq!r$iq!s$iq!t$iq!x$iq'^$iq'g$iq'o$iq~P!#rO!S$|y!W$|y!X$|y!Y$|y!r$|y!s$|y!t$|y!x$|y'^$|y'g$|y'o$|y~P!#rOn'hX~P.jOn[X!O[X!c[X%r[X!T[X%Q[X!][X~P$zO!]dX!c[X!cdX'pdX~P;aOP9TOQ9TO]cOb;POc!jOhcOj9TOkcOlcOq9TOs9TOxRO{cO|cO}cO!TSO!_9VO!dUO!g9TO!h9TO!i9TO!j9TO!k9TO!n!iO#t!lO#x^O']'bO'fQO'oYO'|:}O~O]#qOh$OOj#rOk#qOl#qOq$POs9lOx#xO!T#yO!_;SO!d#vO#V9uO#t$TO$_9oO$a9rO$d$UO']&zO'f#sO~O!R9gO!S$]a~O]#qOh$OOj#rOk#qOl#qOq$POs9mOx#xO!T#yO!_;TO!d#vO#V9vO#t$TO$_9pO$a9sO$d$UO']&zO'f#sO~O#d'iO~P&3xO!S[X!SdX~P;aO!]9ZO~O#W9YO~O!]!wO#W9YO~O!{9jO~O#c9`O~O!{9wO!R'uX!S'uX~O!{9jO!R'sX!S'sX~O#W9xO~O'a9zO~P!#rO#W:RO~O#W:SO~O#W:TO~O!]!wO#W:UO~O!]!wO#W9xO~O#m:VO~P#)gO#W:WO~O#W:XO~O#W:YO~O#W:ZO~O#W:[O~O#m:]O~P!#rO#m:^O~P!#rO#m:_O~P!#rO!O:`O~O!O:aO~P!#rO!O:aO~O!O:bO~P!#rO!]!wO#c;YO~O!]!wO#c;[O~O#x~!b!r!t!u#U#V'|$_$a$d$u%P%Q%R%X%Z%^%_%a%c~UT#x'|#]}'Y'Z#z'Y']'g~", + goto: "#Hc(ZPPPPPPPP([P(lP*`PPPP-zPP.a3s5g5zP5zPPP5zP7t5zP5zP7xPP8OP8dk|}?O}!O>k!O!P?`!P!QCl!Q!R!0[!R![!1q![!]!7s!]!^!8V!^!_!8g!_!`!9d!`!a!:[!a!b!U#R#S2`#S#T!>i#T#o2`#o#p!>y#p#q!?O#q#r!?f#r#s!?x#s$f%T$f$g%c$g#BY2`#BY#BZ!@Y#BZ$IS2`$IS$I_!@Y$I_$I|2`$I|$I}!Bq$I}$JO!Bq$JO$JT2`$JT$JU!@Y$JU$KV2`$KV$KW!@Y$KW&FU2`&FU&FV!@Y&FV?HT2`?HT?HU!@Y?HU~2`W%YR$UWO!^%T!_#o%T#p~%T7Z%jg$UW'Y7ROX%TXY%cYZ%TZ[%c[p%Tpq%cq!^%T!_#o%T#p$f%T$f$g%c$g#BY%T#BY#BZ%c#BZ$IS%T$IS$I_%c$I_$JT%T$JT$JU%c$JU$KV%T$KV$KW%c$KW&FU%T&FU&FV%c&FV?HT%T?HT?HU%c?HU~%T7Z'YR$UW'Z7RO!^%T!_#o%T#p~%T$T'jS$UW!j#{O!^%T!_!`'v!`#o%T#p~%T$O'}S#e#v$UWO!^%T!_!`(Z!`#o%T#p~%T$O(bR#e#v$UWO!^%T!_#o%T#p~%T'u(rZ$UW]!ROY(kYZ)eZr(krs*rs!^(k!^!_+U!_#O(k#O#P-b#P#o(k#o#p+U#p~(k&r)jV$UWOr)ers*Ps!^)e!^!_*a!_#o)e#o#p*a#p~)e&r*WR$P&j$UWO!^%T!_#o%T#p~%T&j*dROr*ars*ms~*a&j*rO$P&j'u*{R$P&j$UW]!RO!^%T!_#o%T#p~%T'm+ZV]!ROY+UYZ*aZr+Urs+ps#O+U#O#P+w#P~+U'm+wO$P&j]!R'm+zROr+Urs,Ts~+U'm,[U$P&j]!ROY,nZr,nrs-Vs#O,n#O#P-[#P~,n!R,sU]!ROY,nZr,nrs-Vs#O,n#O#P-[#P~,n!R-[O]!R!R-_PO~,n'u-gV$UWOr(krs-|s!^(k!^!_+U!_#o(k#o#p+U#p~(k'u.VZ$P&j$UW]!ROY.xYZ%TZr.xrs/rs!^.x!^!_,n!_#O.x#O#P0S#P#o.x#o#p,n#p~.x!Z/PZ$UW]!ROY.xYZ%TZr.xrs/rs!^.x!^!_,n!_#O.x#O#P0S#P#o.x#o#p,n#p~.x!Z/yR$UW]!RO!^%T!_#o%T#p~%T!Z0XT$UWO!^.x!^!_,n!_#o.x#o#p,n#p~.x2k0mZ$UWOt%Ttu1`u!^%T!_!c%T!c!}1`!}#R%T#R#S1`#S#T%T#T#o1`#p$g%T$g~1`2k1g]$UW'o2cOt%Ttu1`u!Q%T!Q![1`![!^%T!_!c%T!c!}1`!}#R%T#R#S1`#S#T%T#T#o1`#p$g%T$g~1`7Z2k_$UW#zS']%k'g2bOt%Ttu2`u}%T}!O3j!O!Q%T!Q![2`![!^%T!_!c%T!c!}2`!}#R%T#R#S2`#S#T%T#T#o2`#p$g%T$g~2`[3q_$UW#zSOt%Ttu3ju}%T}!O3j!O!Q%T!Q![3j![!^%T!_!c%T!c!}3j!}#R%T#R#S3j#S#T%T#T#o3j#p$g%T$g~3j$O4wS#^#v$UWO!^%T!_!`5T!`#o%T#p~%T$O5[R$UW#o#vO!^%T!_#o%T#p~%T6d5lU'x6[$UWOv%Tvw6Ow!^%T!_!`5T!`#o%T#p~%T$O6VS$UW#i#vO!^%T!_!`5T!`#o%T#p~%T'u6jZ$UW]!ROY6cYZ7]Zw6cwx*rx!^6c!^!_8T!_#O6c#O#P:T#P#o6c#o#p8T#p~6c&r7bV$UWOw7]wx*Px!^7]!^!_7w!_#o7]#o#p7w#p~7]&j7zROw7wwx*mx~7w'm8YV]!ROY8TYZ7wZw8Twx+px#O8T#O#P8o#P~8T'm8rROw8Twx8{x~8T'm9SU$P&j]!ROY9fZw9fwx-Vx#O9f#O#P9}#P~9f!R9kU]!ROY9fZw9fwx-Vx#O9f#O#P9}#P~9f!R:QPO~9f'u:YV$UWOw6cwx:ox!^6c!^!_8T!_#o6c#o#p8T#p~6c'u:xZ$P&j$UW]!ROY;kYZ%TZw;kwx/rx!^;k!^!_9f!_#O;k#O#PW{!^%T!_!`5T!`#o%T#p~%T$O>_S#[#v$UWO!^%T!_!`5T!`#o%T#p~%T$u>rSj$m$UWO!^%T!_!`5T!`#o%T#p~%T&i?VR!R&a$UWO!^%T!_#o%T#p~%T7Z?gVu6`$UWO!O%T!O!P?|!P!Q%T!Q![@r![!^%T!_#o%T#p~%Ty@RT$UWO!O%T!O!P@b!P!^%T!_#o%T#p~%Ty@iR!Qq$UWO!^%T!_#o%T#p~%Ty@yZ$UWkqO!Q%T!Q![@r![!^%T!_!g%T!g!hAl!h#R%T#R#S@r#S#X%T#X#YAl#Y#o%T#p~%TyAqZ$UWO{%T{|Bd|}%T}!OBd!O!Q%T!Q![CO![!^%T!_#R%T#R#SCO#S#o%T#p~%TyBiV$UWO!Q%T!Q![CO![!^%T!_#R%T#R#SCO#S#o%T#p~%TyCVV$UWkqO!Q%T!Q![CO![!^%T!_#R%T#R#SCO#S#o%T#p~%T7ZCs`$UW#]#vOYDuYZ%TZzDuz{Jl{!PDu!P!Q!-e!Q!^Du!^!_Fx!_!`!.^!`!a!/]!a!}Du!}#OHq#O#PJQ#P#oDu#o#pFx#p~DuXD|[$UW}POYDuYZ%TZ!PDu!P!QEr!Q!^Du!^!_Fx!_!}Du!}#OHq#O#PJQ#P#oDu#o#pFx#p~DuXEy_$UW}PO!^%T!_#Z%T#Z#[Er#[#]%T#]#^Er#^#a%T#a#bEr#b#g%T#g#hEr#h#i%T#i#jEr#j#m%T#m#nEr#n#o%T#p~%TPF}V}POYFxZ!PFx!P!QGd!Q!}Fx!}#OG{#O#PHh#P~FxPGiU}P#Z#[Gd#]#^Gd#a#bGd#g#hGd#i#jGd#m#nGdPHOTOYG{Z#OG{#O#PH_#P#QFx#Q~G{PHbQOYG{Z~G{PHkQOYFxZ~FxXHvY$UWOYHqYZ%TZ!^Hq!^!_G{!_#OHq#O#PIf#P#QDu#Q#oHq#o#pG{#p~HqXIkV$UWOYHqYZ%TZ!^Hq!^!_G{!_#oHq#o#pG{#p~HqXJVV$UWOYDuYZ%TZ!^Du!^!_Fx!_#oDu#o#pFx#p~Du7ZJs^$UW}POYJlYZKoZzJlz{NQ{!PJl!P!Q!,R!Q!^Jl!^!_!!]!_!}Jl!}#O!'|#O#P!+a#P#oJl#o#p!!]#p~Jl7ZKtV$UWOzKoz{LZ{!^Ko!^!_M]!_#oKo#o#pM]#p~Ko7ZL`X$UWOzKoz{LZ{!PKo!P!QL{!Q!^Ko!^!_M]!_#oKo#o#pM]#p~Ko7ZMSR$UWU7RO!^%T!_#o%T#p~%T7RM`ROzM]z{Mi{~M]7RMlTOzM]z{Mi{!PM]!P!QM{!Q~M]7RNQOU7R7ZNX^$UW}POYJlYZKoZzJlz{NQ{!PJl!P!Q! T!Q!^Jl!^!_!!]!_!}Jl!}#O!'|#O#P!+a#P#oJl#o#p!!]#p~Jl7Z! ^_$UWU7R}PO!^%T!_#Z%T#Z#[Er#[#]%T#]#^Er#^#a%T#a#bEr#b#g%T#g#hEr#h#i%T#i#jEr#j#m%T#m#nEr#n#o%T#p~%T7R!!bY}POY!!]YZM]Zz!!]z{!#Q{!P!!]!P!Q!&x!Q!}!!]!}#O!$`#O#P!&f#P~!!]7R!#VY}POY!!]YZM]Zz!!]z{!#Q{!P!!]!P!Q!#u!Q!}!!]!}#O!$`#O#P!&f#P~!!]7R!#|UU7R}P#Z#[Gd#]#^Gd#a#bGd#g#hGd#i#jGd#m#nGd7R!$cWOY!$`YZM]Zz!$`z{!${{#O!$`#O#P!&S#P#Q!!]#Q~!$`7R!%OYOY!$`YZM]Zz!$`z{!${{!P!$`!P!Q!%n!Q#O!$`#O#P!&S#P#Q!!]#Q~!$`7R!%sTU7ROYG{Z#OG{#O#PH_#P#QFx#Q~G{7R!&VTOY!$`YZM]Zz!$`z{!${{~!$`7R!&iTOY!!]YZM]Zz!!]z{!#Q{~!!]7R!&}_}POzM]z{Mi{#ZM]#Z#[!&x#[#]M]#]#^!&x#^#aM]#a#b!&x#b#gM]#g#h!&x#h#iM]#i#j!&x#j#mM]#m#n!&x#n~M]7Z!(R[$UWOY!'|YZKoZz!'|z{!(w{!^!'|!^!_!$`!_#O!'|#O#P!*o#P#QJl#Q#o!'|#o#p!$`#p~!'|7Z!(|^$UWOY!'|YZKoZz!'|z{!(w{!P!'|!P!Q!)x!Q!^!'|!^!_!$`!_#O!'|#O#P!*o#P#QJl#Q#o!'|#o#p!$`#p~!'|7Z!*PY$UWU7ROYHqYZ%TZ!^Hq!^!_G{!_#OHq#O#PIf#P#QDu#Q#oHq#o#pG{#p~Hq7Z!*tX$UWOY!'|YZKoZz!'|z{!(w{!^!'|!^!_!$`!_#o!'|#o#p!$`#p~!'|7Z!+fX$UWOYJlYZKoZzJlz{NQ{!^Jl!^!_!!]!_#oJl#o#p!!]#p~Jl7Z!,Yc$UW}POzKoz{LZ{!^Ko!^!_M]!_#ZKo#Z#[!,R#[#]Ko#]#^!,R#^#aKo#a#b!,R#b#gKo#g#h!,R#h#iKo#i#j!,R#j#mKo#m#n!,R#n#oKo#o#pM]#p~Ko7Z!-lV$UWT7ROY!-eYZ%TZ!^!-e!^!_!.R!_#o!-e#o#p!.R#p~!-e7R!.WQT7ROY!.RZ~!.R$P!.g[$UW#o#v}POYDuYZ%TZ!PDu!P!QEr!Q!^Du!^!_Fx!_!}Du!}#OHq#O#PJQ#P#oDu#o#pFx#p~Du]!/f[#wS$UW}POYDuYZ%TZ!PDu!P!QEr!Q!^Du!^!_Fx!_!}Du!}#OHq#O#PJQ#P#oDu#o#pFx#p~Duy!0cd$UWkqO!O%T!O!P@r!P!Q%T!Q![!1q![!^%T!_!g%T!g!hAl!h#R%T#R#S!1q#S#U%T#U#V!3X#V#X%T#X#YAl#Y#b%T#b#c!2w#c#d!4m#d#l%T#l#m!5{#m#o%T#p~%Ty!1x_$UWkqO!O%T!O!P@r!P!Q%T!Q![!1q![!^%T!_!g%T!g!hAl!h#R%T#R#S!1q#S#X%T#X#YAl#Y#b%T#b#c!2w#c#o%T#p~%Ty!3OR$UWkqO!^%T!_#o%T#p~%Ty!3^W$UWO!Q%T!Q!R!3v!R!S!3v!S!^%T!_#R%T#R#S!3v#S#o%T#p~%Ty!3}Y$UWkqO!Q%T!Q!R!3v!R!S!3v!S!^%T!_#R%T#R#S!3v#S#b%T#b#c!2w#c#o%T#p~%Ty!4rV$UWO!Q%T!Q!Y!5X!Y!^%T!_#R%T#R#S!5X#S#o%T#p~%Ty!5`X$UWkqO!Q%T!Q!Y!5X!Y!^%T!_#R%T#R#S!5X#S#b%T#b#c!2w#c#o%T#p~%Ty!6QZ$UWO!Q%T!Q![!6s![!^%T!_!c%T!c!i!6s!i#R%T#R#S!6s#S#T%T#T#Z!6s#Z#o%T#p~%Ty!6z]$UWkqO!Q%T!Q![!6s![!^%T!_!c%T!c!i!6s!i#R%T#R#S!6s#S#T%T#T#Z!6s#Z#b%T#b#c!2w#c#o%T#p~%T%w!7|R!]V$UW#m%hO!^%T!_#o%T#p~%T!P!8^R_w$UWO!^%T!_#o%T#p~%T6i!8rR'bd!a0`#x&s'|P!P!Q!8{!^!_!9Q!_!`!9_W!9QO$WW#v!9VP#`#v!_!`!9Y#v!9_O#o#v#v!9dO#a#v%w!9kT!{%o$UWO!^%T!_!`'v!`!a!9z!a#o%T#p~%T$P!:RR#W#w$UWO!^%T!_#o%T#p~%T%w!:gT'a!s#a#v$RS$UWO!^%T!_!`!:v!`!a!;W!a#o%T#p~%T$O!:}R#a#v$UWO!^%T!_#o%T#p~%T$O!;_T#`#v$UWO!^%T!_!`5T!`!a!;n!a#o%T#p~%T$O!;uS#`#v$UWO!^%T!_!`5T!`#o%T#p~%T6i!]S#g#v$UWO!^%T!_!`5T!`#o%T#p~%T$P!>pR$UW'f#wO!^%T!_#o%T#p~%T~!?OO!T~6d!?VT'w6[$UWO!^%T!_!`5T!`#o%T#p#q!=P#q~%T5g!?oR!S5]nQ$UWO!^%T!_#o%T#p~%TX!@PR!kP$UWO!^%T!_#o%T#p~%T7Z!@gr$UW'Y7R#zS']%k'g2bOX%TXY%cYZ%TZ[%c[p%Tpq%cqt%Ttu2`u}%T}!O3j!O!Q%T!Q![2`![!^%T!_!c%T!c!}2`!}#R%T#R#S2`#S#T%T#T#o2`#p$f%T$f$g%c$g#BY2`#BY#BZ!@Y#BZ$IS2`$IS$I_!@Y$I_$JT2`$JT$JU!@Y$JU$KV2`$KV$KW!@Y$KW&FU2`&FU&FV!@Y&FV?HT2`?HT?HU!@Y?HU~2`7Z!CO_$UW'Z7R#zS']%k'g2bOt%Ttu2`u}%T}!O3j!O!Q%T!Q![2`![!^%T!_!c%T!c!}2`!}#R%T#R#S2`#S#T%T#T#o2`#p$g%T$g~2`", + tokenizers: [noSemicolon, incdecToken, template, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, insertSemicolon], + topRules: { "Script": [0, 7] }, + dialects: { jsx: 11707, ts: 11709 }, + dynamicPrecedences: { "149": 1, "176": 1 }, + specialized: [{ term: 289, get: (value, stack) => tsExtends(value, stack) << 1 }, { term: 289, get: (value) => spec_identifier[value] || -1 }, { term: 299, get: (value) => spec_word[value] || -1 }, { term: 63, get: (value) => spec_LessThan[value] || -1 }], + tokenPrec: 11730 +}); + +// node_modules/@codemirror/lang-javascript/dist/index.js +var import_language2 = require("@codemirror/language"); +var import_state3 = require("@codemirror/state"); +var import_view2 = require("@codemirror/view"); +var import_autocomplete = require("@codemirror/autocomplete"); + +// node_modules/@codemirror/lang-javascript/node_modules/@lezer/common/dist/index.js +var DefaultBufferLength2 = 1024; +var nextPropID2 = 0; +var NodeProp2 = class { + constructor(config4 = {}) { + this.id = nextPropID2++; + this.perNode = !!config4.perNode; + this.deserialize = config4.deserialize || (() => { + throw new Error("This node type doesn't define a deserialize function"); }); } - async initialize() { - if (!this.persister) { - console.log("Cache Persister Not Found"); - return; - } - const start = Date.now(); - this.initializeActions(); - this.initializeWaypoints(); - this.initializeKits(); - this.initializeTemplates(); - if (this.settings.spacesEnabled) - await this.initializeSpaces(); - await this.initializeTags(); - await this.initializePaths(); - await this.initializeContexts(); - await this.initializeFrames(); - this.cleanContexts(); - this.refreshMetadata(); - this.dispatchEvent("superstateUpdated", null); - this.ui.notify(`Make.md - Superstate Loaded in ${(Date.now() - start) / 1e3} seconds`, "console"); - this.persister.cleanType("space"); - this.persister.cleanType("path"); - this.persister.cleanType("context"); - this.persister.cleanType("frame"); + add(match2) { + if (this.perNode) + throw new RangeError("Can't add per-node props to node types"); + if (typeof match2 != "function") + match2 = NodeType2.match(match2); + return (type) => { + let result = match2(type); + return result === void 0 ? null : [this, result]; + }; } - async reloadSystemActions() { - const libraries = await this.spaceManager.readSystemCommands(); - libraries.forEach((f2) => this.actions.set(f2.name, f2.commands)); - this.dispatchEvent("actionStateUpdated", { path: "spaces://$actions" }); +}; +NodeProp2.closedBy = new NodeProp2({ deserialize: (str) => str.split(" ") }); +NodeProp2.openedBy = new NodeProp2({ deserialize: (str) => str.split(" ") }); +NodeProp2.group = new NodeProp2({ deserialize: (str) => str.split(" ") }); +NodeProp2.contextHash = new NodeProp2({ perNode: true }); +NodeProp2.lookAhead = new NodeProp2({ perNode: true }); +NodeProp2.mounted = new NodeProp2({ perNode: true }); +var noProps2 = /* @__PURE__ */ Object.create(null); +var NodeType2 = class { + constructor(name317, props, id3, flags = 0) { + this.name = name317; + this.props = props; + this.id = id3; + this.flags = flags; } - async initializeActions() { - await this.reloadSystemActions(); - const promises = this.allSpaces().filter((f2) => f2.type != "default").map((f2) => f2.space).map( - (l2) => this.reloadActions(l2) - ); - await Promise.all(promises); + static define(spec) { + let props = spec.props && spec.props.length ? /* @__PURE__ */ Object.create(null) : noProps2; + let flags = (spec.top ? 1 : 0) | (spec.skipped ? 2 : 0) | (spec.error ? 4 : 0) | (spec.name == null ? 8 : 0); + let type = new NodeType2(spec.name || "", props, spec.id, flags); + if (spec.props) + for (let src of spec.props) { + if (!Array.isArray(src)) + src = src(type); + if (src) { + if (src[0].perNode) + throw new RangeError("Can't store a per-node prop on a node type"); + props[src[0].id] = src[1]; + } + } + return type; } - async initializeKits() { - const kits = await this.spaceManager.readAllKits(); - kits.forEach((f2) => this.kits.set(f2.id, f2)); - if (kits.length == 0) { - this.kits.set("default", { - id: "default", - name: "Default", - colors: {}, - frames: [] - }); - } - this.selectedKit = this.kits.get(this.settings.selectedKit) ?? this.kits.get("default"); - this.selectedKit.frames = [...this.selectedKit.frames, ...this.kit.map((f2) => rootToFrame(f2)).filter((f2) => !this.selectedKit.frames.some((g) => g.schema.id == f2.schema.id))]; - this.selectedKit.frames.forEach((v2) => { - const kitID = mdbSchemaToFrameSchema(v2.schema).def.id; - this.kitFrames.set(kitID, buildRootFromMDBFrame(this, v2, { ...defaultFrameEditorProps, screenType: this.ui.getScreenType() })); - }); - this.dispatchEvent("frameStateUpdated", { path: `spaces://$kit` }); + prop(prop2) { + return this.props[prop2.id]; } - async initializeTemplates() { - const allTemplates = await this.spaceManager.readAllTemplates(); - Object.keys(allTemplates).forEach((f2) => { - this.templateCache.set(f2, allTemplates[f2]); - }); + get isTop() { + return (this.flags & 1) > 0; } - async initializeSpaces() { - const allSpaces = [...this.spaceManager.allSpaces().values()]; - const promises = allSpaces.map((f2) => this.reloadSpace(f2, null, true)); - [...this.spacesIndex.keys()].filter((f2) => !allSpaces.some((g) => g.path == f2)).forEach((f2) => this.onSpaceDeleted(f2)); - await Promise.all(promises); + get isSkipped() { + return (this.flags & 2) > 0; } - getSpaceItems(spacePath, filesOnly) { - const items = [...this.spacesMap.getInverse(spacePath)]; - const ranks = this.contextsIndex.get(spacePath)?.paths ?? []; - return items.map((f2, i4) => { - const pathCache = this.pathsIndex.get(f2); - return { - ...pathCache, - rank: ranks.indexOf(f2) - }; - }).filter((f2) => f2?.hidden != true && f2.path != spacePath); + get isError() { + return (this.flags & 4) > 0; } - async initializeFrames() { - await this.initializeTemplates(); - const promises = this.allSpaces().filter((f2) => f2.type != "default").map((f2) => f2.space).map( - (l2) => this.reloadFrames(l2).then((f2) => this.dispatchEvent("frameStateUpdated", { path: l2.path })) - ); - await Promise.all(promises); + get isAnonymous() { + return (this.flags & 8) > 0; } - async initializeContexts() { - await this.indexer.reload({ type: "contexts", path: "" }).then(async (r2) => { - const promises = [...r2.entries()].map(([path2, { cache: cache2, changed }]) => this.contextReloaded(path2, cache2, changed)); - await Promise.all(promises); - }); + is(name317) { + if (typeof name317 == "string") { + if (this.name == name317) + return true; + let group = this.prop(NodeProp2.group); + return group ? group.indexOf(name317) > -1 : false; + } + return this.id == name317; } - async cleanContexts() { - this.contextsIndex.forEach((context) => { - const contextFiles = [...this.spacesMap.getInverse(context.path)]; - const removeFiles = context.tables?.[defaultContextSchemaID]?.rows.filter((f2) => !contextFiles.includes(f2[PathPropertyName])) ?? []; - if (removeFiles.length > 0) { - this.addToContextStateQueue(() => removePathsInContext(this.spaceManager, removeFiles.map((f2) => f2[PathPropertyName]), this.spacesIndex.get(context.path).space).then((f2) => this.reloadSpaceByPath(context.path))); + static match(map4) { + let direct = /* @__PURE__ */ Object.create(null); + for (let prop2 in map4) + for (let name317 of prop2.split(" ")) + direct[name317] = map4[prop2]; + return (node) => { + for (let groups = node.prop(NodeProp2.group), i4 = -1; i4 < (groups ? groups.length : 0); i4++) { + let found = direct[i4 < 0 ? node.name : groups[i4]]; + if (found) + return found; } - }); - this.spacesIndex.forEach((space2) => { - const removeFiles = [...this.spacesMap.getInverse(space2.path)]; - }); + }; } - async loadFromCache() { - this.dispatchEvent("superstateReindex", null); - if (this.settings.indexSVG) { - const allIcons = await this.persister.loadAll("icon"); - this.spaceManager.allPaths(["svg"]).forEach((s4) => { - const row2 = allIcons.find((f2) => f2.path == s4); - if (row2?.cache.length > 0) - this.iconsCache.set(s4, row2.cache); - }); +}; +NodeType2.none = new NodeType2("", /* @__PURE__ */ Object.create(null), 0, 8); +var CachedNode2 = /* @__PURE__ */ new WeakMap(); +var CachedInnerNode2 = /* @__PURE__ */ new WeakMap(); +var IterMode2; +(function(IterMode4) { + IterMode4[IterMode4["ExcludeBuffers"] = 1] = "ExcludeBuffers"; + IterMode4[IterMode4["IncludeAnonymous"] = 2] = "IncludeAnonymous"; + IterMode4[IterMode4["IgnoreMounts"] = 4] = "IgnoreMounts"; + IterMode4[IterMode4["IgnoreOverlays"] = 8] = "IgnoreOverlays"; +})(IterMode2 || (IterMode2 = {})); +var Tree2 = class { + constructor(type, children, positions, length, props) { + this.type = type; + this.children = children; + this.positions = positions; + this.length = length; + this.props = null; + if (props && props.length) { + this.props = /* @__PURE__ */ Object.create(null); + for (let [prop2, value] of props) + this.props[typeof prop2 == "number" ? prop2 : prop2.id] = value; } - const allPaths = await this.persister.loadAll("path"); - const allSpaces = await this.persister.loadAll("space"); - const allContexts = await this.persister.loadAll("context"); - const allFrames = await this.persister.loadAll("frame"); - allSpaces.forEach((s4) => { - const space2 = safelyParseJSON(s4.cache); - if (space2 && space2.type) { - this.spacesIndex.set(s4.path, space2); - } - }); - allContexts.forEach((s4) => { - const space2 = safelyParseJSON(s4.cache); - if (space2) { - this.contextsIndex.set(s4.path, space2); - } - }); - allFrames.forEach((s4) => { - const space2 = safelyParseJSON(s4.cache); - if (space2) { - this.framesIndex.set(s4.path, space2); + } + toString() { + let mounted = this.prop(NodeProp2.mounted); + if (mounted && !mounted.overlay) + return mounted.tree.toString(); + let children = ""; + for (let ch of this.children) { + let str = ch.toString(); + if (str) { + if (children) + children += ","; + children += str; } - }); - allPaths.forEach((f2) => { - const cache2 = parsePathState(f2.cache); - this.pathsIndex.set(f2.path, cache2); - this.tagsMap.set(f2.path, new Set(cache2.tags)); - this.spacesMap.set(f2.path, new Set(cache2.spaces)); - this.linksMap.set(f2.path, new Set(cache2.outlinks)); - }); - this.dispatchEvent("superstateUpdated", null); + } + return !this.type.name ? children : (/\W/.test(this.type.name) && !this.type.isError ? JSON.stringify(this.type.name) : this.type.name) + (children.length ? "(" + children + ")" : ""); } - dispatchEvent(event, payload) { - this.eventsDispatcher.dispatchEvent(event, payload); + cursor(mode2 = 0) { + return new TreeCursor2(this.topNode, mode2); } - async initializeTags() { - const allTags = this.spaceManager.readTags().map((f2) => tagSpacePathFromTag(f2)); - const promises = [tagsSpacePath, ...allTags].map((l2) => this.reloadPath(l2, true)); - await Promise.all(promises); + cursorAt(pos, side = 0, mode2 = 0) { + let scope = CachedNode2.get(this) || this.topNode; + let cursor2 = new TreeCursor2(scope); + cursor2.moveTo(pos, side); + CachedNode2.set(this, cursor2._tree); + return cursor2; } - async onSpaceDefinitionChanged(space2, oldDef) { - const currentPaths = this.spacesMap.getInverse(space2.path); - const newPaths = []; - if (space2.metadata?.links && !import_lodash9.default.isEqual(space2.metadata.links, oldDef?.links)) { - newPaths.push(...space2.metadata.links); - } - if (space2.metadata?.filters) { - const hasProps = space2.metadata.filters.some((f2) => f2.filters.some((g) => g.fType == "property")); - if (!import_lodash9.default.isEqual(space2.metadata?.filters, oldDef?.filters) || hasProps) { - for (const [k2, f2] of this.pathsIndex) { - if (!f2.hidden && pathByDef(space2.metadata?.filters, f2, space2.properties)) { - newPaths.push(k2); - } - } - } - } - const diff2 = [...import_lodash9.default.difference(newPaths, [...currentPaths]), ...import_lodash9.default.difference([...currentPaths], newPaths)]; - const cachedPromises = diff2.map((f2) => this.reloadPath(f2, true).then((g) => this.dispatchEvent("pathStateUpdated", { path: f2 }))); - await Promise.all(cachedPromises); + get topNode() { + return new TreeNode3(this, 0, 0, null); } - async initializeWaypoints() { - const allWaypoints = await this.spaceManager.readWaypoints(); - if (allWaypoints.length == 0 && this.settings.waypoints.length > 0) { - let newWaypoints = this.settings.waypoints.map((f2) => { - return { name: this.pathsIndex.get(f2)?.displayName, paths: [f2], sticker: f2 == "spaces://$tags" ? "ui//tags" : this.pathsIndex.get(f2)?.label?.sticker }; - }); - if (newWaypoints.length == 0) { - newWaypoints = [{ name: "Home", sticker: "ui//home", paths: ["/"] }]; - } - this.spaceManager.saveWaypoints(newWaypoints); - return; - } - this.waypoints = allWaypoints; + resolve(pos, side = 0) { + let node = resolveNode2(CachedNode2.get(this) || this.topNode, pos, side, false); + CachedNode2.set(this, node); + return node; } - async initializePaths() { - this.dispatchEvent("superstateReindex", null); - const allFiles = this.spaceManager.allPaths(); - const start = Date.now(); - await this.indexer.reload({ type: "paths", path: "" }).then(async (r2) => { - for await (const [path2, { cache: cache2, changed }] of Object.entries(r2)) { - await this.pathReloaded(path2, cache2, changed, false); - } - }); - this.ui.notify(`Make.md - ${allFiles.length} Paths Cached in ${(Date.now() - start) / 1e3} seconds`, "console"); - const allPaths = uniq([...this.spaceManager.allSpaces().map((f2) => f2.path), ...allFiles]); - [...this.pathsIndex.keys()].filter((f2) => !allPaths.some((g) => g == f2)).forEach((f2) => this.onPathDeleted(f2)); - this.dispatchEvent("superstateUpdated", null); + resolveInner(pos, side = 0) { + let node = resolveNode2(CachedInnerNode2.get(this) || this.topNode, pos, side, true); + CachedInnerNode2.set(this, node); + return node; } - async onTagRenamed(tag2, newTag) { - const oldPath = spacePathFromName(tag2); - const newSpaceInfo = fileSystemSpaceInfoFromTag(this.spaceManager, newTag); - await this.onSpaceRenamed(oldPath, newSpaceInfo); - await this.onPathRename(oldPath, newSpaceInfo.path); - this.dispatchEvent("spaceChanged", { path: oldPath, newPath: newSpaceInfo.path }); - const allContextsWithTag = []; - for (const [contextPath, spaceCache] of this.spacesIndex) { - const contextCache = this.contextsIndex.get(contextPath); - if (contextCache?.contexts.includes(tag2)) { - this.addToContextStateQueue(() => renameTagInContexts(this.spaceManager, tag2, newTag, allContextsWithTag)); + iterate(spec) { + let { enter, leave, from = 0, to: to2 = this.length } = spec; + for (let c3 = this.cursor((spec.mode || 0) | IterMode2.IncludeAnonymous); ; ) { + let entered = false; + if (c3.from <= to2 && c3.to >= from && (c3.type.isAnonymous || enter(c3) !== false)) { + if (c3.firstChild()) + continue; + entered = true; } - if (spaceCache.metadata?.contexts.includes(tag2)) { - saveSpaceCache(this, spaceCache.space, { ...spaceCache.metadata, contexts: spaceCache.metadata.contexts.map((f2) => f2 == tag2 ? newTag : f2) }); + for (; ; ) { + if (entered && leave && !c3.type.isAnonymous) + leave(c3); + if (c3.nextSibling()) + break; + if (!c3.parent()) + return; + entered = true; } } - this.dispatchEvent("spaceStateUpdated", { path: "spaces://$tags" }); } - async onTagDeleted(tag2) { - this.tagsMap.getInverse(tag2).forEach((path2) => { - this.deleteTagInPath(tag2, path2); - }); - const spacePath = folderForTagSpace(tag2, this.settings); - await this.spaceManager.deletePath(spacePath); - this.onSpaceDeleted(tagSpacePathFromTag(tag2)); - for (const [contextPath, spaceCache] of this.spacesIndex) { - if (spaceCache.metadata?.contexts.includes(tag2)) { - saveSpaceCache(this, spaceCache.space, { ...spaceCache.metadata, contexts: spaceCache.metadata.contexts.filter((f2) => f2 != tag2) }); - } - } - const allContextsWithTag = []; - for (const [contextPath, contextCache] of this.contextsIndex) { - if (contextCache.contexts.includes(tag2)) { - allContextsWithTag.push(this.spaceManager.spaceInfoForPath(contextCache.path)); - } - } - this.addToContextStateQueue(() => removeTagInContexts(this.spaceManager, tag2, allContextsWithTag)); - this.dispatchEvent("spaceStateUpdated", { path: "spaces://$tags" }); + prop(prop2) { + return !prop2.perNode ? this.type.prop(prop2) : this.props ? this.props[prop2.id] : void 0; } - async deleteTagInPath(tag2, path2) { - let oldMetadata; - if (this.pathsIndex.has(path2)) { - oldMetadata = this.pathsIndex.get(path2); - } - if (oldMetadata) { - const newMetadata = { - ...oldMetadata, - tags: oldMetadata.tags.filter((f2) => f2 != tag2), - spaces: oldMetadata.spaces.filter((f2) => f2 != tagSpacePathFromTag(tag2)) - }; - this.pathsIndex.set(path2, newMetadata); - this.tagsMap.set(path2, new Set(newMetadata.tags)); - this.spacesMap.set(path2, new Set(newMetadata.spaces)); - } else { - await this.reloadPath(path2); - } - this.onPathReloaded(path2); - this.dispatchEvent("pathStateUpdated", { path: path2 }); + get propValues() { + let result = []; + if (this.props) + for (let id3 in this.props) + result.push([+id3, this.props[id3]]); + return result; } - onMetadataChange(path2) { - if (!this.pathsIndex.has(path2)) { - return; - } - this.reloadPath(path2).then( - (f2) => { - const pathState = this.pathsIndex.get(path2); - const spaceState = this.spacesIndex.get(path2); - if (spaceState) { - this.reloadSpace(spaceState.space).then((f3) => this.onSpaceDefinitionChanged(f3, spaceState.metadata)); - } - const allContextsWithFile = pathState.spaces.map((f3) => this.spacesIndex.get(f3)?.space).filter((f3) => f3); - this.addToContextStateQueue(() => updateContextWithProperties(this, path2, allContextsWithFile).then(() => { - allContextsWithFile.forEach((f3) => { - this.dispatchEvent("contextStateUpdated", { path: f3.path }); - }); - })); - this.dispatchEvent("pathStateUpdated", { path: path2 }); - } - ); + balance(config4 = {}) { + return this.children.length <= 8 ? this : balanceRange2(NodeType2.none, this.children, this.positions, 0, this.children.length, 0, this.length, (children, positions, length) => new Tree2(this.type, children, positions, length, this.propValues), config4.makeTree || ((children, positions, length) => new Tree2(NodeType2.none, children, positions, length))); } - reloadSpaceByPath(path2, metadata) { - return this.reloadSpace(this.spaceManager.spaceInfoForPath(path2), metadata); + static build(data2) { + return buildTree2(data2); } - async onPathRename(oldPath, newPath) { - const newFilePath = newPath; - const oldFileCache = this.pathsIndex.get(oldPath); - const oldSpaces = oldFileCache?.spaces ?? []; - if (oldFileCache) { - this.spacesMap.delete(oldPath); - this.spacesMap.deleteInverse(oldPath); - this.linksMap.delete(oldPath); - this.linksMap.deleteInverse(oldPath); - this.pathsIndex.delete(oldPath); - const allContextsWithPath = oldSpaces.map((f2) => this.spacesIndex.get(f2)).filter((f2) => f2); - await renamePathInContexts(this.spaceManager, oldPath, newFilePath, allContextsWithPath.map((f2) => f2.space)); - for (const space2 of allContextsWithPath) { - if (space2.metadata?.links?.includes(oldPath)) { - this.addToContextStateQueue(() => saveSpaceMetadataValue(this, space2.path, "links", space2.metadata.links.map((f2) => f2 == oldPath ? newPath : f2))); - } - await this.reloadContext(space2.space); - } - const allContextsWithLink = []; - for (const [contextPath, contextCache] of this.contextsIndex) { - if (contextCache.outlinks.includes(oldPath)) { - allContextsWithLink.push(this.spacesIndex.get(contextCache.path).space); - } - } - this.addToContextStateQueue(() => renameLinkInContexts(this.spaceManager, oldPath, newFilePath, allContextsWithLink).then((f2) => Promise.all(allContextsWithLink.map((c3) => this.reloadContext(c3))))); - } - if (this.settings.waypoints.includes(oldPath)) { - this.settings.waypoints = this.settings.waypoints.map((f2) => f2 == oldPath ? newPath : f2); - this.saveSettings(); - this.dispatchEvent("settingsChanged", null); - } - await this.reloadPath(newPath, true); - const changedSpaces = uniq([...this.spacesMap.get(newPath) ?? [], ...oldSpaces]); - const cachedPromises = changedSpaces.map((f2) => this.reloadContext(this.spacesIndex.get(f2)?.space)); - await Promise.all(cachedPromises); - changedSpaces.forEach((f2) => this.dispatchEvent("spaceStateUpdated", { path: f2 })); - this.dispatchEvent("pathChanged", { path: oldPath, newPath }); - this.ui.viewsByPath(oldPath).forEach((view) => { - view.openPath(newPath); - }); +}; +Tree2.empty = new Tree2(NodeType2.none, [], [], 0); +var FlatBufferCursor2 = class { + constructor(buffer, index2) { + this.buffer = buffer; + this.index = index2; } - async onPathCreated(path2) { - await this.reloadPath(path2, true); - const parent = getParentPathFromString(path2); - if (this.spacesIndex.has(parent) && this.spacesIndex.get(parent).defPath == path2) { - await this.reloadSpace(this.spacesIndex.get(parent).space); - } - this.dispatchEvent("pathCreated", { path: path2 }); + get id() { + return this.buffer[this.index - 4]; } - onPathDeleted(path2) { - this.spacesMap.delete(path2); - this.linksMap.delete(path2); - this.linksMap.deleteInverse(path2); - this.persister.remove(path2, "path"); - const fileCache = this.pathsIndex.get(path2); - if (!fileCache) { - return; - } - const allContextsWithFile = (fileCache.spaces ?? []).map((f2) => this.spacesIndex.get(f2)?.space).filter((f2) => f2); - this.addToContextStateQueue(() => removePathInContexts(this.spaceManager, path2, allContextsWithFile).then((f2) => allContextsWithFile.forEach((c3) => this.reloadContext(c3)))); - const allContextsWithLink = []; - for (const [contextPath, contextCache] of this.contextsIndex) { - if (contextCache.outlinks.includes(path2) && this.spacesIndex.has(contextCache.path)) { - allContextsWithLink.push(this.spacesIndex.get(contextCache.path).space); - } - } - this.addToContextStateQueue(() => removeLinkInContexts(this.spaceManager, path2, allContextsWithLink).then((f2) => allContextsWithFile.forEach((c3) => this.reloadContext(c3)))); - (fileCache.spaces ?? []).forEach((f2) => { - this.dispatchEvent("spaceStateUpdated", { path: f2 }); - }); - this.pathsIndex.delete(path2); - this.dispatchEvent("pathDeleted", { path: path2 }); + get start() { + return this.buffer[this.index - 3]; } - async onSpaceRenamed(oldPath, newSpaceInfo) { - if (this.spacesIndex.has(oldPath)) { - const oldmetadata = this.spacesIndex.get(oldPath).metadata; - this.spacesIndex.set(newSpaceInfo.path, { - ...this.spacesIndex.get(oldPath), - path: newSpaceInfo.path, - defPath: newSpaceInfo.defPath, - name: newSpaceInfo.name, - space: newSpaceInfo - }); - this.spacesMap.rename(oldPath, newSpaceInfo.path); - this.spacesMap.renameInverse(oldPath, newSpaceInfo.path); - this.spacesIndex.delete(oldPath); - this.contextsIndex.delete(oldPath); - this.framesIndex.delete(oldPath); - this.actionsIndex.delete(oldPath); - await this.reloadSpace(newSpaceInfo, oldmetadata).then((f2) => this.onSpaceDefinitionChanged(f2, oldmetadata)); - await this.reloadContext(newSpaceInfo); - await this.reloadActions(newSpaceInfo); - await this.reloadFrames(newSpaceInfo).then((f2) => this.dispatchEvent("frameStateUpdated", { path: newSpaceInfo.path })); - } + get end() { + return this.buffer[this.index - 2]; } - onSpaceDeleted(space2) { - if (this.spacesIndex.has(space2)) { - this.spacesIndex.delete(space2); - this.contextsIndex.delete(space2); - this.framesIndex.delete(space2); - } - this.spacesMap.delete(space2); - this.spacesMap.deleteInverse(space2); - this.persister.remove(space2, "space"); - this.dispatchEvent("spaceDeleted", { path: space2 }); + get size() { + return this.buffer[this.index - 1]; } - async reloadActions(space2) { - if (!space2) - return false; - this.spaceManager.commandsForSpace(space2.path).then((r2) => { - this.actionsIndex.set(space2.path, r2); - this.dispatchEvent("actionStateUpdated", { path: space2.path }); - }); + get pos() { + return this.index; } - async reloadFrames(space2) { - if (!space2) - return false; - return this.indexer.reload({ type: "frames", path: space2.path }).then((r2) => { - const { changed, cache: cache2 } = r2; - if (!changed) { - return false; - } - this.framesIndex.set(space2.path, cache2); - this.persister.store(space2.path, JSON.stringify(cache2), "frame"); - return true; - }); + next() { + this.index -= 4; } - async reloadContextByPath(path2) { - return this.reloadContext(this.spaceManager.spaceInfoForPath(path2)); + fork() { + return new FlatBufferCursor2(this.buffer, this.index); } - async reloadContext(space2) { - if (!space2) - return false; - return this.indexer.reload({ type: "context", path: space2.path }).then((r2) => { - return this.contextReloaded(space2.path, r2.cache, r2.changed); - }); +}; +var TreeBuffer2 = class { + constructor(buffer, length, set) { + this.buffer = buffer; + this.length = length; + this.set = set; } - async contextReloaded(path2, cache2, changed) { - if (!changed) { - return false; - } - this.contextsIndex.set(path2, cache2); - if (cache2.dbExists) { - if (this.settings.syncFormulaToFrontmatter) { - const allRows = cache2.tables?.[defaultContextSchemaID]?.rows ?? []; - const allColumns = cache2.tables?.[defaultContextSchemaID]?.cols ?? []; - const updatedValues = allRows.filter((f2) => { - const path3 = f2[PathPropertyName]; - const pathCache = this.pathsIndex.get(path3); - if (!pathCache) { - return false; - } - if (pathCache.type == "file" && pathCache.subtype != "md") - return false; - return allColumns.reduce((acc, col, i4) => { - if (acc) - return acc; - if (col.type != "fileprop" || col.primary == "true") - return acc; - if (f2[col.name]?.length > 0 && pathCache.metadata?.property?.[col.name] != f2[col.name]) - return true; - return acc; - }, false); - }); - if (updatedValues.length > 0) { - updatedValues.forEach((f2) => saveProperties(this, f2[PathPropertyName], allColumns.reduce((acc, col, i4) => { - if (col.type == "fileprop" && col.primary != "true") { - return { ...acc, [col.name]: f2[col.name] }; - } - return acc; - }, {}))); - } - } - const contextPaths = cache2.tables?.[defaultContextSchemaID]?.rows.map((f2) => f2[PathPropertyName]) ?? []; - const missingPaths = cache2.paths.filter((f2) => !contextPaths.includes(f2)); - const removedPaths = contextPaths.filter((f2) => !cache2.paths.includes(f2)); - if (missingPaths.length > 0) { - this.addToContextStateQueue(() => insertContextItems(this.spaceManager, missingPaths, path2)); - } - if (removedPaths.length > 0) { - this.addToContextStateQueue(() => removePathsInContext(this.spaceManager, removedPaths, cache2.space)); - } - } - this.persister.store(path2, JSON.stringify(cache2), "context"); - this.dispatchEvent("contextStateUpdated", { path: path2 }); - return true; + get type() { + return NodeType2.none; } - allSpaces(ordered) { - if (ordered) { - return orderArrayByArrayWithKey([...this.spacesIndex.values()], this.spaceOrder(), "path"); + toString() { + let result = []; + for (let index2 = 0; index2 < this.buffer.length; ) { + result.push(this.childString(index2)); + index2 = this.buffer[index2 + 3]; } - return [...this.spacesIndex.values()]; - } - spaceOrder() { - return [...this.settings.waypoints]; + return result.join(","); } - allFrames() { - return [...this.framesIndex.values()].filter((f2) => f2).flatMap((f2) => f2.schemas.filter((f3) => f3.type == "frame").map((s4) => ({ schema: s4, path: f2.path }))); - } - async updateSpaceMetadata(spacePath, metadata) { - const space2 = this.spacesIndex.get(spacePath); - const oldDef = space2?.metadata; - if (!space2) { - return this.reloadSpaceByPath(spacePath); - } - let spaceDefChanged = false; - const spaceSort = metadata?.sort ?? { field: "rank", asc: true, group: true }; - const sortable = spaceSort.field == "rank"; - if (!import_lodash9.default.isEqual(space2.metadata.links, metadata.links) || !import_lodash9.default.isEqual(space2.metadata.filters, metadata.filters)) { - spaceDefChanged = true; - } - const newSpaceCache = { - ...space2, - metadata, - contexts: metadata?.contexts ?? [], - sortable - }; - this.spacesIndex.set(spacePath, newSpaceCache); - if (spaceDefChanged) { - await this.onSpaceDefinitionChanged(newSpaceCache, oldDef); + childString(index2) { + let id3 = this.buffer[index2], endIndex = this.buffer[index2 + 3]; + let type = this.set.types[id3], result = type.name; + if (/\W/.test(result) && !type.isError) + result = JSON.stringify(result); + index2 += 4; + if (endIndex == index2) + return result; + let children = []; + while (index2 < endIndex) { + children.push(this.childString(index2)); + index2 = this.buffer[index2 + 3]; } - this.dispatchEvent("spaceStateUpdated", { path: space2.path }); - return newSpaceCache; + return result + "(" + children.join(",") + ")"; } - async reloadSpace(space2, spaceMetadata, initialized = true) { - if (!space2) - return; - const metadata = spaceMetadata ?? await this.spaceManager.spaceDefForSpace(space2.path); - let pathState = this.pathsIndex.get(space2.path); - const type = this.spaceManager.spaceTypeByString(this.spaceManager.uriByString(space2.path)); - if (type == "default" || type == "tag") { - metadata.filters = []; - metadata.links = []; - } - const propertyTypes = []; - let properties3 = {}; - const frame = this.framesIndex.get(space2.path); - if (frame) { - const frameProps = frame.frames[mainFrameID]?.cols ?? []; - propertyTypes.push(...frameProps); - } else { - const frameProps = await this.spaceManager.readFrame(space2.path, mainFrameID).then((f2) => f2?.cols ?? []); - propertyTypes.push(...frameProps); - } - if (propertyTypes.length > 0) { - if (!pathState) { - const pathCache = this.spaceManager.readPathCache(space2.defPath); - pathState = { - path: space2.path, - name: space2.name, - tags: [], - spaces: [], - outlinks: [], - hidden: false, - metadata: pathCache?.metadata, - type: "space", - subtype: type, - displayName: space2.name, - label: pathCache?.label - }; - } - properties3 = await this.spaceManager.readProperties(space2.defPath).then((f2) => linkContextRow(this.formulaContext, this.pathsIndex, f2, propertyTypes, pathState)); - } - [...this.spacesMap.get(space2.path)].map((f2) => this.contextsIndex.get(f2)).forEach((f2) => { - if (f2) { - const contextProps = f2.tables?.[defaultContextSchemaID]?.cols ?? []; - propertyTypes.push(...contextProps); - properties3 = { ...properties3, ...f2.tables?.[defaultContextSchemaID]?.rows.find((g) => g[PathPropertyName] == space2.path) ?? {} }; - } - }); - const spaceSort = metadata?.sort ?? { field: "rank", asc: true, group: true }; - const sortable = spaceSort.field == "rank" || !spaceSort; - const contexts = metadata?.contexts ?? []; - const dependencies314 = uniq((metadata.filters ?? []).flatMap((f2) => f2.filters).flatMap((f2) => f2.type == "context" ? [f2.field.split(".")[0]] : f2.type == "path" && f2.field == "space" ? parseMultiString(f2.value) : [])); - if (type == "tag" && this.settings.autoAddContextsToSubtags) { - const parentTags = getAllParentTags(space2.name); - contexts.push(...parentTags); - } - const templates = await this.spaceManager.readTemplates(space2.path); - const cache2 = { - name: space2.name, - space: space2, - path: space2.path, - defPath: space2.defPath, - type, - templates, - contexts: contexts.map((f2) => ensureTag(f2)), - metadata, - dependencies: dependencies314, - sortable, - properties: properties3, - propertyTypes - }; - this.spacesIndex.set(space2.path, cache2); - this.persister.store(space2.path, JSON.stringify(cache2), "space"); - cache2.metadata?.links?.forEach((f2) => { - if (pathIsSpace(this, f2)) { - this.spacesMap.set(f2, /* @__PURE__ */ new Set([...this.spacesMap.get(f2), space2.path])); + findChild(startIndex, endIndex, dir, pos, side) { + let { buffer } = this, pick = -1; + for (let i4 = startIndex; i4 != endIndex; i4 = buffer[i4 + 3]) { + if (checkSide2(side, pos, buffer[i4 + 1], buffer[i4 + 2])) { + pick = i4; + if (dir > 0) + break; } - }); - if (initialized) { - this.dispatchEvent("spaceStateUpdated", { path: space2.path }); - return cache2; } + return pick; } - async pathReloaded(path2, cache2, changed, force) { - this.pathsIndex.set(path2, cache2); - await this.onPathReloaded(path2); - if (cache2.subtype == "image" || cache2.metadata?.file?.extension == "svg") { - this.imagesCache.set(cache2.metadata.file.filename, path2); - } - if (!changed && !force) { - return false; - } - this.tagsMap.set(path2, new Set(cache2.tags)); - this.linksMap.set(path2, new Set(cache2.outlinks)); - if (!import_lodash9.default.isEqual(cache2.spaces, Array.from(this.spacesMap.get(path2)))) { - this.spacesMap.set(path2, new Set(cache2.spaces)); - const promises = cache2.tags.map((f2) => this.spacesIndex.has(tagSpacePathFromTag(f2)) ? null : fileSystemSpaceInfoFromTag(this.spaceManager, f2)).filter((f2) => f2).map( - async (f2) => { - await this.reloadSpace(f2); - this.reloadContext(f2); - await this.reloadPath(f2.path); - return; - } - ); - const allPromises = Promise.all(promises); - allPromises.then((f2) => { - this.dispatchEvent("spaceStateUpdated", { path: "spaces://$tags" }); - }); - } - if (force) { - const allContextsWithFile = cache2.spaces.map((f2) => this.spacesIndex.get(f2)?.space).filter((f2) => f2); - this.addToContextStateQueue(() => updateContextWithProperties(this, path2, allContextsWithFile).then((g) => { - allContextsWithFile.forEach((f2) => { - this.reloadContext(f2); - this.dispatchEvent("spaceStateUpdated", { path: f2.path }); - }); - })); - } - if (cache2.metadata?.file?.extension == "svg" && this.settings.indexSVG) { - this.spaceManager.readPath(path2).then((f2) => { - this.iconsCache.set(path2, f2); - this.persister.store(path2, f2, "icon"); - }); + slice(startI, endI, from, to2) { + let b2 = this.buffer; + let copy = new Uint16Array(endI - startI); + for (let i4 = startI, j = 0; i4 < endI; ) { + copy[j++] = b2[i4++]; + copy[j++] = b2[i4++] - from; + copy[j++] = b2[i4++] - from; + copy[j++] = b2[i4++] - startI; } + return new TreeBuffer2(copy, to2 - from, this.set); } - async reloadPath(path2, force) { - if (!path2) - return false; - return this.indexer.reload({ type: "path", path: path2 }).then(async (r2) => { - await this.pathReloaded(path2, r2.cache, r2.changed, force); +}; +function checkSide2(side, pos, from, to2) { + switch (side) { + case -2: + return from < pos; + case -1: + return to2 >= pos && from < pos; + case 0: + return from < pos && to2 > pos; + case 1: + return from <= pos && to2 > pos; + case 2: + return to2 > pos; + case 4: return true; - }); } - async onPathReloaded(path2) { - let pathState; - if (this.pathsIndex.has(path2)) { - pathState = this.pathsIndex.get(path2); +} +function enterUnfinishedNodesBefore2(node, pos) { + let scan = node.childBefore(pos); + while (scan) { + let last = scan.lastChild; + if (!last || last.to != scan.to) + break; + if (last.type.isError && last.from == last.to) { + node = scan; + scan = last.prevSibling; + } else { + scan = last; } - if (!pathState) { - return false; + } + return node; +} +function resolveNode2(node, pos, side, overlays) { + var _a; + while (node.from == node.to || (side < 1 ? node.from >= pos : node.from > pos) || (side > -1 ? node.to <= pos : node.to < pos)) { + let parent = !overlays && node instanceof TreeNode3 && node.index < 0 ? null : node.parent; + if (!parent) + return node; + node = parent; + } + let mode2 = overlays ? 0 : IterMode2.IgnoreOverlays; + if (overlays) + for (let scan = node, parent = scan.parent; parent; scan = parent, parent = scan.parent) { + if (scan instanceof TreeNode3 && scan.index < 0 && ((_a = parent.enter(pos, side, mode2)) === null || _a === void 0 ? void 0 : _a.from) != scan.from) + node = parent; } - await this.persister.store(path2, serializePathState(pathState), "path"); + for (; ; ) { + let inner = node.enter(pos, side, mode2); + if (!inner) + return node; + node = inner; } -}; - -// src/core/middleware/filesystem.ts -var FilesystemMiddleware = class { - constructor() { - this.filesystems = []; - this.filetypes = []; - this.eventDispatch = new EventDispatcher(); +} +var TreeNode3 = class { + constructor(_tree, from, index2, _parent) { + this._tree = _tree; + this.from = from; + this.index = index2; + this._parent = _parent; } - static create() { - return new FilesystemMiddleware(); + get type() { + return this._tree.type; } - resolvePath(path2, source) { - return this.primary.resolvePath(path2, source); + get name() { + return this._tree.type.name; } - keysForCacheType(cacheType) { - return this.primary.keysForCacheType(cacheType); + get to() { + return this.from + this._tree.length; } - allTags() { - return this.primary.readAllTags(); + nextChild(i4, dir, pos, side, mode2 = 0) { + for (let parent = this; ; ) { + for (let { children, positions } = parent._tree, e5 = dir > 0 ? children.length : -1; i4 != e5; i4 += dir) { + let next = children[i4], start = positions[i4] + parent.from; + if (!checkSide2(side, pos, start, start + next.length)) + continue; + if (next instanceof TreeBuffer2) { + if (mode2 & IterMode2.ExcludeBuffers) + continue; + let index2 = next.findChild(0, next.buffer.length, dir, pos - start, side); + if (index2 > -1) + return new BufferNode2(new BufferContext2(parent, next, i4, start), null, index2); + } else if (mode2 & IterMode2.IncludeAnonymous || (!next.type.isAnonymous || hasChild2(next))) { + let mounted; + if (!(mode2 & IterMode2.IgnoreMounts) && next.props && (mounted = next.prop(NodeProp2.mounted)) && !mounted.overlay) + return new TreeNode3(mounted.tree, start, i4, parent); + let inner = new TreeNode3(next, start, i4, parent); + return mode2 & IterMode2.IncludeAnonymous || !inner.type.isAnonymous ? inner : inner.nextChild(dir < 0 ? next.children.length - 1 : 0, dir, pos, side); + } + } + if (mode2 & IterMode2.IncludeAnonymous || !parent.type.isAnonymous) + return null; + if (parent.index >= 0) + i4 = parent.index + dir; + else + i4 = dir < 0 ? -1 : parent._parent._tree.children.length; + parent = parent._parent; + if (!parent) + return null; + } } - fileFragmentChanged(file) { - this.eventDispatch.dispatchEvent("onFileFragmentChanged", { file }); + get firstChild() { + return this.nextChild(0, 1, 0, 4); } - initiateFileSystemAdapter(adapter, primary) { - adapter.initiate(this); - if (primary) { - this.primary = adapter; + get lastChild() { + return this.nextChild(this._tree.children.length - 1, -1, 0, 4); + } + childAfter(pos) { + return this.nextChild(0, 1, pos, 2); + } + childBefore(pos) { + return this.nextChild(this._tree.children.length - 1, -1, pos, -2); + } + enter(pos, side, mode2 = 0) { + let mounted; + if (!(mode2 & IterMode2.IgnoreOverlays) && (mounted = this._tree.prop(NodeProp2.mounted)) && mounted.overlay) { + let rPos = pos - this.from; + for (let { from, to: to2 } of mounted.overlay) { + if ((side > 0 ? from <= rPos : from < rPos) && (side < 0 ? to2 >= rPos : to2 > rPos)) + return new TreeNode3(mounted.tree, mounted.overlay[0].from + this.from, -1, this); + } } - this.filesystems.push(adapter); + return this.nextChild(0, 1, pos, side, mode2); } - initiateFiletypeAdapter(adapter) { - adapter.initiate(this); - this.filetypes.push(adapter); + nextSignificantParent() { + let val = this; + while (val.type.isAnonymous && val._parent) + val = val._parent; + return val; } - filetypeAdaptersForFile(file) { - if (!file) - return []; - return this.filetypes.filter((f2) => f2.supportedFileTypes.includes(file.extension)); + get parent() { + return this._parent ? this._parent.nextSignificantParent() : null; } - filetypeAdaptersForFileFragments(file, fragmentType) { - return this.filetypeAdaptersForFile(file).filter((f2) => f2.contentTypes ? f2.contentTypes(file).includes(fragmentType) : false); + get nextSibling() { + return this._parent && this.index >= 0 ? this._parent.nextChild(this.index + 1, 1, 0, 4) : null; } - getFileCacheTypeByRefString(file, refString) { - const adapters = this.filetypeAdaptersForFile(file); - return adapters.reduce((p, c3) => { - if (p) - return p; - return c3.getCacheTypeByRefString(file, refString); - }, null); + get prevSibling() { + return this._parent && this.index >= 0 ? this._parent.nextChild(this.index - 1, -1, 0, 4) : null; } - allCaches() { - return this.primary.cache; + cursor(mode2 = 0) { + return new TreeCursor2(this, mode2); } - allFiles() { - return this.primary.allFiles(); + get tree() { + return this._tree; } - resourcePathForPath(path2) { - return this.adapterForPath(path2).resourcePathForPath(path2); + toTree() { + return this._tree; } - parentPathForPath(path2) { - return this.adapterForPath(path2).parentPathForPath(path2); + resolve(pos, side = 0) { + return resolveNode2(this, pos, side, false); } - async createFileCache(path2) { - const file = await this.getFile(path2); - for (const adapter of this.filetypeAdaptersForFile(file)) { - if (adapter.parseCache) - await adapter.parseCache(file, false); - } + resolveInner(pos, side = 0) { + return resolveNode2(this, pos, side, true); } - getFileCache(path2) { - return this.adapterForPath(path2).getFileCache(path2); + enterUnfinishedNodesBefore(pos) { + return enterUnfinishedNodesBefore2(this, pos); } - getFileContent(file, contentType, contentId) { - const adapters = this.filetypeAdaptersForFile(file).filter((f2) => f2.contentTypes(file).includes(contentType)); - if (adapters.length >= 1) { - return adapters[0].readContent(file, contentType, contentId); - } + getChild(type, before = null, after = null) { + let r2 = getChildren2(this, type, before, after); + return r2.length ? r2[0] : null; } - updateFileCache(path2, cache2, refresh) { - this.adapterForPath(path2).updateFileCache(path2, cache2, refresh); + getChildren(type, before = null, after = null) { + return getChildren2(this, type, before, after); } - readFileFragments(file, fragmentType, query) { - const adapters = this.filetypeAdaptersForFileFragments(file, fragmentType); - if (adapters.length >= 1) { - return adapters[0].readContent(file, fragmentType, query); - } + toString() { + return this._tree.toString(); } - async newFile(parent, name317, type, content3) { - const adapter = this.filetypes.find((f2) => f2.supportedFileTypes.includes(type)); - if (adapter) - return adapter.newFile(parent, name317, type, content3); + get node() { + return this; } - newFileFragment(file, fragmentType, name317, content3, options) { - const adapters = this.filetypeAdaptersForFileFragments(file, fragmentType); - if (adapters.length >= 1) { - return adapters[0].newContent(file, fragmentType, name317, content3, options); - } + matchContext(context) { + return matchNodeContext2(this, context); } - saveFileLabel(file, key2, value) { - const adapters = this.filetypeAdaptersForFileFragments(file, "label"); - if (adapters.length >= 1) { - return adapters[0].saveContent(file, "label", key2, () => value); - } else { - return this.primary.updateFileLabel(file.path, key2, value); - } +}; +function getChildren2(node, type, before, after) { + let cur = node.cursor(), result = []; + if (!cur.firstChild()) + return result; + if (before != null) { + while (!cur.type.is(before)) + if (!cur.nextSibling()) + return result; } - saveFileFragment(file, fragmentType, fragmentId, saveContent) { - const adapters = this.filetypeAdaptersForFileFragments(file, fragmentType); - if (adapters.length >= 1) { - return adapters[0].saveContent(file, fragmentType, fragmentId, saveContent); - } + for (; ; ) { + if (after != null && cur.type.is(after)) + return result; + if (cur.type.is(type)) + result.push(cur.node); + if (!cur.nextSibling()) + return after == null ? result : []; } - deleteFileFragment(file, fragmentType, fragmentId) { - const adapters = this.filetypeAdaptersForFileFragments(file, fragmentType); - if (adapters.length >= 1) { - return adapters[0].deleteContent(file, fragmentType, fragmentId); +} +function matchNodeContext2(node, context, i4 = context.length - 1) { + for (let p = node.parent; i4 >= 0; p = p.parent) { + if (!p) + return false; + if (!p.type.isAnonymous) { + if (context[i4] && context[i4] != p.name) + return false; + i4--; } } - onCreate(file) { - this.eventDispatch.dispatchEvent("onCreate", { file }); + return true; +} +var BufferContext2 = class { + constructor(parent, buffer, index2, start) { + this.parent = parent; + this.buffer = buffer; + this.index = index2; + this.start = start; } - onModify(file) { - this.eventDispatch.dispatchEvent("onModify", { file }); +}; +var BufferNode2 = class { + constructor(context, _parent, index2) { + this.context = context; + this._parent = _parent; + this.index = index2; + this.type = context.buffer.set.types[context.buffer.buffer[index2]]; } - onRename(file, oldPath) { - this.eventDispatch.dispatchEvent("onRename", { file, oldPath }); + get name() { + return this.type.name; } - onDelete(file) { - this.eventDispatch.dispatchEvent("onDelete", { file }); + get from() { + return this.context.start + this.context.buffer.buffer[this.index + 1]; } - adapterForPath(path2) { - return this.primary; + get to() { + return this.context.start + this.context.buffer.buffer[this.index + 2]; } - async getRoot() { - return this.adapterForPath().getRoot(); + child(dir, pos, side) { + let { buffer } = this.context; + let index2 = buffer.findChild(this.index + 4, buffer.buffer[this.index + 3], dir, pos - this.context.start, side); + return index2 < 0 ? null : new BufferNode2(this.context, this, index2); } - async copyFile(path2, folder, newName) { - return this.adapterForPath(path2).copyFile(path2, folder, newName); + get firstChild() { + return this.child(1, 0, 4); } - async writeTextToFile(path2, content3) { - return this.adapterForPath(path2).writeTextToFile(path2, content3); + get lastChild() { + return this.child(-1, 0, 4); } - async readTextFromFile(path2) { - return this.adapterForPath(path2).readTextFromFile(path2); + childAfter(pos) { + return this.child(1, pos, 2); } - async writeBinaryToFile(path2, buffer) { - return this.adapterForPath(path2).writeBinaryToFile(path2, buffer); + childBefore(pos) { + return this.child(-1, pos, -2); } - async readBinaryToFile(path2) { - return this.adapterForPath(path2).readBinaryToFile(path2); + enter(pos, side, mode2 = 0) { + if (mode2 & IterMode2.ExcludeBuffers) + return null; + let { buffer } = this.context; + let index2 = buffer.findChild(this.index + 4, buffer.buffer[this.index + 3], side > 0 ? 1 : -1, pos - this.context.start, side); + return index2 < 0 ? null : new BufferNode2(this.context, this, index2); } - async renameFile(path2, newPath) { - return this.adapterForPath(path2).renameFile(path2, newPath); + get parent() { + return this._parent || this.context.parent.nextSignificantParent(); } - async createFolder(path2) { - return this.adapterForPath(path2).createFolder(path2); + externalSibling(dir) { + return this._parent ? null : this.context.parent.nextChild(this.context.index + dir, dir, 0, 4); } - async childrenForFolder(path2, type) { - return this.adapterForPath(path2).childrenForFolder(path2, type); + get nextSibling() { + let { buffer } = this.context; + let after = buffer.buffer[this.index + 3]; + if (after < (this._parent ? buffer.buffer[this._parent.index + 3] : buffer.buffer.length)) + return new BufferNode2(this.context, this._parent, after); + return this.externalSibling(1); } - async fileExists(path2) { - return this.adapterForPath(path2).fileExists(path2); + get prevSibling() { + let { buffer } = this.context; + let parentStart = this._parent ? this._parent.index + 4 : 0; + if (this.index == parentStart) + return this.externalSibling(-1); + return new BufferNode2(this.context, this._parent, buffer.findChild(parentStart, this.index, -1, 0, 4)); } - async getFile(path2, source) { - return this.adapterForPath(path2).getFile(path2, source); + cursor(mode2 = 0) { + return new TreeCursor2(this, mode2); } - async deleteFile(path2) { - return this.adapterForPath(path2).deleteFile(path2); + get tree() { + return null; } - async addTagToFile(path2, tag2) { - return this.adapterForPath(path2).addTagToFile(path2, tag2); + toTree() { + let children = [], positions = []; + let { buffer } = this.context; + let startI = this.index + 4, endI = buffer.buffer[this.index + 3]; + if (endI > startI) { + let from = buffer.buffer[this.index + 1], to2 = buffer.buffer[this.index + 2]; + children.push(buffer.slice(startI, endI, from, to2)); + positions.push(0); + } + return new Tree2(this.type, children, positions, this.to - this.from); } - async renameTagForFile(path2, oldTag, newTag) { - return this.adapterForPath(path2).renameTagForFile(path2, oldTag, newTag); + resolve(pos, side = 0) { + return resolveNode2(this, pos, side, false); } - async removeTagFromFile(path2, tag2) { - return this.adapterForPath(path2).removeTagFromFile(path2, tag2); + resolveInner(pos, side = 0) { + return resolveNode2(this, pos, side, true); } - filesForTag(tag2) { - return this.primary.filesForTag(tag2); + enterUnfinishedNodesBefore(pos) { + return enterUnfinishedNodesBefore2(this, pos); } -}; - -// src/core/spaceManager/filesystemAdapter/filesystemAdapter.ts -var defaultTemplatesFolder = ".space/templates"; -var defaultKitsFolder = ".space/kits"; -var defaultActionsFolder = ".space/actions"; -var defaultWaypointsFile = ".space/waypoints.json"; -var defaultSpaceFolder = ".space"; -var FilesystemSpaceAdapter = class { - constructor(fileSystem) { - this.fileSystem = fileSystem; - this.schemes = ["spaces", "vault"]; - this.onCreate = async (payload) => { - if (payload.file.isFolder) { - this.spaceManager.onSpaceCreated(payload.file.path); - } else { - this.spaceManager.onPathCreated(payload.file.path); - } - }; - this.onDelete = (payload) => { - if (!payload.file) - return; - if (!payload.file.isFolder && payload.file.extension != "mdb") { - this.spaceManager.onPathDeleted(payload.file.path); - } else if (payload.file.isFolder) { - this.spaceManager.onSpaceDeleted(payload.file.path); - } - }; - this.onRename = (payload) => { - if (!payload.file) - return; - if (!payload.file.isFolder && payload.file.extension != "mdb") { - this.spaceManager.onPathChanged(payload.file.path, payload.oldPath); - } else if (payload.file.isFolder) { - this.spaceManager.onSpaceRenamed(payload.file.path, payload.oldPath); - } - }; - this.authorities = ["vault"]; - fileSystem.eventDispatch.addListener("onCreate", this.onCreate, 0, this); - fileSystem.eventDispatch.addListener("onRename", this.onRename, 0, this); - fileSystem.eventDispatch.addListener("onDelete", this.onDelete, 0, this); - fileSystem.eventDispatch.addListener("onCacheUpdated", this.onMetadataChange, 0, this); + toString() { + return this.context.buffer.childString(this.index); } - initiateAdapter(manager) { - this.spaceManager = manager; + getChild(type, before = null, after = null) { + let r2 = getChildren2(this, type, before, after); + return r2.length ? r2[0] : null; } - async readTemplates(path2) { - return (await this.childrenForPath(`${path2}/.space/templates`)).filter((f2) => !f2.startsWith(".")).map((f2) => f2.split("/").pop()); + getChildren(type, before = null, after = null) { + return getChildren2(this, type, before, after); } - async saveTemplate(path2, space2) { - return this.copyPath(path2, `${space2}/.space/templates`); + get node() { + return this; } - deleteTemplate(path2, space2) { - return this.deletePath(`${space2}/.space/templates/${path2}`); + matchContext(context) { + return matchNodeContext2(this, context); } - async readWaypoints() { - if (!await this.fileSystem.fileExists(defaultSpaceFolder)) { - await this.fileSystem.createFolder(defaultSpaceFolder); - } - if (!await this.fileSystem.fileExists(defaultWaypointsFile)) { - return []; +}; +var TreeCursor2 = class { + constructor(node, mode2 = 0) { + this.mode = mode2; + this.buffer = null; + this.stack = []; + this.index = 0; + this.bufferNode = null; + if (node instanceof TreeNode3) { + this.yieldNode(node); + } else { + this._tree = node.context.parent; + this.buffer = node.context; + for (let n3 = node._parent; n3; n3 = n3._parent) + this.stack.unshift(n3.index); + this.bufferNode = node; + this.yieldBuf(node.index); } - return this.fileSystem.readTextFromFile(defaultWaypointsFile).then((f2) => ensureArray(safelyParseJSON(f2))); } - async saveWaypoints(waypoints) { - if (!await this.fileSystem.fileExists(defaultSpaceFolder)) { - await this.fileSystem.createFolder(defaultSpaceFolder); - } - return this.fileSystem.writeTextToFile(defaultWaypointsFile, JSON.stringify(waypoints)); + get name() { + return this.type.name; } - async readTemplate(name317) { - const g = `${defaultTemplatesFolder}/${name317}`; - if (await this.fileSystem.fileExists(g)) { - return this.fileSystem.readFileFragments({ - path: g + "/.space/views.mdb", - name: "views", - filename: "views.mdb", - parent: g, - isFolder: false, - extension: "mdb" - }, "mdbTables"); - } + yieldNode(node) { + if (!node) + return false; + this._tree = node; + this.type = node.type; + this.from = node.from; + this.to = node.to; + return true; } - async readAllKits() { - const strings = (await this.childrenForPath(defaultKitsFolder)).map((f2) => f2.split("/").pop()); - const kits = Promise.all(strings.map(async (f2) => { - const frames = await this.readKitFrames(f2); - return { - id: f2, - name: f2, - colors: {}, - frames: Object.values(frames ?? {}) - }; - })); - return kits; + yieldBuf(index2, type) { + this.index = index2; + let { start, buffer } = this.buffer; + this.type = type || buffer.set.types[buffer.buffer[index2]]; + this.from = start + buffer.buffer[index2 + 1]; + this.to = start + buffer.buffer[index2 + 2]; + return true; } - async readAllTemplates() { - const strings = (await this.childrenForPath(defaultTemplatesFolder)).map((f2) => f2.split("/").pop()); - const templates = {}; - for (const string4 of strings) { - const template2 = await this.readTemplate(string4); - if (template2) { - templates[string4] = template2; - } + yield(node) { + if (!node) + return false; + if (node instanceof TreeNode3) { + this.buffer = null; + return this.yieldNode(node); } - return templates; - } - async readKitFrames(name317) { - return this.fileSystem.readFileFragments({ - path: `${defaultKitsFolder}/${name317}/kit.mdb`, - name: "kit", - filename: "kit.mdb", - parent: `${defaultKitsFolder}/${name317}`, - isFolder: false, - extension: "mdb" - }, "mdbTables"); + this.buffer = node.context; + return this.yieldBuf(node.index, node.type); } - async saveFrameKit(frames, name317) { - const mdbFile = { - path: `${defaultKitsFolder}/${name317}/kit.mdb`, - name: "kit", - filename: "kit.mdb", - parent: `${defaultKitsFolder}/${name317}`, - isFolder: false, - extension: "mdb" - }; - await this.fileSystem.saveFileFragment(mdbFile, "schema", frames.schema.id, () => frames.schema); - this.fileSystem.saveFileFragment(mdbFile, "mdbFrame", frames.schema.id, () => frames); + toString() { + return this.buffer ? this.buffer.buffer.childString(this.index) : this._tree.toString(); } - async saveSpaceTemplate(frames, name317) { - let templateName = name317; - if (await this.fileSystem.fileExists(defaultTemplatesFolder)) { - const paths = await this.childrenForPath(`${defaultTemplatesFolder}/${name317}`); - templateName = uniqueNameFromString(templateName, paths); - } - await this.fileSystem.newFile(`${defaultTemplatesFolder}/${templateName}/.space`, "view", "mdb", frames); + enterChild(dir, pos, side) { + if (!this.buffer) + return this.yield(this._tree.nextChild(dir < 0 ? this._tree._tree.children.length - 1 : 0, dir, pos, side, this.mode)); + let { buffer } = this.buffer; + let index2 = buffer.findChild(this.index + 4, buffer.buffer[this.index + 3], dir, pos - this.buffer.start, side); + if (index2 < 0) + return false; + this.stack.push(this.index); + return this.yieldBuf(index2); } - async onMetadataChange(payload) { - if (!payload.path) - return; - for (const space2 of this.allSpaces()) { - if (space2.defPath == payload.path) { - this.spaceManager.onPathPropertyChanged(space2.path); - return; - } - } - this.spaceManager.onPathPropertyChanged(payload.path); + firstChild() { + return this.enterChild(1, 0, 4); } - uriByPath(path2) { - return this.spaceManager.uriByString(path2); + lastChild() { + return this.enterChild(-1, 0, 4); } - allPaths(type) { - return [...this.fileSystem.allFiles().filter((f2) => type ? type.some((g) => g == "folder" ? f2.isFolder : f2.extension == g) : true).map((g) => g.path)]; + childAfter(pos) { + return this.enterChild(1, pos, 2); } - async pathExists(path2) { - return this.fileSystem.fileExists(path2); + childBefore(pos) { + return this.enterChild(-1, pos, -2); } - async createItemAtPath(parent, type, name317, content3) { - const parentURI = await this.getPathInfo(parent); - if (!parentURI?.isFolder) { - const file = await this.fileSystem.getFile(parent); - if (!file) - return null; - return this.fileSystem.newFileFragment(file, type, name317, content3)?.then((f2) => file.path); - } - return this.fileSystem.newFile(parent, name317, type, content3).then((f2) => f2?.path); + enter(pos, side, mode2 = this.mode) { + if (!this.buffer) + return this.yield(this._tree.enter(pos, side, mode2)); + return mode2 & IterMode2.ExcludeBuffers ? false : this.enterChild(1, pos, side); } - async renamePath(oldPath, path2) { - const uri = this.uriByPath(oldPath); - const newUri = this.uriByPath(path2); - const file = await this.fileSystem.getFile(uri.path); - if (uri.refStr) { - const refType = await this.fileSystem.getFileCacheTypeByRefString(file, uri.refStr); - return await this.fileSystem.saveFileFragment(file, refType, uri.refStr, () => newUri.refStr); - } - return await this.fileSystem.renameFile(oldPath, path2); + parent() { + if (!this.buffer) + return this.yieldNode(this.mode & IterMode2.IncludeAnonymous ? this._tree._parent : this._tree.parent); + if (this.stack.length) + return this.yieldBuf(this.stack.pop()); + let parent = this.mode & IterMode2.IncludeAnonymous ? this.buffer.parent : this.buffer.parent.nextSignificantParent(); + this.buffer = null; + return this.yieldNode(parent); } - async deletePath(path2) { - const uri = this.uriByPath(path2); - if (uri.refStr) { - const file = await this.fileSystem.getFile(uri.path); - const refType = await this.fileSystem.getFileCacheTypeByRefString(file, uri.refStr); - return this.fileSystem.deleteFileFragment(file, refType, uri.refStr); + sibling(dir) { + if (!this.buffer) + return !this._tree._parent ? false : this.yield(this._tree.index < 0 ? null : this._tree._parent.nextChild(this._tree.index + dir, dir, 0, 4, this.mode)); + let { buffer } = this.buffer, d4 = this.stack.length - 1; + if (dir < 0) { + let parentStart = d4 < 0 ? 0 : this.stack[d4] + 4; + if (this.index != parentStart) + return this.yieldBuf(buffer.findChild(parentStart, this.index, -1, 0, 4)); + } else { + let after = buffer.buffer[this.index + 3]; + if (after < (d4 < 0 ? buffer.buffer.length : buffer.buffer[this.stack[d4] + 3])) + return this.yieldBuf(after); } - return this.fileSystem.deleteFile(path2); + return d4 < 0 ? this.yield(this.buffer.parent.nextChild(this.buffer.index + dir, dir, 0, 4, this.mode)) : false; } - async getPathInfo(path2) { - const uri = this.uriByPath(path2); - const file = await this.fileSystem.getFile(uri.path); - if (uri.refStr) { - const type = this.fileSystem.getFileCacheTypeByRefString(file, uri.refStr); - } - return file; + nextSibling() { + return this.sibling(1); } - keysForCacheType(path2) { - return this.fileSystem.keysForCacheType(path2); + prevSibling() { + return this.sibling(-1); } - readPathCache(path2) { - const uri = this.uriByPath(path2); - if (uri.scheme == "spaces") { - if (path2.startsWith(tagsSpacePath)) { - return { - file: null, - metadata: null, - label: { - name: "Tags", - sticker: "", - color: "" - }, - type: "space", - parent: "", - tags: [] - }; - } - if (uri.authority.charAt(0) == "#") { - return { - file: null, - metadata: null, - label: { - name: uri.authority, - sticker: "", - color: "" - }, - type: "space", - parent: "", - tags: [] - }; + atLastNode(dir) { + let index2, parent, { buffer } = this; + if (buffer) { + if (dir > 0) { + if (this.index < buffer.buffer.buffer.length) + return false; } else { - return { - file: null, - metadata: null, - label: { - name: "Tags", - sticker: "", - color: "" - }, - type: "space", - parent: "", - tags: [] - }; + for (let i4 = 0; i4 < this.index; i4++) + if (buffer.buffer.buffer[i4 + 3] < this.index) + return false; } + ({ index: index2, parent } = buffer); + } else { + ({ index: index2, _parent: parent } = this._tree); } - return this.fileSystem.getFileCache(path2); + for (; parent; { index: index2, _parent: parent } = parent) { + if (index2 > -1) + for (let i4 = index2 + dir, e5 = dir < 0 ? -1 : parent._tree.children.length; i4 != e5; i4 += dir) { + let child = parent._tree.children[i4]; + if (this.mode & IterMode2.IncludeAnonymous || child instanceof TreeBuffer2 || !child.type.isAnonymous || hasChild2(child)) + return false; + } + } + return true; } - async readPath(path2) { - const uri = this.uriByPath(path2); - const file = await this.fileSystem.getFile(uri.path); - if (uri.refStr) { - const fragmentType = this.fileSystem.getFileCacheTypeByRefString(file, uri.refStr); - this.fileSystem.getFileContent(file, fragmentType, uri.refStr); + move(dir, enter) { + if (enter && this.enterChild(dir, 0, 4)) + return true; + for (; ; ) { + if (this.sibling(dir)) + return true; + if (this.atLastNode(dir) || !this.parent()) + return false; } - return this.fileSystem.readTextFromFile(path2); } - async copyPath(path2, newPath, newName) { - const uri = this.uriByPath(path2); - const file = await this.fileSystem.getFile(uri.path); - return this.fileSystem.copyFile(file.path, newPath, newName); + next(enter = true) { + return this.move(1, enter); } - async writeToPath(path2, content3, binary) { - const uri = this.uriByPath(path2); - const file = await this.fileSystem.getFile(uri.path); - if (uri.refStr) { - const fragmentType = this.fileSystem.getFileCacheTypeByRefString(file, uri.refStr); - this.fileSystem.saveFileFragment(file, fragmentType, uri.refStr, () => content3); - } - if (binary) { - return this.fileSystem.writeBinaryToFile(path2, content3); + prev(enter = true) { + return this.move(-1, enter); + } + moveTo(pos, side = 0) { + while (this.from == this.to || (side < 1 ? this.from >= pos : this.from > pos) || (side > -1 ? this.to <= pos : this.to < pos)) + if (!this.parent()) + break; + while (this.enterChild(1, pos, side)) { } - return this.fileSystem.writeTextToFile(path2, content3); + return this; } - async childrenForPath(path2, type) { - if (await this.fileSystem.fileExists(path2)) - return this.fileSystem.childrenForFolder(path2, type); - return []; + get node() { + if (!this.buffer) + return this._tree; + let cache2 = this.bufferNode, result = null, depth = 0; + if (cache2 && cache2.context == this.buffer) { + scan: + for (let index2 = this.index, d4 = this.stack.length; d4 >= 0; ) { + for (let c3 = cache2; c3; c3 = c3._parent) + if (c3.index == index2) { + if (index2 == this.index) + return c3; + result = c3; + depth = d4 + 1; + break scan; + } + index2 = this.stack[--d4]; + } + } + for (let i4 = depth; i4 < this.stack.length; i4++) + result = new BufferNode2(this.buffer, result, this.stack[i4]); + return this.bufferNode = new BufferNode2(this.buffer, result, this.index); } - parentPathForPath(path2) { - return this.fileSystem.parentPathForPath(path2); + get tree() { + return this.buffer ? null : this._tree._tree; } - async readFrame(path2, schema) { - const mdbFile = await this.fileSystem.getFile(this.spaceInfoForPath(path2).framePath); - if (!mdbFile) { - const defaultTemplate2 = this.defaultFrame(); - if (Object.keys(defaultTemplate2).some((f2) => f2 == schema)) { - const defaultTable = defaultTemplate2[schema]; - return defaultTable; + iterate(enter, leave) { + for (let depth = 0; ; ) { + let mustLeave = false; + if (this.type.isAnonymous || enter(this) !== false) { + if (this.firstChild()) { + depth++; + continue; + } + if (!this.type.isAnonymous) + mustLeave = true; + } + for (; ; ) { + if (mustLeave && leave) + leave(this); + mustLeave = this.type.isAnonymous; + if (this.nextSibling()) + break; + if (!depth) + return; + this.parent(); + depth--; + mustLeave = true; } } - return this.fileSystem.readFileFragments(mdbFile, "mdbTable", schema); } - async readAllFrames(path2) { - const mdbFile = await this.fileSystem.getFile(this.spaceInfoForPath(path2).framePath); - if (!mdbFile) { - return this.defaultFrame(); + matchContext(context) { + if (!this.buffer) + return matchNodeContext2(this.node, context); + let { buffer } = this.buffer, { types: types2 } = buffer.set; + for (let i4 = context.length - 1, d4 = this.stack.length - 1; i4 >= 0; d4--) { + if (d4 < 0) + return matchNodeContext2(this.node, context, i4); + let type = types2[buffer.buffer[this.stack[d4]]]; + if (!type.isAnonymous) { + if (context[i4] && context[i4] != type.name) + return false; + i4--; + } } - return this.fileSystem.readFileFragments(mdbFile, "mdbTables"); + return true; } - async readTable(path2, schema) { - const spaceInfo = this.spaceInfoForPath(path2); - const mdbFile = await this.fileSystem.getFile(spaceInfo.dbPath); - if (!mdbFile && schema == defaultContextDBSchema.id) { - const defaultTable = defaultTableDataForContext(this.spaceManager.superstate, spaceInfo); - return defaultTable; +}; +function hasChild2(tree) { + return tree.children.some((ch) => ch instanceof TreeBuffer2 || !ch.type.isAnonymous || hasChild2(ch)); +} +function buildTree2(data2) { + var _a; + let { buffer, nodeSet, maxBufferLength = DefaultBufferLength2, reused = [], minRepeatType = nodeSet.types.length } = data2; + let cursor2 = Array.isArray(buffer) ? new FlatBufferCursor2(buffer, buffer.length) : buffer; + let types2 = nodeSet.types; + let contextHash = 0, lookAhead = 0; + function takeNode(parentStart, minPos, children2, positions2, inRepeat) { + let { id: id3, start, end, size: size2 } = cursor2; + let lookAheadAtStart = lookAhead; + while (size2 < 0) { + cursor2.next(); + if (size2 == -1) { + let node2 = reused[id3]; + children2.push(node2); + positions2.push(start - parentStart); + return; + } else if (size2 == -3) { + contextHash = id3; + return; + } else if (size2 == -4) { + lookAhead = id3; + return; + } else { + throw new RangeError(`Unrecognized record size: ${size2}`); + } } - return this.fileSystem.readFileFragments(mdbFile, "mdbTable", schema); - } - async spaceInitiated(path2) { - const spaceInfo = this.spaceInfoForPath(path2); - const mdbFile = await this.fileSystem.getFile(spaceInfo.dbPath); - if (mdbFile) - return true; - return false; - } - async tablesForSpace(path2) { - const spaceInfo = this.spaceInfoForPath(path2); - const mdbFile = await this.fileSystem.getFile(spaceInfo.dbPath); - if (!mdbFile) { - return defaultContextTable.rows; + let type = types2[id3], node, buffer2; + let startPos = start - parentStart; + if (end - start <= maxBufferLength && (buffer2 = findBufferSize(cursor2.pos - minPos, inRepeat))) { + let data3 = new Uint16Array(buffer2.size - buffer2.skip); + let endPos = cursor2.pos - buffer2.size, index2 = data3.length; + while (cursor2.pos > endPos) + index2 = copyToBuffer(buffer2.start, data3, index2); + node = new TreeBuffer2(data3, end - buffer2.start, nodeSet); + startPos = buffer2.start - parentStart; + } else { + let endPos = cursor2.pos - size2; + cursor2.next(); + let localChildren = [], localPositions = []; + let localInRepeat = id3 >= minRepeatType ? id3 : -1; + let lastGroup = 0, lastEnd = end; + while (cursor2.pos > endPos) { + if (localInRepeat >= 0 && cursor2.id == localInRepeat && cursor2.size >= 0) { + if (cursor2.end <= lastEnd - maxBufferLength) { + makeRepeatLeaf(localChildren, localPositions, start, lastGroup, cursor2.end, lastEnd, localInRepeat, lookAheadAtStart); + lastGroup = localChildren.length; + lastEnd = cursor2.end; + } + cursor2.next(); + } else { + takeNode(start, endPos, localChildren, localPositions, localInRepeat); + } + } + if (localInRepeat >= 0 && lastGroup > 0 && lastGroup < localChildren.length) + makeRepeatLeaf(localChildren, localPositions, start, lastGroup, start, lastEnd, localInRepeat, lookAheadAtStart); + localChildren.reverse(); + localPositions.reverse(); + if (localInRepeat > -1 && lastGroup > 0) { + let make = makeBalanced(type); + node = balanceRange2(type, localChildren, localPositions, 0, localChildren.length, 0, end - start, make, make); + } else { + node = makeTree(type, localChildren, localPositions, end - start, lookAheadAtStart - end); + } } - return this.fileSystem.readFileFragments(mdbFile, "schemas", null); + children2.push(node); + positions2.push(startPos); } - defaultDBTablesForContext(spaceInfo) { - const table = defaultTableDataForContext(this.spaceManager.superstate, spaceInfo); - const defaultFields = defaultFieldsForContext(spaceInfo); - const defaultTable = defaultTablesForContext(spaceInfo); - return { - ...defaultTable, - m_fields: { - uniques: defaultFields.uniques, - cols: defaultFields.cols, - rows: [...defaultFields.rows ?? [], ...table.cols] - }, - [table.schema.id]: { - uniques: table.cols.filter((c3) => c3.unique == "true").map((c3) => c3.name), - cols: table.cols.map((c3) => c3.name), - rows: table.rows + function makeBalanced(type) { + return (children2, positions2, length2) => { + let lookAhead2 = 0, lastI = children2.length - 1, last, lookAheadProp; + if (lastI >= 0 && (last = children2[lastI]) instanceof Tree2) { + if (!lastI && last.type == type && last.length == length2) + return last; + if (lookAheadProp = last.prop(NodeProp2.lookAhead)) + lookAhead2 = positions2[lastI] + last.length + lookAheadProp; } + return makeTree(type, children2, positions2, length2, lookAhead2); }; } - defaultFrame() { - if (this.spaceManager.superstate.settings.defaultSpaceTemplate.length > 0 && this.spaceManager.superstate.templateCache.has(this.spaceManager.superstate.settings.defaultSpaceTemplate)) { - return this.spaceManager.superstate.templateCache.get(this.spaceManager.superstate.settings.defaultSpaceTemplate); + function makeRepeatLeaf(children2, positions2, base2, i4, from, to2, type, lookAhead2) { + let localChildren = [], localPositions = []; + while (children2.length > i4) { + localChildren.push(children2.pop()); + localPositions.push(positions2.pop() + base2 - from); } - return DefaultMDBTables; + children2.push(makeTree(nodeSet.types[type], localChildren, localPositions, to2 - from, lookAhead2 - to2)); + positions2.push(from - base2); } - async createDefaultTable(path2) { - const spaceInfo = this.spaceInfoForPath(path2); - const dbPath = this.spaceInfoForPath(path2).dbPath; - const extension = dbPath.split(".").pop(); - const folder = dbPath.split("/").slice(0, -1).join("/"); - const filename = dbPath.split("/").pop().split(".")[0]; - return this.fileSystem.newFile(folder, filename, extension, this.defaultDBTablesForContext(spaceInfo)); + function makeTree(type, children2, positions2, length2, lookAhead2 = 0, props) { + if (contextHash) { + let pair2 = [NodeProp2.contextHash, contextHash]; + props = props ? [pair2].concat(props) : [pair2]; + } + if (lookAhead2 > 25) { + let pair2 = [NodeProp2.lookAhead, lookAhead2]; + props = props ? [pair2].concat(props) : [pair2]; + } + return new Tree2(type, children2, positions2, length2, props); } - async createDefaultFrames(path2) { - const defaultSpaceTemplate = this.defaultFrame(); - const dbField = { - ...mdbFrameToDBTables(defaultSpaceTemplate), - m_schema: defaultFramesTable - }; - const dbPath = this.spaceInfoForPath(path2).framePath; - const extension = dbPath.split(".").pop(); - const folder = dbPath.split("/").slice(0, -1).join("/"); - const filename = dbPath.split("/").pop().split(".")[0]; - return this.fileSystem.newFile(folder, filename, extension, dbField); + function findBufferSize(maxSize, inRepeat) { + let fork = cursor2.fork(); + let size2 = 0, start = 0, skip = 0, minStart = fork.end - maxBufferLength; + let result = { size: 0, start: 0, skip: 0 }; + scan: + for (let minPos = fork.pos - maxSize; fork.pos > minPos; ) { + let nodeSize4 = fork.size; + if (fork.id == inRepeat && nodeSize4 >= 0) { + result.size = size2; + result.start = start; + result.skip = skip; + skip += 4; + size2 += 4; + fork.next(); + continue; + } + let startPos = fork.pos - nodeSize4; + if (nodeSize4 < 0 || startPos < minPos || fork.start < minStart) + break; + let localSkipped = fork.id >= minRepeatType ? 4 : 0; + let nodeStart = fork.start; + fork.next(); + while (fork.pos > startPos) { + if (fork.size < 0) { + if (fork.size == -3) + localSkipped += 4; + else + break scan; + } else if (fork.id >= minRepeatType) { + localSkipped += 4; + } + fork.next(); + } + start = nodeStart; + size2 += nodeSize4; + skip += localSkipped; + } + if (inRepeat < 0 || size2 == maxSize) { + result.size = size2; + result.start = start; + result.skip = skip; + } + return result.size > 4 ? result : void 0; } - async createTable(path2, schema) { - let mdbFile = await this.fileSystem.getFile(this.spaceInfoForPath(path2).dbPath); - if (!mdbFile) { - mdbFile = await this.createDefaultTable(path2); + function copyToBuffer(bufferStart, buffer2, index2) { + let { id: id3, start, end, size: size2 } = cursor2; + cursor2.next(); + if (size2 >= 0 && id3 < minRepeatType) { + let startIndex = index2; + if (size2 > 4) { + let endPos = cursor2.pos - (size2 - 4); + while (cursor2.pos > endPos) + index2 = copyToBuffer(bufferStart, buffer2, index2); + } + buffer2[--index2] = startIndex; + buffer2[--index2] = end - bufferStart; + buffer2[--index2] = start - bufferStart; + buffer2[--index2] = id3; + } else if (size2 == -3) { + contextHash = id3; + } else if (size2 == -4) { + lookAhead = id3; } - return this.fileSystem.newFileFragment(mdbFile, "schema", schema.id, schema); + return index2; } - async saveTableSchema(path2, schemaId, saveSchema) { - let mdbFile = await this.fileSystem.getFile(this.spaceInfoForPath(path2).dbPath); - if (!mdbFile) { - mdbFile = await this.createDefaultTable(path2); + let children = [], positions = []; + while (cursor2.pos > 0) + takeNode(data2.start || 0, data2.bufferStart || 0, children, positions, -1); + let length = (_a = data2.length) !== null && _a !== void 0 ? _a : children.length ? positions[0] + children[0].length : 0; + return new Tree2(types2[data2.topID], children.reverse(), positions.reverse(), length); +} +var nodeSizeCache2 = /* @__PURE__ */ new WeakMap(); +function nodeSize2(balanceType, node) { + if (!balanceType.isAnonymous || node instanceof TreeBuffer2 || node.type != balanceType) + return 1; + let size2 = nodeSizeCache2.get(node); + if (size2 == null) { + size2 = 1; + for (let child of node.children) { + if (child.type != balanceType || !(child instanceof Tree2)) { + size2 = 1; + break; + } + size2 += nodeSize2(balanceType, child); } - return this.fileSystem.saveFileFragment(mdbFile, "schema", schemaId, saveSchema); + nodeSizeCache2.set(node, size2); } - async saveTable(path2, table, force) { - let mdbFile = await this.fileSystem.getFile(this.spaceInfoForPath(path2).dbPath); - if (!mdbFile) { - if (force) { - mdbFile = await this.createDefaultTable(path2); + return size2; +} +function balanceRange2(balanceType, children, positions, from, to2, start, length, mkTop, mkTree) { + let total = 0; + for (let i4 = from; i4 < to2; i4++) + total += nodeSize2(balanceType, children[i4]); + let maxChild = Math.ceil(total * 1.5 / 8); + let localChildren = [], localPositions = []; + function divide3(children2, positions2, from2, to3, offset2) { + for (let i4 = from2; i4 < to3; ) { + let groupFrom = i4, groupStart = positions2[i4], groupSize = nodeSize2(balanceType, children2[i4]); + i4++; + for (; i4 < to3; i4++) { + let nextSize = nodeSize2(balanceType, children2[i4]); + if (groupSize + nextSize >= maxChild) + break; + groupSize += nextSize; + } + if (i4 == groupFrom + 1) { + if (groupSize > maxChild) { + let only = children2[groupFrom]; + divide3(only.children, only.positions, 0, only.children.length, positions2[groupFrom] + offset2); + continue; + } + localChildren.push(children2[groupFrom]); } else { - return null; + let length2 = positions2[i4 - 1] + children2[i4 - 1].length - groupStart; + localChildren.push(balanceRange2(balanceType, children2, positions2, groupFrom, i4, groupStart, length2, null, mkTree)); } + localPositions.push(groupStart + offset2 - start); } - return this.fileSystem.saveFileFragment(mdbFile, "mdbTable", table.schema.id, () => table); } - async deleteTable(path2, name317) { - const mdbFile = await this.fileSystem.getFile(this.spaceInfoForPath(path2).dbPath); - return this.fileSystem.deleteFileFragment(mdbFile, "schema", name317); + divide3(children, positions, from, to2, 0); + return (mkTop || mkTree)(localChildren, localPositions, length); +} +var NodeWeakMap = class { + constructor() { + this.map = /* @__PURE__ */ new WeakMap(); } - async readAllTables(path2) { - const spaceInfo = this.spaceInfoForPath(path2); - const mdbFile = await this.fileSystem.getFile(spaceInfo.dbPath); - if (!mdbFile) { - const defaultTable = defaultTableDataForContext(this.spaceManager.superstate, spaceInfo); - return { - [defaultTable.schema.id]: defaultTable - }; - } - return this.fileSystem.readFileFragments(mdbFile, "mdbTables", null); + setBuffer(buffer, index2, value) { + let inner = this.map.get(buffer); + if (!inner) + this.map.set(buffer, inner = /* @__PURE__ */ new Map()); + inner.set(index2, value); } - async framesForSpace(path2) { - const mdbFile = await this.fileSystem.getFile(this.spaceInfoForPath(path2).framePath); - if (!mdbFile) { - const frames = this.defaultFrame(); - return Object.values(frames).map((f2) => f2.schema); - } - return this.fileSystem.readFileFragments(mdbFile, "schemas", null); + getBuffer(buffer, index2) { + let inner = this.map.get(buffer); + return inner && inner.get(index2); } - async createFrame(path2, schema) { - let mdbFile = await this.fileSystem.getFile(this.spaceInfoForPath(path2).framePath); - if (!mdbFile) { - mdbFile = await this.createDefaultFrames(path2); - } - return this.fileSystem.newFileFragment(mdbFile, "schema", schema.id, schema); + set(node, value) { + if (node instanceof BufferNode2) + this.setBuffer(node.context.buffer, node.index, value); + else if (node instanceof TreeNode3) + this.map.set(node.tree, value); } - async deleteFrame(path2, name317) { - const mdbFile = await this.fileSystem.getFile(this.spaceInfoForPath(path2).framePath); - return this.fileSystem.deleteFileFragment(mdbFile, "schema", name317); + get(node) { + return node instanceof BufferNode2 ? this.getBuffer(node.context.buffer, node.index) : node instanceof TreeNode3 ? this.map.get(node.tree) : void 0; } - async saveFrameSchema(path2, schemaId, saveSchema) { - let mdbFile = await this.fileSystem.getFile(this.spaceInfoForPath(path2).framePath); - if (!mdbFile) { - mdbFile = await this.createDefaultFrames(path2); - } - return this.fileSystem.saveFileFragment(mdbFile, "schema", schemaId, saveSchema); + cursorSet(cursor2, value) { + if (cursor2.buffer) + this.setBuffer(cursor2.buffer.buffer, cursor2.index, value); + else + this.map.set(cursor2.tree, value); } - async saveFrame(path2, frame) { - let mdbFile = await this.fileSystem.getFile(this.spaceInfoForPath(path2).framePath); - if (!mdbFile) { - mdbFile = await this.createDefaultFrames(path2); - } - return this.fileSystem.saveFileFragment(mdbFile, "mdbFrame", frame.schema.id, () => frame); + cursorGet(cursor2) { + return cursor2.buffer ? this.getBuffer(cursor2.buffer.buffer, cursor2.index) : this.map.get(cursor2.tree); } - async createDefaultCommands(path2) { - const dbField = { - m_fields: { - uniques: fieldSchema.uniques, - cols: fieldSchema.cols, - rows: [] - }, - m_schema: { - uniques: [], - cols: ["id", "name", "type", "def", "predicate", "primary"], - rows: [] - } - }; - const dbPath = this.spaceInfoForPath(path2).commandsPath; - const extension = dbPath.split(".").pop(); - const folder = dbPath.split("/").slice(0, -1).join("/"); - const filename = dbPath.split("/").pop().split(".")[0]; - return this.fileSystem.newFile(folder, filename, extension, dbField); +}; +var stoppedInner2 = new NodeProp2({ perNode: true }); + +// node_modules/@codemirror/lang-javascript/dist/index.js +var snippets = [ + /* @__PURE__ */ (0, import_autocomplete.snippetCompletion)("function ${name}(${params}) {\n ${}\n}", { + label: "function", + detail: "definition", + type: "keyword" + }), + /* @__PURE__ */ (0, import_autocomplete.snippetCompletion)("for (let ${index} = 0; ${index} < ${bound}; ${index}++) {\n ${}\n}", { + label: "for", + detail: "loop", + type: "keyword" + }), + /* @__PURE__ */ (0, import_autocomplete.snippetCompletion)("for (let ${name} of ${collection}) {\n ${}\n}", { + label: "for", + detail: "of loop", + type: "keyword" + }), + /* @__PURE__ */ (0, import_autocomplete.snippetCompletion)("try {\n ${}\n} catch (${error}) {\n ${}\n}", { + label: "try", + detail: "block", + type: "keyword" + }), + /* @__PURE__ */ (0, import_autocomplete.snippetCompletion)("class ${name} {\n constructor(${params}) {\n ${}\n }\n}", { + label: "class", + detail: "definition", + type: "keyword" + }), + /* @__PURE__ */ (0, import_autocomplete.snippetCompletion)('import {${names}} from "${module}"\n${}', { + label: "import", + detail: "named", + type: "keyword" + }), + /* @__PURE__ */ (0, import_autocomplete.snippetCompletion)('import ${name} from "${module}"\n${}', { + label: "import", + detail: "default", + type: "keyword" + }) +]; +var cache = /* @__PURE__ */ new NodeWeakMap(); +var ScopeNodes = /* @__PURE__ */ new Set([ + "Script", + "Block", + "FunctionExpression", + "FunctionDeclaration", + "ArrowFunction", + "MethodDeclaration", + "ForStatement" +]); +function defID(type) { + return (node, def) => { + let id3 = node.node.getChild("VariableDefinition"); + if (id3) + def(id3, type); + return true; + }; +} +var functionContext = ["FunctionDeclaration"]; +var gatherCompletions = { + FunctionDeclaration: /* @__PURE__ */ defID("function"), + ClassDeclaration: /* @__PURE__ */ defID("class"), + ClassExpression: () => true, + EnumDeclaration: /* @__PURE__ */ defID("constant"), + TypeAliasDeclaration: /* @__PURE__ */ defID("type"), + NamespaceDeclaration: /* @__PURE__ */ defID("namespace"), + VariableDefinition(node, def) { + if (!node.matchContext(functionContext)) + def(node, "variable"); + }, + TypeDefinition(node, def) { + def(node, "type"); + }, + __proto__: null +}; +function getScope(doc, node) { + let cached = cache.get(node); + if (cached) + return cached; + let completions = [], top = true; + function def(node2, type) { + let name317 = doc.sliceString(node2.from, node2.to); + completions.push({ label: name317, type }); } - async commandsForSpace(path2) { - const mdbFile = await this.fileSystem.getFile(this.spaceInfoForPath(path2).commandsPath); - if (!mdbFile) { - return []; + node.cursor(IterMode2.IncludeAnonymous).iterate((node2) => { + if (top) { + top = false; + } else if (node2.name) { + let gather = gatherCompletions[node2.name]; + if (gather && gather(node2, def) || ScopeNodes.has(node2.name)) + return false; + } else if (node2.to - node2.from > 8192) { + for (let c3 of getScope(doc, node2.node)) + completions.push(c3); + return false; } - return this.fileSystem.readFileFragments(mdbFile, "mdbCommands", null); + }); + cache.set(node, completions); + return completions; +} +var Identifier = /^[\w$\xa1-\uffff][\w$\d\xa1-\uffff]*$/; +function localCompletionSource(context) { + let inner = (0, import_language2.syntaxTree)(context.state).resolve(context.pos, -1); + if (inner.name == "TemplateString" || inner.name == "String" || inner.name == "LineComment" || inner.name == "BlockComment") + return null; + let isWord = inner.to - inner.from < 20 && Identifier.test(context.state.sliceDoc(inner.from, inner.to)); + if (!isWord && !context.explicit) + return null; + let options = []; + for (let pos = inner; pos; pos = pos.parent) { + if (ScopeNodes.has(pos.name)) + options = options.concat(getScope(context.state.doc, pos)); } - async runCommand(path2, name317, args) { - const mdbFile = await this.fileSystem.getFile(this.spaceInfoForPath(path2).commandsPath); - if (!mdbFile) { - return { result: null, error: "No commands file found" }; - } - const command = await this.fileSystem.readFileFragments(mdbFile, "mdbCommand", name317); - if (!command) { - return { result: null, error: "No command found" }; - } - let result; - let error; - try { - if (command.schema.type == "script") - result = executeCode(command.code, args); - if (command.schema.type == "formula") - result = runFormulaWithContext(this.spaceManager.superstate.formulaContext, this.spaceManager.superstate.pathsIndex, command.code, command.fields.reduce((p, c3) => ({ ...p, [c3.name]: c3 }), {}), args, this.spaceManager.superstate.pathsIndex.get(path2)); - } catch (e5) { - error = e5; - } - return { result, error }; + return { + options, + from: isWord ? inner.from : context.pos, + validFor: Identifier + }; +} +var javascriptLanguage = /* @__PURE__ */ import_language2.LRLanguage.define({ + parser: /* @__PURE__ */ parser2.configure({ + props: [ + /* @__PURE__ */ import_language2.indentNodeProp.add({ + IfStatement: /* @__PURE__ */ (0, import_language2.continuedIndent)({ except: /^\s*({|else\b)/ }), + TryStatement: /* @__PURE__ */ (0, import_language2.continuedIndent)({ except: /^\s*({|catch\b|finally\b)/ }), + LabeledStatement: import_language2.flatIndent, + SwitchBody: (context) => { + let after = context.textAfter, closed = /^\s*\}/.test(after), isCase = /^\s*(case|default)\b/.test(after); + return context.baseIndent + (closed ? 0 : isCase ? 1 : 2) * context.unit; + }, + Block: /* @__PURE__ */ (0, import_language2.delimitedIndent)({ closing: "}" }), + ArrowFunction: (cx) => cx.baseIndent + cx.unit, + "TemplateString BlockComment": () => -1, + "Statement Property": /* @__PURE__ */ (0, import_language2.continuedIndent)({ except: /^{/ }), + JSXElement(context) { + let closed = /^\s*<\//.test(context.textAfter); + return context.lineIndent(context.node.from) + (closed ? 0 : context.unit); + }, + JSXEscape(context) { + let closed = /\s*\}/.test(context.textAfter); + return context.lineIndent(context.node.from) + (closed ? 0 : context.unit); + }, + "JSXOpenTag JSXSelfClosingTag"(context) { + return context.column(context.node.from) + context.unit; + } + }), + /* @__PURE__ */ import_language2.foldNodeProp.add({ + "Block ClassBody SwitchBody EnumBody ObjectExpression ArrayExpression": import_language2.foldInside, + BlockComment(tree) { + return { from: tree.from + 2, to: tree.to - 2 }; + } + }) + ] + }), + languageData: { + closeBrackets: { brackets: ["(", "[", "{", "'", '"', "`"] }, + commentTokens: { line: "//", block: { open: "/*", close: "*/" } }, + indentOnInput: /^\s*(?:case |default:|\{|\}|<\/)$/, + wordChars: "$" } - async createCommand(path2, schema) { - let mdbFile = await this.fileSystem.getFile(this.spaceInfoForPath(path2).commandsPath); - if (!mdbFile) { - mdbFile = await this.createDefaultCommands(path2); +}); +var typescriptLanguage = /* @__PURE__ */ javascriptLanguage.configure({ dialect: "ts" }); +var jsxLanguage = /* @__PURE__ */ javascriptLanguage.configure({ dialect: "jsx" }); +var tsxLanguage = /* @__PURE__ */ javascriptLanguage.configure({ dialect: "jsx ts" }); +function javascript(config4 = {}) { + let lang = config4.jsx ? config4.typescript ? tsxLanguage : jsxLanguage : config4.typescript ? typescriptLanguage : javascriptLanguage; + return new import_language2.LanguageSupport(lang, [ + javascriptLanguage.data.of({ + autocomplete: (0, import_autocomplete.ifNotIn)(["LineComment", "BlockComment", "String"], (0, import_autocomplete.completeFromList)(snippets)) + }), + javascriptLanguage.data.of({ + autocomplete: localCompletionSource + }), + config4.jsx ? autoCloseTags : [] + ]); +} +function elementName(doc, tree, max5 = doc.length) { + if (!tree) + return ""; + let name317 = tree.getChild("JSXIdentifier"); + return name317 ? doc.sliceString(name317.from, Math.min(name317.to, max5)) : ""; +} +var android = typeof navigator == "object" && /* @__PURE__ */ /Android\b/.test(navigator.userAgent); +var autoCloseTags = /* @__PURE__ */ import_view2.EditorView.inputHandler.of((view, from, to2, text2) => { + if ((android ? view.composing : view.compositionStarted) || view.state.readOnly || from != to2 || text2 != ">" && text2 != "/" || !javascriptLanguage.isActiveAt(view.state, from, -1)) + return false; + let { state } = view; + let changes = state.changeByRange((range2) => { + var _a, _b, _c; + let { head } = range2, around2 = (0, import_language2.syntaxTree)(state).resolveInner(head, -1), name317; + if (around2.name == "JSXStartTag") + around2 = around2.parent; + if (text2 == ">" && around2.name == "JSXFragmentTag") { + return { range: import_state3.EditorSelection.cursor(head + 1), changes: { from: head, insert: `><>` } }; + } else if (text2 == ">" && around2.name == "JSXIdentifier") { + if (((_b = (_a = around2.parent) === null || _a === void 0 ? void 0 : _a.lastChild) === null || _b === void 0 ? void 0 : _b.name) != "JSXEndTag" && (name317 = elementName(state.doc, around2.parent, head))) + return { range: import_state3.EditorSelection.cursor(head + 1), changes: { from: head, insert: `>` } }; + } else if (text2 == "/" && around2.name == "JSXFragmentTag") { + let empty3 = around2.parent, base2 = empty3 === null || empty3 === void 0 ? void 0 : empty3.parent; + if (empty3.from == head - 1 && ((_c = base2.lastChild) === null || _c === void 0 ? void 0 : _c.name) != "JSXEndTag" && (name317 = elementName(state.doc, base2 === null || base2 === void 0 ? void 0 : base2.firstChild, head))) { + let insert2 = `/${name317}>`; + return { range: import_state3.EditorSelection.cursor(head + insert2.length), changes: { from: head, insert: insert2 } }; + } } - return this.fileSystem.newFileFragment(mdbFile, "schema", schema.id, schema); + return { range: range2 }; + }); + if (changes.changes.empty) + return false; + view.dispatch(changes, { userEvent: "input.type", scrollIntoView: true }); + return true; +}); + +// node_modules/@lezer/common/dist/index.js +var DefaultBufferLength3 = 1024; +var nextPropID3 = 0; +var NodeProp3 = class { + constructor(config4 = {}) { + this.id = nextPropID3++; + this.perNode = !!config4.perNode; + this.deserialize = config4.deserialize || (() => { + throw new Error("This node type doesn't define a deserialize function"); + }); } - async readSystemCommands() { - const strings = (await this.childrenForPath(defaultActionsFolder, "folder")).map((f2) => f2.split("/").pop()); - const kits = Promise.all(strings.map(async (f2) => { - const frames = await this.readLibraryCommands(f2); - return { - name: f2, - commands: Object.values(frames ?? {}) - }; - })); - return kits; + add(match2) { + if (this.perNode) + throw new RangeError("Can't add per-node props to node types"); + if (typeof match2 != "function") + match2 = NodeType3.match(match2); + return (type) => { + let result = match2(type); + return result === void 0 ? null : [this, result]; + }; } - async readLibraryCommands(name317) { - return this.fileSystem.readFileFragments({ - path: `${defaultActionsFolder}/${name317}/commands.mdb`, - name: "commands", - filename: "commands.mdb", - parent: `${defaultKitsFolder}/${name317}`, - isFolder: false, - extension: "mdb" - }, "mdbCommands"); +}; +NodeProp3.closedBy = new NodeProp3({ deserialize: (str) => str.split(" ") }); +NodeProp3.openedBy = new NodeProp3({ deserialize: (str) => str.split(" ") }); +NodeProp3.group = new NodeProp3({ deserialize: (str) => str.split(" ") }); +NodeProp3.isolate = new NodeProp3({ deserialize: (value) => { + if (value && value != "rtl" && value != "ltr" && value != "auto") + throw new RangeError("Invalid value for isolate: " + value); + return value || "auto"; +} }); +NodeProp3.contextHash = new NodeProp3({ perNode: true }); +NodeProp3.lookAhead = new NodeProp3({ perNode: true }); +NodeProp3.mounted = new NodeProp3({ perNode: true }); +var MountedTree = class { + constructor(tree, overlay, parser3) { + this.tree = tree; + this.overlay = overlay; + this.parser = parser3; } - async saveSystemCommand(lib, command) { - const mdbFile = { - path: `${defaultActionsFolder}/${lib}/commands.mdb`, - name: "commands", - filename: "commands.mdb", - parent: `${defaultActionsFolder}/${lib}`, - isFolder: false, - extension: "mdb" - }; - if (command) { - await this.fileSystem.saveFileFragment(mdbFile, "schema", command.schema.id, () => command.schema); - await this.fileSystem.saveFileFragment(mdbFile, "mdbCommand", command.schema.id, () => command); - } else { - const dbField = { - m_fields: { - uniques: fieldSchema.uniques, - cols: fieldSchema.cols, - rows: [] - }, - m_schema: { - uniques: [], - cols: ["id", "name", "type", "def", "predicate", "primary"], - rows: [] + static get(tree) { + return tree && tree.props && tree.props[NodeProp3.mounted.id]; + } +}; +var noProps3 = /* @__PURE__ */ Object.create(null); +var NodeType3 = class { + constructor(name317, props, id3, flags = 0) { + this.name = name317; + this.props = props; + this.id = id3; + this.flags = flags; + } + static define(spec) { + let props = spec.props && spec.props.length ? /* @__PURE__ */ Object.create(null) : noProps3; + let flags = (spec.top ? 1 : 0) | (spec.skipped ? 2 : 0) | (spec.error ? 4 : 0) | (spec.name == null ? 8 : 0); + let type = new NodeType3(spec.name || "", props, spec.id, flags); + if (spec.props) + for (let src of spec.props) { + if (!Array.isArray(src)) + src = src(type); + if (src) { + if (src[0].perNode) + throw new RangeError("Can't store a per-node prop on a node type"); + props[src[0].id] = src[1]; } - }; - const dbPath = mdbFile.path; - const extension = dbPath.split(".").pop(); - const folder = dbPath.split("/").slice(0, -1).join("/"); - const filename = dbPath.split("/").pop().split(".")[0]; - await this.fileSystem.newFile(folder, filename, extension, dbField); - } + } + return type; } - async deleteCommand(path2, name317) { - const mdbFile = await this.fileSystem.getFile(this.spaceInfoForPath(path2).commandsPath); - return this.fileSystem.deleteFileFragment(mdbFile, "mdbCommand", name317); + prop(prop2) { + return this.props[prop2.id]; } - async saveCommand(path2, schemaId, saveCommand) { - let mdbFile = await this.fileSystem.getFile(this.spaceInfoForPath(path2).commandsPath); - if (!mdbFile) { - mdbFile = await this.createDefaultCommands(path2); + get isTop() { + return (this.flags & 1) > 0; + } + get isSkipped() { + return (this.flags & 2) > 0; + } + get isError() { + return (this.flags & 4) > 0; + } + get isAnonymous() { + return (this.flags & 8) > 0; + } + is(name317) { + if (typeof name317 == "string") { + if (this.name == name317) + return true; + let group = this.prop(NodeProp3.group); + return group ? group.indexOf(name317) > -1 : false; } - return this.fileSystem.saveFileFragment(mdbFile, "mdbCommand", schemaId, saveCommand); + return this.id == name317; } - async contextForSpace(path2) { - const mdbFile = await this.fileSystem.getFile(this.spaceInfoForPath(path2).dbPath); - if (!mdbFile) { - return defaultTableDataForContext(this.spaceManager.superstate, this.spaceInfoForPath(path2)); + static match(map4) { + let direct = /* @__PURE__ */ Object.create(null); + for (let prop2 in map4) + for (let name317 of prop2.split(" ")) + direct[name317] = map4[prop2]; + return (node) => { + for (let groups = node.prop(NodeProp3.group), i4 = -1; i4 < (groups ? groups.length : 0); i4++) { + let found = direct[i4 < 0 ? node.name : groups[i4]]; + if (found) + return found; + } + }; + } +}; +NodeType3.none = new NodeType3("", /* @__PURE__ */ Object.create(null), 0, 8); +var CachedNode3 = /* @__PURE__ */ new WeakMap(); +var CachedInnerNode3 = /* @__PURE__ */ new WeakMap(); +var IterMode3; +(function(IterMode4) { + IterMode4[IterMode4["ExcludeBuffers"] = 1] = "ExcludeBuffers"; + IterMode4[IterMode4["IncludeAnonymous"] = 2] = "IncludeAnonymous"; + IterMode4[IterMode4["IgnoreMounts"] = 4] = "IgnoreMounts"; + IterMode4[IterMode4["IgnoreOverlays"] = 8] = "IgnoreOverlays"; +})(IterMode3 || (IterMode3 = {})); +var Tree3 = class { + constructor(type, children, positions, length, props) { + this.type = type; + this.children = children; + this.positions = positions; + this.length = length; + this.props = null; + if (props && props.length) { + this.props = /* @__PURE__ */ Object.create(null); + for (let [prop2, value] of props) + this.props[typeof prop2 == "number" ? prop2 : prop2.id] = value; } - return this.fileSystem.readFileFragments(mdbFile, "mdbTable", defaultContextSchemaID); } - async addSpaceProperty(path2, property) { - const mdbFile = await this.fileSystem.getFile(this.spaceInfoForPath(path2)?.dbPath); - if (!mdbFile) { - await this.createDefaultTable(path2); + toString() { + let mounted = MountedTree.get(this); + if (mounted && !mounted.overlay) + return mounted.tree.toString(); + let children = ""; + for (let ch of this.children) { + let str = ch.toString(); + if (str) { + if (children) + children += ","; + children += str; + } } - return this.fileSystem.newFileFragment(mdbFile, "field", property.name, property); + return !this.type.name ? children : (/\W/.test(this.type.name) && !this.type.isError ? JSON.stringify(this.type.name) : this.type.name) + (children.length ? "(" + children + ")" : ""); } - async deleteSpaceProperty(path2, property) { - const mdbFile = await this.fileSystem.getFile(this.spaceInfoForPath(path2).dbPath); - return this.fileSystem.deleteFileFragment(mdbFile, "field", property); + cursor(mode2 = 0) { + return new TreeCursor3(this.topNode, mode2); } - async saveSpaceProperty(path2, property, oldProperty) { - const mdbFile = await this.fileSystem.getFile(this.spaceInfoForPath(path2).dbPath); - if (!mdbFile) { - await this.createDefaultTable(path2); - } - return this.fileSystem.saveFileFragment(mdbFile, "field", oldProperty, (prev) => ({ ...prev, ...property })); + cursorAt(pos, side = 0, mode2 = 0) { + let scope = CachedNode3.get(this) || this.topNode; + let cursor2 = new TreeCursor3(scope); + cursor2.moveTo(pos, side); + CachedNode3.set(this, cursor2._tree); + return cursor2; } - async addProperty(path2, property) { - const file = await this.fileSystem.getFile(path2); - this.fileSystem.newFileFragment(file, "property", property.name, property); + get topNode() { + return new TreeNode4(this, 0, 0, null); } - async saveProperties(path2, properties3) { - const file = await this.fileSystem.getFile(path2); - this.fileSystem.saveFileFragment(file, "property", null, (prev) => ({ ...prev, ...properties3 })); + resolve(pos, side = 0) { + let node = resolveNode3(CachedNode3.get(this) || this.topNode, pos, side, false); + CachedNode3.set(this, node); + return node; } - async readLabel(path2) { - return this.fileSystem.getFileCache(path2).label; + resolveInner(pos, side = 0) { + let node = resolveNode3(CachedInnerNode3.get(this) || this.topNode, pos, side, true); + CachedInnerNode3.set(this, node); + return node; } - async saveLabel(path2, label, value) { - const file = await this.fileSystem.getFile(path2); - this.fileSystem.saveFileLabel(file, label, value); + resolveStack(pos, side = 0) { + return stackIterator(this, pos, side); } - async renameProperty(path2, property, newProperty) { - const file = await this.fileSystem.getFile(path2); - this.fileSystem.saveFileFragment(file, "property", null, (prev) => { - const { [property]: value, ...properties3 } = prev; - if (!value) - return prev; - return { ...properties3, [newProperty]: value }; - }); + iterate(spec) { + let { enter, leave, from = 0, to: to2 = this.length } = spec; + let mode2 = spec.mode || 0, anon = (mode2 & IterMode3.IncludeAnonymous) > 0; + for (let c3 = this.cursor(mode2 | IterMode3.IncludeAnonymous); ; ) { + let entered = false; + if (c3.from <= to2 && c3.to >= from && (!anon && c3.type.isAnonymous || enter(c3) !== false)) { + if (c3.firstChild()) + continue; + entered = true; + } + for (; ; ) { + if (entered && leave && (anon || !c3.type.isAnonymous)) + leave(c3); + if (c3.nextSibling()) + break; + if (!c3.parent()) + return; + entered = true; + } + } } - async readProperties(path2) { - const file = await this.fileSystem.getFile(path2); - return this.fileSystem.readFileFragments(file, "property", null); + prop(prop2) { + return !prop2.perNode ? this.type.prop(prop2) : this.props ? this.props[prop2.id] : void 0; } - async deleteProperty(path2, property) { - const file = await this.fileSystem.getFile(path2); - this.fileSystem.deleteFileFragment(file, "property", property); + get propValues() { + let result = []; + if (this.props) + for (let id3 in this.props) + result.push([+id3, this.props[id3]]); + return result; } - allSpaces() { - const tagSpace = this.spaceManager.spaceInfoForPath(tagsSpacePath); - const getAllTagContextFiles = () => this.readTags().map((f2) => fileSystemSpaceInfoFromTag(this.spaceManager, tagPathToTag(f2))) ?? []; - const getAllFolderContextFiles = () => { - const folders = this.allPaths(["folder"]).filter((f2) => !f2.startsWith(this.spaceManager.superstate.settings.spacesFolder + "/#")); - return folders.map((f2) => fileSystemSpaceInfoFromFolder(this.spaceManager, f2)); - }; - const allTagSpaces = this.spaceManager.superstate.settings.enableDefaultSpaces ? getAllTagContextFiles() : []; - const allFolders = getAllFolderContextFiles(); - return [tagSpace, ...allTagSpaces, ...allFolders]; + balance(config4 = {}) { + return this.children.length <= 8 ? this : balanceRange3(NodeType3.none, this.children, this.positions, 0, this.children.length, 0, this.length, (children, positions, length) => new Tree3(this.type, children, positions, length, this.propValues), config4.makeTree || ((children, positions, length) => new Tree3(NodeType3.none, children, positions, length))); } - readTags() { - return this.fileSystem.allTags(); + static build(data2) { + return buildTree3(data2); } - spaceInfoForPath(path2) { - return fileSystemSpaceInfoByPath(this.spaceManager, path2); +}; +Tree3.empty = new Tree3(NodeType3.none, [], [], 0); +var FlatBufferCursor3 = class { + constructor(buffer, index2) { + this.buffer = buffer; + this.index = index2; } - allCaches() { - return this.fileSystem.allCaches(); + get id() { + return this.buffer[this.index - 4]; } - async spaceDefForSpace(path2) { - const space2 = this.spaceInfoForPath(path2); - if (!space2) - return null; - const defFile = await this.fileSystem.getFile(space2.defPath); - const metaCache = defFile ? this.fileSystem.getFileCache(defFile.path)?.frontmatter : null; - const spaceDef = metaCache ?? {}; - return parseSpaceMetadata(spaceDef, this.spaceManager.superstate.settings); + get start() { + return this.buffer[this.index - 3]; } - async createSpace(name317, parentPath, definition) { - const spaceInfo = this.spaceInfoForPath(parentPath); - const newPath = spaceInfo.folderPath == "/" ? name317 : spaceInfo.folderPath + "/" + name317; - await this.fileSystem.createFolder(newPath); - if (Object.keys(definition ?? {}).length > 0) - return this.saveSpace(newPath, () => definition); + get end() { + return this.buffer[this.index - 2]; } - async saveSpace(path2, definitionFn, properties3) { - const metadata = definitionFn(await this.spaceDefForSpace(path2)) ?? {}; - const spaceInfo = this.spaceInfoForPath(path2); - let file = await this.fileSystem.getFile(spaceInfo.defPath); - if (!file) { - file = await this.fileSystem.newFile(spaceInfo.folderPath, spaceInfo.name, "md"); - } - await this.fileSystem.saveFileFragment(file, "frontmatter", null, (frontmatter) => ({ - ...frontmatter, - [spaceFilterKey(this.spaceManager.superstate.settings)]: metadata.filters, - [spaceContextsKey(this.spaceManager.superstate.settings)]: metadata.contexts, - [spaceLinksKey(this.spaceManager.superstate.settings)]: metadata.links, - [spaceSortKey(this.spaceManager.superstate.settings)]: metadata.sort, - [spaceTemplateKey(this.spaceManager.superstate.settings)]: metadata.template, - [spaceTemplateNameKey(this.spaceManager.superstate.settings)]: metadata.templateName, - ...properties3 ?? {} - })); - return; + get size() { + return this.buffer[this.index - 1]; } - renameSpace(oldPath, newPath) { - const spaceInfo = this.spaceInfoForPath(oldPath); - const newSpaceInfo = this.spaceInfoForPath(newPath); - this.fileSystem.renameFile(spaceInfo.folderPath, newSpaceInfo.folderPath).then((f2) => this.fileSystem.renameFile(movePath(spaceInfo.defPath, newSpaceInfo.path), newSpaceInfo.defPath)); + get pos() { + return this.index; } - deleteSpace(path2) { - const spaceCache = this.spaceInfoForPath(path2); - const spaceInfo = fileSystemSpaceInfoFromTag(this.spaceManager, spaceCache.name); - this.fileSystem.deleteFile(spaceInfo.folderPath); + next() { + this.index -= 4; } - childrenForSpace(path2) { - return this.fileSystem.allFiles().filter((f2) => f2.parent == path2).map((f2) => f2.path); + fork() { + return new FlatBufferCursor3(this.buffer, this.index); } - addTag(path2, tag2) { - this.fileSystem.addTagToFile(path2, tag2); +}; +var TreeBuffer3 = class { + constructor(buffer, length, set) { + this.buffer = buffer; + this.length = length; + this.set = set; } - renameTag(path2, tag2, newTag) { - this.fileSystem.renameTagForFile(path2, tag2, newTag); + get type() { + return NodeType3.none; } - deleteTag(path2, tag2) { - this.fileSystem.removeTagFromFile(path2, tag2); + toString() { + let result = []; + for (let index2 = 0; index2 < this.buffer.length; ) { + result.push(this.childString(index2)); + index2 = this.buffer[index2 + 3]; + } + return result.join(","); } - pathsForTag(tag2) { - return this.fileSystem.filesForTag(tag2); + childString(index2) { + let id3 = this.buffer[index2], endIndex = this.buffer[index2 + 3]; + let type = this.set.types[id3], result = type.name; + if (/\W/.test(result) && !type.isError) + result = JSON.stringify(result); + index2 += 4; + if (endIndex == index2) + return result; + let children = []; + while (index2 < endIndex) { + children.push(this.childString(index2)); + index2 = this.buffer[index2 + 3]; + } + return result + "(" + children.join(",") + ")"; } - resolvePath(path2, source) { - return this.fileSystem.resolvePath(path2, source); + findChild(startIndex, endIndex, dir, pos, side) { + let { buffer } = this, pick = -1; + for (let i4 = startIndex; i4 != endIndex; i4 = buffer[i4 + 3]) { + if (checkSide3(side, pos, buffer[i4 + 1], buffer[i4 + 2])) { + pick = i4; + if (dir > 0) + break; + } + } + return pick; + } + slice(startI, endI, from) { + let b2 = this.buffer; + let copy = new Uint16Array(endI - startI), len = 0; + for (let i4 = startI, j = 0; i4 < endI; ) { + copy[j++] = b2[i4++]; + copy[j++] = b2[i4++] - from; + let to2 = copy[j++] = b2[i4++] - from; + copy[j++] = b2[i4++] - startI; + len = Math.max(len, to2); + } + return new TreeBuffer3(copy, len, this.set); } }; - -// src/core/react/components/UI/Menus/menu/SelectMenu.tsx -var import_react17 = __toESM(require_react()); - -// node_modules/fuse.js/dist/fuse.mjs -function isArray4(value) { - return !Array.isArray ? getTag(value) === "[object Array]" : Array.isArray(value); -} -var INFINITY = 1 / 0; -function baseToString(value) { - if (typeof value == "string") { - return value; +function checkSide3(side, pos, from, to2) { + switch (side) { + case -2: + return from < pos; + case -1: + return to2 >= pos && from < pos; + case 0: + return from < pos && to2 > pos; + case 1: + return from <= pos && to2 > pos; + case 2: + return to2 > pos; + case 4: + return true; } - let result = value + ""; - return result == "0" && 1 / value == -INFINITY ? "-0" : result; -} -function toString2(value) { - return value == null ? "" : baseToString(value); -} -function isString4(value) { - return typeof value === "string"; -} -function isNumber3(value) { - return typeof value === "number"; -} -function isBoolean2(value) { - return value === true || value === false || isObjectLike(value) && getTag(value) == "[object Boolean]"; -} -function isObject2(value) { - return typeof value === "object"; -} -function isObjectLike(value) { - return isObject2(value) && value !== null; -} -function isDefined(value) { - return value !== void 0 && value !== null; -} -function isBlank(value) { - return !value.trim().length; -} -function getTag(value) { - return value == null ? value === void 0 ? "[object Undefined]" : "[object Null]" : Object.prototype.toString.call(value); } -var INCORRECT_INDEX_TYPE = "Incorrect 'index' type"; -var LOGICAL_SEARCH_INVALID_QUERY_FOR_KEY = (key2) => `Invalid value for key ${key2}`; -var PATTERN_LENGTH_TOO_LARGE = (max5) => `Pattern length exceeds max of ${max5}.`; -var MISSING_KEY_PROPERTY = (name317) => `Missing ${name317} property in key`; -var INVALID_KEY_WEIGHT_VALUE = (key2) => `Property 'weight' in key '${key2}' must be a positive integer`; -var hasOwn2 = Object.prototype.hasOwnProperty; -var KeyStore = class { - constructor(keys) { - this._keys = []; - this._keyMap = {}; - let totalWeight = 0; - keys.forEach((key2) => { - let obj = createKey(key2); - this._keys.push(obj); - this._keyMap[obj.id] = obj; - totalWeight += obj.weight; - }); - this._keys.forEach((key2) => { - key2.weight /= totalWeight; - }); - } - get(keyId) { - return this._keyMap[keyId]; - } - keys() { - return this._keys; - } - toJSON() { - return JSON.stringify(this._keys); +function resolveNode3(node, pos, side, overlays) { + var _a; + while (node.from == node.to || (side < 1 ? node.from >= pos : node.from > pos) || (side > -1 ? node.to <= pos : node.to < pos)) { + let parent = !overlays && node instanceof TreeNode4 && node.index < 0 ? null : node.parent; + if (!parent) + return node; + node = parent; } -}; -function createKey(key2) { - let path2 = null; - let id3 = null; - let src = null; - let weight = 1; - let getFn = null; - if (isString4(key2) || isArray4(key2)) { - src = key2; - path2 = createKeyPath(key2); - id3 = createKeyId(key2); - } else { - if (!hasOwn2.call(key2, "name")) { - throw new Error(MISSING_KEY_PROPERTY("name")); - } - const name317 = key2.name; - src = name317; - if (hasOwn2.call(key2, "weight")) { - weight = key2.weight; - if (weight <= 0) { - throw new Error(INVALID_KEY_WEIGHT_VALUE(name317)); - } + let mode2 = overlays ? 0 : IterMode3.IgnoreOverlays; + if (overlays) + for (let scan = node, parent = scan.parent; parent; scan = parent, parent = scan.parent) { + if (scan instanceof TreeNode4 && scan.index < 0 && ((_a = parent.enter(pos, side, mode2)) === null || _a === void 0 ? void 0 : _a.from) != scan.from) + node = parent; } - path2 = createKeyPath(name317); - id3 = createKeyId(name317); - getFn = key2.getFn; + for (; ; ) { + let inner = node.enter(pos, side, mode2); + if (!inner) + return node; + node = inner; } - return { path: path2, id: id3, weight, src, getFn }; -} -function createKeyPath(key2) { - return isArray4(key2) ? key2 : key2.split("."); -} -function createKeyId(key2) { - return isArray4(key2) ? key2.join(".") : key2; -} -function get(obj, path2) { - let list = []; - let arr = false; - const deepGet = (obj2, path3, index2) => { - if (!isDefined(obj2)) { - return; - } - if (!path3[index2]) { - list.push(obj2); - } else { - let key2 = path3[index2]; - const value = obj2[key2]; - if (!isDefined(value)) { - return; - } - if (index2 === path3.length - 1 && (isString4(value) || isNumber3(value) || isBoolean2(value))) { - list.push(toString2(value)); - } else if (isArray4(value)) { - arr = true; - for (let i4 = 0, len = value.length; i4 < len; i4 += 1) { - deepGet(value[i4], path3, index2 + 1); - } - } else if (path3.length) { - deepGet(value, path3, index2 + 1); - } - } - }; - deepGet(obj, isString4(path2) ? path2.split(".") : path2, 0); - return arr ? list : list[0]; -} -var MatchOptions = { - includeMatches: false, - findAllMatches: false, - minMatchCharLength: 1 -}; -var BasicOptions = { - isCaseSensitive: false, - includeScore: false, - keys: [], - shouldSort: true, - sortFn: (a4, b2) => a4.score === b2.score ? a4.idx < b2.idx ? -1 : 1 : a4.score < b2.score ? -1 : 1 -}; -var FuzzyOptions = { - location: 0, - threshold: 0.6, - distance: 100 -}; -var AdvancedOptions = { - useExtendedSearch: false, - getFn: get, - ignoreLocation: false, - ignoreFieldNorm: false, - fieldNormWeight: 1 -}; -var Config = { - ...BasicOptions, - ...MatchOptions, - ...FuzzyOptions, - ...AdvancedOptions -}; -var SPACE = /[^ ]+/g; -function norm2(weight = 1, mantissa = 3) { - const cache2 = /* @__PURE__ */ new Map(); - const m4 = Math.pow(10, mantissa); - return { - get(value) { - const numTokens = value.match(SPACE).length; - if (cache2.has(numTokens)) { - return cache2.get(numTokens); - } - const norm3 = 1 / Math.pow(numTokens, 0.5 * weight); - const n3 = parseFloat(Math.round(norm3 * m4) / m4); - cache2.set(numTokens, n3); - return n3; - }, - clear() { - cache2.clear(); - } - }; } -var FuseIndex = class { - constructor({ - getFn = Config.getFn, - fieldNormWeight = Config.fieldNormWeight - } = {}) { - this.norm = norm2(fieldNormWeight, 3); - this.getFn = getFn; - this.isCreated = false; - this.setIndexRecords(); +var BaseNode = class { + cursor(mode2 = 0) { + return new TreeCursor3(this, mode2); } - setSources(docs = []) { - this.docs = docs; + getChild(type, before = null, after = null) { + let r2 = getChildren3(this, type, before, after); + return r2.length ? r2[0] : null; } - setIndexRecords(records = []) { - this.records = records; + getChildren(type, before = null, after = null) { + return getChildren3(this, type, before, after); } - setKeys(keys = []) { - this.keys = keys; - this._keysMap = {}; - keys.forEach((key2, idx) => { - this._keysMap[key2.id] = idx; - }); + resolve(pos, side = 0) { + return resolveNode3(this, pos, side, false); } - create() { - if (this.isCreated || !this.docs.length) { - return; - } - this.isCreated = true; - if (isString4(this.docs[0])) { - this.docs.forEach((doc, docIndex) => { - this._addString(doc, docIndex); - }); - } else { - this.docs.forEach((doc, docIndex) => { - this._addObject(doc, docIndex); - }); - } - this.norm.clear(); + resolveInner(pos, side = 0) { + return resolveNode3(this, pos, side, true); } - add(doc) { - const idx = this.size(); - if (isString4(doc)) { - this._addString(doc, idx); - } else { - this._addObject(doc, idx); - } + matchContext(context) { + return matchNodeContext3(this, context); } - removeAt(idx) { - this.records.splice(idx, 1); - for (let i4 = idx, len = this.size(); i4 < len; i4 += 1) { - this.records[i4].i -= 1; + enterUnfinishedNodesBefore(pos) { + let scan = this.childBefore(pos), node = this; + while (scan) { + let last = scan.lastChild; + if (!last || last.to != scan.to) + break; + if (last.type.isError && last.from == last.to) { + node = scan; + scan = last.prevSibling; + } else { + scan = last; + } } + return node; } - getValueForItemAtKeyId(item, keyId) { - return item[this._keysMap[keyId]]; + get node() { + return this; } - size() { - return this.records.length; + get next() { + return this.parent; } - _addString(doc, docIndex) { - if (!isDefined(doc) || isBlank(doc)) { - return; - } - let record = { - v: doc, - i: docIndex, - n: this.norm.get(doc) - }; - this.records.push(record); +}; +var TreeNode4 = class extends BaseNode { + constructor(_tree, from, index2, _parent) { + super(); + this._tree = _tree; + this.from = from; + this.index = index2; + this._parent = _parent; } - _addObject(doc, docIndex) { - let record = { i: docIndex, $: {} }; - this.keys.forEach((key2, keyIndex) => { - let value = key2.getFn ? key2.getFn(doc) : this.getFn(doc, key2.path); - if (!isDefined(value)) { - return; - } - if (isArray4(value)) { - let subRecords = []; - const stack = [{ nestedArrIndex: -1, value }]; - while (stack.length) { - const { nestedArrIndex, value: value2 } = stack.pop(); - if (!isDefined(value2)) { + get type() { + return this._tree.type; + } + get name() { + return this._tree.type.name; + } + get to() { + return this.from + this._tree.length; + } + nextChild(i4, dir, pos, side, mode2 = 0) { + for (let parent = this; ; ) { + for (let { children, positions } = parent._tree, e5 = dir > 0 ? children.length : -1; i4 != e5; i4 += dir) { + let next = children[i4], start = positions[i4] + parent.from; + if (!checkSide3(side, pos, start, start + next.length)) + continue; + if (next instanceof TreeBuffer3) { + if (mode2 & IterMode3.ExcludeBuffers) continue; - } - if (isString4(value2) && !isBlank(value2)) { - let subRecord = { - v: value2, - i: nestedArrIndex, - n: this.norm.get(value2) - }; - subRecords.push(subRecord); - } else if (isArray4(value2)) { - value2.forEach((item, k2) => { - stack.push({ - nestedArrIndex: k2, - value: item - }); - }); - } else - ; + let index2 = next.findChild(0, next.buffer.length, dir, pos - start, side); + if (index2 > -1) + return new BufferNode3(new BufferContext3(parent, next, i4, start), null, index2); + } else if (mode2 & IterMode3.IncludeAnonymous || (!next.type.isAnonymous || hasChild3(next))) { + let mounted; + if (!(mode2 & IterMode3.IgnoreMounts) && (mounted = MountedTree.get(next)) && !mounted.overlay) + return new TreeNode4(mounted.tree, start, i4, parent); + let inner = new TreeNode4(next, start, i4, parent); + return mode2 & IterMode3.IncludeAnonymous || !inner.type.isAnonymous ? inner : inner.nextChild(dir < 0 ? next.children.length - 1 : 0, dir, pos, side); } - record.$[keyIndex] = subRecords; - } else if (isString4(value) && !isBlank(value)) { - let subRecord = { - v: value, - n: this.norm.get(value) - }; - record.$[keyIndex] = subRecord; } - }); - this.records.push(record); + if (mode2 & IterMode3.IncludeAnonymous || !parent.type.isAnonymous) + return null; + if (parent.index >= 0) + i4 = parent.index + dir; + else + i4 = dir < 0 ? -1 : parent._parent._tree.children.length; + parent = parent._parent; + if (!parent) + return null; + } } - toJSON() { - return { - keys: this.keys, - records: this.records - }; + get firstChild() { + return this.nextChild(0, 1, 0, 4); } -}; -function createIndex2(keys, docs, { getFn = Config.getFn, fieldNormWeight = Config.fieldNormWeight } = {}) { - const myIndex = new FuseIndex({ getFn, fieldNormWeight }); - myIndex.setKeys(keys.map(createKey)); - myIndex.setSources(docs); - myIndex.create(); - return myIndex; -} -function parseIndex(data2, { getFn = Config.getFn, fieldNormWeight = Config.fieldNormWeight } = {}) { - const { keys, records } = data2; - const myIndex = new FuseIndex({ getFn, fieldNormWeight }); - myIndex.setKeys(keys); - myIndex.setIndexRecords(records); - return myIndex; -} -function computeScore$1(pattern, { - errors = 0, - currentLocation = 0, - expectedLocation = 0, - distance: distance2 = Config.distance, - ignoreLocation = Config.ignoreLocation -} = {}) { - const accuracy = errors / pattern.length; - if (ignoreLocation) { - return accuracy; + get lastChild() { + return this.nextChild(this._tree.children.length - 1, -1, 0, 4); } - const proximity = Math.abs(expectedLocation - currentLocation); - if (!distance2) { - return proximity ? 1 : accuracy; + childAfter(pos) { + return this.nextChild(0, 1, pos, 2); } - return accuracy + proximity / distance2; -} -function convertMaskToIndices(matchmask = [], minMatchCharLength = Config.minMatchCharLength) { - let indices = []; - let start = -1; - let end = -1; - let i4 = 0; - for (let len = matchmask.length; i4 < len; i4 += 1) { - let match2 = matchmask[i4]; - if (match2 && start === -1) { - start = i4; - } else if (!match2 && start !== -1) { - end = i4 - 1; - if (end - start + 1 >= minMatchCharLength) { - indices.push([start, end]); + childBefore(pos) { + return this.nextChild(this._tree.children.length - 1, -1, pos, -2); + } + enter(pos, side, mode2 = 0) { + let mounted; + if (!(mode2 & IterMode3.IgnoreOverlays) && (mounted = MountedTree.get(this._tree)) && mounted.overlay) { + let rPos = pos - this.from; + for (let { from, to: to2 } of mounted.overlay) { + if ((side > 0 ? from <= rPos : from < rPos) && (side < 0 ? to2 >= rPos : to2 > rPos)) + return new TreeNode4(mounted.tree, mounted.overlay[0].from + this.from, -1, this); } - start = -1; } + return this.nextChild(0, 1, pos, side, mode2); } - if (matchmask[i4 - 1] && i4 - start >= minMatchCharLength) { - indices.push([start, i4 - 1]); + nextSignificantParent() { + let val = this; + while (val.type.isAnonymous && val._parent) + val = val._parent; + return val; } - return indices; -} -var MAX_BITS = 32; -function search(text2, pattern, patternAlphabet, { - location = Config.location, - distance: distance2 = Config.distance, - threshold = Config.threshold, - findAllMatches = Config.findAllMatches, - minMatchCharLength = Config.minMatchCharLength, - includeMatches = Config.includeMatches, - ignoreLocation = Config.ignoreLocation -} = {}) { - if (pattern.length > MAX_BITS) { - throw new Error(PATTERN_LENGTH_TOO_LARGE(MAX_BITS)); + get parent() { + return this._parent ? this._parent.nextSignificantParent() : null; } - const patternLen = pattern.length; - const textLen = text2.length; - const expectedLocation = Math.max(0, Math.min(location, textLen)); - let currentThreshold = threshold; - let bestLocation = expectedLocation; - const computeMatches = minMatchCharLength > 1 || includeMatches; - const matchMask = computeMatches ? Array(textLen) : []; - let index2; - while ((index2 = text2.indexOf(pattern, bestLocation)) > -1) { - let score = computeScore$1(pattern, { - currentLocation: index2, - expectedLocation, - distance: distance2, - ignoreLocation - }); - currentThreshold = Math.min(score, currentThreshold); - bestLocation = index2 + patternLen; - if (computeMatches) { - let i4 = 0; - while (i4 < patternLen) { - matchMask[index2 + i4] = 1; - i4 += 1; - } - } + get nextSibling() { + return this._parent && this.index >= 0 ? this._parent.nextChild(this.index + 1, 1, 0, 4) : null; } - bestLocation = -1; - let lastBitArr = []; - let finalScore = 1; - let binMax = patternLen + textLen; - const mask = 1 << patternLen - 1; - for (let i4 = 0; i4 < patternLen; i4 += 1) { - let binMin = 0; - let binMid = binMax; - while (binMin < binMid) { - const score2 = computeScore$1(pattern, { - errors: i4, - currentLocation: expectedLocation + binMid, - expectedLocation, - distance: distance2, - ignoreLocation - }); - if (score2 <= currentThreshold) { - binMin = binMid; - } else { - binMax = binMid; - } - binMid = Math.floor((binMax - binMin) / 2 + binMin); - } - binMax = binMid; - let start = Math.max(1, expectedLocation - binMid + 1); - let finish = findAllMatches ? textLen : Math.min(expectedLocation + binMid, textLen) + patternLen; - let bitArr = Array(finish + 2); - bitArr[finish + 1] = (1 << i4) - 1; - for (let j = finish; j >= start; j -= 1) { - let currentLocation = j - 1; - let charMatch = patternAlphabet[text2.charAt(currentLocation)]; - if (computeMatches) { - matchMask[currentLocation] = +!!charMatch; - } - bitArr[j] = (bitArr[j + 1] << 1 | 1) & charMatch; - if (i4) { - bitArr[j] |= (lastBitArr[j + 1] | lastBitArr[j]) << 1 | 1 | lastBitArr[j + 1]; - } - if (bitArr[j] & mask) { - finalScore = computeScore$1(pattern, { - errors: i4, - currentLocation, - expectedLocation, - distance: distance2, - ignoreLocation - }); - if (finalScore <= currentThreshold) { - currentThreshold = finalScore; - bestLocation = currentLocation; - if (bestLocation <= expectedLocation) { - break; - } - start = Math.max(1, 2 * expectedLocation - bestLocation); - } - } - } - const score = computeScore$1(pattern, { - errors: i4 + 1, - currentLocation: expectedLocation, - expectedLocation, - distance: distance2, - ignoreLocation - }); - if (score > currentThreshold) { - break; - } - lastBitArr = bitArr; + get prevSibling() { + return this._parent && this.index >= 0 ? this._parent.nextChild(this.index - 1, -1, 0, 4) : null; } - const result = { - isMatch: bestLocation >= 0, - score: Math.max(1e-3, finalScore) - }; - if (computeMatches) { - const indices = convertMaskToIndices(matchMask, minMatchCharLength); - if (!indices.length) { - result.isMatch = false; - } else if (includeMatches) { - result.indices = indices; - } + get tree() { + return this._tree; } - return result; -} -function createPatternAlphabet(pattern) { - let mask = {}; - for (let i4 = 0, len = pattern.length; i4 < len; i4 += 1) { - const char = pattern.charAt(i4); - mask[char] = (mask[char] || 0) | 1 << len - i4 - 1; + toTree() { + return this._tree; } - return mask; -} -var BitapSearch = class { - constructor(pattern, { - location = Config.location, - threshold = Config.threshold, - distance: distance2 = Config.distance, - includeMatches = Config.includeMatches, - findAllMatches = Config.findAllMatches, - minMatchCharLength = Config.minMatchCharLength, - isCaseSensitive = Config.isCaseSensitive, - ignoreLocation = Config.ignoreLocation - } = {}) { - this.options = { - location, - threshold, - distance: distance2, - includeMatches, - findAllMatches, - minMatchCharLength, - isCaseSensitive, - ignoreLocation - }; - this.pattern = isCaseSensitive ? pattern : pattern.toLowerCase(); - this.chunks = []; - if (!this.pattern.length) { - return; - } - const addChunk = (pattern2, startIndex) => { - this.chunks.push({ - pattern: pattern2, - alphabet: createPatternAlphabet(pattern2), - startIndex - }); - }; - const len = this.pattern.length; - if (len > MAX_BITS) { - let i4 = 0; - const remainder = len % MAX_BITS; - const end = len - remainder; - while (i4 < end) { - addChunk(this.pattern.substr(i4, MAX_BITS), i4); - i4 += MAX_BITS; - } - if (remainder) { - const startIndex = len - MAX_BITS; - addChunk(this.pattern.substr(startIndex), startIndex); - } - } else { - addChunk(this.pattern, 0); - } + toString() { + return this._tree.toString(); } - searchIn(text2) { - const { isCaseSensitive, includeMatches } = this.options; - if (!isCaseSensitive) { - text2 = text2.toLowerCase(); - } - if (this.pattern === text2) { - let result2 = { - isMatch: true, - score: 0 - }; - if (includeMatches) { - result2.indices = [[0, text2.length - 1]]; - } - return result2; +}; +function getChildren3(node, type, before, after) { + let cur = node.cursor(), result = []; + if (!cur.firstChild()) + return result; + if (before != null) + for (let found = false; !found; ) { + found = cur.type.is(before); + if (!cur.nextSibling()) + return result; } - const { - location, - distance: distance2, - threshold, - findAllMatches, - minMatchCharLength, - ignoreLocation - } = this.options; - let allIndices = []; - let totalScore = 0; - let hasMatches = false; - this.chunks.forEach(({ pattern, alphabet, startIndex }) => { - const { isMatch: isMatch2, score, indices } = search(text2, pattern, alphabet, { - location: location + startIndex, - distance: distance2, - threshold, - findAllMatches, - minMatchCharLength, - includeMatches, - ignoreLocation - }); - if (isMatch2) { - hasMatches = true; - } - totalScore += score; - if (isMatch2 && indices) { - allIndices = [...allIndices, ...indices]; - } - }); - let result = { - isMatch: hasMatches, - score: hasMatches ? totalScore / this.chunks.length : 1 - }; - if (hasMatches && includeMatches) { - result.indices = allIndices; + for (; ; ) { + if (after != null && cur.type.is(after)) + return result; + if (cur.type.is(type)) + result.push(cur.node); + if (!cur.nextSibling()) + return after == null ? result : []; + } +} +function matchNodeContext3(node, context, i4 = context.length - 1) { + for (let p = node.parent; i4 >= 0; p = p.parent) { + if (!p) + return false; + if (!p.type.isAnonymous) { + if (context[i4] && context[i4] != p.name) + return false; + i4--; } - return result; + } + return true; +} +var BufferContext3 = class { + constructor(parent, buffer, index2, start) { + this.parent = parent; + this.buffer = buffer; + this.index = index2; + this.start = start; } }; -var BaseMatch = class { - constructor(pattern) { - this.pattern = pattern; +var BufferNode3 = class extends BaseNode { + get name() { + return this.type.name; } - static isMultiMatch(pattern) { - return getMatch(pattern, this.multiRegex); + get from() { + return this.context.start + this.context.buffer.buffer[this.index + 1]; } - static isSingleMatch(pattern) { - return getMatch(pattern, this.singleRegex); + get to() { + return this.context.start + this.context.buffer.buffer[this.index + 2]; } - search() { + constructor(context, _parent, index2) { + super(); + this.context = context; + this._parent = _parent; + this.index = index2; + this.type = context.buffer.set.types[context.buffer.buffer[index2]]; } -}; -function getMatch(pattern, exp3) { - const matches = pattern.match(exp3); - return matches ? matches[1] : null; -} -var ExactMatch = class extends BaseMatch { - constructor(pattern) { - super(pattern); + child(dir, pos, side) { + let { buffer } = this.context; + let index2 = buffer.findChild(this.index + 4, buffer.buffer[this.index + 3], dir, pos - this.context.start, side); + return index2 < 0 ? null : new BufferNode3(this.context, this, index2); } - static get type() { - return "exact"; + get firstChild() { + return this.child(1, 0, 4); } - static get multiRegex() { - return /^="(.*)"$/; + get lastChild() { + return this.child(-1, 0, 4); } - static get singleRegex() { - return /^=(.*)$/; + childAfter(pos) { + return this.child(1, pos, 2); } - search(text2) { - const isMatch2 = text2 === this.pattern; - return { - isMatch: isMatch2, - score: isMatch2 ? 0 : 1, - indices: [0, this.pattern.length - 1] - }; + childBefore(pos) { + return this.child(-1, pos, -2); } -}; -var InverseExactMatch = class extends BaseMatch { - constructor(pattern) { - super(pattern); + enter(pos, side, mode2 = 0) { + if (mode2 & IterMode3.ExcludeBuffers) + return null; + let { buffer } = this.context; + let index2 = buffer.findChild(this.index + 4, buffer.buffer[this.index + 3], side > 0 ? 1 : -1, pos - this.context.start, side); + return index2 < 0 ? null : new BufferNode3(this.context, this, index2); } - static get type() { - return "inverse-exact"; + get parent() { + return this._parent || this.context.parent.nextSignificantParent(); } - static get multiRegex() { - return /^!"(.*)"$/; + externalSibling(dir) { + return this._parent ? null : this.context.parent.nextChild(this.context.index + dir, dir, 0, 4); } - static get singleRegex() { - return /^!(.*)$/; + get nextSibling() { + let { buffer } = this.context; + let after = buffer.buffer[this.index + 3]; + if (after < (this._parent ? buffer.buffer[this._parent.index + 3] : buffer.buffer.length)) + return new BufferNode3(this.context, this._parent, after); + return this.externalSibling(1); } - search(text2) { - const index2 = text2.indexOf(this.pattern); - const isMatch2 = index2 === -1; - return { - isMatch: isMatch2, - score: isMatch2 ? 0 : 1, - indices: [0, text2.length - 1] - }; + get prevSibling() { + let { buffer } = this.context; + let parentStart = this._parent ? this._parent.index + 4 : 0; + if (this.index == parentStart) + return this.externalSibling(-1); + return new BufferNode3(this.context, this._parent, buffer.findChild(parentStart, this.index, -1, 0, 4)); } -}; -var PrefixExactMatch = class extends BaseMatch { - constructor(pattern) { - super(pattern); + get tree() { + return null; } - static get type() { - return "prefix-exact"; + toTree() { + let children = [], positions = []; + let { buffer } = this.context; + let startI = this.index + 4, endI = buffer.buffer[this.index + 3]; + if (endI > startI) { + let from = buffer.buffer[this.index + 1]; + children.push(buffer.slice(startI, endI, from)); + positions.push(0); + } + return new Tree3(this.type, children, positions, this.to - this.from); } - static get multiRegex() { - return /^\^"(.*)"$/; + toString() { + return this.context.buffer.childString(this.index); } - static get singleRegex() { - return /^\^(.*)$/; +}; +function iterStack(heads) { + if (!heads.length) + return null; + let pick = 0, picked = heads[0]; + for (let i4 = 1; i4 < heads.length; i4++) { + let node = heads[i4]; + if (node.from > picked.from || node.to < picked.to) { + picked = node; + pick = i4; + } } - search(text2) { - const isMatch2 = text2.startsWith(this.pattern); - return { - isMatch: isMatch2, - score: isMatch2 ? 0 : 1, - indices: [0, this.pattern.length - 1] - }; + let next = picked instanceof TreeNode4 && picked.index < 0 ? null : picked.parent; + let newHeads = heads.slice(); + if (next) + newHeads[pick] = next; + else + newHeads.splice(pick, 1); + return new StackIterator(newHeads, picked); +} +var StackIterator = class { + constructor(heads, node) { + this.heads = heads; + this.node = node; } -}; -var InversePrefixExactMatch = class extends BaseMatch { - constructor(pattern) { - super(pattern); + get next() { + return iterStack(this.heads); } - static get type() { - return "inverse-prefix-exact"; +}; +function stackIterator(tree, pos, side) { + let inner = tree.resolveInner(pos, side), layers = null; + for (let scan = inner instanceof TreeNode4 ? inner : inner.context.parent; scan; scan = scan.parent) { + if (scan.index < 0) { + let parent = scan.parent; + (layers || (layers = [inner])).push(parent.resolve(pos, side)); + scan = parent; + } else { + let mount = MountedTree.get(scan.tree); + if (mount && mount.overlay && mount.overlay[0].from <= pos && mount.overlay[mount.overlay.length - 1].to >= pos) { + let root = new TreeNode4(mount.tree, mount.overlay[0].from + scan.from, -1, scan); + (layers || (layers = [inner])).push(resolveNode3(root, pos, side, false)); + } + } } - static get multiRegex() { - return /^!\^"(.*)"$/; + return layers ? iterStack(layers) : inner; +} +var TreeCursor3 = class { + get name() { + return this.type.name; } - static get singleRegex() { - return /^!\^(.*)$/; + constructor(node, mode2 = 0) { + this.mode = mode2; + this.buffer = null; + this.stack = []; + this.index = 0; + this.bufferNode = null; + if (node instanceof TreeNode4) { + this.yieldNode(node); + } else { + this._tree = node.context.parent; + this.buffer = node.context; + for (let n3 = node._parent; n3; n3 = n3._parent) + this.stack.unshift(n3.index); + this.bufferNode = node; + this.yieldBuf(node.index); + } } - search(text2) { - const isMatch2 = !text2.startsWith(this.pattern); - return { - isMatch: isMatch2, - score: isMatch2 ? 0 : 1, - indices: [0, text2.length - 1] - }; + yieldNode(node) { + if (!node) + return false; + this._tree = node; + this.type = node.type; + this.from = node.from; + this.to = node.to; + return true; } -}; -var SuffixExactMatch = class extends BaseMatch { - constructor(pattern) { - super(pattern); + yieldBuf(index2, type) { + this.index = index2; + let { start, buffer } = this.buffer; + this.type = type || buffer.set.types[buffer.buffer[index2]]; + this.from = start + buffer.buffer[index2 + 1]; + this.to = start + buffer.buffer[index2 + 2]; + return true; } - static get type() { - return "suffix-exact"; + yield(node) { + if (!node) + return false; + if (node instanceof TreeNode4) { + this.buffer = null; + return this.yieldNode(node); + } + this.buffer = node.context; + return this.yieldBuf(node.index, node.type); } - static get multiRegex() { - return /^"(.*)"\$$/; + toString() { + return this.buffer ? this.buffer.buffer.childString(this.index) : this._tree.toString(); } - static get singleRegex() { - return /^(.*)\$$/; + enterChild(dir, pos, side) { + if (!this.buffer) + return this.yield(this._tree.nextChild(dir < 0 ? this._tree._tree.children.length - 1 : 0, dir, pos, side, this.mode)); + let { buffer } = this.buffer; + let index2 = buffer.findChild(this.index + 4, buffer.buffer[this.index + 3], dir, pos - this.buffer.start, side); + if (index2 < 0) + return false; + this.stack.push(this.index); + return this.yieldBuf(index2); } - search(text2) { - const isMatch2 = text2.endsWith(this.pattern); - return { - isMatch: isMatch2, - score: isMatch2 ? 0 : 1, - indices: [text2.length - this.pattern.length, text2.length - 1] - }; + firstChild() { + return this.enterChild(1, 0, 4); } -}; -var InverseSuffixExactMatch = class extends BaseMatch { - constructor(pattern) { - super(pattern); + lastChild() { + return this.enterChild(-1, 0, 4); } - static get type() { - return "inverse-suffix-exact"; + childAfter(pos) { + return this.enterChild(1, pos, 2); } - static get multiRegex() { - return /^!"(.*)"\$$/; + childBefore(pos) { + return this.enterChild(-1, pos, -2); } - static get singleRegex() { - return /^!(.*)\$$/; + enter(pos, side, mode2 = this.mode) { + if (!this.buffer) + return this.yield(this._tree.enter(pos, side, mode2)); + return mode2 & IterMode3.ExcludeBuffers ? false : this.enterChild(1, pos, side); } - search(text2) { - const isMatch2 = !text2.endsWith(this.pattern); - return { - isMatch: isMatch2, - score: isMatch2 ? 0 : 1, - indices: [0, text2.length - 1] - }; + parent() { + if (!this.buffer) + return this.yieldNode(this.mode & IterMode3.IncludeAnonymous ? this._tree._parent : this._tree.parent); + if (this.stack.length) + return this.yieldBuf(this.stack.pop()); + let parent = this.mode & IterMode3.IncludeAnonymous ? this.buffer.parent : this.buffer.parent.nextSignificantParent(); + this.buffer = null; + return this.yieldNode(parent); } -}; -var FuzzyMatch = class extends BaseMatch { - constructor(pattern, { - location = Config.location, - threshold = Config.threshold, - distance: distance2 = Config.distance, - includeMatches = Config.includeMatches, - findAllMatches = Config.findAllMatches, - minMatchCharLength = Config.minMatchCharLength, - isCaseSensitive = Config.isCaseSensitive, - ignoreLocation = Config.ignoreLocation - } = {}) { - super(pattern); - this._bitapSearch = new BitapSearch(pattern, { - location, - threshold, - distance: distance2, - includeMatches, - findAllMatches, - minMatchCharLength, - isCaseSensitive, - ignoreLocation - }); - } - static get type() { - return "fuzzy"; + sibling(dir) { + if (!this.buffer) + return !this._tree._parent ? false : this.yield(this._tree.index < 0 ? null : this._tree._parent.nextChild(this._tree.index + dir, dir, 0, 4, this.mode)); + let { buffer } = this.buffer, d4 = this.stack.length - 1; + if (dir < 0) { + let parentStart = d4 < 0 ? 0 : this.stack[d4] + 4; + if (this.index != parentStart) + return this.yieldBuf(buffer.findChild(parentStart, this.index, -1, 0, 4)); + } else { + let after = buffer.buffer[this.index + 3]; + if (after < (d4 < 0 ? buffer.buffer.length : buffer.buffer[this.stack[d4] + 3])) + return this.yieldBuf(after); + } + return d4 < 0 ? this.yield(this.buffer.parent.nextChild(this.buffer.index + dir, dir, 0, 4, this.mode)) : false; } - static get multiRegex() { - return /^"(.*)"$/; + nextSibling() { + return this.sibling(1); } - static get singleRegex() { - return /^(.*)$/; + prevSibling() { + return this.sibling(-1); } - search(text2) { - return this._bitapSearch.searchIn(text2); + atLastNode(dir) { + let index2, parent, { buffer } = this; + if (buffer) { + if (dir > 0) { + if (this.index < buffer.buffer.buffer.length) + return false; + } else { + for (let i4 = 0; i4 < this.index; i4++) + if (buffer.buffer.buffer[i4 + 3] < this.index) + return false; + } + ({ index: index2, parent } = buffer); + } else { + ({ index: index2, _parent: parent } = this._tree); + } + for (; parent; { index: index2, _parent: parent } = parent) { + if (index2 > -1) + for (let i4 = index2 + dir, e5 = dir < 0 ? -1 : parent._tree.children.length; i4 != e5; i4 += dir) { + let child = parent._tree.children[i4]; + if (this.mode & IterMode3.IncludeAnonymous || child instanceof TreeBuffer3 || !child.type.isAnonymous || hasChild3(child)) + return false; + } + } + return true; } -}; -var IncludeMatch = class extends BaseMatch { - constructor(pattern) { - super(pattern); + move(dir, enter) { + if (enter && this.enterChild(dir, 0, 4)) + return true; + for (; ; ) { + if (this.sibling(dir)) + return true; + if (this.atLastNode(dir) || !this.parent()) + return false; + } } - static get type() { - return "include"; + next(enter = true) { + return this.move(1, enter); } - static get multiRegex() { - return /^'"(.*)"$/; + prev(enter = true) { + return this.move(-1, enter); } - static get singleRegex() { - return /^'(.*)$/; + moveTo(pos, side = 0) { + while (this.from == this.to || (side < 1 ? this.from >= pos : this.from > pos) || (side > -1 ? this.to <= pos : this.to < pos)) + if (!this.parent()) + break; + while (this.enterChild(1, pos, side)) { + } + return this; } - search(text2) { - let location = 0; - let index2; - const indices = []; - const patternLen = this.pattern.length; - while ((index2 = text2.indexOf(this.pattern, location)) > -1) { - location = index2 + patternLen; - indices.push([index2, location - 1]); + get node() { + if (!this.buffer) + return this._tree; + let cache2 = this.bufferNode, result = null, depth = 0; + if (cache2 && cache2.context == this.buffer) { + scan: + for (let index2 = this.index, d4 = this.stack.length; d4 >= 0; ) { + for (let c3 = cache2; c3; c3 = c3._parent) + if (c3.index == index2) { + if (index2 == this.index) + return c3; + result = c3; + depth = d4 + 1; + break scan; + } + index2 = this.stack[--d4]; + } } - const isMatch2 = !!indices.length; - return { - isMatch: isMatch2, - score: isMatch2 ? 0 : 1, - indices - }; + for (let i4 = depth; i4 < this.stack.length; i4++) + result = new BufferNode3(this.buffer, result, this.stack[i4]); + return this.bufferNode = new BufferNode3(this.buffer, result, this.index); } -}; -var searchers = [ - ExactMatch, - IncludeMatch, - PrefixExactMatch, - InversePrefixExactMatch, - InverseSuffixExactMatch, - SuffixExactMatch, - InverseExactMatch, - FuzzyMatch -]; -var searchersLen = searchers.length; -var SPACE_RE = / +(?=(?:[^\"]*\"[^\"]*\")*[^\"]*$)/; -var OR_TOKEN = "|"; -function parseQuery(pattern, options = {}) { - return pattern.split(OR_TOKEN).map((item) => { - let query = item.trim().split(SPACE_RE).filter((item2) => item2 && !!item2.trim()); - let results = []; - for (let i4 = 0, len = query.length; i4 < len; i4 += 1) { - const queryItem = query[i4]; - let found = false; - let idx = -1; - while (!found && ++idx < searchersLen) { - const searcher = searchers[idx]; - let token = searcher.isMultiMatch(queryItem); - if (token) { - results.push(new searcher(token, options)); - found = true; + get tree() { + return this.buffer ? null : this._tree._tree; + } + iterate(enter, leave) { + for (let depth = 0; ; ) { + let mustLeave = false; + if (this.type.isAnonymous || enter(this) !== false) { + if (this.firstChild()) { + depth++; + continue; } + if (!this.type.isAnonymous) + mustLeave = true; } - if (found) { - continue; - } - idx = -1; - while (++idx < searchersLen) { - const searcher = searchers[idx]; - let token = searcher.isSingleMatch(queryItem); - if (token) { - results.push(new searcher(token, options)); + for (; ; ) { + if (mustLeave && leave) + leave(this); + mustLeave = this.type.isAnonymous; + if (this.nextSibling()) break; - } + if (!depth) + return; + this.parent(); + depth--; + mustLeave = true; } } - return results; - }); -} -var MultiMatchSet = /* @__PURE__ */ new Set([FuzzyMatch.type, IncludeMatch.type]); -var ExtendedSearch = class { - constructor(pattern, { - isCaseSensitive = Config.isCaseSensitive, - includeMatches = Config.includeMatches, - minMatchCharLength = Config.minMatchCharLength, - ignoreLocation = Config.ignoreLocation, - findAllMatches = Config.findAllMatches, - location = Config.location, - threshold = Config.threshold, - distance: distance2 = Config.distance - } = {}) { - this.query = null; - this.options = { - isCaseSensitive, - includeMatches, - minMatchCharLength, - findAllMatches, - ignoreLocation, - location, - threshold, - distance: distance2 - }; - this.pattern = isCaseSensitive ? pattern : pattern.toLowerCase(); - this.query = parseQuery(this.pattern, this.options); } - static condition(_15, options) { - return options.useExtendedSearch; + matchContext(context) { + if (!this.buffer) + return matchNodeContext3(this.node, context); + let { buffer } = this.buffer, { types: types2 } = buffer.set; + for (let i4 = context.length - 1, d4 = this.stack.length - 1; i4 >= 0; d4--) { + if (d4 < 0) + return matchNodeContext3(this.node, context, i4); + let type = types2[buffer.buffer[this.stack[d4]]]; + if (!type.isAnonymous) { + if (context[i4] && context[i4] != type.name) + return false; + i4--; + } + } + return true; } - searchIn(text2) { - const query = this.query; - if (!query) { - return { - isMatch: false, - score: 1 - }; +}; +function hasChild3(tree) { + return tree.children.some((ch) => ch instanceof TreeBuffer3 || !ch.type.isAnonymous || hasChild3(ch)); +} +function buildTree3(data2) { + var _a; + let { buffer, nodeSet, maxBufferLength = DefaultBufferLength3, reused = [], minRepeatType = nodeSet.types.length } = data2; + let cursor2 = Array.isArray(buffer) ? new FlatBufferCursor3(buffer, buffer.length) : buffer; + let types2 = nodeSet.types; + let contextHash = 0, lookAhead = 0; + function takeNode(parentStart, minPos, children2, positions2, inRepeat, depth) { + let { id: id3, start, end, size: size2 } = cursor2; + let lookAheadAtStart = lookAhead; + while (size2 < 0) { + cursor2.next(); + if (size2 == -1) { + let node2 = reused[id3]; + children2.push(node2); + positions2.push(start - parentStart); + return; + } else if (size2 == -3) { + contextHash = id3; + return; + } else if (size2 == -4) { + lookAhead = id3; + return; + } else { + throw new RangeError(`Unrecognized record size: ${size2}`); + } } - const { includeMatches, isCaseSensitive } = this.options; - text2 = isCaseSensitive ? text2 : text2.toLowerCase(); - let numMatches = 0; - let allIndices = []; - let totalScore = 0; - for (let i4 = 0, qLen = query.length; i4 < qLen; i4 += 1) { - const searchers2 = query[i4]; - allIndices.length = 0; - numMatches = 0; - for (let j = 0, pLen = searchers2.length; j < pLen; j += 1) { - const searcher = searchers2[j]; - const { isMatch: isMatch2, indices, score } = searcher.search(text2); - if (isMatch2) { - numMatches += 1; - totalScore += score; - if (includeMatches) { - const type = searcher.constructor.type; - if (MultiMatchSet.has(type)) { - allIndices = [...allIndices, ...indices]; - } else { - allIndices.push(indices); - } + let type = types2[id3], node, buffer2; + let startPos = start - parentStart; + if (end - start <= maxBufferLength && (buffer2 = findBufferSize(cursor2.pos - minPos, inRepeat))) { + let data3 = new Uint16Array(buffer2.size - buffer2.skip); + let endPos = cursor2.pos - buffer2.size, index2 = data3.length; + while (cursor2.pos > endPos) + index2 = copyToBuffer(buffer2.start, data3, index2); + node = new TreeBuffer3(data3, end - buffer2.start, nodeSet); + startPos = buffer2.start - parentStart; + } else { + let endPos = cursor2.pos - size2; + cursor2.next(); + let localChildren = [], localPositions = []; + let localInRepeat = id3 >= minRepeatType ? id3 : -1; + let lastGroup = 0, lastEnd = end; + while (cursor2.pos > endPos) { + if (localInRepeat >= 0 && cursor2.id == localInRepeat && cursor2.size >= 0) { + if (cursor2.end <= lastEnd - maxBufferLength) { + makeRepeatLeaf(localChildren, localPositions, start, lastGroup, cursor2.end, lastEnd, localInRepeat, lookAheadAtStart); + lastGroup = localChildren.length; + lastEnd = cursor2.end; } + cursor2.next(); + } else if (depth > 2500) { + takeFlatNode(start, endPos, localChildren, localPositions); } else { - totalScore = 0; - numMatches = 0; - allIndices.length = 0; - break; + takeNode(start, endPos, localChildren, localPositions, localInRepeat, depth + 1); } } - if (numMatches) { - let result = { - isMatch: true, - score: totalScore / numMatches - }; - if (includeMatches) { - result.indices = allIndices; - } - return result; + if (localInRepeat >= 0 && lastGroup > 0 && lastGroup < localChildren.length) + makeRepeatLeaf(localChildren, localPositions, start, lastGroup, start, lastEnd, localInRepeat, lookAheadAtStart); + localChildren.reverse(); + localPositions.reverse(); + if (localInRepeat > -1 && lastGroup > 0) { + let make = makeBalanced(type); + node = balanceRange3(type, localChildren, localPositions, 0, localChildren.length, 0, end - start, make, make); + } else { + node = makeTree(type, localChildren, localPositions, end - start, lookAheadAtStart - end); } } - return { - isMatch: false, - score: 1 - }; - } -}; -var registeredSearchers = []; -function register(...args) { - registeredSearchers.push(...args); -} -function createSearcher(pattern, options) { - for (let i4 = 0, len = registeredSearchers.length; i4 < len; i4 += 1) { - let searcherClass = registeredSearchers[i4]; - if (searcherClass.condition(pattern, options)) { - return new searcherClass(pattern, options); - } + children2.push(node); + positions2.push(startPos); } - return new BitapSearch(pattern, options); -} -var LogicalOperator = { - AND: "$and", - OR: "$or" -}; -var KeyType = { - PATH: "$path", - PATTERN: "$val" -}; -var isExpression = (query) => !!(query[LogicalOperator.AND] || query[LogicalOperator.OR]); -var isPath = (query) => !!query[KeyType.PATH]; -var isLeaf = (query) => !isArray4(query) && isObject2(query) && !isExpression(query); -var convertToExplicit = (query) => ({ - [LogicalOperator.AND]: Object.keys(query).map((key2) => ({ - [key2]: query[key2] - })) -}); -function parse5(query, options, { auto = true } = {}) { - const next = (query2) => { - let keys = Object.keys(query2); - const isQueryPath = isPath(query2); - if (!isQueryPath && keys.length > 1 && !isExpression(query2)) { - return next(convertToExplicit(query2)); - } - if (isLeaf(query2)) { - const key2 = isQueryPath ? query2[KeyType.PATH] : keys[0]; - const pattern = isQueryPath ? query2[KeyType.PATTERN] : query2[key2]; - if (!isString4(pattern)) { - throw new Error(LOGICAL_SEARCH_INVALID_QUERY_FOR_KEY(key2)); - } - const obj = { - keyId: createKeyId(key2), - pattern - }; - if (auto) { - obj.searcher = createSearcher(pattern, options); + function takeFlatNode(parentStart, minPos, children2, positions2) { + let nodes = []; + let nodeCount = 0, stopAt = -1; + while (cursor2.pos > minPos) { + let { id: id3, start, end, size: size2 } = cursor2; + if (size2 > 4) { + cursor2.next(); + } else if (stopAt > -1 && start < stopAt) { + break; + } else { + if (stopAt < 0) + stopAt = end - maxBufferLength; + nodes.push(id3, start, end); + nodeCount++; + cursor2.next(); } - return obj; } - let node = { - children: [], - operator: keys[0] - }; - keys.forEach((key2) => { - const value = query2[key2]; - if (isArray4(value)) { - value.forEach((item) => { - node.children.push(next(item)); - }); + if (nodeCount) { + let buffer2 = new Uint16Array(nodeCount * 4); + let start = nodes[nodes.length - 2]; + for (let i4 = nodes.length - 3, j = 0; i4 >= 0; i4 -= 3) { + buffer2[j++] = nodes[i4]; + buffer2[j++] = nodes[i4 + 1] - start; + buffer2[j++] = nodes[i4 + 2] - start; + buffer2[j++] = j; } - }); - return node; - }; - if (!isExpression(query)) { - query = convertToExplicit(query); - } - return next(query); -} -function computeScore(results, { ignoreFieldNorm = Config.ignoreFieldNorm }) { - results.forEach((result) => { - let totalScore = 1; - result.matches.forEach(({ key: key2, norm: norm3, score }) => { - const weight = key2 ? key2.weight : null; - totalScore *= Math.pow( - score === 0 && weight ? Number.EPSILON : score, - (weight || 1) * (ignoreFieldNorm ? 1 : norm3) - ); - }); - result.score = totalScore; - }); -} -function transformMatches(result, data2) { - const matches = result.matches; - data2.matches = []; - if (!isDefined(matches)) { - return; - } - matches.forEach((match2) => { - if (!isDefined(match2.indices) || !match2.indices.length) { - return; - } - const { indices, value } = match2; - let obj = { - indices, - value - }; - if (match2.key) { - obj.key = match2.key.src; - } - if (match2.idx > -1) { - obj.refIndex = match2.idx; - } - data2.matches.push(obj); - }); -} -function transformScore(result, data2) { - data2.score = result.score; -} -function format7(results, docs, { - includeMatches = Config.includeMatches, - includeScore = Config.includeScore -} = {}) { - const transformers = []; - if (includeMatches) - transformers.push(transformMatches); - if (includeScore) - transformers.push(transformScore); - return results.map((result) => { - const { idx } = result; - const data2 = { - item: docs[idx], - refIndex: idx - }; - if (transformers.length) { - transformers.forEach((transformer) => { - transformer(result, data2); - }); - } - return data2; - }); -} -var Fuse = class { - constructor(docs, options = {}, index2) { - this.options = { ...Config, ...options }; - if (this.options.useExtendedSearch && false) { - throw new Error(EXTENDED_SEARCH_UNAVAILABLE); - } - this._keyStore = new KeyStore(this.options.keys); - this.setCollection(docs, index2); - } - setCollection(docs, index2) { - this._docs = docs; - if (index2 && !(index2 instanceof FuseIndex)) { - throw new Error(INCORRECT_INDEX_TYPE); - } - this._myIndex = index2 || createIndex2(this.options.keys, this._docs, { - getFn: this.options.getFn, - fieldNormWeight: this.options.fieldNormWeight - }); - } - add(doc) { - if (!isDefined(doc)) { - return; + children2.push(new TreeBuffer3(buffer2, nodes[2] - start, nodeSet)); + positions2.push(start - parentStart); } - this._docs.push(doc); - this._myIndex.add(doc); } - remove(predicate = () => false) { - const results = []; - for (let i4 = 0, len = this._docs.length; i4 < len; i4 += 1) { - const doc = this._docs[i4]; - if (predicate(doc, i4)) { - this.removeAt(i4); - i4 -= 1; - len -= 1; - results.push(doc); + function makeBalanced(type) { + return (children2, positions2, length2) => { + let lookAhead2 = 0, lastI = children2.length - 1, last, lookAheadProp; + if (lastI >= 0 && (last = children2[lastI]) instanceof Tree3) { + if (!lastI && last.type == type && last.length == length2) + return last; + if (lookAheadProp = last.prop(NodeProp3.lookAhead)) + lookAhead2 = positions2[lastI] + last.length + lookAheadProp; } - } - return results; - } - removeAt(idx) { - this._docs.splice(idx, 1); - this._myIndex.removeAt(idx); + return makeTree(type, children2, positions2, length2, lookAhead2); + }; } - getIndex() { - return this._myIndex; + function makeRepeatLeaf(children2, positions2, base2, i4, from, to2, type, lookAhead2) { + let localChildren = [], localPositions = []; + while (children2.length > i4) { + localChildren.push(children2.pop()); + localPositions.push(positions2.pop() + base2 - from); + } + children2.push(makeTree(nodeSet.types[type], localChildren, localPositions, to2 - from, lookAhead2 - to2)); + positions2.push(from - base2); } - search(query, { limit = -1 } = {}) { - const { - includeMatches, - includeScore, - shouldSort, - sortFn, - ignoreFieldNorm - } = this.options; - let results = isString4(query) ? isString4(this._docs[0]) ? this._searchStringList(query) : this._searchObjectList(query) : this._searchLogical(query); - computeScore(results, { ignoreFieldNorm }); - if (shouldSort) { - results.sort(sortFn); + function makeTree(type, children2, positions2, length2, lookAhead2 = 0, props) { + if (contextHash) { + let pair2 = [NodeProp3.contextHash, contextHash]; + props = props ? [pair2].concat(props) : [pair2]; } - if (isNumber3(limit) && limit > -1) { - results = results.slice(0, limit); + if (lookAhead2 > 25) { + let pair2 = [NodeProp3.lookAhead, lookAhead2]; + props = props ? [pair2].concat(props) : [pair2]; } - return format7(results, this._docs, { - includeMatches, - includeScore - }); - } - _searchStringList(query) { - const searcher = createSearcher(query, this.options); - const { records } = this._myIndex; - const results = []; - records.forEach(({ v: text2, i: idx, n: norm3 }) => { - if (!isDefined(text2)) { - return; - } - const { isMatch: isMatch2, score, indices } = searcher.searchIn(text2); - if (isMatch2) { - results.push({ - item: text2, - idx, - matches: [{ score, value: text2, norm: norm3, indices }] - }); - } - }); - return results; + return new Tree3(type, children2, positions2, length2, props); } - _searchLogical(query) { - const expression = parse5(query, this.options); - const evaluate2 = (node, item, idx) => { - if (!node.children) { - const { keyId, searcher } = node; - const matches = this._findMatches({ - key: this._keyStore.get(keyId), - value: this._myIndex.getValueForItemAtKeyId(item, keyId), - searcher - }); - if (matches && matches.length) { - return [ - { - idx, - item, - matches - } - ]; - } - return []; - } - const res = []; - for (let i4 = 0, len = node.children.length; i4 < len; i4 += 1) { - const child = node.children[i4]; - const result = evaluate2(child, item, idx); - if (result.length) { - res.push(...result); - } else if (node.operator === LogicalOperator.AND) { - return []; + function findBufferSize(maxSize, inRepeat) { + let fork = cursor2.fork(); + let size2 = 0, start = 0, skip = 0, minStart = fork.end - maxBufferLength; + let result = { size: 0, start: 0, skip: 0 }; + scan: + for (let minPos = fork.pos - maxSize; fork.pos > minPos; ) { + let nodeSize4 = fork.size; + if (fork.id == inRepeat && nodeSize4 >= 0) { + result.size = size2; + result.start = start; + result.skip = skip; + skip += 4; + size2 += 4; + fork.next(); + continue; } - } - return res; - }; - const records = this._myIndex.records; - const resultMap = {}; - const results = []; - records.forEach(({ $: item, i: idx }) => { - if (isDefined(item)) { - let expResults = evaluate2(expression, item, idx); - if (expResults.length) { - if (!resultMap[idx]) { - resultMap[idx] = { idx, item, matches: [] }; - results.push(resultMap[idx]); + let startPos = fork.pos - nodeSize4; + if (nodeSize4 < 0 || startPos < minPos || fork.start < minStart) + break; + let localSkipped = fork.id >= minRepeatType ? 4 : 0; + let nodeStart = fork.start; + fork.next(); + while (fork.pos > startPos) { + if (fork.size < 0) { + if (fork.size == -3) + localSkipped += 4; + else + break scan; + } else if (fork.id >= minRepeatType) { + localSkipped += 4; } - expResults.forEach(({ matches }) => { - resultMap[idx].matches.push(...matches); - }); + fork.next(); } + start = nodeStart; + size2 += nodeSize4; + skip += localSkipped; } - }); - return results; + if (inRepeat < 0 || size2 == maxSize) { + result.size = size2; + result.start = start; + result.skip = skip; + } + return result.size > 4 ? result : void 0; } - _searchObjectList(query) { - const searcher = createSearcher(query, this.options); - const { keys, records } = this._myIndex; - const results = []; - records.forEach(({ $: item, i: idx }) => { - if (!isDefined(item)) { - return; - } - let matches = []; - keys.forEach((key2, keyIndex) => { - matches.push( - ...this._findMatches({ - key: key2, - value: item[keyIndex], - searcher - }) - ); - }); - if (matches.length) { - results.push({ - idx, - item, - matches - }); + function copyToBuffer(bufferStart, buffer2, index2) { + let { id: id3, start, end, size: size2 } = cursor2; + cursor2.next(); + if (size2 >= 0 && id3 < minRepeatType) { + let startIndex = index2; + if (size2 > 4) { + let endPos = cursor2.pos - (size2 - 4); + while (cursor2.pos > endPos) + index2 = copyToBuffer(bufferStart, buffer2, index2); } - }); - return results; + buffer2[--index2] = startIndex; + buffer2[--index2] = end - bufferStart; + buffer2[--index2] = start - bufferStart; + buffer2[--index2] = id3; + } else if (size2 == -3) { + contextHash = id3; + } else if (size2 == -4) { + lookAhead = id3; + } + return index2; } - _findMatches({ key: key2, value, searcher }) { - if (!isDefined(value)) { - return []; + let children = [], positions = []; + while (cursor2.pos > 0) + takeNode(data2.start || 0, data2.bufferStart || 0, children, positions, -1, 0); + let length = (_a = data2.length) !== null && _a !== void 0 ? _a : children.length ? positions[0] + children[0].length : 0; + return new Tree3(types2[data2.topID], children.reverse(), positions.reverse(), length); +} +var nodeSizeCache3 = /* @__PURE__ */ new WeakMap(); +function nodeSize3(balanceType, node) { + if (!balanceType.isAnonymous || node instanceof TreeBuffer3 || node.type != balanceType) + return 1; + let size2 = nodeSizeCache3.get(node); + if (size2 == null) { + size2 = 1; + for (let child of node.children) { + if (child.type != balanceType || !(child instanceof Tree3)) { + size2 = 1; + break; + } + size2 += nodeSize3(balanceType, child); } - let matches = []; - if (isArray4(value)) { - value.forEach(({ v: text2, i: idx, n: norm3 }) => { - if (!isDefined(text2)) { - return; - } - const { isMatch: isMatch2, score, indices } = searcher.searchIn(text2); - if (isMatch2) { - matches.push({ - score, - key: key2, - value: text2, - idx, - norm: norm3, - indices - }); + nodeSizeCache3.set(node, size2); + } + return size2; +} +function balanceRange3(balanceType, children, positions, from, to2, start, length, mkTop, mkTree) { + let total = 0; + for (let i4 = from; i4 < to2; i4++) + total += nodeSize3(balanceType, children[i4]); + let maxChild = Math.ceil(total * 1.5 / 8); + let localChildren = [], localPositions = []; + function divide3(children2, positions2, from2, to3, offset2) { + for (let i4 = from2; i4 < to3; ) { + let groupFrom = i4, groupStart = positions2[i4], groupSize = nodeSize3(balanceType, children2[i4]); + i4++; + for (; i4 < to3; i4++) { + let nextSize = nodeSize3(balanceType, children2[i4]); + if (groupSize + nextSize >= maxChild) + break; + groupSize += nextSize; + } + if (i4 == groupFrom + 1) { + if (groupSize > maxChild) { + let only = children2[groupFrom]; + divide3(only.children, only.positions, 0, only.children.length, positions2[groupFrom] + offset2); + continue; } - }); - } else { - const { v: text2, n: norm3 } = value; - const { isMatch: isMatch2, score, indices } = searcher.searchIn(text2); - if (isMatch2) { - matches.push({ score, key: key2, value: text2, norm: norm3, indices }); + localChildren.push(children2[groupFrom]); + } else { + let length2 = positions2[i4 - 1] + children2[i4 - 1].length - groupStart; + localChildren.push(balanceRange3(balanceType, children2, positions2, groupFrom, i4, groupStart, length2, null, mkTree)); } + localPositions.push(groupStart + offset2 - start); } - return matches; } -}; -Fuse.version = "7.0.0"; -Fuse.createIndex = createIndex2; -Fuse.parseIndex = parseIndex; -Fuse.config = Config; -{ - Fuse.parseQuery = parse5; -} -{ - register(ExtendedSearch); + divide3(children, positions, from, to2, 0); + return (mkTop || mkTree)(localChildren, localPositions, length); } +var stoppedInner3 = new NodeProp3({ perNode: true }); -// src/core/react/components/UI/Menus/menu/SelectMenuComponent.tsx -var import_react16 = __toESM(require_react()); - -// src/core/react/components/UI/Menus/menu/SelectMenuInput.tsx -var import_react12 = __toESM(require_react()); -var SIZER_STYLES = { - position: "absolute", - width: 0, - height: 0, - visibility: "hidden", - overflow: "scroll", - whiteSpace: "pre" -}; -var STYLE_PROPS = [ - "fontSize", - "fontFamily", - "fontWeight", - "fontStyle", - "letterSpacing", - "textTransform" -]; -var SelectMenuSearch = (0, import_react12.forwardRef)( - (props, input) => { - const { classNames: classNames13, inputAttributes, inputEventHandlers, index: index2 } = props; - const sizer = (0, import_react12.useRef)(null); - const [inputWidth, setInputWidth] = (0, import_react12.useState)(null); - const [query, setQuery] = (0, import_react12.useState)(""); - const [placeholderText, setPlaceholderText] = (0, import_react12.useState)(""); - (0, import_react12.useEffect)(() => { - copyInputStyles(); - updateInputWidth(); - setTimeout(() => { - input.current?.focus(); - }, 50); - }, []); - (0, import_react12.useEffect)(() => { - if (query !== props.query || placeholderText !== props.placeholderText) { - setQuery(props.query); - setPlaceholderText(props.placeholderText); - updateInputWidth(); - } - }, [props.query, props.placeholderText]); - const copyInputStyles = () => { - const inputStyle = window.getComputedStyle(input.current); - STYLE_PROPS.forEach((prop2) => { - sizer.current.style[prop2] = inputStyle[prop2]; - }); - }; - const updateInputWidth = () => { - const _inputWidth = Math.ceil(sizer.current.scrollWidth) + 2; - if (_inputWidth !== inputWidth) { - setInputWidth(_inputWidth); - } +// node_modules/@lezer/highlight/dist/index.js +var nextTagID2 = 0; +var Tag2 = class { + constructor(set, base2, modified) { + this.set = set; + this.base = base2; + this.modified = modified; + this.id = nextTagID2++; + } + static define(parent) { + if (parent === null || parent === void 0 ? void 0 : parent.base) + throw new Error("Can not derive from a modified tag"); + let tag2 = new Tag2([], null, []); + tag2.set.push(tag2); + if (parent) + for (let t5 of parent.set) + tag2.set.push(t5); + return tag2; + } + static defineModifier() { + let mod3 = new Modifier2(); + return (tag2) => { + if (tag2.modified.indexOf(mod3) > -1) + return tag2; + return Modifier2.get(tag2.base || tag2, tag2.modified.concat(mod3).sort((a4, b2) => a4.id - b2.id)); }; - return /* @__PURE__ */ import_react12.default.createElement("div", { - className: classNames13.searchWrapper - }, /* @__PURE__ */ import_react12.default.createElement("input", { - ...inputAttributes, - ...inputEventHandlers, - ref: input, - value: query, - placeholder: placeholderText, - className: classNames13.searchInput, - role: "combobox", - style: { width: "100%" }, - onClick: (e5) => e5.stopPropagation() - }), /* @__PURE__ */ import_react12.default.createElement("div", { - ref: sizer, - style: SIZER_STYLES - }, query || placeholderText)); } -); -var SelectMenuInput_default = SelectMenuSearch; -SelectMenuSearch.displayName = "SelectMenuSearch"; - -// src/core/react/components/UI/Menus/menu/SelectMenuPill.tsx -var import_react13 = __toESM(require_react()); -var SelectMenuPillComponent = (props) => { - return /* @__PURE__ */ import_react13.default.createElement("button", { - type: "button", - className: props.classNames.selectedTag, - onClick: props.onDelete - }, /* @__PURE__ */ import_react13.default.createElement("span", { - className: props.classNames.selectedTagName - }, props.tag.name)); }; -var SelectMenuPill_default = SelectMenuPillComponent; - -// src/core/react/components/UI/Stickers/Sticker.tsx -var import_react14 = __toESM(require_react()); -var Sticker = (props) => { - return /* @__PURE__ */ import_react14.default.createElement("div", { - className: "mk-sticker", - dangerouslySetInnerHTML: { - __html: props.ui.getSticker(props.sticker) - } - }); +var nextModifierID2 = 0; +var Modifier2 = class { + constructor() { + this.instances = []; + this.id = nextModifierID2++; + } + static get(base2, mods) { + if (!mods.length) + return base2; + let exists = mods[0].instances.find((t5) => t5.base == base2 && sameArray2(mods, t5.modified)); + if (exists) + return exists; + let set = [], tag2 = new Tag2(set, base2, mods); + for (let m4 of mods) + m4.instances.push(tag2); + let configs = powerSet(mods); + for (let parent of base2.set) + if (!parent.modified.length) + for (let config4 of configs) + set.push(Modifier2.get(parent, config4)); + return tag2; + } }; - -// src/core/react/components/UI/Menus/menu/SelectMenuSuggestions.tsx -var import_react15 = __toESM(require_react()); - -// src/core/react/components/UI/Menus/menu/concerns/matchers.js -function escapeForRegExp(string4) { - return string4.replace(/[-\\^$*+?.()|[\]{}]/g, "\\$&"); -} -function matchAny(string4) { - return new RegExp(escapeForRegExp(string4), "gi"); -} -function matchExact(string4) { - return new RegExp(`^${escapeForRegExp(string4)}$`, "i"); -} - -// src/core/react/components/UI/Menus/menu/SelectMenuSuggestions.tsx -function markIt(name317, query) { - const regexp = matchAny(query); - return name317?.replace(regexp, "$&"); +function sameArray2(a4, b2) { + return a4.length == b2.length && a4.every((x2, i4) => x2 == b2[i4]); } -var SelectMenuSuggestionsComponent = (props) => { - const ref2 = (0, import_react15.useRef)(null); - (0, import_react15.useEffect)(() => { - if (props.active) { - ref2?.current?.scrollIntoViewIfNeeded(); - } - }, [props.active]); - return /* @__PURE__ */ import_react15.default.createElement(import_react15.default.Fragment, null, props.item.icon && /* @__PURE__ */ import_react15.default.createElement(Sticker, { - ui: props.ui, - sticker: props.item.icon - }), /* @__PURE__ */ import_react15.default.createElement("div", { - ref: ref2, - className: "mk-menu-options-inner" - }, props.item.onToggle && /* @__PURE__ */ import_react15.default.createElement("div", null, "Toggle"), /* @__PURE__ */ import_react15.default.createElement("span", { - style: props.item.color?.length > 0 ? { - background: props.item.color, - padding: "2px 4px", - borderRadius: "4px", - color: props.item.color == "var(--mk-color-none)" ? "inherit" : "var(--mk-color-white)" - } : {}, - dangerouslySetInnerHTML: { - __html: markIt(props.item.name, props.query) +function powerSet(array) { + let sets = [[]]; + for (let i4 = 0; i4 < array.length; i4++) { + for (let j = 0, e5 = sets.length; j < e5; j++) { + sets.push(sets[j].concat(array[i4])); } - }), props.item.description && /* @__PURE__ */ import_react15.default.createElement("span", { - "aria-label": props.item.description, - className: "mk-menu-options-description", - dangerouslySetInnerHTML: { - __html: markIt(props.item.description, props.query) + } + return sets.sort((a4, b2) => b2.length - a4.length); +} +var ruleNodeProp2 = new NodeProp3(); +var Rule2 = class { + constructor(tags3, mode2, context, next) { + this.tags = tags3; + this.mode = mode2; + this.context = context; + this.next = next; + } + get opaque() { + return this.mode == 0; + } + get inherit() { + return this.mode == 1; + } + sort(other) { + if (!other || other.depth < this.depth) { + this.next = other; + return this; } - })), props.item.type == 1 /* Disclosure */ && /* @__PURE__ */ import_react15.default.createElement("span", null, props.item.value), props.item.type == 3 /* Radio */ && props.item.value && /* @__PURE__ */ import_react15.default.createElement("div", { - className: "mk-icon-small", - dangerouslySetInnerHTML: { - __html: props.ui.getSticker("ui//check") - } - }), props.item.onMoreOptions || props.onMoreOption && props.item.removeable ? /* @__PURE__ */ import_react15.default.createElement("div", { - onClick: (e5) => { - e5.stopPropagation(); - e5.preventDefault(); - props.item.onMoreOptions ? props.item.onMoreOptions(e5) : props.onMoreOption(e5, props.item.value); - }, - className: "mk-icon-small", - dangerouslySetInnerHTML: { - __html: props.ui.getSticker("ui//options") - } - }) : null, props.item.removeable && props.onDeleteOption && /* @__PURE__ */ import_react15.default.createElement("div", { - onClick: (e5) => { - e5.stopPropagation(); - e5.preventDefault(); - props.onDeleteOption(props.item.value); - }, - className: "mk-icon-small", - dangerouslySetInnerHTML: { - __html: props.ui.getSticker("ui//close") - } - }), props.item.type == 6 /* Submenu */ && /* @__PURE__ */ import_react15.default.createElement("div", { - className: "mk-icon-small", - dangerouslySetInnerHTML: { - __html: props.ui.getSticker("ui//chevron-right") - } - })); -}; -var SelectMenuInput = (props) => { - const [value, setValue] = (0, import_react15.useState)(props.value); - return /* @__PURE__ */ import_react15.default.createElement("input", { - type: "text", - value, - onKeyDown: (e5) => { - if (e5.key == "Enter") { - props.setValue(value); - } - }, - onMouseDown: (e5) => e5.stopPropagation(), - onClick: (e5) => e5.stopPropagation(), - onFocus: (e5) => { - e5.stopPropagation(); - }, - onChange: (e5) => setValue(e5.target.value), - onBlur: (e5) => props.setValue(value) - }); + other.next = this.sort(other.next); + return other; + } + get depth() { + return this.context ? this.context.length : 0; + } }; -var SelectMenuSuggestions = (props) => { - const options = props.options.map((item, index2) => { - const key2 = `${props.id}-${index2}`; - const className = item.type == -1 /* Separator */ ? "mk-menu-separator" : item.type == 2 /* Input */ ? "mk-menu-input" : item.type == 5 /* Custom */ ? "mk-menu-custom" : `mk-menu-option ${props.index === index2 && props.classNames.suggestionActive} ${item.disabled && props.classNames.suggestionDisabled}`; - return /* @__PURE__ */ import_react15.default.createElement("div", { - ref: (ref2) => { - if (props.refs?.current) - props.refs.current[index2] = ref2; - }, - onMouseDown: (e5) => { - if (!props.isDisclosureMenu) - e5.stopPropagation(); - e5.preventDefault(); - }, - onClick: (e5) => { - if (item.onSubmenu && props.openSubmenu) { - const el = props.refs?.current[index2].getBoundingClientRect(); - props.openSubmenu(item.onSubmenu(el)); - } else if (item.onClick) { - item.onClick(e5); - if (item.type != 6 /* Submenu */ && item.type != 1 /* Disclosure */) { - props.hide(); - } - } else { - if (item.type == null || item.type == 0 /* Option */ || item.type == 1 /* Disclosure */) { - props.selectOption(item, { - ctrlKey: e5.ctrlKey, - metaKey: e5.metaKey, - altKey: e5.altKey, - shiftKey: e5.shiftKey, - doubleClick: e5.detail == 2 - }); - if (!props.isDisclosureMenu) - e5.stopPropagation(); +Rule2.empty = new Rule2([], 2, null); +function tagHighlighter2(tags3, options) { + let map4 = /* @__PURE__ */ Object.create(null); + for (let style of tags3) { + if (!Array.isArray(style.tag)) + map4[style.tag.id] = style.class; + else + for (let tag2 of style.tag) + map4[tag2.id] = style.class; + } + let { scope, all: all2 = null } = options || {}; + return { + style: (tags4) => { + let cls = all2; + for (let tag2 of tags4) { + for (let sub2 of tag2.set) { + let tagClass = map4[sub2.id]; + if (tagClass) { + cls = cls ? cls + " " + tagClass : tagClass; + break; } } - }, - id: key2, - key: key2, - className - }, item.type == -1 /* Separator */ ? /* @__PURE__ */ import_react15.default.createElement(import_react15.default.Fragment, null) : item.type == -2 /* Section */ ? /* @__PURE__ */ import_react15.default.createElement("div", { - className: "mk-menu-options-section" - }, item.name) : item.type == 2 /* Input */ ? /* @__PURE__ */ import_react15.default.createElement(SelectMenuInput, { - value: item.value, - setValue: item.onValueChange - }) : item.type == 5 /* Custom */ ? /* @__PURE__ */ import_react15.default.createElement(item.fragment, { - hide: props.hide - }) : /* @__PURE__ */ import_react15.default.createElement(SelectMenuSuggestionsComponent, { - ui: props.ui, - item, - query: props.query, - active: index2 == props.index, - onMoreOption: props.moreOption, - onDeleteOption: props.deleteOption - })); - }); - return /* @__PURE__ */ import_react15.default.createElement("div", { - className: "mk-menu-suggestions" - }, options, props.query && props.allowNew && /* @__PURE__ */ import_react15.default.createElement("div", { - className: "mk-menu-option", - onMouseDown: (e5) => e5.preventDefault(), - onClick: (e5) => props.selectOption( - { name: props.query, value: props.query }, - { - ctrlKey: e5.ctrlKey, - metaKey: e5.metaKey, - altKey: e5.altKey, - shiftKey: e5.shiftKey } - ) - }, /* @__PURE__ */ import_react15.default.createElement("div", { - className: "mk-sticker", - dangerouslySetInnerHTML: { - __html: props.ui.getSticker("ui//plus") - } - }), /* @__PURE__ */ import_react15.default.createElement("div", { - className: "mk-menu-options-inner" - }, props.addKeyword ?? "Add", " ", props.query))); + return cls; + }, + scope + }; +} +var t3 = Tag2.define; +var comment2 = t3(); +var name316 = t3(); +var typeName3 = t3(name316); +var propertyName2 = t3(name316); +var literal3 = t3(); +var string3 = t3(literal3); +var number3 = t3(literal3); +var content2 = t3(); +var heading2 = t3(content2); +var keyword2 = t3(); +var operator2 = t3(); +var punctuation2 = t3(); +var bracket2 = t3(punctuation2); +var meta2 = t3(); +var tags2 = { + comment: comment2, + lineComment: t3(comment2), + blockComment: t3(comment2), + docComment: t3(comment2), + name: name316, + variableName: t3(name316), + typeName: typeName3, + tagName: t3(typeName3), + propertyName: propertyName2, + attributeName: t3(propertyName2), + className: t3(name316), + labelName: t3(name316), + namespace: t3(name316), + macroName: t3(name316), + literal: literal3, + string: string3, + docString: t3(string3), + character: t3(string3), + attributeValue: t3(string3), + number: number3, + integer: t3(number3), + float: t3(number3), + bool: t3(literal3), + regexp: t3(literal3), + escape: t3(literal3), + color: t3(literal3), + url: t3(literal3), + keyword: keyword2, + self: t3(keyword2), + null: t3(keyword2), + atom: t3(keyword2), + unit: t3(keyword2), + modifier: t3(keyword2), + operatorKeyword: t3(keyword2), + controlKeyword: t3(keyword2), + definitionKeyword: t3(keyword2), + moduleKeyword: t3(keyword2), + operator: operator2, + derefOperator: t3(operator2), + arithmeticOperator: t3(operator2), + logicOperator: t3(operator2), + bitwiseOperator: t3(operator2), + compareOperator: t3(operator2), + updateOperator: t3(operator2), + definitionOperator: t3(operator2), + typeOperator: t3(operator2), + controlOperator: t3(operator2), + punctuation: punctuation2, + separator: t3(punctuation2), + bracket: bracket2, + angleBracket: t3(bracket2), + squareBracket: t3(bracket2), + paren: t3(bracket2), + brace: t3(bracket2), + content: content2, + heading: heading2, + heading1: t3(heading2), + heading2: t3(heading2), + heading3: t3(heading2), + heading4: t3(heading2), + heading5: t3(heading2), + heading6: t3(heading2), + contentSeparator: t3(content2), + list: t3(content2), + quote: t3(content2), + emphasis: t3(content2), + strong: t3(content2), + link: t3(content2), + monospace: t3(content2), + strikethrough: t3(content2), + inserted: t3(), + deleted: t3(), + changed: t3(), + invalid: t3(), + meta: meta2, + documentMeta: t3(meta2), + annotation: t3(meta2), + processingInstruction: t3(meta2), + definition: Tag2.defineModifier(), + constant: Tag2.defineModifier(), + function: Tag2.defineModifier(), + standard: Tag2.defineModifier(), + local: Tag2.defineModifier(), + special: Tag2.defineModifier() }; -var SelectMenuSuggestions_default = SelectMenuSuggestions; +var classHighlighter2 = tagHighlighter2([ + { tag: tags2.link, class: "tok-link" }, + { tag: tags2.heading, class: "tok-heading" }, + { tag: tags2.emphasis, class: "tok-emphasis" }, + { tag: tags2.strong, class: "tok-strong" }, + { tag: tags2.keyword, class: "tok-keyword" }, + { tag: tags2.atom, class: "tok-atom" }, + { tag: tags2.bool, class: "tok-bool" }, + { tag: tags2.url, class: "tok-url" }, + { tag: tags2.labelName, class: "tok-labelName" }, + { tag: tags2.inserted, class: "tok-inserted" }, + { tag: tags2.deleted, class: "tok-deleted" }, + { tag: tags2.literal, class: "tok-literal" }, + { tag: tags2.string, class: "tok-string" }, + { tag: tags2.number, class: "tok-number" }, + { tag: [tags2.regexp, tags2.escape, tags2.special(tags2.string)], class: "tok-string2" }, + { tag: tags2.variableName, class: "tok-variableName" }, + { tag: tags2.local(tags2.variableName), class: "tok-variableName tok-local" }, + { tag: tags2.definition(tags2.variableName), class: "tok-variableName tok-definition" }, + { tag: tags2.special(tags2.variableName), class: "tok-variableName2" }, + { tag: tags2.definition(tags2.propertyName), class: "tok-propertyName tok-definition" }, + { tag: tags2.typeName, class: "tok-typeName" }, + { tag: tags2.namespace, class: "tok-namespace" }, + { tag: tags2.className, class: "tok-className" }, + { tag: tags2.macroName, class: "tok-macroName" }, + { tag: tags2.propertyName, class: "tok-propertyName" }, + { tag: tags2.operator, class: "tok-operator" }, + { tag: tags2.comment, class: "tok-comment" }, + { tag: tags2.meta, class: "tok-meta" }, + { tag: tags2.invalid, class: "tok-invalid" }, + { tag: tags2.punctuation, class: "tok-punctuation" } +]); -// src/core/react/components/UI/Menus/menu/concerns/focusNextElement.js -function focusNextElement(scope, currentTarget) { - const interactiveEls = scope.querySelectorAll("a,button,input"); - const currentEl = Array.prototype.findIndex.call( - interactiveEls, - (element) => element === currentTarget - ); - const nextEl = interactiveEls[currentEl - 1] || interactiveEls[currentEl + 1]; - if (nextEl) { - nextEl.focus(); +// node_modules/@uiw/codemirror-themes/esm/index.js +var import_view3 = require("@codemirror/view"); +var import_language3 = require("@codemirror/language"); +var createTheme = (_ref) => { + var { + theme, + settings = {}, + styles: styles2 = [] + } = _ref; + var themeOptions = { + ".cm-gutters": {} + }; + var baseStyle = {}; + if (settings.background) { + baseStyle.backgroundColor = settings.background; } -} - -// src/core/react/components/UI/Menus/menu/SelectMenuComponent.tsx -var KEYS = { - ENTER: "Enter", - TAB: "Tab", - BACKSPACE: "Backspace", - UP_ARROW: "ArrowUp", - UP_ARROW_COMPAT: "Up", - DOWN_ARROW: "ArrowDown", - DOWN_ARROW_COMPAT: "Down" -}; -var CLASS_NAMES = { - root: "mk-menu-container", - rootFocused: "mk-focused", - selected: "mk-menu-input-wrapper", - selectedTagWrapper: "mk-menu-selected-tag-wrapper", - selectedTag: "mk-menu-selected-tag", - selectedTagName: "mk-menu-selected-tag-name", - search: "mk-menu-search", - searchWrapper: "mk-menu-search-container", - searchInput: "mk-menu-search-input", - suggestions: "mk-menu-suggestions", - suggestionActive: "mk-active", - suggestionDisabled: "mk-disabled" -}; -var defaultProps = { - ui: null, - id: "SelectMenu", - tags: [], - hide: () => null, - suggestionsOnly: false, - placeholderText: i18n_default.labels.optionItemSelectPlaceholder, - noSuggestionsText: null, - newTagText: null, - suggestions: [], - suggestionsFilter: defaultSuggestionsFilter, - suggestionsTransform: null, - classNames: CLASS_NAMES, - delimiters: [KEYS.ENTER], - minQueryLength: 2, - maxSuggestionsLength: 8, - inputAttributes: {} -}; -var findMatchIndex = (options, query) => { - return options.findIndex((option) => matchExact(query).test(option.name)); -}; -var pressDelimiter = (props, query, index2, options, addTag2, modifiers) => { - if (query.length >= props.minQueryLength) { - const match2 = findMatchIndex(options, query); - const _index = index2 === -1 ? match2 : index2; - const tag2 = _index > -1 ? options[_index] : null; - if (tag2) { - addTag2(tag2, modifiers); - } else { - addTag2({ name: query, value: query }, modifiers); - } + if (settings.backgroundImage) { + baseStyle.backgroundImage = settings.backgroundImage; } -}; -function defaultSuggestionsFilter(item, query) { - const regexp = matchAny(query); - return regexp.test(item.name); -} -function getOptions2(props, query, section) { - let options; - let suggestions = props.suggestions; - if (section.length > 0) { - suggestions = props.suggestions.filter((f2) => f2.section == section); + if (settings.foreground) { + baseStyle.color = settings.foreground; } - const fuseOptions = { - threshold: 0, - ignoreLocation: true, - keys: ["name", "value"] - }; - const fuse = new Fuse(suggestions, fuseOptions); - options = query.length == 0 ? suggestions : fuse.search(query).map((result) => result.item); - options = options.slice(0, props.maxSuggestionsLength); - if (props.newTagText && findMatchIndex(options, query) === -1) { - options.push({ id: 0, name: query, value: query }); - } else if (props.noSuggestionsText && options.length === 0) { - options.push({ - id: 0, - name: props.noSuggestionsText, - value: "", - disabled: true - }); + if (settings.background || settings.foreground) { + themeOptions["&"] = baseStyle; } - return options; -} -var SelectMenuComponent = import_react16.default.forwardRef( - (_props, ref2) => { - const props = { ...defaultProps, ..._props }; - const [options, setOptions] = (0, import_react16.useState)([]); - const refs = (0, import_react16.useRef)([]); - const sections = (0, import_react16.useMemo)(() => { - if (!props.showSections) - return []; - return [ - { - name: "All", - value: "" - }, - ...props.sections ?? uniq(props.suggestions.map((f2) => f2.section)).filter((f2) => f2) - ]; - }, [props.showSections, props.sections, props.suggestions]); - const inputRef = (0, import_react16.useRef)(null); - const [section, setSection] = (0, import_react16.useState)(""); - const [query, setQuery] = (0, import_react16.useState)(""); - const [focused, setFocused] = (0, import_react16.useState)(false); - const [index2, setIndex] = (0, import_react16.useState)(0); - const onComposition = (0, import_react16.useRef)(false); - (0, import_react16.useEffect)(() => { - if (ref2) { - ref2.current = () => { - if (!focused) { - inputRef?.current?.focus(); - setFocused(true); - return false; - } - return true; - }; - } - }, [focused]); - (0, import_react16.useEffect)(() => { - if (query.length == 0 && props.defaultSuggestions) { - setOptions(props.defaultSuggestions); - return; - } - setOptions(getOptions2(props, query, section)); - }, [query, props.defaultSuggestions, section, props.suggestions]); - const container = (0, import_react16.useRef)(null); - const onInput = (e5) => { - if (e5.type === "compositionstart") { - onComposition.current = true; - return; - } - if (e5.type === "compositionend") { - onComposition.current = false; - } - if (onComposition.current) { - return; - } - const _query = e5.target.value; - if (props.onInput) { - props.onInput(_query); - } - if (_query.length === query.length + 1 && props.delimiters.indexOf(query.slice(-1)) > -1) { - pressDelimiter(props, query, index2, options, addTag2, {}); - } else if (_query !== query) { - setQuery(_query); - } - }; - const onKeyDown = (e5) => { - if (props.delimiters.indexOf(e5.key) > -1) { - if (query || index2 > -1) { - e5.preventDefault(); - } - pressDelimiter(props, query, index2, options, addTag2, { - ctrlKey: e5.ctrlKey, - metaKey: e5.metaKey, - altKey: e5.altKey, - shiftKey: e5.shiftKey - }); - } - if (e5.key == "Escape") { - return; - } - if (e5.key === KEYS.TAB) { - pressTabKey(e5); - } - if (e5.key === KEYS.BACKSPACE) { - pressBackspaceKey(); - } - if (e5.key === KEYS.UP_ARROW || e5.key === KEYS.UP_ARROW_COMPAT) { - pressUpKey(e5); - } - if (e5.key === KEYS.DOWN_ARROW || e5.key === KEYS.DOWN_ARROW_COMPAT) { - pressDownKey(e5); - } - e5.stopPropagation(); - }; - const onBlur = () => { - setFocused(false); - if (props.onBlur) { - props.onBlur(); - } - }; - const onFocus = () => { - setFocused(true); - if (props.onFocus) { - props.onFocus(); - } - }; - const onDeleteTag = (index3, event) => { - if (container.current) { - focusNextElement(container.current, event.currentTarget); - } - deleteTag(index3); - }; - const addTag2 = (tag2, modifiers) => { - if (tag2.disabled) { - return; - } - if (props.onValidate && !props.onValidate(tag2)) { - return; - } - props.onAddition(tag2, modifiers); - clearInput(); - }; - const deleteTag = (i4) => { - props.onDelete(i4); + if (settings.fontFamily) { + themeOptions["&.cm-editor .cm-scroller"] = { + fontFamily: settings.fontFamily }; - const clearInput = () => { - setQuery(""); - setIndex(-1); + } + if (settings.gutterBackground) { + themeOptions[".cm-gutters"].backgroundColor = settings.gutterBackground; + } + if (settings.gutterForeground) { + themeOptions[".cm-gutters"].color = settings.gutterForeground; + } + if (settings.gutterBorder) { + themeOptions[".cm-gutters"].borderRightColor = settings.gutterBorder; + } + if (settings.caret) { + themeOptions[".cm-content"] = { + caretColor: settings.caret }; - const clearSelectedIndex = () => { - setIndex(-1); + themeOptions[".cm-cursor, .cm-dropCursor"] = { + borderLeftColor: settings.caret }; - const pressUpKey = (e5) => { - e5.preventDefault(); - const size2 = options.length - 1; - const newIndex = index2 <= 0 ? size2 : index2 - 1; - if (options[newIndex].disabled) { - setIndex(newIndex <= 0 ? size2 : newIndex - 1); - } else { - setIndex(newIndex); - } + } + var activeLineGutterStyle = {}; + if (settings.gutterActiveForeground) { + activeLineGutterStyle.color = settings.gutterActiveForeground; + } + if (settings.lineHighlight) { + themeOptions[".cm-activeLine"] = { + backgroundColor: settings.lineHighlight }; - const pressDownKey = (e5) => { - e5.preventDefault(); - const size2 = options.length - 1; - const newIndex = index2 >= size2 ? 0 : index2 + 1; - if (options[newIndex].disabled) { - setIndex(newIndex >= size2 ? 0 : newIndex + 1); - } else { - setIndex(newIndex); - } + activeLineGutterStyle.backgroundColor = settings.lineHighlight; + } + themeOptions[".cm-activeLineGutter"] = activeLineGutterStyle; + if (settings.selection) { + themeOptions["&.cm-focused .cm-selectionBackground, & .cm-line::selection, & .cm-selectionLayer .cm-selectionBackground, .cm-content ::selection"] = { + background: settings.selection + " !important" }; - function pressBackspaceKey() { - if (!query.length) { - deleteTag(props.tags.length - 1); - } - } - function pressTabKey(e5) { - if (props.showSections) { - e5.preventDefault(); - e5.stopPropagation(); - setSection((p) => { - const sectionIndex = sections.findIndex((g) => g.value == p); - if (e5.shiftKey) { - if (sectionIndex == 0) { - return p; - } - if (props.onSelectSection) { - props.onSelectSection(sections[sectionIndex - 1].value); - } - return sections[sectionIndex - 1].value; - } - if (sectionIndex == sections.length - 1) { - return p; - } - if (props.onSelectSection) { - props.onSelectSection(sections[sectionIndex + 1].value); - } - return sections[sectionIndex + 1].value; - }); - } - } - const focusInput = () => { - inputRef.current.focus(); + } + if (settings.selectionMatch) { + themeOptions["& .cm-selectionMatch"] = { + backgroundColor: settings.selectionMatch }; - const inputEventHandlers = { - onChange: onInput, - onBlur, - onFocus, - onInput: () => { + } + var themeExtension = import_view3.EditorView.theme(themeOptions, { + dark: theme === "dark" + }); + var highlightStyle = import_language3.HighlightStyle.define(styles2); + var extension = [themeExtension, (0, import_language3.syntaxHighlighting)(highlightStyle)]; + return extension; +}; + +// node_modules/@uiw/codemirror-theme-abcdef/esm/index.js +var defaultSettingsAbcdef = { + background: "#0f0f0f", + foreground: "#defdef", + caret: "#00FF00", + selection: "#515151", + selectionMatch: "#515151", + gutterBackground: "#555", + gutterForeground: "#FFFFFF", + lineHighlight: "#0a6bcb3d" +}; +var abcdefInit = (options) => { + var { + theme = "dark", + settings = {}, + styles: styles2 = [] + } = options || {}; + return createTheme({ + theme, + settings: _extends({}, defaultSettingsAbcdef, settings), + styles: [ + { + tag: tags2.keyword, + color: "darkgoldenrod", + fontWeight: "bold" }, - onKeyDown, - onCompositionEnd: onInput, - onCompositionStart: onInput - }; - (0, import_react16.useEffect)(() => { - props.ui.inputManager.on("keydown", onKeyDown); - return () => { - props.ui.inputManager.off("keydown", onKeyDown); - }; - }, [options, index2]); - const expanded = focused && query.length >= props.minQueryLength; - const classNames13 = Object.assign({}, CLASS_NAMES, props.classNames); - if (props.wrapperClass) { - classNames13.root = `${classNames13.root} ${props.wrapperClass}`; - } - const rootClassNames = [classNames13.root]; - focused && rootClassNames.push(classNames13.rootFocused); - const submenuRef = (0, import_react16.useRef)(null); - const openSubmenu = (menu) => { - if (submenuRef.current) { - submenuRef.current.hide(); - } - submenuRef.current = menu; - }; - return /* @__PURE__ */ import_react16.default.createElement("div", { - ref: container, - className: rootClassNames.join(" "), - style: !props.suggestionsOnly ? { - "--mk-menu-max-height": "200px" - } : {} - }, !props.suggestionsOnly ? /* @__PURE__ */ import_react16.default.createElement("div", { - className: classNames13.selected, - "aria-relevant": "additions removals", - "aria-live": "polite" - }, props.tags.length > 0 && /* @__PURE__ */ import_react16.default.createElement("div", { - className: classNames13.selectedTagWrapper - }, props.tags.map((tag2, i4) => /* @__PURE__ */ import_react16.default.createElement(SelectMenuPill_default, { - key: i4, - tag: tag2, - classNames: classNames13, - onDelete: (e5) => onDeleteTag(i4, e5) - }))), /* @__PURE__ */ import_react16.default.createElement("div", { - className: classNames13.search - }, /* @__PURE__ */ import_react16.default.createElement(SelectMenuInput_default, { - ui: props.ui, - ref: inputRef, - query, - index: index2, - id: props.id, - classNames: classNames13, - inputAttributes: props.inputAttributes, - inputEventHandlers, - expanded, - placeholderText: props.placeholderText - }))) : null, props.showSections ? /* @__PURE__ */ import_react16.default.createElement("div", { - className: "mk-menu-sections" - }, sections.map((f2, i4) => /* @__PURE__ */ import_react16.default.createElement("div", { - key: i4, - onClick: (e5) => { - e5.stopPropagation(); - setSection(f2.value); + { + tag: tags2.atom, + color: "#77F" }, - className: `${section == f2.value ? "is-active" : ""} mk-menu-section` - }, f2.name == "" ? i18n_default.labels.all : f2.name))) : /* @__PURE__ */ import_react16.default.createElement(import_react16.default.Fragment, null), options.length || props.allowNew ? /* @__PURE__ */ import_react16.default.createElement(SelectMenuSuggestions_default, { - ui: props.ui, - hide: () => { - props.hide(); + { + tag: tags2.comment, + color: "#7a7b7c", + fontStyle: "italic" }, - addKeyword: props.addKeyword, - refs, - options, - query, - setIndex, - index: index2, - id: props.id, - classNames: classNames13, - expanded, - selectOption: addTag2, - allowNew: props.allowNew, - moreOption: props.onMoreOption, - deleteOption: props.onDeleteOption, - isDisclosureMenu: props.isDisclosure, - openSubmenu - }) : null, props.previewComponent); - } -); -SelectMenuComponent.displayName = "SelectMenuComponent"; -var SelectMenuComponent_default = SelectMenuComponent; - -// src/core/react/components/UI/Menus/menu/SelectMenu.tsx -var SelectMenu = import_react17.default.forwardRef( - (props, ref2) => { - const initialOptions = props.options.map((o2, i4) => { - return { - ...o2, - id: i4 + 1 - }; - }); - (0, import_react17.useEffect)(() => { - setSuggestions( - props.options.map((o2, i4) => { - return { - ...o2, - id: i4 + 1 - }; - }) - ); - }, [props.options]); - const [suggestions, setSuggestions] = (0, import_react17.useState)(initialOptions); - const [tags3, setTags] = (0, import_react17.useState)( - props.value.map( - (v2) => initialOptions.find((f2) => f2.value == v2) ?? { - id: 0, - name: v2, - value: v2 - } - ) - ); - const onDelete = (0, import_react17.useCallback)( - (tagIndex) => { - const newTags = tags3.filter((_15, i4) => i4 !== tagIndex); - setTags(newTags); - if (props.saveOptions) - props.saveOptions( - suggestions.map((f2) => f2.value), - newTags.map((f2) => f2.value), - false - ); + { + tag: tags2.number, + color: "violet" }, - [suggestions, tags3, props] - ); - const onDeleteOption = (0, import_react17.useCallback)( - (removeTag) => { - const newSuggestions = suggestions.filter((f2) => f2.value != removeTag); - const newTags = tags3.filter((f2) => f2.value != removeTag); - setSuggestions(newSuggestions); - setTags(newTags); - if (props.removeOption) - props.removeOption(removeTag); - props.hide(); + { + tag: tags2.definition(tags2.variableName), + color: "#fffabc" }, - [tags3, suggestions, props] - ); - const onAddition = (0, import_react17.useCallback)( - (newTag, modifiers) => { - let tag2 = newTag; - let newSuggestions = suggestions; - let newTags = tags3; - if (!suggestions.find((s4) => s4.value == newTag.value)) { - tag2 = { - id: suggestions.length + 1, - name: newTag.name, - value: newTag.value ?? newTag.name - }; - newSuggestions = [...suggestions, tag2]; - setSuggestions(newSuggestions); - } - if (props.multi) { - if (!tags3.find((t5) => t5.value == tag2.value)) { - newTags = [...tags3, tag2]; - setTags(newTags); - } - } else { - newTags = [tag2]; - setTags(newTags); - } - if (props.saveOptions) - props.saveOptions( - newSuggestions.map((f2) => f2.value), - newTags.map((f2) => f2.value), - true - ); - if (!props.multi && newTag.type != 1 /* Disclosure */) { - props.hide(); - } + { + tag: tags2.variableName, + color: "#abcdef" }, - [tags3, suggestions] - ); - const onValidation = (0, import_react17.useCallback)( - (newTag) => { - if (!props.editable && !suggestions.find((s4) => s4.value == newTag.value)) { - return false; - } - if (newTag.name.length == 0) { - return false; - } - return true; + { + tag: tags2.function(tags2.variableName), + color: "#fffabc" }, - [suggestions] - ); - return /* @__PURE__ */ import_react17.default.createElement(SelectMenuComponent_default, { - tags: props.multi ? tags3 : [], - suggestions, - ui: props.ui, - ref: ref2, - addKeyword: props.addKeyword, - hide: props.hide, - onDelete, - wrapperClass: props.wrapperClass, - onMoreOption: props.onMoreOption, - onDeleteOption, - onAddition, - onValidate: onValidation, - onSelectSection: props.onSelectSection, - defaultSuggestions: props.defaultOptions, - placeholderText: props.placeholder ?? "", - minQueryLength: 0, - onHover: props.onHover, - showSections: props.showSections, - sections: props.sections, - maxSuggestionsLength: props.showAll ? Math.min(50, props.options.length) : 25, - suggestionsOnly: !props.searchable && !props.editable, - allowNew: props.editable, - previewComponent: props.previewComponent, - isDisclosure: props.isDisclosure - }); - } -); -SelectMenu.displayName = "SelectMenu"; -var SelectMenu_default = SelectMenu; + { + tag: tags2.typeName, + color: "#FFDD44" + }, + { + tag: tags2.tagName, + color: "#def" + }, + { + tag: tags2.string, + color: "#2b4" + }, + { + tag: tags2.meta, + color: "#C9F" + }, + { + tag: tags2.bracket, + color: "#8a8a8a" + }, + { + tag: tags2.attributeName, + color: "#DDFF00" + }, + { + tag: tags2.heading, + color: "aquamarine", + fontWeight: "bold" + }, + { + tag: tags2.link, + color: "blueviolet", + fontWeight: "bold" + }, + ...styles2 + ] + }); +}; +var abcdef = abcdefInit(); -// src/core/react/components/Explorer/Explorer.tsx -var import_react82 = __toESM(require_react()); +// node_modules/@uiw/react-codemirror/esm/index.js +var esm_exports = {}; +__export(esm_exports, { + basicSetup: () => basicSetup, + color: () => color, + default: () => esm_default, + defaultLightThemeOption: () => defaultLightThemeOption, + getDefaultExtensions: () => getDefaultExtensions, + getStatistics: () => getStatistics, + minimalSetup: () => minimalSetup, + oneDark: () => oneDark, + oneDarkHighlightStyle: () => oneDarkHighlightStyle, + oneDarkTheme: () => oneDarkTheme, + useCodeMirror: () => useCodeMirror +}); -// src/core/utils/uuid.js -function genId() { - return ([1e7] + -1e3 + -4e3 + -8e3 + -1e11).replace( - /[018]/g, - (c3) => (c3 ^ crypto.getRandomValues(new Uint8Array(1))[0] & 15 >> c3 / 4).toString(16) - ); +// node_modules/@babel/runtime/helpers/esm/objectWithoutPropertiesLoose.js +function _objectWithoutPropertiesLoose(source, excluded) { + if (source == null) + return {}; + var target = {}; + var sourceKeys = Object.keys(source); + var key2, i4; + for (i4 = 0; i4 < sourceKeys.length; i4++) { + key2 = sourceKeys[i4]; + if (excluded.indexOf(key2) >= 0) + continue; + target[key2] = source[key2]; + } + return target; } -// src/core/react/context/PathContext.tsx -var import_react18 = __toESM(require_react()); -var PathContext = (0, import_react18.createContext)({ - uid: "", - readMode: false, - pathState: null, - addToSpace: () => null, - removeFromSpace: () => null -}); -var PathProvider = (props) => { - const [pathState, setPathState] = (0, import_react18.useState)( - props.pathState ?? props.superstate.pathsIndex.get(props.path) - ); - const addToSpace = async (spacePath) => { - const spaceCache = props.superstate.spacesIndex.get(spacePath); - if (spaceCache) { - addPathToSpaceAtIndex(props.superstate, spaceCache, pathState.path, -1); - } - }; - const removeFromSpace = (spacePath) => { - removePathsFromSpace(props.superstate, spacePath, [pathState.path]); - }; - const readMode = props.readMode; - (0, import_react18.useEffect)(() => { - const reloadPath = () => { - if (!props.pathState) - setPathState(props.superstate.pathsIndex.get(props.path)); - }; - const changePath = (payload) => { - if (payload.path == pathState?.path) { - setPathState(props.superstate.pathsIndex.get(payload.newPath)); - } - }; - const refreshPath = (payload) => { - if (payload.path == props.path) { - reloadPath(); - } - }; - reloadPath(); - props.superstate.eventsDispatcher.addListener( - "pathStateUpdated", - refreshPath - ); - props.superstate.eventsDispatcher.addListener( - "superstateUpdated", - reloadPath - ); - props.superstate.eventsDispatcher.addListener("pathChanged", changePath); - return () => { - props.superstate.eventsDispatcher.removeListener( - "superstateUpdated", - reloadPath - ); - props.superstate.eventsDispatcher.removeListener( - "pathStateUpdated", - refreshPath - ); - props.superstate.eventsDispatcher.removeListener( - "pathChanged", - changePath - ); - }; - }, [props.path]); - return /* @__PURE__ */ import_react18.default.createElement(PathContext.Provider, { - value: { - uid: genId(), - readMode, - pathState, - addToSpace, - removeFromSpace - } - }, pathState ? props.children : /* @__PURE__ */ import_react18.default.createElement(import_react18.default.Fragment, null)); -}; +// node_modules/@uiw/react-codemirror/esm/index.js +var import_react13 = __toESM(require_react()); -// src/core/react/components/PathView/NoteView.tsx -var import_react19 = __toESM(require_react()); -var NoteView = (0, import_react19.forwardRef)((props, ref2) => { - const flowRef = (0, import_react19.useRef)(null); - const [existsPas, setExistsPas] = (0, import_react19.useState)(false); - const [loaded, setLoaded] = (0, import_react19.useState)(false); - const loadPath = async (force) => { - const div2 = flowRef.current; - const path2 = props.superstate.spaceManager.uriByString( - props.path, - props.source - ); - const properties3 = props.properties; - const pathState = props.superstate.pathsIndex.get(path2.path); - const filePath = pathState?.type == "space" ? props.superstate.spacesIndex.get(props.path)?.defPath : pathState?.path; - if (!filePath) { - if (!force) { - setExistsPas(true); - setLoaded(false); - return; - } else { - const parent = props.superstate.spaceManager.parentPathForPath( - path2.path - ); - if (!parent) - return; - const newPath = await props.superstate.spaceManager.createItemAtPath( - parent, - "md", - pathToString(props.path) - ); - setExistsPas(false); - await props.superstate.ui.openPath(newPath, false, div2, properties3); - } - } else { - setExistsPas(false); - props.superstate.ui.openPath(filePath, false, div2, properties3); - } - setLoaded(true); - }; - const toggleFlow = () => { - if (props.load) { - loadPath(); - } else { - if (flowRef?.current) - flowRef.current.innerHTML = ""; - } - }; - (0, import_react19.useEffect)(() => { - toggleFlow(); - }, [props.load, props.path]); - return /* @__PURE__ */ import_react19.default.createElement(import_react19.default.Fragment, null, /* @__PURE__ */ import_react19.default.createElement("div", { - className: `${props.classname ?? ""} mk-flowspace-editor`, - ref: flowRef, - onClick: (e5) => e5.stopPropagation() - }), existsPas ? /* @__PURE__ */ import_react19.default.createElement("div", { - onClick: () => loadPath(true), - className: "mk-placeholder", - style: { color: "var(--mk-ui-text-tertiary)" } - }, i18n_default.labels.notePlaceholder.replace( - "${1}", - pathToString(props.path) - )) : /* @__PURE__ */ import_react19.default.createElement(import_react19.default.Fragment, null)); -}); -NoteView.displayName = "FlowView"; - -// src/core/react/components/UI/Toggles/CollapseToggle.tsx -var import_react20 = __toESM(require_react()); -var CollapseToggle = (props) => { - return /* @__PURE__ */ import_react20.default.createElement("button", { - className: `mk-collapse ${props.collapsed ? "mk-collapsed" : ""}`, - onClick: (e5) => { - if (!props.onToggle) - return; - e5.stopPropagation(); - props.onToggle(!props.collapsed, e5); - }, - dangerouslySetInnerHTML: { - __html: props.superstate.ui.getSticker("ui//collapse") - } - }); -}; - -// src/core/react/components/Explorer/ContextPropertiesView.tsx -var import_react81 = __toESM(require_react()); - -// src/core/react/components/Explorer/PathContextList.tsx -var import_react79 = __toESM(require_react()); +// node_modules/@uiw/react-codemirror/esm/useCodeMirror.js +var import_react12 = __toESM(require_react()); +var import_state6 = require("@codemirror/state"); +var import_view8 = require("@codemirror/view"); -// src/core/react/components/UI/Menus/contexts/newSpacePropertyMenu.tsx -var import_react32 = __toESM(require_react()); +// node_modules/@uiw/react-codemirror/esm/getDefaultExtensions.js +var import_commands2 = require("@codemirror/commands"); -// node_modules/@lezer/javascript/node_modules/@lezer/common/dist/index.js -var DefaultBufferLength = 1024; -var nextPropID = 0; -var Range2 = class { - constructor(from, to2) { - this.from = from; - this.to = to2; - } -}; -var NodeProp = class { - constructor(config4 = {}) { - this.id = nextPropID++; - this.perNode = !!config4.perNode; - this.deserialize = config4.deserialize || (() => { - throw new Error("This node type doesn't define a deserialize function"); - }); +// node_modules/@uiw/codemirror-extensions-basic-setup/esm/index.js +var import_view4 = require("@codemirror/view"); +var import_state4 = require("@codemirror/state"); +var import_commands = require("@codemirror/commands"); +var import_search = require("@codemirror/search"); +var import_autocomplete2 = require("@codemirror/autocomplete"); +var import_language4 = require("@codemirror/language"); +var import_lint = require("@codemirror/lint"); +var basicSetup = function basicSetup2(options) { + if (options === void 0) { + options = {}; } - add(match2) { - if (this.perNode) - throw new RangeError("Can't add per-node props to node types"); - if (typeof match2 != "function") - match2 = NodeType.match(match2); - return (type) => { - let result = match2(type); - return result === void 0 ? null : [this, result]; - }; + var { + crosshairCursor: initCrosshairCursor = false + } = options; + var keymaps = []; + if (options.closeBracketsKeymap !== false) { + keymaps = keymaps.concat(import_autocomplete2.closeBracketsKeymap); } -}; -NodeProp.closedBy = new NodeProp({ deserialize: (str) => str.split(" ") }); -NodeProp.openedBy = new NodeProp({ deserialize: (str) => str.split(" ") }); -NodeProp.group = new NodeProp({ deserialize: (str) => str.split(" ") }); -NodeProp.contextHash = new NodeProp({ perNode: true }); -NodeProp.lookAhead = new NodeProp({ perNode: true }); -NodeProp.mounted = new NodeProp({ perNode: true }); -var noProps = /* @__PURE__ */ Object.create(null); -var NodeType = class { - constructor(name317, props, id3, flags = 0) { - this.name = name317; - this.props = props; - this.id = id3; - this.flags = flags; + if (options.defaultKeymap !== false) { + keymaps = keymaps.concat(import_commands.defaultKeymap); } - static define(spec) { - let props = spec.props && spec.props.length ? /* @__PURE__ */ Object.create(null) : noProps; - let flags = (spec.top ? 1 : 0) | (spec.skipped ? 2 : 0) | (spec.error ? 4 : 0) | (spec.name == null ? 8 : 0); - let type = new NodeType(spec.name || "", props, spec.id, flags); - if (spec.props) - for (let src of spec.props) { - if (!Array.isArray(src)) - src = src(type); - if (src) { - if (src[0].perNode) - throw new RangeError("Can't store a per-node prop on a node type"); - props[src[0].id] = src[1]; - } - } - return type; + if (options.searchKeymap !== false) { + keymaps = keymaps.concat(import_search.searchKeymap); } - prop(prop2) { - return this.props[prop2.id]; + if (options.historyKeymap !== false) { + keymaps = keymaps.concat(import_commands.historyKeymap); } - get isTop() { - return (this.flags & 1) > 0; + if (options.foldKeymap !== false) { + keymaps = keymaps.concat(import_language4.foldKeymap); } - get isSkipped() { - return (this.flags & 2) > 0; + if (options.completionKeymap !== false) { + keymaps = keymaps.concat(import_autocomplete2.completionKeymap); } - get isError() { - return (this.flags & 4) > 0; + if (options.lintKeymap !== false) { + keymaps = keymaps.concat(import_lint.lintKeymap); } - get isAnonymous() { - return (this.flags & 8) > 0; + var extensions = []; + if (options.lineNumbers !== false) + extensions.push((0, import_view4.lineNumbers)()); + if (options.highlightActiveLineGutter !== false) + extensions.push((0, import_view4.highlightActiveLineGutter)()); + if (options.highlightSpecialChars !== false) + extensions.push((0, import_view4.highlightSpecialChars)()); + if (options.history !== false) + extensions.push((0, import_commands.history)()); + if (options.foldGutter !== false) + extensions.push((0, import_language4.foldGutter)()); + if (options.drawSelection !== false) + extensions.push((0, import_view4.drawSelection)()); + if (options.dropCursor !== false) + extensions.push((0, import_view4.dropCursor)()); + if (options.allowMultipleSelections !== false) + extensions.push(import_state4.EditorState.allowMultipleSelections.of(true)); + if (options.indentOnInput !== false) + extensions.push((0, import_language4.indentOnInput)()); + if (options.syntaxHighlighting !== false) + extensions.push((0, import_language4.syntaxHighlighting)(import_language4.defaultHighlightStyle, { + fallback: true + })); + if (options.bracketMatching !== false) + extensions.push((0, import_language4.bracketMatching)()); + if (options.closeBrackets !== false) + extensions.push((0, import_autocomplete2.closeBrackets)()); + if (options.autocompletion !== false) + extensions.push((0, import_autocomplete2.autocompletion)()); + if (options.rectangularSelection !== false) + extensions.push((0, import_view4.rectangularSelection)()); + if (initCrosshairCursor !== false) + extensions.push((0, import_view4.crosshairCursor)()); + if (options.highlightActiveLine !== false) + extensions.push((0, import_view4.highlightActiveLine)()); + if (options.highlightSelectionMatches !== false) + extensions.push((0, import_search.highlightSelectionMatches)()); + if (options.tabSize && typeof options.tabSize === "number") + extensions.push(import_language4.indentUnit.of(" ".repeat(options.tabSize))); + return extensions.concat([import_view4.keymap.of(keymaps.flat())]).filter(Boolean); +}; +var minimalSetup = function minimalSetup2(options) { + if (options === void 0) { + options = {}; } - is(name317) { - if (typeof name317 == "string") { - if (this.name == name317) - return true; - let group = this.prop(NodeProp.group); - return group ? group.indexOf(name317) > -1 : false; - } - return this.id == name317; + var keymaps = []; + if (options.defaultKeymap !== false) { + keymaps = keymaps.concat(import_commands.defaultKeymap); } - static match(map4) { - let direct = /* @__PURE__ */ Object.create(null); - for (let prop2 in map4) - for (let name317 of prop2.split(" ")) - direct[name317] = map4[prop2]; - return (node) => { - for (let groups = node.prop(NodeProp.group), i4 = -1; i4 < (groups ? groups.length : 0); i4++) { - let found = direct[i4 < 0 ? node.name : groups[i4]]; - if (found) - return found; - } - }; + if (options.historyKeymap !== false) { + keymaps = keymaps.concat(import_commands.historyKeymap); } + var extensions = []; + if (options.highlightSpecialChars !== false) + extensions.push((0, import_view4.highlightSpecialChars)()); + if (options.history !== false) + extensions.push((0, import_commands.history)()); + if (options.drawSelection !== false) + extensions.push((0, import_view4.drawSelection)()); + if (options.syntaxHighlighting !== false) + extensions.push((0, import_language4.syntaxHighlighting)(import_language4.defaultHighlightStyle, { + fallback: true + })); + return extensions.concat([import_view4.keymap.of(keymaps.flat())]).filter(Boolean); }; -NodeType.none = new NodeType("", /* @__PURE__ */ Object.create(null), 0, 8); -var NodeSet = class { - constructor(types2) { - this.types = types2; - for (let i4 = 0; i4 < types2.length; i4++) - if (types2[i4].id != i4) - throw new RangeError("Node type ids should correspond to array positions when creating a node set"); - } - extend(...props) { - let newTypes = []; - for (let type of this.types) { - let newProps = null; - for (let source of props) { - let add4 = source(type); - if (add4) { - if (!newProps) - newProps = Object.assign({}, type.props); - newProps[add4[0].id] = add4[1]; - } - } - newTypes.push(newProps ? new NodeType(type.name, newProps, type.id, type.flags) : type); - } - return new NodeSet(newTypes); - } + +// node_modules/@uiw/react-codemirror/esm/getDefaultExtensions.js +var import_view7 = require("@codemirror/view"); + +// node_modules/@codemirror/theme-one-dark/dist/index.js +var import_view5 = require("@codemirror/view"); +var import_language5 = require("@codemirror/language"); +var chalky = "#e5c07b"; +var coral = "#e06c75"; +var cyan = "#56b6c2"; +var invalid = "#ffffff"; +var ivory = "#abb2bf"; +var stone = "#7d8799"; +var malibu = "#61afef"; +var sage = "#98c379"; +var whiskey = "#d19a66"; +var violet = "#c678dd"; +var darkBackground = "#21252b"; +var highlightBackground = "#2c313a"; +var background = "#282c34"; +var tooltipBackground = "#353a42"; +var selection = "#3E4451"; +var cursor = "#528bff"; +var color = { + chalky, + coral, + cyan, + invalid, + ivory, + stone, + malibu, + sage, + whiskey, + violet, + darkBackground, + highlightBackground, + background, + tooltipBackground, + selection, + cursor }; -var CachedNode = /* @__PURE__ */ new WeakMap(); -var CachedInnerNode = /* @__PURE__ */ new WeakMap(); -var IterMode; -(function(IterMode4) { - IterMode4[IterMode4["ExcludeBuffers"] = 1] = "ExcludeBuffers"; - IterMode4[IterMode4["IncludeAnonymous"] = 2] = "IncludeAnonymous"; - IterMode4[IterMode4["IgnoreMounts"] = 4] = "IgnoreMounts"; - IterMode4[IterMode4["IgnoreOverlays"] = 8] = "IgnoreOverlays"; -})(IterMode || (IterMode = {})); -var Tree = class { - constructor(type, children, positions, length, props) { - this.type = type; - this.children = children; - this.positions = positions; - this.length = length; - this.props = null; - if (props && props.length) { - this.props = /* @__PURE__ */ Object.create(null); - for (let [prop2, value] of props) - this.props[typeof prop2 == "number" ? prop2 : prop2.id] = value; - } - } - toString() { - let mounted = this.prop(NodeProp.mounted); - if (mounted && !mounted.overlay) - return mounted.tree.toString(); - let children = ""; - for (let ch of this.children) { - let str = ch.toString(); - if (str) { - if (children) - children += ","; - children += str; - } +var oneDarkTheme = /* @__PURE__ */ import_view5.EditorView.theme({ + "&": { + color: ivory, + backgroundColor: background + }, + ".cm-content": { + caretColor: cursor + }, + ".cm-cursor, .cm-dropCursor": { borderLeftColor: cursor }, + "&.cm-focused > .cm-scroller > .cm-selectionLayer .cm-selectionBackground, .cm-selectionBackground, .cm-content ::selection": { backgroundColor: selection }, + ".cm-panels": { backgroundColor: darkBackground, color: ivory }, + ".cm-panels.cm-panels-top": { borderBottom: "2px solid black" }, + ".cm-panels.cm-panels-bottom": { borderTop: "2px solid black" }, + ".cm-searchMatch": { + backgroundColor: "#72a1ff59", + outline: "1px solid #457dff" + }, + ".cm-searchMatch.cm-searchMatch-selected": { + backgroundColor: "#6199ff2f" + }, + ".cm-activeLine": { backgroundColor: "#6699ff0b" }, + ".cm-selectionMatch": { backgroundColor: "#aafe661a" }, + "&.cm-focused .cm-matchingBracket, &.cm-focused .cm-nonmatchingBracket": { + backgroundColor: "#bad0f847" + }, + ".cm-gutters": { + backgroundColor: background, + color: stone, + border: "none" + }, + ".cm-activeLineGutter": { + backgroundColor: highlightBackground + }, + ".cm-foldPlaceholder": { + backgroundColor: "transparent", + border: "none", + color: "#ddd" + }, + ".cm-tooltip": { + border: "none", + backgroundColor: tooltipBackground + }, + ".cm-tooltip .cm-tooltip-arrow:before": { + borderTopColor: "transparent", + borderBottomColor: "transparent" + }, + ".cm-tooltip .cm-tooltip-arrow:after": { + borderTopColor: tooltipBackground, + borderBottomColor: tooltipBackground + }, + ".cm-tooltip-autocomplete": { + "& > ul > li[aria-selected]": { + backgroundColor: highlightBackground, + color: ivory } - return !this.type.name ? children : (/\W/.test(this.type.name) && !this.type.isError ? JSON.stringify(this.type.name) : this.type.name) + (children.length ? "(" + children + ")" : ""); - } - cursor(mode2 = 0) { - return new TreeCursor(this.topNode, mode2); } - cursorAt(pos, side = 0, mode2 = 0) { - let scope = CachedNode.get(this) || this.topNode; - let cursor2 = new TreeCursor(scope); - cursor2.moveTo(pos, side); - CachedNode.set(this, cursor2._tree); - return cursor2; +}, { dark: true }); +var oneDarkHighlightStyle = /* @__PURE__ */ import_language5.HighlightStyle.define([ + { + tag: tags2.keyword, + color: violet + }, + { + tag: [tags2.name, tags2.deleted, tags2.character, tags2.propertyName, tags2.macroName], + color: coral + }, + { + tag: [/* @__PURE__ */ tags2.function(tags2.variableName), tags2.labelName], + color: malibu + }, + { + tag: [tags2.color, /* @__PURE__ */ tags2.constant(tags2.name), /* @__PURE__ */ tags2.standard(tags2.name)], + color: whiskey + }, + { + tag: [/* @__PURE__ */ tags2.definition(tags2.name), tags2.separator], + color: ivory + }, + { + tag: [tags2.typeName, tags2.className, tags2.number, tags2.changed, tags2.annotation, tags2.modifier, tags2.self, tags2.namespace], + color: chalky + }, + { + tag: [tags2.operator, tags2.operatorKeyword, tags2.url, tags2.escape, tags2.regexp, tags2.link, /* @__PURE__ */ tags2.special(tags2.string)], + color: cyan + }, + { + tag: [tags2.meta, tags2.comment], + color: stone + }, + { + tag: tags2.strong, + fontWeight: "bold" + }, + { + tag: tags2.emphasis, + fontStyle: "italic" + }, + { + tag: tags2.strikethrough, + textDecoration: "line-through" + }, + { + tag: tags2.link, + color: stone, + textDecoration: "underline" + }, + { + tag: tags2.heading, + fontWeight: "bold", + color: coral + }, + { + tag: [tags2.atom, tags2.bool, /* @__PURE__ */ tags2.special(tags2.variableName)], + color: whiskey + }, + { + tag: [tags2.processingInstruction, tags2.string, tags2.inserted], + color: sage + }, + { + tag: tags2.invalid, + color: invalid } - get topNode() { - return new TreeNode2(this, 0, 0, null); +]); +var oneDark = [oneDarkTheme, /* @__PURE__ */ (0, import_language5.syntaxHighlighting)(oneDarkHighlightStyle)]; + +// node_modules/@uiw/react-codemirror/esm/getDefaultExtensions.js +var import_state5 = require("@codemirror/state"); + +// node_modules/@uiw/react-codemirror/esm/theme/light.js +var import_view6 = require("@codemirror/view"); +var defaultLightThemeOption = import_view6.EditorView.theme({ + "&": { + backgroundColor: "#fff" } - resolve(pos, side = 0) { - let node = resolveNode(CachedNode.get(this) || this.topNode, pos, side, false); - CachedNode.set(this, node); - return node; +}, { + dark: false +}); + +// node_modules/@uiw/react-codemirror/esm/getDefaultExtensions.js +var getDefaultExtensions = function getDefaultExtensions2(optios) { + if (optios === void 0) { + optios = {}; } - resolveInner(pos, side = 0) { - let node = resolveNode(CachedInnerNode.get(this) || this.topNode, pos, side, true); - CachedInnerNode.set(this, node); - return node; + var { + indentWithTab: defaultIndentWithTab = true, + editable = true, + readOnly = false, + theme = "light", + placeholder: placeholderStr = "", + basicSetup: defaultBasicSetup = true + } = optios; + var getExtensions = []; + if (defaultIndentWithTab) { + getExtensions.unshift(import_view7.keymap.of([import_commands2.indentWithTab])); } - iterate(spec) { - let { enter, leave, from = 0, to: to2 = this.length } = spec; - for (let c3 = this.cursor((spec.mode || 0) | IterMode.IncludeAnonymous); ; ) { - let entered = false; - if (c3.from <= to2 && c3.to >= from && (c3.type.isAnonymous || enter(c3) !== false)) { - if (c3.firstChild()) - continue; - entered = true; - } - for (; ; ) { - if (entered && leave && !c3.type.isAnonymous) - leave(c3); - if (c3.nextSibling()) - break; - if (!c3.parent()) - return; - entered = true; - } + if (defaultBasicSetup) { + if (typeof defaultBasicSetup === "boolean") { + getExtensions.unshift(basicSetup()); + } else { + getExtensions.unshift(basicSetup(defaultBasicSetup)); } } - prop(prop2) { - return !prop2.perNode ? this.type.prop(prop2) : this.props ? this.props[prop2.id] : void 0; + if (placeholderStr) { + getExtensions.unshift((0, import_view7.placeholder)(placeholderStr)); } - get propValues() { - let result = []; - if (this.props) - for (let id3 in this.props) - result.push([+id3, this.props[id3]]); - return result; + switch (theme) { + case "light": + getExtensions.push(defaultLightThemeOption); + break; + case "dark": + getExtensions.push(oneDark); + break; + case "none": + break; + default: + getExtensions.push(theme); + break; } - balance(config4 = {}) { - return this.children.length <= 8 ? this : balanceRange(NodeType.none, this.children, this.positions, 0, this.children.length, 0, this.length, (children, positions, length) => new Tree(this.type, children, positions, length, this.propValues), config4.makeTree || ((children, positions, length) => new Tree(NodeType.none, children, positions, length))); + if (editable === false) { + getExtensions.push(import_view7.EditorView.editable.of(false)); } - static build(data2) { - return buildTree(data2); + if (readOnly) { + getExtensions.push(import_state5.EditorState.readOnly.of(true)); } + return [...getExtensions]; }; -Tree.empty = new Tree(NodeType.none, [], [], 0); -var FlatBufferCursor = class { - constructor(buffer, index2) { - this.buffer = buffer; - this.index = index2; - } - get id() { - return this.buffer[this.index - 4]; - } - get start() { - return this.buffer[this.index - 3]; - } - get end() { - return this.buffer[this.index - 2]; - } - get size() { - return this.buffer[this.index - 1]; - } - get pos() { - return this.index; - } - next() { - this.index -= 4; - } - fork() { - return new FlatBufferCursor(this.buffer, this.index); - } + +// node_modules/@uiw/react-codemirror/esm/utils.js +var getStatistics = (view) => { + return { + line: view.state.doc.lineAt(view.state.selection.main.from), + lineCount: view.state.doc.lines, + lineBreak: view.state.lineBreak, + length: view.state.doc.length, + readOnly: view.state.readOnly, + tabSize: view.state.tabSize, + selection: view.state.selection, + selectionAsSingle: view.state.selection.asSingle().main, + ranges: view.state.selection.ranges, + selectionCode: view.state.sliceDoc(view.state.selection.main.from, view.state.selection.main.to), + selections: view.state.selection.ranges.map((r2) => view.state.sliceDoc(r2.from, r2.to)), + selectedText: view.state.selection.ranges.some((r2) => !r2.empty) + }; }; -var TreeBuffer = class { - constructor(buffer, length, set) { - this.buffer = buffer; - this.length = length; - this.set = set; - } - get type() { - return NodeType.none; - } - toString() { - let result = []; - for (let index2 = 0; index2 < this.buffer.length; ) { - result.push(this.childString(index2)); - index2 = this.buffer[index2 + 3]; + +// node_modules/@uiw/react-codemirror/esm/useCodeMirror.js +var External = import_state6.Annotation.define(); +var emptyExtensions = []; +function useCodeMirror(props) { + var { + value, + selection: selection2, + onChange, + onStatistics, + onCreateEditor, + onUpdate, + extensions = emptyExtensions, + autoFocus, + theme = "light", + height = null, + minHeight = null, + maxHeight = null, + width = null, + minWidth = null, + maxWidth = null, + placeholder: placeholderStr = "", + editable = true, + readOnly = false, + indentWithTab: defaultIndentWithTab = true, + basicSetup: defaultBasicSetup = true, + root, + initialState: initialState2 + } = props; + var [container, setContainer] = (0, import_react12.useState)(); + var [view, setView] = (0, import_react12.useState)(); + var [state, setState] = (0, import_react12.useState)(); + var defaultThemeOption = import_view8.EditorView.theme({ + "&": { + height, + minHeight, + maxHeight, + width, + minWidth, + maxWidth + }, + "& .cm-scroller": { + height: "100% !important" } - return result.join(","); - } - childString(index2) { - let id3 = this.buffer[index2], endIndex = this.buffer[index2 + 3]; - let type = this.set.types[id3], result = type.name; - if (/\W/.test(result) && !type.isError) - result = JSON.stringify(result); - index2 += 4; - if (endIndex == index2) - return result; - let children = []; - while (index2 < endIndex) { - children.push(this.childString(index2)); - index2 = this.buffer[index2 + 3]; + }); + var updateListener = import_view8.EditorView.updateListener.of((vu) => { + if (vu.docChanged && typeof onChange === "function" && !vu.transactions.some((tr) => tr.annotation(External))) { + var doc = vu.state.doc; + var _value = doc.toString(); + onChange(_value, vu); } - return result + "(" + children.join(",") + ")"; + onStatistics && onStatistics(getStatistics(vu)); + }); + var defaultExtensions = getDefaultExtensions({ + theme, + editable, + readOnly, + placeholder: placeholderStr, + indentWithTab: defaultIndentWithTab, + basicSetup: defaultBasicSetup + }); + var getExtensions = [updateListener, defaultThemeOption, ...defaultExtensions]; + if (onUpdate && typeof onUpdate === "function") { + getExtensions.push(import_view8.EditorView.updateListener.of(onUpdate)); } - findChild(startIndex, endIndex, dir, pos, side) { - let { buffer } = this, pick = -1; - for (let i4 = startIndex; i4 != endIndex; i4 = buffer[i4 + 3]) { - if (checkSide(side, pos, buffer[i4 + 1], buffer[i4 + 2])) { - pick = i4; - if (dir > 0) - break; + getExtensions = getExtensions.concat(extensions); + (0, import_react12.useEffect)(() => { + if (container && !state) { + var config4 = { + doc: value, + selection: selection2, + extensions: getExtensions + }; + var stateCurrent = initialState2 ? import_state6.EditorState.fromJSON(initialState2.json, config4, initialState2.fields) : import_state6.EditorState.create(config4); + setState(stateCurrent); + if (!view) { + var viewCurrent = new import_view8.EditorView({ + state: stateCurrent, + parent: container, + root + }); + setView(viewCurrent); + onCreateEditor && onCreateEditor(viewCurrent, stateCurrent); } } - return pick; - } - slice(startI, endI, from, to2) { - let b2 = this.buffer; - let copy = new Uint16Array(endI - startI); - for (let i4 = startI, j = 0; i4 < endI; ) { - copy[j++] = b2[i4++]; - copy[j++] = b2[i4++] - from; - copy[j++] = b2[i4++] - from; - copy[j++] = b2[i4++] - startI; + return () => { + if (view) { + setState(void 0); + setView(void 0); + } + }; + }, [container, state]); + (0, import_react12.useEffect)(() => setContainer(props.container), [props.container]); + (0, import_react12.useEffect)(() => () => { + if (view) { + view.destroy(); + setView(void 0); } - return new TreeBuffer(copy, to2 - from, this.set); - } -}; -function checkSide(side, pos, from, to2) { - switch (side) { - case -2: - return from < pos; - case -1: - return to2 >= pos && from < pos; - case 0: - return from < pos && to2 > pos; - case 1: - return from <= pos && to2 > pos; - case 2: - return to2 > pos; - case 4: - return true; - } -} -function enterUnfinishedNodesBefore(node, pos) { - let scan = node.childBefore(pos); - while (scan) { - let last = scan.lastChild; - if (!last || last.to != scan.to) - break; - if (last.type.isError && last.from == last.to) { - node = scan; - scan = last.prevSibling; - } else { - scan = last; + }, [view]); + (0, import_react12.useEffect)(() => { + if (autoFocus && view) { + view.focus(); } - } - return node; -} -function resolveNode(node, pos, side, overlays) { - var _a; - while (node.from == node.to || (side < 1 ? node.from >= pos : node.from > pos) || (side > -1 ? node.to <= pos : node.to < pos)) { - let parent = !overlays && node instanceof TreeNode2 && node.index < 0 ? null : node.parent; - if (!parent) - return node; - node = parent; - } - let mode2 = overlays ? 0 : IterMode.IgnoreOverlays; - if (overlays) - for (let scan = node, parent = scan.parent; parent; scan = parent, parent = scan.parent) { - if (scan instanceof TreeNode2 && scan.index < 0 && ((_a = parent.enter(pos, side, mode2)) === null || _a === void 0 ? void 0 : _a.from) != scan.from) - node = parent; + }, [autoFocus, view]); + (0, import_react12.useEffect)(() => { + if (view) { + view.dispatch({ + effects: import_state6.StateEffect.reconfigure.of(getExtensions) + }); } - for (; ; ) { - let inner = node.enter(pos, side, mode2); - if (!inner) - return node; - node = inner; - } + }, [theme, extensions, height, minHeight, maxHeight, width, minWidth, maxWidth, placeholderStr, editable, readOnly, defaultIndentWithTab, defaultBasicSetup, onChange, onUpdate]); + (0, import_react12.useEffect)(() => { + if (value === void 0) { + return; + } + var currentValue = view ? view.state.doc.toString() : ""; + if (view && value !== currentValue) { + view.dispatch({ + changes: { + from: 0, + to: currentValue.length, + insert: value || "" + }, + annotations: [External.of(true)] + }); + } + }, [value, view]); + return { + state, + setState, + view, + setView, + container, + setContainer + }; } -var TreeNode2 = class { - constructor(_tree, from, index2, _parent) { - this._tree = _tree; - this.from = from; - this.index = index2; - this._parent = _parent; - } - get type() { - return this._tree.type; - } - get name() { - return this._tree.type.name; - } - get to() { - return this.from + this._tree.length; + +// node_modules/@uiw/react-codemirror/esm/index.js +var import_jsx_runtime = __toESM(require_jsx_runtime()); +__reExport(esm_exports, require("@codemirror/view")); +__reExport(esm_exports, require("@codemirror/state")); +var _excluded = ["className", "value", "selection", "extensions", "onChange", "onStatistics", "onCreateEditor", "onUpdate", "autoFocus", "theme", "height", "minHeight", "maxHeight", "width", "minWidth", "maxWidth", "basicSetup", "placeholder", "indentWithTab", "editable", "readOnly", "root", "initialState"]; +var ReactCodeMirror = /* @__PURE__ */ (0, import_react13.forwardRef)((props, ref2) => { + var { + className, + value = "", + selection: selection2, + extensions = [], + onChange, + onStatistics, + onCreateEditor, + onUpdate, + autoFocus, + theme = "light", + height, + minHeight, + maxHeight, + width, + minWidth, + maxWidth, + basicSetup: basicSetup3, + placeholder: placeholder2, + indentWithTab: indentWithTab2, + editable, + readOnly, + root, + initialState: initialState2 + } = props, other = _objectWithoutPropertiesLoose(props, _excluded); + var editor = (0, import_react13.useRef)(null); + var { + state, + view, + container + } = useCodeMirror({ + container: editor.current, + root, + value, + autoFocus, + theme, + height, + minHeight, + maxHeight, + width, + minWidth, + maxWidth, + basicSetup: basicSetup3, + placeholder: placeholder2, + indentWithTab: indentWithTab2, + editable, + readOnly, + selection: selection2, + onChange, + onStatistics, + onCreateEditor, + onUpdate, + extensions, + initialState: initialState2 + }); + (0, import_react13.useImperativeHandle)(ref2, () => ({ + editor: editor.current, + state, + view + }), [editor, container, state, view]); + if (typeof value !== "string") { + throw new Error("value must be typeof string but got " + typeof value); } - nextChild(i4, dir, pos, side, mode2 = 0) { - for (let parent = this; ; ) { - for (let { children, positions } = parent._tree, e5 = dir > 0 ? children.length : -1; i4 != e5; i4 += dir) { - let next = children[i4], start = positions[i4] + parent.from; - if (!checkSide(side, pos, start, start + next.length)) - continue; - if (next instanceof TreeBuffer) { - if (mode2 & IterMode.ExcludeBuffers) - continue; - let index2 = next.findChild(0, next.buffer.length, dir, pos - start, side); - if (index2 > -1) - return new BufferNode(new BufferContext(parent, next, i4, start), null, index2); - } else if (mode2 & IterMode.IncludeAnonymous || (!next.type.isAnonymous || hasChild(next))) { - let mounted; - if (!(mode2 & IterMode.IgnoreMounts) && next.props && (mounted = next.prop(NodeProp.mounted)) && !mounted.overlay) - return new TreeNode2(mounted.tree, start, i4, parent); - let inner = new TreeNode2(next, start, i4, parent); - return mode2 & IterMode.IncludeAnonymous || !inner.type.isAnonymous ? inner : inner.nextChild(dir < 0 ? next.children.length - 1 : 0, dir, pos, side); - } + var defaultClassNames2 = typeof theme === "string" ? "cm-theme-" + theme : "cm-theme"; + return /* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", _extends({ + ref: editor, + className: "" + defaultClassNames2 + (className ? " " + className : "") + }, other)); +}); +ReactCodeMirror.displayName = "CodeMirror"; +var esm_default = ReactCodeMirror; + +// src/core/react/components/SpaceEditor/Actions/FormulaEditor.tsx +var import_react15 = __toESM(require_react()); + +// src/core/utils/frames/runner.ts +var executeTreeNode = async (_treeNode, store, executionContext) => { + const treeNode = _treeNode; + if (store.prevState[treeNode.id] && treeNode.node.type != "content") { + let skipped = false; + if (treeNode.node.type == "slides" || treeNode.node.type == "slide" || treeNode.node.type == "delta") { + skipped = false; + } else { + const childDepCheck = (treeNode.execPropsOptions.children ?? []).some((f2) => Object.keys(store.newState).includes(f2)); + const sameProps = Object.keys(store.newState[treeNode.id]?.props ?? {}).every((f2) => store.newState[treeNode.id]?.props[f2] == store.prevState[treeNode.id]?.props[f2]); + const sameStyles = Object.keys(store.newState[treeNode.id]?.styles ?? {}).every((f2) => store.newState[treeNode.id]?.styles[f2] == store.prevState[treeNode.id]?.styles[f2]); + const sameDepValues = treeNode.execPropsOptions.deps.every((f2) => { + if (f2[0] == "$api") + return true; + if (store.newState[f2[0]]?.[f2[1]]?.[f2[2]] === void 0) + return true; + return store.newState[f2[0]]?.[f2[1]]?.[f2[2]] === store.prevState[f2[0]]?.[f2[1]]?.[f2[2]]; + }); + if (sameProps && sameStyles && sameDepValues && !childDepCheck) { + skipped = true; } - if (mode2 & IterMode.IncludeAnonymous || !parent.type.isAnonymous) - return null; - if (parent.index >= 0) - i4 = parent.index + dir; - else - i4 = dir < 0 ? -1 : parent._parent._tree.children.length; - parent = parent._parent; - if (!parent) - return null; } + if (skipped) + return { id: executionContext.runID, root: executionContext.root, exec: treeNode, state: store.state, slides: store.slides, newState: store.newState, prevState: store.prevState, contexts: executionContext.contexts }; } - get firstChild() { - return this.nextChild(0, 1, 0, 4); - } - get lastChild() { - return this.nextChild(this._tree.children.length - 1, -1, 0, 4); - } - childAfter(pos) { - return this.nextChild(0, 1, pos, 2); + let execState = await executeNode(treeNode, store, executionContext.contexts, executionContext.api); + if (treeNode.node.type == "list") { + let uid = 0; + treeNode.children = ensureArray(execState.state[treeNode.id].props.value).flatMap((f2, i4) => treeNode.execPropsOptions.template.map((n3) => { + const [tree, m4] = linkTreeNodes({ ...n3, node: { ...n3.node, props: { ...n3.node.props, _index: `${i4}`, value: `${treeNode.id}.props.value[${i4}]` } } }, uid); + uid = m4; + return buildExecutable(tree); + })); } - childBefore(pos) { - return this.nextChild(this._tree.children.length - 1, -1, pos, -2); + if (typeof execState.state[treeNode.id]?.actions?.onRun == "function") { + execState.state[treeNode.id].actions?.onRun( + null, + null, + execState, + (s4) => { + executionContext.saveState(s4, { state: execState.state, slides: execState.slides, root: executionContext.root, exec: executionContext.exec, id: executionContext.runID, contexts: executionContext.contexts }); + }, + executionContext.api + ); } - enter(pos, side, mode2 = 0) { - let mounted; - if (!(mode2 & IterMode.IgnoreOverlays) && (mounted = this._tree.prop(NodeProp.mounted)) && mounted.overlay) { - let rPos = pos - this.from; - for (let { from, to: to2 } of mounted.overlay) { - if ((side > 0 ? from <= rPos : from < rPos) && (side < 0 ? to2 >= rPos : to2 > rPos)) - return new TreeNode2(mounted.tree, mounted.overlay[0].from + this.from, -1, this); + treeNode.children = [ + ...treeNode.children.filter((b2) => b2.node.type == "slides"), + ...treeNode.children.filter((b2) => b2.node.type != "slides") + ]; + for (let i4 = 0; i4 < treeNode.children.length; i4++) { + const [newState, newNode2] = await executeTreeNode(treeNode.children[i4], execState, executionContext).then((f2) => [{ state: f2.state, newState: f2.newState, slides: f2.slides, prevState: f2.prevState }, f2.exec]); + execState = newState; + treeNode.children[i4] = newNode2; + if (newNode2.node.type == "slides") { + const prop2 = newState.state[newNode2.id].props.value; + const state = newState.state[newNode2.node.parentId]?.props[prop2]; + let currentSlide; + if (executionContext.selectedSlide) { + currentSlide = newNode2.children.find((f2) => f2.id == executionContext.selectedSlide); + } + if (state !== null && !currentSlide) { + currentSlide = newNode2.children.find((f2) => newState.state[f2.id].props.value == state); + } + if (currentSlide) { + currentSlide.children.forEach((f2) => { + if (!execState.newState[f2.node.ref]) { + execState.newState[f2.node.ref] = { props: {}, styles: {}, actions: {} }; + } + if (f2.node.ref == treeNode.id) { + execState.state[f2.node.ref].props = { ...execState.state[f2.node.ref].props, ...execState.state[f2.node.id].props }; + execState.state[f2.node.ref].styles = { ...execState.state[f2.node.ref].styles, ...execState.state[f2.node.id].styles }; + execState.state[f2.node.ref].actions = { ...execState.state[f2.node.ref].actions, ...execState.state[f2.node.id].actions }; + } else { + execState.newState[f2.node.ref].props = { ...execState.newState[f2.node.ref].props, ...execState.state[f2.node.id].props }; + execState.newState[f2.node.ref].styles = { ...execState.newState[f2.node.ref].styles, ...execState.state[f2.node.id].styles }; + execState.newState[f2.node.ref].actions = { ...execState.newState[f2.node.ref].actions, ...execState.state[f2.node.id].actions }; + } + }); } } - return this.nextChild(0, 1, pos, side, mode2); - } - nextSignificantParent() { - let val = this; - while (val.type.isAnonymous && val._parent) - val = val._parent; - return val; - } - get parent() { - return this._parent ? this._parent.nextSignificantParent() : null; - } - get nextSibling() { - return this._parent && this.index >= 0 ? this._parent.nextChild(this.index + 1, 1, 0, 4) : null; - } - get prevSibling() { - return this._parent && this.index >= 0 ? this._parent.nextChild(this.index - 1, -1, 0, 4) : null; - } - cursor(mode2 = 0) { - return new TreeCursor(this, mode2); - } - get tree() { - return this._tree; - } - toTree() { - return this._tree; - } - resolve(pos, side = 0) { - return resolveNode(this, pos, side, false); - } - resolveInner(pos, side = 0) { - return resolveNode(this, pos, side, true); - } - enterUnfinishedNodesBefore(pos) { - return enterUnfinishedNodesBefore(this, pos); - } - getChild(type, before = null, after = null) { - let r2 = getChildren(this, type, before, after); - return r2.length ? r2[0] : null; - } - getChildren(type, before = null, after = null) { - return getChildren(this, type, before, after); - } - toString() { - return this._tree.toString(); - } - get node() { - return this; - } - matchContext(context) { - return matchNodeContext(this, context); } + return { id: executionContext.runID, root: executionContext.root, exec: treeNode, state: execState.state, slides: execState.slides, newState: execState.newState, prevState: execState.prevState, contexts: executionContext.contexts }; }; -function getChildren(node, type, before, after) { - let cur = node.cursor(), result = []; - if (!cur.firstChild()) - return result; - if (before != null) { - while (!cur.type.is(before)) - if (!cur.nextSibling()) - return result; - } - for (; ; ) { - if (after != null && cur.type.is(after)) - return result; - if (cur.type.is(type)) - result.push(cur.node); - if (!cur.nextSibling()) - return after == null ? result : []; - } -} -function matchNodeContext(node, context, i4 = context.length - 1) { - for (let p = node.parent; i4 >= 0; p = p.parent) { - if (!p) - return false; - if (!p.type.isAnonymous) { - if (context[i4] && context[i4] != p.name) - return false; - i4--; - } - } - return true; -} -var BufferContext = class { - constructor(parent, buffer, index2, start) { - this.parent = parent; - this.buffer = buffer; - this.index = index2; - this.start = start; - } +var executeNode = async (executable, results, contexts, api) => { + const propResults = await executePropsCodeBlocks(executable, results, contexts, api); + const stylesResults = executeCodeBlocks(executable.node, "styles", executable.execStyles, propResults); + const actions = executeCodeBlocks(executable.node, "actions", executable.execActions, stylesResults); + return actions; }; -var BufferNode = class { - constructor(context, _parent, index2) { - this.context = context; - this._parent = _parent; - this.index = index2; - this.type = context.buffer.set.types[context.buffer.buffer[index2]]; - } - get name() { - return this.type.name; - } - get from() { - return this.context.start + this.context.buffer.buffer[this.index + 1]; - } - get to() { - return this.context.start + this.context.buffer.buffer[this.index + 2]; - } - child(dir, pos, side) { - let { buffer } = this.context; - let index2 = buffer.findChild(this.index + 4, buffer.buffer[this.index + 3], dir, pos - this.context.start, side); - return index2 < 0 ? null : new BufferNode(this.context, this, index2); - } - get firstChild() { - return this.child(1, 0, 4); - } - get lastChild() { - return this.child(-1, 0, 4); - } - childAfter(pos) { - return this.child(1, pos, 2); - } - childBefore(pos) { - return this.child(-1, pos, -2); - } - enter(pos, side, mode2 = 0) { - if (mode2 & IterMode.ExcludeBuffers) - return null; - let { buffer } = this.context; - let index2 = buffer.findChild(this.index + 4, buffer.buffer[this.index + 3], side > 0 ? 1 : -1, pos - this.context.start, side); - return index2 < 0 ? null : new BufferNode(this.context, this, index2); - } - get parent() { - return this._parent || this.context.parent.nextSignificantParent(); - } - externalSibling(dir) { - return this._parent ? null : this.context.parent.nextChild(this.context.index + dir, dir, 0, 4); - } - get nextSibling() { - let { buffer } = this.context; - let after = buffer.buffer[this.index + 3]; - if (after < (this._parent ? buffer.buffer[this._parent.index + 3] : buffer.buffer.length)) - return new BufferNode(this.context, this._parent, after); - return this.externalSibling(1); - } - get prevSibling() { - let { buffer } = this.context; - let parentStart = this._parent ? this._parent.index + 4 : 0; - if (this.index == parentStart) - return this.externalSibling(-1); - return new BufferNode(this.context, this._parent, buffer.findChild(parentStart, this.index, -1, 0, 4)); - } - cursor(mode2 = 0) { - return new TreeCursor(this, mode2); - } - get tree() { - return null; - } - toTree() { - let children = [], positions = []; - let { buffer } = this.context; - let startI = this.index + 4, endI = buffer.buffer[this.index + 3]; - if (endI > startI) { - let from = buffer.buffer[this.index + 1], to2 = buffer.buffer[this.index + 2]; - children.push(buffer.slice(startI, endI, from, to2)); - positions.push(0); - } - return new Tree(this.type, children, positions, this.to - this.from); - } - resolve(pos, side = 0) { - return resolveNode(this, pos, side, false); - } - resolveInner(pos, side = 0) { - return resolveNode(this, pos, side, true); - } - enterUnfinishedNodesBefore(pos) { - return enterUnfinishedNodesBefore(this, pos); - } - toString() { - return this.context.buffer.childString(this.index); - } - getChild(type, before = null, after = null) { - let r2 = getChildren(this, type, before, after); - return r2.length ? r2[0] : null; - } - getChildren(type, before = null, after = null) { - return getChildren(this, type, before, after); - } - get node() { - return this; - } - matchContext(context) { - return matchNodeContext(this, context); - } +var executeCode = (code, environment) => { + const isMultiLine = typeof code === "string" || code instanceof String ? code.includes("\n") : false; + const func = isMultiLine ? new Function(`with(this) { ${code} }`) : new Function(`with(this) { return ${code}; }`); + return func.call(environment); }; -var TreeCursor = class { - constructor(node, mode2 = 0) { - this.mode = mode2; - this.buffer = null; - this.stack = []; - this.index = 0; - this.bufferNode = null; - if (node instanceof TreeNode2) { - this.yieldNode(node); - } else { - this._tree = node.context.parent; - this.buffer = node.context; - for (let n3 = node._parent; n3; n3 = n3._parent) - this.stack.unshift(n3.index); - this.bufferNode = node; - this.yieldBuf(node.index); - } - } - get name() { - return this.type.name; - } - yieldNode(node) { - if (!node) - return false; - this._tree = node; - this.type = node.type; - this.from = node.from; - this.to = node.to; - return true; - } - yieldBuf(index2, type) { - this.index = index2; - let { start, buffer } = this.buffer; - this.type = type || buffer.set.types[buffer.buffer[index2]]; - this.from = start + buffer.buffer[index2 + 1]; - this.to = start + buffer.buffer[index2 + 2]; - return true; - } - yield(node) { - if (!node) - return false; - if (node instanceof TreeNode2) { - this.buffer = null; - return this.yieldNode(node); - } - this.buffer = node.context; - return this.yieldBuf(node.index, node.type); - } - toString() { - return this.buffer ? this.buffer.buffer.childString(this.index) : this._tree.toString(); - } - enterChild(dir, pos, side) { - if (!this.buffer) - return this.yield(this._tree.nextChild(dir < 0 ? this._tree._tree.children.length - 1 : 0, dir, pos, side, this.mode)); - let { buffer } = this.buffer; - let index2 = buffer.findChild(this.index + 4, buffer.buffer[this.index + 3], dir, pos - this.buffer.start, side); - if (index2 < 0) - return false; - this.stack.push(this.index); - return this.yieldBuf(index2); - } - firstChild() { - return this.enterChild(1, 0, 4); - } - lastChild() { - return this.enterChild(-1, 0, 4); - } - childAfter(pos) { - return this.enterChild(1, pos, 2); - } - childBefore(pos) { - return this.enterChild(-1, pos, -2); - } - enter(pos, side, mode2 = this.mode) { - if (!this.buffer) - return this.yield(this._tree.enter(pos, side, mode2)); - return mode2 & IterMode.ExcludeBuffers ? false : this.enterChild(1, pos, side); - } - parent() { - if (!this.buffer) - return this.yieldNode(this.mode & IterMode.IncludeAnonymous ? this._tree._parent : this._tree.parent); - if (this.stack.length) - return this.yieldBuf(this.stack.pop()); - let parent = this.mode & IterMode.IncludeAnonymous ? this.buffer.parent : this.buffer.parent.nextSignificantParent(); - this.buffer = null; - return this.yieldNode(parent); - } - sibling(dir) { - if (!this.buffer) - return !this._tree._parent ? false : this.yield(this._tree.index < 0 ? null : this._tree._parent.nextChild(this._tree.index + dir, dir, 0, 4, this.mode)); - let { buffer } = this.buffer, d4 = this.stack.length - 1; - if (dir < 0) { - let parentStart = d4 < 0 ? 0 : this.stack[d4] + 4; - if (this.index != parentStart) - return this.yieldBuf(buffer.findChild(parentStart, this.index, -1, 0, 4)); - } else { - let after = buffer.buffer[this.index + 3]; - if (after < (d4 < 0 ? buffer.buffer.length : buffer.buffer[this.stack[d4] + 3])) - return this.yieldBuf(after); - } - return d4 < 0 ? this.yield(this.buffer.parent.nextChild(this.buffer.index + dir, dir, 0, 4, this.mode)) : false; - } - nextSibling() { - return this.sibling(1); - } - prevSibling() { - return this.sibling(-1); - } - atLastNode(dir) { - let index2, parent, { buffer } = this; - if (buffer) { - if (dir > 0) { - if (this.index < buffer.buffer.buffer.length) - return false; +var executePropsCodeBlocks = async (executable, results, contexts, api) => { + const { id: id3 } = executable.node; + const codeBlockStore = executable.execProps ?? {}; + const environment = results.state; + environment[id3] = { + props: results.state[id3]?.props ?? {}, + actions: results.state[id3]?.actions ?? {}, + styles: results.state[id3]?.styles ?? {} + }; + environment.$contexts = contexts, environment.$api = api; + for (const { name: key2, isConst } of executable.execPropsOptions.props) { + try { + let result; + if (key2 in (results.newState?.[id3]?.["props"] || {}) && isConst) { + result = results.newState[id3]["props"][key2]; } else { - for (let i4 = 0; i4 < this.index; i4++) - if (buffer.buffer.buffer[i4 + 3] < this.index) - return false; + result = codeBlockStore[key2]?.call(environment); } - ({ index: index2, parent } = buffer); - } else { - ({ index: index2, _parent: parent } = this._tree); - } - for (; parent; { index: index2, _parent: parent } = parent) { - if (index2 > -1) - for (let i4 = index2 + dir, e5 = dir < 0 ? -1 : parent._tree.children.length; i4 != e5; i4 += dir) { - let child = parent._tree.children[i4]; - if (this.mode & IterMode.IncludeAnonymous || child instanceof TreeBuffer || !child.type.isAnonymous || hasChild(child)) - return false; - } - } - return true; - } - move(dir, enter) { - if (enter && this.enterChild(dir, 0, 4)) - return true; - for (; ; ) { - if (this.sibling(dir)) - return true; - if (this.atLastNode(dir) || !this.parent()) - return false; - } - } - next(enter = true) { - return this.move(1, enter); - } - prev(enter = true) { - return this.move(-1, enter); - } - moveTo(pos, side = 0) { - while (this.from == this.to || (side < 1 ? this.from >= pos : this.from > pos) || (side > -1 ? this.to <= pos : this.to < pos)) - if (!this.parent()) - break; - while (this.enterChild(1, pos, side)) { - } - return this; - } - get node() { - if (!this.buffer) - return this._tree; - let cache2 = this.bufferNode, result = null, depth = 0; - if (cache2 && cache2.context == this.buffer) { - scan: - for (let index2 = this.index, d4 = this.stack.length; d4 >= 0; ) { - for (let c3 = cache2; c3; c3 = c3._parent) - if (c3.index == index2) { - if (index2 == this.index) - return c3; - result = c3; - depth = d4 + 1; - break scan; - } - index2 = this.stack[--d4]; + if (result !== null) { + environment[id3]["props"][key2] = result; + results.state[id3]["props"][key2] = result; + if (results.newState) { + results.newState[id3] = results.newState[id3] ?? { props: {}, styles: {}, actions: {} }; + results.newState[id3]["props"][key2] = result; } - } - for (let i4 = depth; i4 < this.stack.length; i4++) - result = new BufferNode(this.buffer, result, this.stack[i4]); - return this.bufferNode = new BufferNode(this.buffer, result, this.index); - } - get tree() { - return this.buffer ? null : this._tree._tree; - } - iterate(enter, leave) { - for (let depth = 0; ; ) { - let mustLeave = false; - if (this.type.isAnonymous || enter(this) !== false) { - if (this.firstChild()) { - depth++; - continue; + } else { + delete environment[id3]["props"][key2]; + delete results.state[id3]["props"][key2]; + if (results.newState?.[id3]) { + delete results.newState[id3]["props"][key2]; } - if (!this.type.isAnonymous) - mustLeave = true; - } - for (; ; ) { - if (mustLeave && leave) - leave(this); - mustLeave = this.type.isAnonymous; - if (this.nextSibling()) - break; - if (!depth) - return; - this.parent(); - depth--; - mustLeave = true; - } - } - } - matchContext(context) { - if (!this.buffer) - return matchNodeContext(this.node, context); - let { buffer } = this.buffer, { types: types2 } = buffer.set; - for (let i4 = context.length - 1, d4 = this.stack.length - 1; i4 >= 0; d4--) { - if (d4 < 0) - return matchNodeContext(this.node, context, i4); - let type = types2[buffer.buffer[this.stack[d4]]]; - if (!type.isAnonymous) { - if (context[i4] && context[i4] != type.name) - return false; - i4--; } + } catch (error) { + console.log(key2, error); } - return true; } + return results; }; -function hasChild(tree) { - return tree.children.some((ch) => ch instanceof TreeBuffer || !ch.type.isAnonymous || hasChild(ch)); -} -function buildTree(data2) { - var _a; - let { buffer, nodeSet, maxBufferLength = DefaultBufferLength, reused = [], minRepeatType = nodeSet.types.length } = data2; - let cursor2 = Array.isArray(buffer) ? new FlatBufferCursor(buffer, buffer.length) : buffer; - let types2 = nodeSet.types; - let contextHash = 0, lookAhead = 0; - function takeNode(parentStart, minPos, children2, positions2, inRepeat) { - let { id: id3, start, end, size: size2 } = cursor2; - let lookAheadAtStart = lookAhead; - while (size2 < 0) { - cursor2.next(); - if (size2 == -1) { - let node2 = reused[id3]; - children2.push(node2); - positions2.push(start - parentStart); - return; - } else if (size2 == -3) { - contextHash = id3; - return; - } else if (size2 == -4) { - lookAhead = id3; - return; - } else { - throw new RangeError(`Unrecognized record size: ${size2}`); - } - } - let type = types2[id3], node, buffer2; - let startPos = start - parentStart; - if (end - start <= maxBufferLength && (buffer2 = findBufferSize(cursor2.pos - minPos, inRepeat))) { - let data3 = new Uint16Array(buffer2.size - buffer2.skip); - let endPos = cursor2.pos - buffer2.size, index2 = data3.length; - while (cursor2.pos > endPos) - index2 = copyToBuffer(buffer2.start, data3, index2); - node = new TreeBuffer(data3, end - buffer2.start, nodeSet); - startPos = buffer2.start - parentStart; - } else { - let endPos = cursor2.pos - size2; - cursor2.next(); - let localChildren = [], localPositions = []; - let localInRepeat = id3 >= minRepeatType ? id3 : -1; - let lastGroup = 0, lastEnd = end; - while (cursor2.pos > endPos) { - if (localInRepeat >= 0 && cursor2.id == localInRepeat && cursor2.size >= 0) { - if (cursor2.end <= lastEnd - maxBufferLength) { - makeRepeatLeaf(localChildren, localPositions, start, lastGroup, cursor2.end, lastEnd, localInRepeat, lookAheadAtStart); - lastGroup = localChildren.length; - lastEnd = cursor2.end; - } - cursor2.next(); - } else { - takeNode(start, endPos, localChildren, localPositions, localInRepeat); - } - } - if (localInRepeat >= 0 && lastGroup > 0 && lastGroup < localChildren.length) - makeRepeatLeaf(localChildren, localPositions, start, lastGroup, start, lastEnd, localInRepeat, lookAheadAtStart); - localChildren.reverse(); - localPositions.reverse(); - if (localInRepeat > -1 && lastGroup > 0) { - let make = makeBalanced(type); - node = balanceRange(type, localChildren, localPositions, 0, localChildren.length, 0, end - start, make, make); +function executeCodeBlocks(node, type, codeBlockStore, results) { + const { id: id3 } = node; + for (const key2 of Object.keys(codeBlockStore)) { + let result; + try { + if (key2 in (results.newState?.[id3]?.[type] || {})) { + result = results.newState[id3][type][key2]; } else { - node = makeTree(type, localChildren, localPositions, end - start, lookAheadAtStart - end); - } - } - children2.push(node); - positions2.push(startPos); - } - function makeBalanced(type) { - return (children2, positions2, length2) => { - let lookAhead2 = 0, lastI = children2.length - 1, last, lookAheadProp; - if (lastI >= 0 && (last = children2[lastI]) instanceof Tree) { - if (!lastI && last.type == type && last.length == length2) - return last; - if (lookAheadProp = last.prop(NodeProp.lookAhead)) - lookAhead2 = positions2[lastI] + last.length + lookAheadProp; - } - return makeTree(type, children2, positions2, length2, lookAhead2); - }; - } - function makeRepeatLeaf(children2, positions2, base2, i4, from, to2, type, lookAhead2) { - let localChildren = [], localPositions = []; - while (children2.length > i4) { - localChildren.push(children2.pop()); - localPositions.push(positions2.pop() + base2 - from); - } - children2.push(makeTree(nodeSet.types[type], localChildren, localPositions, to2 - from, lookAhead2 - to2)); - positions2.push(from - base2); - } - function makeTree(type, children2, positions2, length2, lookAhead2 = 0, props) { - if (contextHash) { - let pair2 = [NodeProp.contextHash, contextHash]; - props = props ? [pair2].concat(props) : [pair2]; - } - if (lookAhead2 > 25) { - let pair2 = [NodeProp.lookAhead, lookAhead2]; - props = props ? [pair2].concat(props) : [pair2]; - } - return new Tree(type, children2, positions2, length2, props); - } - function findBufferSize(maxSize, inRepeat) { - let fork = cursor2.fork(); - let size2 = 0, start = 0, skip = 0, minStart = fork.end - maxBufferLength; - let result = { size: 0, start: 0, skip: 0 }; - scan: - for (let minPos = fork.pos - maxSize; fork.pos > minPos; ) { - let nodeSize4 = fork.size; - if (fork.id == inRepeat && nodeSize4 >= 0) { - result.size = size2; - result.start = start; - result.skip = skip; - skip += 4; - size2 += 4; - fork.next(); - continue; - } - let startPos = fork.pos - nodeSize4; - if (nodeSize4 < 0 || startPos < minPos || fork.start < minStart) - break; - let localSkipped = fork.id >= minRepeatType ? 4 : 0; - let nodeStart = fork.start; - fork.next(); - while (fork.pos > startPos) { - if (fork.size < 0) { - if (fork.size == -3) - localSkipped += 4; - else - break scan; - } else if (fork.id >= minRepeatType) { - localSkipped += 4; - } - fork.next(); - } - start = nodeStart; - size2 += nodeSize4; - skip += localSkipped; - } - if (inRepeat < 0 || size2 == maxSize) { - result.size = size2; - result.start = start; - result.skip = skip; - } - return result.size > 4 ? result : void 0; - } - function copyToBuffer(bufferStart, buffer2, index2) { - let { id: id3, start, end, size: size2 } = cursor2; - cursor2.next(); - if (size2 >= 0 && id3 < minRepeatType) { - let startIndex = index2; - if (size2 > 4) { - let endPos = cursor2.pos - (size2 - 4); - while (cursor2.pos > endPos) - index2 = copyToBuffer(bufferStart, buffer2, index2); - } - buffer2[--index2] = startIndex; - buffer2[--index2] = end - bufferStart; - buffer2[--index2] = start - bufferStart; - buffer2[--index2] = id3; - } else if (size2 == -3) { - contextHash = id3; - } else if (size2 == -4) { - lookAhead = id3; - } - return index2; - } - let children = [], positions = []; - while (cursor2.pos > 0) - takeNode(data2.start || 0, data2.bufferStart || 0, children, positions, -1); - let length = (_a = data2.length) !== null && _a !== void 0 ? _a : children.length ? positions[0] + children[0].length : 0; - return new Tree(types2[data2.topID], children.reverse(), positions.reverse(), length); -} -var nodeSizeCache = /* @__PURE__ */ new WeakMap(); -function nodeSize(balanceType, node) { - if (!balanceType.isAnonymous || node instanceof TreeBuffer || node.type != balanceType) - return 1; - let size2 = nodeSizeCache.get(node); - if (size2 == null) { - size2 = 1; - for (let child of node.children) { - if (child.type != balanceType || !(child instanceof Tree)) { - size2 = 1; - break; - } - size2 += nodeSize(balanceType, child); - } - nodeSizeCache.set(node, size2); - } - return size2; -} -function balanceRange(balanceType, children, positions, from, to2, start, length, mkTop, mkTree) { - let total = 0; - for (let i4 = from; i4 < to2; i4++) - total += nodeSize(balanceType, children[i4]); - let maxChild = Math.ceil(total * 1.5 / 8); - let localChildren = [], localPositions = []; - function divide3(children2, positions2, from2, to3, offset2) { - for (let i4 = from2; i4 < to3; ) { - let groupFrom = i4, groupStart = positions2[i4], groupSize = nodeSize(balanceType, children2[i4]); - i4++; - for (; i4 < to3; i4++) { - let nextSize = nodeSize(balanceType, children2[i4]); - if (groupSize + nextSize >= maxChild) - break; - groupSize += nextSize; + result = codeBlockStore[key2]?.call(results.state); } - if (i4 == groupFrom + 1) { - if (groupSize > maxChild) { - let only = children2[groupFrom]; - divide3(only.children, only.positions, 0, only.children.length, positions2[groupFrom] + offset2); - continue; - } - localChildren.push(children2[groupFrom]); + if (result !== null) { + results.state[node.id][type][key2] = result; } else { - let length2 = positions2[i4 - 1] + children2[i4 - 1].length - groupStart; - localChildren.push(balanceRange(balanceType, children2, positions2, groupFrom, i4, groupStart, length2, null, mkTree)); + delete results.state[node.id][type][key2]; } - localPositions.push(groupStart + offset2 - start); + } catch (error) { + console.log(error, key2); } } - divide3(children, positions, from, to2, 0); - return (mkTop || mkTree)(localChildren, localPositions, length); + return results; } -var Parser4 = class { - startParse(input, fragments, ranges) { - if (typeof input == "string") - input = new StringInput(input); - ranges = !ranges ? [new Range2(0, input.length)] : ranges.length ? ranges.map((r2) => new Range2(r2.from, r2.to)) : [new Range2(0, 0)]; - return this.createParse(input, fragments || [], ranges); - } - parse(input, fragments, ranges) { - let parse7 = this.startParse(input, fragments, ranges); - for (; ; ) { - let done = parse7.advance(); - if (done) - return done; - } - } + +// src/core/react/components/SpaceEditor/Actions/ActionTester.tsx +var import_react14 = __toESM(require_react()); + +// src/core/utils/contexts/predicate/filter.ts +var listEquals = (value, filterValue) => { + const valueList = value ? parseMultiString(value) : []; + const strings = filterValue ? parseMultiString(filterValue) : []; + return strings.every((f2) => valueList.some((g) => g == f2)) && valueList.every((f2) => strings.some((g) => g == f2)); }; -var StringInput = class { - constructor(string4) { - this.string = string4; - } - get length() { - return this.string.length; - } - chunk(from) { - return this.string.slice(from); - } - get lineChunks() { +var stringEqual = (value, filterValue) => { + return value == filterValue; +}; +var empty2 = (value, filterValue) => { + return (value ?? "").length == 0; +}; +var stringCompare = (value, filterValue) => { + return (value ?? "").toLowerCase().includes((filterValue ?? "").toLowerCase()); +}; +var greaterThan = (value, filterValue) => { + return parseFloat(value) > parseFloat(filterValue); +}; +var lessThan = (value, filterValue) => { + return parseInt(value) < parseInt(filterValue); +}; +var dateAfter = (value, filterValue) => { + const dateValue = isNaN(Date.parse(value)) ? new Date(parseInt(value)) : new Date(value); + const dateFilterValue = isNaN(Date.parse(filterValue)) ? new Date(parseInt(filterValue)) : new Date(filterValue); + return dateValue.valueOf() >= dateFilterValue.valueOf(); +}; +var dateBefore = (value, filterValue) => { + const dateValue = isNaN(Date.parse(value)) ? new Date(parseInt(value)) : new Date(value); + const dateFilterValue = isNaN(Date.parse(filterValue)) ? new Date(parseInt(filterValue)) : new Date(filterValue); + return dateValue.valueOf() < dateFilterValue.valueOf(); +}; +var listIncludes = (value, filterValue) => { + const valueList = value ? parseMultiString(value) : []; + const strings = filterValue ? parseMultiString(filterValue) : []; + if (valueList.length == 0) return false; + return strings.some((f2) => valueList.some((g) => g == f2)); +}; +var isSameDay2 = (value, filterValue) => { + if (!value) + return false; + const inputDate = new Date(`${value.toString().replace(".", ":")}`); + const currentDate = new Date(`${filterValue}`); + return inputDate.getMonth() === currentDate.getMonth() && inputDate.getDate() === currentDate.getDate(); +}; +var isSameDayAsToday = (value) => { + if (!value) + return false; + const inputDate = new Date(`${value.toString()}T00:00`); + const currentDate = new Date(); + return inputDate.getMonth() === currentDate.getMonth() && inputDate.getDate() === currentDate.getDate(); +}; +var filterReturnForCol = (col, filter4, row2, properties3) => { + if (!col) + return true; + const filterType = filterFnTypes[filter4?.fn]; + let result = true; + if (filterType && filterType.fn) { + const value = filter4.fType == "property" ? properties3[filter4.value] : filter4.value; + result = filterType.fn(row2[filter4.field], value); } - read(from, to2) { - return this.string.slice(from, to2); - } + return result; }; -var stoppedInner = new NodeProp({ perNode: true }); -// node_modules/@lezer/javascript/node_modules/@lezer/lr/dist/index.js -var Stack = class { - constructor(p, stack, state, reducePos, pos, score, buffer, bufferBase, curContext, lookAhead = 0, parent) { - this.p = p; - this.stack = stack; - this.state = state; - this.reducePos = reducePos; - this.pos = pos; - this.score = score; - this.buffer = buffer; - this.bufferBase = bufferBase; - this.curContext = curContext; - this.lookAhead = lookAhead; - this.parent = parent; - } - toString() { - return `[${this.stack.filter((_15, i4) => i4 % 3 == 0).concat(this.state)}]@${this.pos}${this.score ? "!" + this.score : ""}`; - } - static start(p, state, pos = 0) { - let cx = p.parser.context; - return new Stack(p, [], state, pos, pos, 0, [], 0, cx ? new StackContext(cx, cx.start) : null, 0, null); +// src/core/utils/contexts/predicate/filterFns/filterFnTypes.ts +var filterFnTypes = { + isNotEmpty: { + type: ["text", "file", "number", "option", "option-multi", "link", "link-multi", "image"], + fn: (v2, f2) => !empty2(v2, ""), + valueType: "none" + }, + isEmpty: { + type: ["text", "file", "number", "option", "option-multi", "link", "link-multi", "image"], + fn: (v2, f2) => empty2(v2, ""), + valueType: "none" + }, + include: { + fn: (v2, f2) => stringCompare(v2, f2), + type: ["text", "file", "link", "image"], + valueType: "text" + }, + notInclude: { + type: ["text", "file", "link", "image"], + fn: (v2, f2) => !stringCompare(v2, f2), + valueType: "text" + }, + is: { + type: ["text"], + fn: (v2, f2) => stringEqual(v2, f2), + valueType: "text" + }, + isNot: { + type: ["text"], + fn: (v2, f2) => !stringEqual(v2, f2), + valueType: "text" + }, + equal: { + type: ["number"], + fn: (v2, f2) => stringEqual(v2, f2), + valueType: "number" + }, + isLink: { + type: ["link", "context"], + fn: (v2, f2) => stringEqual(v2, f2), + valueType: "link" + }, + isNotLink: { + type: ["link", "context"], + fn: (v2, f2) => !stringEqual(v2, f2), + valueType: "link" + }, + isGreatThan: { + type: ["number"], + fn: (v2, f2) => greaterThan(v2, f2), + valueType: "number" + }, + isLessThan: { + type: ["number"], + fn: (v2, f2) => lessThan(v2, f2), + valueType: "number" + }, + isLessThanOrEqual: { + type: ["number"], + fn: (v2, f2) => !greaterThan(v2, f2), + valueType: "number" + }, + isGreatThanOrEqual: { + type: ["number"], + fn: (v2, f2) => !lessThan(v2, f2), + valueType: "number" + }, + dateBefore: { + type: ["date"], + fn: (v2, f2) => dateBefore(v2, f2), + valueType: "date" + }, + dateAfter: { + type: ["date"], + fn: (v2, f2) => dateAfter(v2, f2), + valueType: "date" + }, + isSameDate: { + type: ["date"], + fn: (v2, f2) => isSameDay2(v2, f2), + valueType: "date" + }, + isSameDateAsToday: { + type: ["date"], + fn: (v2, f2) => isSameDayAsToday(v2, f2), + valueType: "none" + }, + isExactList: { + type: ["option", "option-multi", "link-multi", "context-multi", "tags-multi"], + fn: (v2, f2) => listEquals(v2, f2), + valueType: "list" + }, + isAnyInList: { + type: ["option", "context", "link", "option-multi", "link-multi", "context-multi", "tags-multi"], + fn: (v2, f2) => listIncludes(v2, f2), + valueType: "list" + }, + isNoneInList: { + type: ["option", "context", "link", "option-multi", "link-multi", "context-multi", "tags-multi"], + fn: (v2, f2) => !listIncludes(v2, f2), + valueType: "list" + }, + isTrue: { + type: ["boolean"], + fn: (v2, f2) => v2 == "true", + valueType: "none" + }, + isFalse: { + type: ["boolean"], + fn: (v2, f2) => v2 != "true", + valueType: "none" } - get context() { - return this.curContext ? this.curContext.context : null; +}; + +// src/core/utils/commands/filter.ts +var filterForAny = (props, filters) => { + return filters.reduce((p, c3) => { + if (p == true) + return true; + return props ? filterForProps(props, c3) : false; + }, false); +}; +var filterForProps = (props, def) => { + const filterFn = filterFnTypes[def.fn]; + let result = true; + if (filterFn) { + result = filterFn.fn(parseProperty(def.field, props[def.field]), def.value); } - pushState(state, start) { - this.stack.push(this.state, start, this.bufferBase + this.buffer.length); - this.state = state; + return result; +}; +var filterPathsForAll = (props, filters) => { + return filters.reduce((p, c3) => { + if (p == false) + return false; + return props ? filterForProps(props, c3) : false; + }, true); +}; +var resultForFilters = (filters, props) => { + const pathInFilter = filters.reduce((p, c3) => { + if (!p || c3.filters.length == 0) + return false; + const result = c3.type == "any" ? filterForAny(props, c3.filters) : filterPathsForAll(props, c3.filters); + return result; + }, true); + return pathInFilter; +}; + +// src/core/utils/commands/actions.ts +var import_lodash8 = __toESM(require_lodash()); +var parseActionString = (actionString) => { + return safelyParseJSON(actionString); +}; +var runActionString = async (superstate, actionString, instance) => { + const actionTree = parseActionString(actionString); + return runActionTree(superstate, actionTree, instance); +}; +var runActionTree = async (superstate, actionTree, instance) => { + if (instance.iterations > superstate.settings.actionMaxSteps) { + alert("Max steps reached, you can change this in settings."); + return; } - reduce(action) { - let depth = action >> 19, type = action & 65535; - let { parser: parser3 } = this.p; - let dPrec = parser3.dynamicPrecedence(type); - if (dPrec) - this.score += dPrec; - if (depth == 0) { - this.pushState(parser3.getGoto(this.state, type, true), this.reducePos); - if (type < parser3.minRepeatTerm) - this.storeNode(type, this.reducePos, this.reducePos, 4, true); - this.reduceContext(type, this.reducePos); - return; - } - let base2 = this.stack.length - (depth - 1) * 3 - (action & 262144 ? 6 : 0); - let start = this.stack[base2 - 2]; - let bufferBase = this.stack[base2 - 1], count3 = this.bufferBase + this.buffer.length - bufferBase; - if (type < parser3.minRepeatTerm || action & 131072) { - let pos = parser3.stateFlag(this.state, 1) ? this.pos : this.reducePos; - this.storeNode(type, start, pos, count3 + 4, true); + const newInstance = { + ...instance, + iterations: instance.iterations + 1, + props: { + ...actionTree?.props ?? {}, + ...Object.keys(actionTree.linked ?? {}).reduce( + (p, c3) => ({ ...p, [c3]: instance.instanceProps[actionTree.linked[c3]] }), + {} + ), + ...actionTree.result ? { [actionTree.result]: instance.result } : {} } - if (action & 262144) { - this.state = this.stack[base2]; - } else { - let baseStateID = this.stack[base2 - 3]; - this.state = parser3.getGoto(baseStateID, type, true); + }; + const action = superstate.cli.commandForAction(actionTree.action); + if (action.schema.type == "builtin") { + if (action.schema.id == "loop" && (0, import_lodash8.isArray)(instance.result)) { + const loopResults = await Promise.all( + instance.result.map( + (item) => Promise.all( + actionTree.children.map( + (child) => runActionTree(superstate, child, resultInstance) + ) + ).then((results) => results[results.length - 1]) + ) + ); + return loopResults; } - while (this.stack.length > base2) - this.stack.pop(); - this.reduceContext(type, start); - } - storeNode(term, start, end, size2 = 4, isReduce = false) { - if (term == 0 && (!this.stack.length || this.stack[this.stack.length - 1] < this.buffer.length + this.bufferBase)) { - let cur = this, top = this.buffer.length; - if (top == 0 && cur.parent) { - top = cur.bufferBase - cur.parent.bufferBase; - cur = cur.parent; - } - if (top > 0 && cur.buffer[top - 4] == 0 && cur.buffer[top - 1] > -1) { - if (start == end) - return; - if (cur.buffer[top - 2] >= start) { - cur.buffer[top - 2] = end; - return; - } + if (action.schema.id == "filter") { + const result2 = resultForFilters( + actionTree.props.$function, + newInstance.instanceProps + ); + if (!result2) { + return; } } - if (!isReduce || this.pos == end) { - this.buffer.push(term, start, end, size2); - } else { - let index2 = this.buffer.length; - if (index2 > 0 && this.buffer[index2 - 4] != 0) - while (index2 > 0 && this.buffer[index2 - 2] > end) { - this.buffer[index2] = this.buffer[index2 - 4]; - this.buffer[index2 + 1] = this.buffer[index2 - 3]; - this.buffer[index2 + 2] = this.buffer[index2 - 2]; - this.buffer[index2 + 3] = this.buffer[index2 - 1]; - index2 -= 4; - if (size2 > 4) - size2 -= 4; - } - this.buffer[index2] = term; - this.buffer[index2 + 1] = start; - this.buffer[index2 + 2] = end; - this.buffer[index2 + 3] = size2; - } } - shift(action, next, nextEnd) { - let start = this.pos; - if (action & 131072) { - this.pushState(action & 65535, this.pos); - } else if ((action & 262144) == 0) { - let nextState = action, { parser: parser3 } = this.p; - if (nextEnd > this.pos || next <= parser3.maxNode) { - this.pos = nextEnd; - if (!parser3.stateFlag(nextState, 1)) - this.reducePos = nextEnd; - } - this.pushState(nextState, start); - this.shiftContext(next, start); - if (next <= parser3.maxNode) - this.buffer.push(next, start, nextEnd, 4); + let result; + try { + if (action.schema.type == "api") { + const [namespace, method] = action.schema.id.split("."); + result = await superstate.api[namespace]?.[method]?.(...action.fields.map((f2) => newInstance.props[f2.name])); } else { - this.pos = nextEnd; - this.shiftContext(next, start); - if (next <= this.p.parser.maxNode) - this.buffer.push(next, start, nextEnd, 4); - } - } - apply(action, next, nextEnd) { - if (action & 65536) - this.reduce(action); - else - this.shift(action, next, nextEnd); - } - useNode(value, next) { - let index2 = this.p.reused.length - 1; - if (index2 < 0 || this.p.reused[index2] != value) { - this.p.reused.push(value); - index2++; - } - let start = this.pos; - this.reducePos = this.pos = start + value.length; - this.pushState(next, start); - this.buffer.push(index2, start, this.reducePos, -1); - if (this.curContext) - this.updateContext(this.curContext.tracker.reuse(this.curContext.context, value, this, this.p.stream.reset(this.pos - value.length))); - } - split() { - let parent = this; - let off = parent.buffer.length; - while (off > 0 && parent.buffer[off - 2] > parent.reducePos) - off -= 4; - let buffer = parent.buffer.slice(off), base2 = parent.bufferBase + off; - while (parent && base2 == parent.bufferBase) - parent = parent.parent; - return new Stack(this.p, this.stack.slice(), this.state, this.reducePos, this.pos, this.score, buffer, base2, this.curContext, this.lookAhead, parent); - } - recoverByDelete(next, nextEnd) { - let isNode3 = next <= this.p.parser.maxNode; - if (isNode3) - this.storeNode(next, this.pos, nextEnd, 4); - this.storeNode(0, this.pos, nextEnd, isNode3 ? 8 : 4); - this.pos = this.reducePos = nextEnd; - this.score -= 190; - } - canShift(term) { - for (let sim = new SimulatedStack(this); ; ) { - let action = this.p.parser.stateSlot(sim.state, 4) || this.p.parser.hasAction(sim.state, term); - if ((action & 65536) == 0) - return true; - if (action == 0) - return false; - sim.reduce(action); + result = await superstate.cli.runCommand( + actionTree.action, + newInstance + ); } + } catch (e5) { + console.error(e5); } - recoverByInsert(next) { - if (this.stack.length >= 300) - return []; - let nextStates = this.p.parser.nextStates(this.state); - if (nextStates.length > 4 << 1 || this.stack.length >= 120) { - let best = []; - for (let i4 = 0, s4; i4 < nextStates.length; i4 += 2) { - if ((s4 = nextStates[i4 + 1]) != this.state && this.p.parser.hasAction(s4, next)) - best.push(nextStates[i4], s4); - } - if (this.stack.length < 120) - for (let i4 = 0; best.length < 4 << 1 && i4 < nextStates.length; i4 += 2) { - let s4 = nextStates[i4 + 1]; - if (!best.some((v2, i5) => i5 & 1 && v2 == s4)) - best.push(nextStates[i4], s4); - } - nextStates = best; - } - let result = []; - for (let i4 = 0; i4 < nextStates.length && result.length < 4; i4 += 2) { - let s4 = nextStates[i4 + 1]; - if (s4 == this.state) - continue; - let stack = this.split(); - stack.pushState(s4, this.pos); - stack.storeNode(0, stack.pos, stack.pos, 4, true); - stack.shiftContext(nextStates[i4], this.pos); - stack.score -= 200; - result.push(stack); - } + const resultInstance = { + ...newInstance, + result + }; + if (actionTree.children?.length === 0) return result; - } - forceReduce() { - let reduce2 = this.p.parser.stateSlot(this.state, 5); - if ((reduce2 & 65536) == 0) - return false; - let { parser: parser3 } = this.p; - if (!parser3.validAction(this.state, reduce2)) { - let depth = reduce2 >> 19, term = reduce2 & 65535; - let target = this.stack.length - depth * 3; - if (target < 0 || parser3.getGoto(this.stack[target], term, false) < 0) - return false; - this.storeNode(0, this.reducePos, this.reducePos, 4, true); - this.score -= 100; - } - this.reducePos = this.pos; - this.reduce(reduce2); - return true; - } - forceAll() { - while (!this.p.parser.stateFlag(this.state, 2)) { - if (!this.forceReduce()) { - this.storeNode(0, this.pos, this.pos, 4, true); - break; + const childrenResults = await Promise.all( + actionTree.children.map( + (child) => runActionTree(superstate, child, resultInstance) + ) + ); + return childrenResults[childrenResults.length - 1]; +}; + +// src/core/react/components/SpaceEditor/Actions/ActionTester.tsx +var ActionTester = (props) => { + const path2 = props.superstate.pathsIndex.get(props.path); + const [fieldValues, setFieldValues] = (0, import_react14.useState)({}); + const [result, setResult] = (0, import_react14.useState)(); + const [error, setError] = (0, import_react14.useState)(); + const runCommand = async () => { + const values2 = Object.keys(fieldValues).reduce( + (f2, g) => { + const col = props.fields.find((c3) => c3.name == g); + const value = parsePropertyValue(col.type, fieldValues[g]); + if (value?.length > 0) + return { ...f2, [g]: parsePropertyValue(col.type, fieldValues[g]) }; + return f2; + }, + { + ...props.value, + $api: props.superstate.api, + $contexts: { + $space: { + path: path2 + }, + $context: {} + }, + $properties: props.fields } + ); + let result2; + let error2; + try { + if (props.type == "actions") + result2 = await runActionString(props.superstate, props.code, { + props: {}, + instanceProps: values2, + iterations: 0 + }); + if (props.type == "script") + result2 = await executeCode(props.code, values2); + if (props.type == "formula") + result2 = await runFormulaWithContext( + props.superstate.formulaContext, + props.superstate.pathsIndex, + props.code, + props.fields.reduce((p, c3) => ({ ...p, [c3.name]: c3 }), {}), + values2, + path2, + true + ); + } catch (e5) { + error2 = e5; } - return this; - } - get deadEnd() { - if (this.stack.length != 3) - return false; - let { parser: parser3 } = this.p; - return parser3.data[parser3.stateSlot(this.state, 1)] == 65535 && !parser3.stateSlot(this.state, 4); - } - restart() { - this.state = this.stack[0]; - this.stack.length = 0; - } - sameState(other) { - if (this.state != other.state || this.stack.length != other.stack.length) - return false; - for (let i4 = 0; i4 < this.stack.length; i4 += 3) - if (this.stack[i4] != other.stack[i4]) - return false; - return true; - } - get parser() { - return this.p.parser; - } - dialectEnabled(dialectID) { - return this.p.parser.dialect.flags[dialectID]; - } - shiftContext(term, start) { - if (this.curContext) - this.updateContext(this.curContext.tracker.shift(this.curContext.context, term, this, this.p.stream.reset(start))); - } - reduceContext(term, start) { - if (this.curContext) - this.updateContext(this.curContext.tracker.reduce(this.curContext.context, term, this, this.p.stream.reset(start))); - } - emitContext() { - let last = this.buffer.length - 1; - if (last < 0 || this.buffer[last] != -3) - this.buffer.push(this.curContext.hash, this.reducePos, this.reducePos, -3); - } - emitLookAhead() { - let last = this.buffer.length - 1; - if (last < 0 || this.buffer[last] != -4) - this.buffer.push(this.lookAhead, this.reducePos, this.reducePos, -4); - } - updateContext(context) { - if (context != this.curContext.context) { - let newCx = new StackContext(this.curContext.tracker, context); - if (newCx.hash != this.curContext.hash) - this.emitContext(); - this.curContext = newCx; - } - } - setLookAhead(lookAhead) { - if (lookAhead > this.lookAhead) { - this.emitLookAhead(); - this.lookAhead = lookAhead; - } - } - close() { - if (this.curContext && this.curContext.tracker.strict) - this.emitContext(); - if (this.lookAhead > 0) - this.emitLookAhead(); - } + setResult(result2); + setError(error2); + }; + return /* @__PURE__ */ import_react14.default.createElement("div", { + className: "mk-editor-tester" + }, "= ", result && String(result), /* @__PURE__ */ import_react14.default.createElement("div", { + className: "mk-menu-separator" + }), /* @__PURE__ */ import_react14.default.createElement("span", null), /* @__PURE__ */ import_react14.default.createElement("button", { + onClick: () => runCommand() + }, i18n_default.buttons.run)); }; -var StackContext = class { - constructor(tracker, context) { - this.tracker = tracker; - this.context = context; - this.hash = tracker.strict ? tracker.hash(context) : 0; - } + +// src/core/react/components/SpaceEditor/Actions/FormulaEditor.tsx +var FormulaEditor = (props) => { + const [formula, setFormula] = (0, import_react15.useState)(props.formula); + const saveFormula = (fml) => { + setFormula(fml); + }; + const save = () => { + props.saveFormula(formula); + props.hide(); + }; + (0, import_react15.useEffect)(() => { + setFormula(props.formula); + }, [props.formula]); + return /* @__PURE__ */ import_react15.default.createElement("div", { + className: "mk-editor-formula" + }, /* @__PURE__ */ import_react15.default.createElement("div", { + className: "mk-space-editor-header" + }, /* @__PURE__ */ import_react15.default.createElement("div", { + className: "mk-space-editor-header-title" + }, /* @__PURE__ */ import_react15.default.createElement("div", { + className: "mk-space-editor-title" + }, "Formula"), /* @__PURE__ */ import_react15.default.createElement("div", { + className: "mk-space-editor-description" + }, props.description ?? "Use formula to filter and transform your data")), /* @__PURE__ */ import_react15.default.createElement("span", null), /* @__PURE__ */ import_react15.default.createElement("button", { + "aria-label": "Save Formula", + onClick: () => save() + }, "Done")), /* @__PURE__ */ import_react15.default.createElement(esm_default, { + value: formula, + height: "200px", + theme: abcdef, + basicSetup: { + syntaxHighlighting: true, + history: true, + closeBrackets: true, + autocompletion: true, + defaultKeymap: true, + lineNumbers: false + }, + extensions: [javascript()], + onChange: saveFormula + }), /* @__PURE__ */ import_react15.default.createElement(ActionTester, { + type: "formula", + code: formula, + fields: props.fields, + value: props.value, + superstate: props.superstate, + path: props.path + })); }; -var Recover; -(function(Recover2) { - Recover2[Recover2["Insert"] = 200] = "Insert"; - Recover2[Recover2["Delete"] = 190] = "Delete"; - Recover2[Recover2["Reduce"] = 100] = "Reduce"; - Recover2[Recover2["MaxNext"] = 4] = "MaxNext"; - Recover2[Recover2["MaxInsertStackDepth"] = 300] = "MaxInsertStackDepth"; - Recover2[Recover2["DampenInsertStackDepth"] = 120] = "DampenInsertStackDepth"; -})(Recover || (Recover = {})); -var SimulatedStack = class { - constructor(start) { - this.start = start; - this.state = start.state; - this.stack = start.stack; - this.base = this.stack.length; - } - reduce(action) { - let term = action & 65535, depth = action >> 19; - if (depth == 0) { - if (this.stack == this.start.stack) - this.stack = this.stack.slice(); - this.stack.push(this.state, 0, 0); - this.base += 3; - } else { - this.base -= (depth - 1) * 3; - } - let goto = this.start.p.parser.getGoto(this.stack[this.base - 3], term, true); - this.state = goto; - } + +// src/core/utils/contexts/predicate/sort.ts +var simpleSort = (a4, b2) => { + if (a4 < b2) + return -1; + if (a4 > b2) + return 1; + return 0; }; -var StackBufferCursor = class { - constructor(stack, pos, index2) { - this.stack = stack; - this.pos = pos; - this.index = index2; - this.buffer = stack.buffer; - if (this.index == 0) - this.maybeNext(); - } - static create(stack, pos = stack.bufferBase + stack.buffer.length) { - return new StackBufferCursor(stack, pos, pos - stack.bufferBase); - } - maybeNext() { - let next = this.stack.parent; - if (next != null) { - this.index = this.stack.bufferBase - next.bufferBase; - this.stack = next; - this.buffer = next.buffer; - } - } - get id() { - return this.buffer[this.index - 4]; - } - get start() { - return this.buffer[this.index - 3]; - } - get end() { - return this.buffer[this.index - 2]; - } - get size() { - return this.buffer[this.index - 1]; - } - next() { - this.index -= 4; - this.pos -= 4; - if (this.index == 0) - this.maybeNext(); - } - fork() { - return new StackBufferCursor(this.stack, this.pos, this.index); - } +var linkSort = (value, filterValue) => { + const a4 = value.split("/").pop(); + const b2 = filterValue.split("/").pop(); + return simpleSort(a4.toLowerCase(), b2.toLowerCase()); }; -var CachedToken = class { - constructor() { - this.start = -1; - this.value = -1; - this.end = -1; - this.extended = -1; - this.lookAhead = 0; - this.mask = 0; - this.context = 0; +var stringSort = (value, filterValue) => simpleSort(value.toLowerCase(), filterValue.toLowerCase()); +var numSort = (value, filterValue) => simpleSort(parseFloat(value), parseFloat(filterValue)); +var boolSort = (value, filterValue) => simpleSort(value == "true" ? 1 : 0, filterValue == "true" ? 1 : 0); +var countSort = (value, filterValue) => simpleSort(parseMultiString(value).length, parseMultiString(filterValue).length); +var normalizedSortForType = (type, desc) => { + return Object.keys(sortFnTypes).find( + (f2) => sortFnTypes[f2].type.some((g) => g == type) && sortFnTypes[f2].desc == desc + ); +}; +var sortFnTypes = { + alphabetical: { + type: ["text", "option"], + fn: stringSort, + label: i18n_default.sortTypes.alphaAsc, + desc: false + }, + reverseAlphabetical: { + type: ["text", "option"], + fn: (v2, f2) => stringSort(v2, f2) * -1, + label: i18n_default.sortTypes.alphaDesc, + desc: true + }, + linkAlphabetical: { + type: ["link", "context", "file", "image"], + fn: linkSort, + label: i18n_default.sortTypes.alphaAsc, + desc: false + }, + linkReverseAlphabetical: { + type: ["link", "context", "file", "image"], + fn: (v2, f2) => linkSort(v2, f2) * -1, + label: i18n_default.sortTypes.alphaDesc, + desc: true + }, + earliest: { + type: ["date"], + fn: stringSort, + label: i18n_default.sortTypes.earliest, + desc: false + }, + latest: { + type: ["date"], + fn: (v2, f2) => stringSort(v2, f2) * -1, + label: i18n_default.sortTypes.latest, + desc: true + }, + boolean: { + type: ["boolean"], + fn: boolSort, + label: i18n_default.sortTypes.checkAsc, + desc: false + }, + booleanReverse: { + type: ["boolean"], + fn: (v2, f2) => boolSort(v2, f2) * -1, + label: i18n_default.sortTypes.checkDesc, + desc: true + }, + number: { + type: ["number"], + fn: numSort, + label: "1 \u2192 9", + desc: false + }, + reverseNumber: { + type: ["number"], + fn: (v2, f2) => numSort(v2, f2) * -1, + label: "9 \u2192 1", + desc: true + }, + count: { + type: ["option-multi", "context-multi", "link-multi", "tags-multi"], + fn: countSort, + label: i18n_default.sortTypes.itemsDesc, + desc: true + }, + reverseCount: { + type: ["option-multi", "context-multi", "link-multi", "tags-multi"], + fn: (v2, f2) => countSort(v2, f2) * -1, + label: i18n_default.sortTypes.itemsAsc, + desc: false } }; -var nullToken = new CachedToken(); -var InputStream = class { - constructor(input, ranges) { - this.input = input; - this.ranges = ranges; - this.chunk = ""; - this.chunkOff = 0; - this.chunk2 = ""; - this.chunk2Pos = 0; - this.next = -1; - this.token = nullToken; - this.rangeIndex = 0; - this.pos = this.chunkPos = ranges[0].from; - this.range = ranges[0]; - this.end = ranges[ranges.length - 1].to; - this.readNext(); +var sortReturnForCol = (col, sort2, row2, row22) => { + if (!col) + return 0; + const sortType = sortFnTypes[sort2.fn]; + if (sortType) { + return sortType.fn(row2[sort2.field], row22[sort2.field]); } - resolveOffset(offset2, assoc) { - let range2 = this.range, index2 = this.rangeIndex; - let pos = this.pos + offset2; - while (pos < range2.from) { - if (!index2) - return null; - let next = this.ranges[--index2]; - pos -= range2.from - next.to; - range2 = next; - } - while (assoc < 0 ? pos > range2.to : pos >= range2.to) { - if (index2 == this.ranges.length - 1) - return null; - let next = this.ranges[++index2]; - pos += next.from - range2.to; - range2 = next; + return 0; +}; + +// src/core/react/components/UI/Menus/contexts/spacePropertyMenu.tsx +var import_react16 = __toESM(require_react()); +var selectPropertyTypeMenu = (e5, ui, selectedType) => { + ui.openMenu(e5.target.getBoundingClientRect(), { + ui, + multi: false, + editable: false, + searchable: false, + saveOptions: selectedType, + value: [], + showAll: true, + options: fieldTypes.filter((f2) => !f2.restricted).map((f2, i4) => ({ + id: i4 + 1, + name: f2.label, + value: f2.type, + icon: f2.icon + })) + }); +}; +var PropertyMenuComponent = (props) => { + const [field, setField] = (0, import_react16.useState)(props.field); + const selectedType = (_15, value) => { + const newField = { + ...field, + type: value[0], + value: JSON.stringify(getNewValueForType(field, value)) + }; + setField(newField); + props.saveField(newField); + }; + const selectedValue = (value) => { + const newField = { ...field, value }; + setField(newField); + props.saveField(newField); + }; + const toggleMulti = () => { + const newField = { + ...field, + type: field.type == fieldType.multiType ? fieldType.type : fieldType.multiType + }; + setField(newField); + props.saveField(newField); + }; + const fieldType = fieldTypeForType(field.type, field.name) ?? fieldTypes[0]; + const getNewValueForType = (f2, value) => { + if (value[0].startsWith("option")) { + return JSON.stringify({ + options: props.options.map((f3) => ({ + name: f3, + value: f3 + })) + }); } - return pos; - } - peek(offset2) { - let idx = this.chunkOff + offset2, pos, result; - if (idx >= 0 && idx < this.chunk.length) { - pos = this.pos + offset2; - result = this.chunk.charCodeAt(idx); - } else { - let resolved = this.resolveOffset(offset2, 1); - if (resolved == null) - return -1; - pos = resolved; - if (pos >= this.chunk2Pos && pos < this.chunk2Pos + this.chunk2.length) { - result = this.chunk2.charCodeAt(pos - this.chunk2Pos); - } else { - let i4 = this.rangeIndex, range2 = this.range; - while (range2.to <= pos) - range2 = this.ranges[++i4]; - this.chunk2 = this.input.chunk(this.chunk2Pos = pos); - if (pos + this.chunk2.length > range2.to) - this.chunk2 = this.chunk2.slice(0, range2.to - pos); - result = this.chunk2.charCodeAt(0); + return value[0] == fieldType.type || value[0] == fieldType.multiType ? f2.value : null; + }; + return /* @__PURE__ */ import_react16.default.createElement(import_react16.default.Fragment, null, /* @__PURE__ */ import_react16.default.createElement("li", null, /* @__PURE__ */ import_react16.default.createElement("div", { + className: "mk-menu-option", + onClick: (e5) => selectPropertyTypeMenu(e5, props.superstate.ui, selectedType) + }, /* @__PURE__ */ import_react16.default.createElement("span", null, i18n_default.labels.propertyType), /* @__PURE__ */ import_react16.default.createElement("span", null, fieldType.label))), fieldType.multi ? /* @__PURE__ */ import_react16.default.createElement("div", { + className: "mk-menu-option" + }, /* @__PURE__ */ import_react16.default.createElement("span", null, i18n_default.labels.multiple), /* @__PURE__ */ import_react16.default.createElement("input", { + type: "checkbox", + checked: field.type == fieldType.multiType, + onChange: () => toggleMulti() + })) : /* @__PURE__ */ import_react16.default.createElement(import_react16.default.Fragment, null), /* @__PURE__ */ import_react16.default.createElement("div", { + className: "mk-menu-separator" + }), /* @__PURE__ */ import_react16.default.createElement(PropertyValueComponent, { + superstate: props.superstate, + name: field.name, + table: field.table, + fields: props.fields, + fieldType: fieldType.type, + value: field.value, + contextPath: props.contextPath, + saveValue: selectedValue + })); +}; +var showPropertyMenu = (props) => { + const { + superstate, + rect, + editable, + options, + field, + fields, + contextPath, + saveField, + hide, + deleteColumn, + sortColumn, + editCode, + hidden + } = props; + const menuOptions = []; + if (editable) { + menuOptions.push( + menuInput( + field?.name ?? "", + (value) => saveField({ ...field, name: value }) + ) + ); + menuOptions.push(menuSeparator); + menuOptions.push({ + name: "", + type: 5 /* Custom */, + fragment: () => /* @__PURE__ */ import_react16.default.createElement(PropertyMenuComponent, { + superstate, + field, + fields, + contextPath, + options, + saveField + }) + }); + menuOptions.push(menuSeparator); + menuOptions.push({ + name: i18n_default.menu.setIcon, + icon: "ui//gem", + onClick: () => { + superstate.ui.openPalette((_props) => /* @__PURE__ */ import_react16.default.createElement(StickerModal_default, { + ui: superstate.ui, + hide: _props.hide, + selectedSticker: (emoji) => saveField({ ...field, attrs: JSON.stringify({ icon: emoji }) }) + })); } + }); + menuOptions.push(menuSeparator); + const sortableString = normalizedSortForType(field.type, false); + if (sortableString && sortColumn) { + menuOptions.push({ + name: i18n_default.menu.sortAscending, + icon: "ui//sort-asc", + onClick: () => { + sortColumn({ + field: field.name + field.table, + fn: sortableString + }); + } + }); + menuOptions.push({ + name: i18n_default.menu.sortDescending, + icon: "ui//sort-desc", + onClick: () => { + sortColumn({ + field: field.name + field.table, + fn: normalizedSortForType(field.type, true) + }); + } + }); } - if (pos >= this.token.lookAhead) - this.token.lookAhead = pos + 1; - return result; - } - acceptToken(token, endOffset = 0) { - let end = endOffset ? this.resolveOffset(endOffset, -1) : this.pos; - if (end == null || end < this.token.start) - throw new RangeError("Token end out of bounds"); - this.token.value = token; - this.token.end = end; - } - getChunk() { - if (this.pos >= this.chunk2Pos && this.pos < this.chunk2Pos + this.chunk2.length) { - let { chunk, chunkPos } = this; - this.chunk = this.chunk2; - this.chunkPos = this.chunk2Pos; - this.chunk2 = chunk; - this.chunk2Pos = chunkPos; - this.chunkOff = this.pos - this.chunkPos; - } else { - this.chunk2 = this.chunk; - this.chunk2Pos = this.chunkPos; - let nextChunk = this.input.chunk(this.pos); - let end = this.pos + nextChunk.length; - this.chunk = end > this.range.to ? nextChunk.slice(0, this.range.to - this.pos) : nextChunk; - this.chunkPos = this.pos; - this.chunkOff = 0; - } - } - readNext() { - if (this.chunkOff >= this.chunk.length) { - this.getChunk(); - if (this.chunkOff == this.chunk.length) - return this.next = -1; - } - return this.next = this.chunk.charCodeAt(this.chunkOff); - } - advance(n3 = 1) { - this.chunkOff += n3; - while (this.pos + n3 >= this.range.to) { - if (this.rangeIndex == this.ranges.length - 1) - return this.setDone(); - n3 -= this.range.to - this.pos; - this.range = this.ranges[++this.rangeIndex]; - this.pos = this.range.from; - } - this.pos += n3; - if (this.pos >= this.token.lookAhead) - this.token.lookAhead = this.pos + 1; - return this.readNext(); - } - setDone() { - this.pos = this.chunkPos = this.end; - this.range = this.ranges[this.rangeIndex = this.ranges.length - 1]; - this.chunk = ""; - return this.next = -1; - } - reset(pos, token) { - if (token) { - this.token = token; - token.start = pos; - token.lookAhead = pos + 1; - token.value = token.extended = -1; - } else { - this.token = nullToken; - } - if (this.pos != pos) { - this.pos = pos; - if (pos == this.end) { - this.setDone(); - return this; - } - while (pos < this.range.from) - this.range = this.ranges[--this.rangeIndex]; - while (pos >= this.range.to) - this.range = this.ranges[++this.rangeIndex]; - if (pos >= this.chunkPos && pos < this.chunkPos + this.chunk.length) { - this.chunkOff = pos - this.chunkPos; + menuOptions.push(menuSeparator); + if (hide) { + if (!hidden) { + menuOptions.push({ + name: i18n_default.menu.hideProperty, + icon: "ui//eye-off", + onClick: () => { + hide(field, true); + } + }); } else { - this.chunk = ""; - this.chunkOff = 0; + menuOptions.push({ + name: i18n_default.menu.unhideProperty, + icon: "ui//eye", + onClick: () => { + hide(field, false); + } + }); } - this.readNext(); } - return this; - } - read(from, to2) { - if (from >= this.chunkPos && to2 <= this.chunkPos + this.chunk.length) - return this.chunk.slice(from - this.chunkPos, to2 - this.chunkPos); - if (from >= this.chunk2Pos && to2 <= this.chunk2Pos + this.chunk2.length) - return this.chunk2.slice(from - this.chunk2Pos, to2 - this.chunk2Pos); - if (from >= this.range.from && to2 <= this.range.to) - return this.input.read(from, to2); - let result = ""; - for (let r2 of this.ranges) { - if (r2.from >= to2) - break; - if (r2.to > from) - result += this.input.read(Math.max(r2.from, from), Math.min(r2.to, to2)); + if (editCode) { + menuOptions.push({ + name: i18n_default.menu.editCode, + icon: "ui//code", + onClick: () => { + editCode(); + } + }); + } + if (deleteColumn) { + menuOptions.push({ + name: i18n_default.menu.deleteProperty, + icon: "ui//trash", + onClick: () => { + deleteColumn(field); + } + }); } - return result; } + const menu = superstate.ui.openMenu( + rect, + defaultMenu(superstate.ui, menuOptions) + ); + return menu; }; -var TokenGroup = class { - constructor(data2, id3) { - this.data = data2; - this.id = id3; + +// src/core/react/components/UI/Menus/menu/concerns/matchers.js +function escapeForRegExp(string4) { + return string4.replace(/[-\\^$*+?.()|[\]{}]/g, "\\$&"); +} +function matchAny(string4) { + return new RegExp(escapeForRegExp(string4), "gi"); +} +function matchExact(string4) { + return new RegExp(`^${escapeForRegExp(string4)}$`, "i"); +} + +// src/core/react/context/ContextEditorContext.tsx +var import_lodash9 = __toESM(require_lodash()); +var import_react20 = __toESM(require_react()); + +// src/utils/sanitizers.ts +var sanitizeSQLStatement = (name317) => { + try { + return name317?.replace(/'/g, `''`); + } catch (e5) { + console.log(e5, name317); + return ""; } - token(input, stack) { - readToken(this.data, input, stack, this.id); +}; +var sanitizeColumnName = (name317) => { + if (name317?.charAt(0) == "_") { + return sanitizeColumnName(name317.substring(1)); } + return name317?.replace(/"/g, ``); }; -TokenGroup.prototype.contextual = TokenGroup.prototype.fallback = TokenGroup.prototype.extend = false; -var ExternalTokenizer = class { - constructor(token, options = {}) { - this.token = token; - this.contextual = !!options.contextual; - this.fallback = !!options.fallback; - this.extend = !!options.extend; +var sanitizeTableName = (name317) => { + return name317?.replace(/[^a-z0-9+]+/gi, ""); +}; +var illegalRe = /[\/\?<>\\:\*\|":]/g; +var controlRe = /[\x00-\x1f\x80-\x9f]/g; +var reservedRe = /^\.+$/; +var windowsReservedRe = /^(con|prn|aux|nul|com[0-9]|lpt[0-9])(\..*)?$/i; +var sanitizeFileName = (name317) => { + const replacement = ""; + return name317.replace(illegalRe, replacement).replace(controlRe, replacement).replace(reservedRe, replacement).replace(windowsReservedRe, replacement); +}; + +// src/core/utils/contexts/predicate/predicate.tsx +var defaultPredicateFnForType = (type, types2) => { + const fnType = Object.keys(types2).find( + (f2) => types2[f2].type.find((g) => g == type) + ); + return fnType; +}; +var allPredicateFns = (types2) => { + return Object.keys(types2); +}; +var predicateFnsForType = (type, types2) => { + const fnTypes = Object.keys(types2).filter( + (f2) => types2[f2].type.find((g) => g == type) + ); + return fnTypes; +}; +var cleanPredicateType = (type, definedTypes) => { + return type.filter((f2) => Object.keys(definedTypes).find((g) => g == f2.fn)); +}; +var validatePredicate = (prevPredicate, defaultPredicate2) => { + if (!prevPredicate) { + return defaultPredicate2; } + return { + ...defaultPredicate2, + view: prevPredicate.view, + listItem: prevPredicate.listItem, + listGroup: prevPredicate.listGroup, + listView: prevPredicate.listView, + listViewProps: prevPredicate.listViewProps, + listItemProps: prevPredicate.listItemProps, + listGroupProps: prevPredicate.listGroupProps, + filters: Array.isArray(prevPredicate.filters) ? cleanPredicateType(prevPredicate.filters, filterFnTypes) : [], + sort: Array.isArray(prevPredicate.sort) ? cleanPredicateType(prevPredicate.sort, sortFnTypes) : [], + groupBy: Array.isArray(prevPredicate.groupBy) ? prevPredicate.groupBy : [], + colsOrder: Array.isArray(prevPredicate.colsOrder) ? prevPredicate.colsOrder : [], + colsHidden: Array.isArray(prevPredicate.colsHidden) ? prevPredicate.colsHidden : [], + colsSize: prevPredicate.colsSize ?? {} + }; }; -function readToken(data2, input, stack, group) { - let state = 0, groupMask = 1 << group, { parser: parser3 } = stack.p, { dialect } = parser3; - scan: - for (; ; ) { - if ((groupMask & data2[state]) == 0) - break; - let accEnd = data2[state + 1]; - for (let i4 = state + 3; i4 < accEnd; i4 += 2) - if ((data2[i4 + 1] & groupMask) > 0) { - let term = data2[i4]; - if (dialect.allows(term) && (input.token.value == -1 || input.token.value == term || parser3.overrides(term, input.token.value))) { - input.acceptToken(term); - break; - } - } - for (let next = input.next, low = 0, high = data2[state + 2]; low < high; ) { - let mid = low + high >> 1; - let index2 = accEnd + mid + (mid << 1); - let from = data2[index2], to2 = data2[index2 + 1]; - if (next < from) - high = mid; - else if (next >= to2) - low = mid + 1; - else { - state = data2[index2 + 2]; - input.advance(); - continue scan; - } - } - break; - } +var defaultPredicateForSchema = (schema) => { + return schema?.primary == "true" ? defaultPredicate : { + ...defaultPredicate, + view: "table" + }; +}; +var defaultPredicate = { + view: "list", + filters: [], + listView: "", + listItem: "", + listGroup: "", + listGroupProps: {}, + listViewProps: {}, + listItemProps: {}, + sort: [], + groupBy: [], + colsOrder: [], + colsHidden: [], + colsSize: {} +}; + +// src/core/react/context/FramesMDBContext.tsx +var import_react19 = __toESM(require_react()); + +// src/core/react/context/SpaceContext.tsx +var import_react18 = __toESM(require_react()); + +// src/core/utils/uuid.js +function genId() { + return ([1e7] + -1e3 + -4e3 + -8e3 + -1e11).replace( + /[018]/g, + (c3) => (c3 ^ crypto.getRandomValues(new Uint8Array(1))[0] & 15 >> c3 / 4).toString(16) + ); } -function decodeArray(input, Type = Uint16Array) { - if (typeof input != "string") - return input; - let array = null; - for (let pos = 0, out = 0; pos < input.length; ) { - let value = 0; - for (; ; ) { - let next = input.charCodeAt(pos++), stop = false; - if (next == 126) { - value = 65535; - break; - } - if (next >= 92) - next--; - if (next >= 34) - next--; - let digit = next - 32; - if (digit >= 46) { - digit -= 46; - stop = true; - } - value += digit; - if (stop) - break; - value *= 46; + +// src/core/react/context/PathContext.tsx +var import_react17 = __toESM(require_react()); +var PathContext = (0, import_react17.createContext)({ + uid: "", + readMode: false, + pathState: null, + addToSpace: () => null, + removeFromSpace: () => null +}); +var PathProvider = (props) => { + const [pathState, setPathState] = (0, import_react17.useState)( + props.pathState ?? props.superstate.pathsIndex.get(props.path) + ); + const addToSpace = async (spacePath) => { + const spaceCache = props.superstate.spacesIndex.get(spacePath); + if (spaceCache) { + addPathToSpaceAtIndex(props.superstate, spaceCache, pathState.path, -1); } - if (array) - array[out++] = value; - else - array = new Type(value); - } - return array; -} -var verbose = typeof process != "undefined" && process.env && /\bparse\b/.test(process.env.LOG); -var stackIDs = null; -var Safety; -(function(Safety2) { - Safety2[Safety2["Margin"] = 25] = "Margin"; -})(Safety || (Safety = {})); -function cutAt(tree, pos, side) { - let cursor2 = tree.cursor(IterMode.IncludeAnonymous); - cursor2.moveTo(pos); - for (; ; ) { - if (!(side < 0 ? cursor2.childBefore(pos) : cursor2.childAfter(pos))) - for (; ; ) { - if ((side < 0 ? cursor2.to < pos : cursor2.from > pos) && !cursor2.type.isError) - return side < 0 ? Math.max(0, Math.min(cursor2.to - 1, pos - 25)) : Math.min(tree.length, Math.max(cursor2.from + 1, pos + 25)); - if (side < 0 ? cursor2.prevSibling() : cursor2.nextSibling()) - break; - if (!cursor2.parent()) - return side < 0 ? 0 : tree.length; - } - } -} -var FragmentCursor = class { - constructor(fragments, nodeSet) { - this.fragments = fragments; - this.nodeSet = nodeSet; - this.i = 0; - this.fragment = null; - this.safeFrom = -1; - this.safeTo = -1; - this.trees = []; - this.start = []; - this.index = []; - this.nextFragment(); - } - nextFragment() { - let fr = this.fragment = this.i == this.fragments.length ? null : this.fragments[this.i++]; - if (fr) { - this.safeFrom = fr.openStart ? cutAt(fr.tree, fr.from + fr.offset, 1) - fr.offset : fr.from; - this.safeTo = fr.openEnd ? cutAt(fr.tree, fr.to + fr.offset, -1) - fr.offset : fr.to; - while (this.trees.length) { - this.trees.pop(); - this.start.pop(); - this.index.pop(); - } - this.trees.push(fr.tree); - this.start.push(-fr.offset); - this.index.push(0); - this.nextStart = this.safeFrom; - } else { - this.nextStart = 1e9; - } - } - nodeAt(pos) { - if (pos < this.nextStart) - return null; - while (this.fragment && this.safeTo <= pos) - this.nextFragment(); - if (!this.fragment) - return null; - for (; ; ) { - let last = this.trees.length - 1; - if (last < 0) { - this.nextFragment(); - return null; - } - let top = this.trees[last], index2 = this.index[last]; - if (index2 == top.children.length) { - this.trees.pop(); - this.start.pop(); - this.index.pop(); - continue; - } - let next = top.children[index2]; - let start = this.start[last] + top.positions[index2]; - if (start > pos) { - this.nextStart = start; - return null; + }; + const removeFromSpace = (spacePath) => { + removePathsFromSpace(props.superstate, spacePath, [pathState.path]); + }; + const readMode = props.readMode; + (0, import_react17.useEffect)(() => { + const reloadPath = () => { + if (!props.pathState) + setPathState(props.superstate.pathsIndex.get(props.path)); + }; + const changePath = (payload) => { + if (payload.path == pathState?.path) { + setPathState(props.superstate.pathsIndex.get(payload.newPath)); } - if (next instanceof Tree) { - if (start == pos) { - if (start < this.safeFrom) - return null; - let end = start + next.length; - if (end <= this.safeTo) { - let lookAhead = next.prop(NodeProp.lookAhead); - if (!lookAhead || end + lookAhead < this.fragment.to) - return next; - } - } - this.index[last]++; - if (start + next.length >= Math.max(this.safeFrom, pos)) { - this.trees.push(next); - this.start.push(start); - this.index.push(0); - } - } else { - this.index[last]++; - this.nextStart = start + next.length; + }; + const refreshPath = (payload) => { + if (payload.path == props.path) { + reloadPath(); } + }; + reloadPath(); + props.superstate.eventsDispatcher.addListener( + "pathStateUpdated", + refreshPath + ); + props.superstate.eventsDispatcher.addListener( + "superstateUpdated", + reloadPath + ); + props.superstate.eventsDispatcher.addListener("pathChanged", changePath); + return () => { + props.superstate.eventsDispatcher.removeListener( + "superstateUpdated", + reloadPath + ); + props.superstate.eventsDispatcher.removeListener( + "pathStateUpdated", + refreshPath + ); + props.superstate.eventsDispatcher.removeListener( + "pathChanged", + changePath + ); + }; + }, [props.path]); + return /* @__PURE__ */ import_react17.default.createElement(PathContext.Provider, { + value: { + uid: genId(), + readMode, + pathState, + addToSpace, + removeFromSpace } - } + }, pathState ? props.children : /* @__PURE__ */ import_react17.default.createElement(import_react17.default.Fragment, null)); }; -var TokenCache = class { - constructor(parser3, stream) { - this.stream = stream; - this.tokens = []; - this.mainToken = null; - this.actions = []; - this.tokens = parser3.tokenizers.map((_15) => new CachedToken()); - } - getActions(stack) { - let actionIndex = 0; - let main = null; - let { parser: parser3 } = stack.p, { tokenizers } = parser3; - let mask = parser3.stateSlot(stack.state, 3); - let context = stack.curContext ? stack.curContext.hash : 0; - let lookAhead = 0; - for (let i4 = 0; i4 < tokenizers.length; i4++) { - if ((1 << i4 & mask) == 0) - continue; - let tokenizer2 = tokenizers[i4], token = this.tokens[i4]; - if (main && !tokenizer2.fallback) - continue; - if (tokenizer2.contextual || token.start != stack.pos || token.mask != mask || token.context != context) { - this.updateCachedToken(token, tokenizer2, stack); - token.mask = mask; - token.context = context; - } - if (token.lookAhead > token.end + 25) - lookAhead = Math.max(token.lookAhead, lookAhead); - if (token.value != 0) { - let startIndex = actionIndex; - if (token.extended > -1) - actionIndex = this.addActions(stack, token.extended, token.end, actionIndex); - actionIndex = this.addActions(stack, token.value, token.end, actionIndex); - if (!tokenizer2.extend) { - main = token; - if (actionIndex > startIndex) - break; - } + +// src/core/react/context/SpaceContext.tsx +var SpaceContext = (0, import_react18.createContext)({ + spaceInfo: null, + readMode: false, + spaceState: null +}); +var SpaceProvider = (props) => { + const { pathState } = (0, import_react18.useContext)(PathContext); + const spaceInfo = (0, import_react18.useMemo)(() => { + return props.superstate.spacesIndex.get(pathState.path)?.space; + }, [pathState]); + const readMode = spaceInfo?.readOnly; + const [spaceState, setSpaceState] = (0, import_react18.useState)(null); + (0, import_react18.useEffect)(() => { + const reloadSpace = () => { + setSpaceState(props.superstate.spacesIndex.get(pathState.path)); + }; + const refreshSpace = (payload) => { + if (payload.path == pathState.path) { + reloadSpace(); } + }; + reloadSpace(); + props.superstate.eventsDispatcher.addListener( + "spaceStateUpdated", + refreshSpace + ); + return () => { + props.superstate.eventsDispatcher.removeListener( + "spaceStateUpdated", + refreshSpace + ); + }; + }, [pathState]); + return /* @__PURE__ */ import_react18.default.createElement(SpaceContext.Provider, { + value: { + spaceState, + readMode, + spaceInfo } - while (this.actions.length > actionIndex) - this.actions.pop(); - if (lookAhead) - stack.setLookAhead(lookAhead); - if (!main && stack.pos == this.stream.end) { - main = new CachedToken(); - main.value = stack.p.parser.eofTerm; - main.start = main.end = stack.pos; - actionIndex = this.addActions(stack, main.value, main.end, actionIndex); + }, spaceInfo && props.children); +}; + +// src/core/react/context/FramesMDBContext.tsx +var FramesMDBContext = (0, import_react19.createContext)({ + frameSchemas: [], + frames: [], + tableData: null, + saveFrame: () => null, + frameSchema: null, + setFrameSchema: () => null, + saveSchema: () => null, + deleteSchema: () => null, + saveProperty: () => false, + newProperty: () => false, + delProperty: () => null, + getMDBData: () => null, + undoLastAction: () => null, + redoAction: () => null +}); +var FramesMDBProvider = (props) => { + const [history2, setHistory] = (0, import_react19.useState)([]); + const [future, setFuture] = (0, import_react19.useState)([]); + const [schemaTable, setSchemaTable] = (0, import_react19.useState)(null); + const schemas = (0, import_react19.useMemo)( + () => (schemaTable?.rows ?? []).map( + (f2) => mdbSchemaToFrameSchema(f2) + ) ?? [], + [schemaTable] + ); + const frames = schemas.filter((f2) => f2.type == "frame"); + const [frameData, setFrameData] = (0, import_react19.useState)(null); + const [frameSchema, setFrameSchema] = (0, import_react19.useState)(null); + const tableData = (0, import_react19.useMemo)(() => { + return frameData?.[frameSchema?.id]; + }, [frameData, frameSchema]); + const { spaceInfo, readMode } = (0, import_react19.useContext)(SpaceContext); + const deleteSchema = async (table) => { + if (table.primary) + return; + await props.superstate.spaceManager.deleteFrame(spaceInfo.path, table.id); + const newSchemaTable = { + ...schemaTable, + rows: schemaTable.rows.filter((f2) => f2.id != table.id) + }; + setSchemaTable(newSchemaTable); + }; + const saveSchema = async (table) => { + const newSchema = schemaTable.rows.find((f2) => f2.id == table.id) ? true : false; + const newSchemaTable = newSchema ? { + ...schemaTable, + rows: schemaTable.rows.map( + (f2) => f2.id == table.id ? frameSchemaToTableSchema(table) : f2 + ) + } : { + ...schemaTable, + rows: [...schemaTable.rows, frameSchemaToTableSchema(table)] + }; + if (!spaceInfo.readOnly) { + await props.superstate.spaceManager.saveFrameSchema( + spaceInfo.path, + table.id, + () => frameSchemaToTableSchema(table) + ); } - this.mainToken = main; - return this.actions; - } - getMainToken(stack) { - if (this.mainToken) - return this.mainToken; - let main = new CachedToken(), { pos, p } = stack; - main.start = pos; - main.end = Math.min(pos + 1, p.stream.end); - main.value = pos == p.stream.end ? p.parser.eofTerm : 0; - return main; - } - updateCachedToken(token, tokenizer2, stack) { - tokenizer2.token(this.stream.reset(stack.pos, token), stack); - if (token.value > -1) { - let { parser: parser3 } = stack.p; - for (let i4 = 0; i4 < parser3.specialized.length; i4++) - if (parser3.specialized[i4] == token.value) { - let result = parser3.specializers[i4](this.stream.read(token.start, token.end), stack); - if (result >= 0 && stack.p.parser.dialect.allows(result >> 1)) { - if ((result & 1) == 0) - token.value = result >> 1; - else - token.extended = result >> 1; - break; - } + if (table.id == frameSchema?.id) { + setFrameSchema(table); + setFrameData((f2) => ({ + ...f2, + [table.id]: { + ...f2[table.id], + schema: frameSchemaToTableSchema(table) } - } else { - token.value = 0; - token.end = Math.min(stack.p.stream.end, stack.pos + 1); + })); } - } - putAction(action, token, end, index2) { - for (let i4 = 0; i4 < index2; i4 += 3) - if (this.actions[i4] == action) - return index2; - this.actions[index2++] = action; - this.actions[index2++] = token; - this.actions[index2++] = end; - return index2; - } - addActions(stack, token, end, index2) { - let { state } = stack, { parser: parser3 } = stack.p, { data: data2 } = parser3; - for (let set = 0; set < 2; set++) { - for (let i4 = parser3.stateSlot(state, set ? 2 : 1); ; i4 += 3) { - if (data2[i4] == 65535) { - if (data2[i4 + 1] == 1) { - i4 = pair(data2, i4 + 2); + setSchemaTable(newSchemaTable); + }; + (0, import_react19.useEffect)(() => { + if (schemaTable) + getMDBData().then((f2) => { + if (f2 && Object.keys(f2).length > 0) { + setFrameData(f2); + } + }); + }, [schemaTable]); + (0, import_react19.useEffect)(() => { + if (schemaTable) { + setFrameSchema((p) => { + if (props.schema) { + const preselectSchema = mdbSchemaToFrameSchema( + schemaTable.rows.find( + (g) => g.id == props.schema + ) + ); + if (preselectSchema) { + return preselectSchema; } else { - if (index2 == 0 && data2[i4 + 1] == 2) - index2 = this.putAction(pair(data2, i4 + 2), token, end, index2); - break; + if (props.schema == defaultFrameListViewSchema.id) { + return mdbSchemaToFrameSchema(defaultFrameListViewSchema); + } + const newSchema = { + id: uniqueNameFromString( + sanitizeTableName(props.schema), + schemaTable.rows.map((g) => g.id) + ), + name: props.schema, + type: "frame" + }; + return newSchema; } - } - if (data2[i4] == token) - index2 = this.putAction(pair(data2, i4 + 1), token, end, index2); - } - } - return index2; - } -}; -var Rec; -(function(Rec2) { - Rec2[Rec2["Distance"] = 5] = "Distance"; - Rec2[Rec2["MaxRemainingPerStep"] = 3] = "MaxRemainingPerStep"; - Rec2[Rec2["MinBufferLengthPrune"] = 500] = "MinBufferLengthPrune"; - Rec2[Rec2["ForceReduceLimit"] = 10] = "ForceReduceLimit"; - Rec2[Rec2["CutDepth"] = 15e3] = "CutDepth"; - Rec2[Rec2["CutTo"] = 9e3] = "CutTo"; -})(Rec || (Rec = {})); -var Parse = class { - constructor(parser3, input, fragments, ranges) { - this.parser = parser3; - this.input = input; - this.ranges = ranges; - this.recovering = 0; - this.nextStackID = 9812; - this.minStackPos = 0; - this.reused = []; - this.stoppedAt = null; - this.stream = new InputStream(input, ranges); - this.tokens = new TokenCache(parser3, this.stream); - this.topTerm = parser3.top[1]; - let { from } = ranges[0]; - this.stacks = [Stack.start(this, parser3.top[0], from)]; - this.fragments = fragments.length && this.stream.end - from > parser3.bufferLength * 4 ? new FragmentCursor(fragments, parser3.nodeSet) : null; - } - get parsedPos() { - return this.minStackPos; - } - advance() { - let stacks = this.stacks, pos = this.minStackPos; - let newStacks = this.stacks = []; - let stopped, stoppedTokens; - for (let i4 = 0; i4 < stacks.length; i4++) { - let stack = stacks[i4]; - for (; ; ) { - this.tokens.mainToken = null; - if (stack.pos > pos) { - newStacks.push(stack); - } else if (this.advanceStack(stack, newStacks, stacks)) { - continue; } else { - if (!stopped) { - stopped = []; - stoppedTokens = []; - } - stopped.push(stack); - let tok = this.tokens.getMainToken(stack); - stoppedTokens.push(tok.value, tok.end); - } - break; - } - } - if (!newStacks.length) { - let finished = stopped && findFinished(stopped); - if (finished) - return this.stackToTree(finished); - if (this.parser.strict) { - if (verbose && stopped) - console.log("Stuck with token " + (this.tokens.mainToken ? this.parser.getName(this.tokens.mainToken.value) : "none")); - throw new SyntaxError("No parse at " + pos); - } - if (!this.recovering) - this.recovering = 5; - } - if (this.recovering && stopped) { - let finished = this.stoppedAt != null && stopped[0].pos > this.stoppedAt ? stopped[0] : this.runRecovery(stopped, stoppedTokens, newStacks); - if (finished) - return this.stackToTree(finished.forceAll()); - } - if (this.recovering) { - let maxRemaining = this.recovering == 1 ? 1 : this.recovering * 3; - if (newStacks.length > maxRemaining) { - newStacks.sort((a4, b2) => b2.score - a4.score); - while (newStacks.length > maxRemaining) - newStacks.pop(); - } - if (newStacks.some((s4) => s4.reducePos > pos)) - this.recovering--; - } else if (newStacks.length > 1) { - outer: - for (let i4 = 0; i4 < newStacks.length - 1; i4++) { - let stack = newStacks[i4]; - for (let j = i4 + 1; j < newStacks.length; j++) { - let other = newStacks[j]; - if (stack.sameState(other) || stack.buffer.length > 500 && other.buffer.length > 500) { - if ((stack.score - other.score || stack.buffer.length - other.buffer.length) > 0) { - newStacks.splice(j--, 1); - } else { - newStacks.splice(i4--, 1); - continue outer; - } + if (p) { + return mdbSchemaToFrameSchema( + schemaTable.rows?.find((g) => g.id == p.id) + ); + } else { + if (props.contextSchema) { + return mdbSchemaToFrameSchema({ + id: uniqueNameFromString( + props.contextSchema, + schemaTable?.rows.map((f2) => f2.id) ?? [] + ), + name: "Table", + type: "view", + predicate: JSON.stringify({ + ...defaultPredicate, + view: "table" + }), + def: JSON.stringify({ + db: props.contextSchema, + icon: "ui//table" + }) + }); + } else { + return mdbSchemaToFrameSchema(defaultFrameListViewSchema); } } } + return p; + }); } - this.minStackPos = newStacks[0].pos; - for (let i4 = 1; i4 < newStacks.length; i4++) - if (newStacks[i4].pos < this.minStackPos) - this.minStackPos = newStacks[i4].pos; - return null; - } - stopAt(pos) { - if (this.stoppedAt != null && this.stoppedAt < pos) - throw new RangeError("Can't move stoppedAt forward"); - this.stoppedAt = pos; - } - advanceStack(stack, stacks, split) { - let start = stack.pos, { parser: parser3 } = this; - let base2 = verbose ? this.stackID(stack) + " -> " : ""; - if (this.stoppedAt != null && start > this.stoppedAt) - return stack.forceReduce() ? stack : null; - if (this.fragments) { - let strictCx = stack.curContext && stack.curContext.tracker.strict, cxHash = strictCx ? stack.curContext.hash : 0; - for (let cached = this.fragments.nodeAt(start); cached; ) { - let match2 = this.parser.nodeSet.types[cached.type.id] == cached.type ? parser3.getGoto(stack.state, cached.type.id) : -1; - if (match2 > -1 && cached.length && (!strictCx || (cached.prop(NodeProp.contextHash) || 0) == cxHash)) { - stack.useNode(cached, match2); - if (verbose) - console.log(base2 + this.stackID(stack) + ` (via reuse of ${parser3.getName(cached.type.id)})`); - return true; - } - if (!(cached instanceof Tree) || cached.children.length == 0 || cached.positions[0] > 0) - break; - let inner = cached.children[0]; - if (inner instanceof Tree && cached.positions[0] == 0) - cached = inner; - else - break; + }, [schemaTable, props.contextSchema, props.schema]); + const loadTables = (0, import_react19.useCallback)(async () => { + if (!spaceInfo) + return; + props.superstate.spaceManager.framesForSpace(spaceInfo.path).then((f2) => { + if (f2) + setSchemaTable((prev) => ({ + uniques: [], + cols: ["id", "name", "type", "def", "predicate", "primary"], + rows: f2 + })); + }); + }, [props.schema, spaceInfo]); + const refreshSpace = (0, import_react19.useCallback)( + async (payload) => { + if (payload.path == spaceInfo.path) { + loadTables(); + return; } + }, + [spaceInfo, loadTables] + ); + (0, import_react19.useEffect)(() => { + props.superstate.eventsDispatcher.addListener( + "frameStateUpdated", + refreshSpace + ); + return () => { + props.superstate.eventsDispatcher.removeListener( + "frameStateUpdated", + refreshSpace + ); + }; + }, [refreshSpace]); + const getMDBData = async () => { + const tables = await props.superstate.spaceManager.readAllFrames( + spaceInfo.path + ); + return tables; + }; + (0, import_react19.useEffect)(() => { + loadTables(); + }, [spaceInfo, props.schema]); + const saveFrame = async (newTable, track = true) => { + if (spaceInfo.readOnly) + return; + if (track) { + setHistory((prevHistory) => [...prevHistory, newTable]); + setFuture([]); } - let defaultReduce = parser3.stateSlot(stack.state, 4); - if (defaultReduce > 0) { - stack.reduce(defaultReduce); - if (verbose) - console.log(base2 + this.stackID(stack) + ` (via always-reduce ${parser3.getName(defaultReduce & 65535)})`); - return true; + await props.superstate.spaceManager.saveFrame(spaceInfo.path, newTable).then((f2) => { + setFrameData((p) => ({ + ...p, + [newTable.schema.id]: newTable + })); + }); + }; + const undoLastAction = () => { + if (history2.length === 0) + return; + const newHistory = history2.slice(0, -1); + const undoneState = history2[history2.length - 1]; + setHistory(newHistory); + setFuture((prevFuture) => [undoneState, ...prevFuture]); + if (newHistory.length > 0) { + const lastState = newHistory[newHistory.length - 1]; + saveFrame(lastState, false); } - if (stack.stack.length >= 15e3) { - while (stack.stack.length > 9e3 && stack.forceReduce()) { - } + }; + const redoAction = () => { + if (future.length === 0) + return; + const newFuture = future.slice(1); + const redoneState = future[0]; + setFuture(newFuture); + setHistory((prevHistory) => [...prevHistory, redoneState]); + saveFrame(redoneState, false); + }; + const delProperty = (column2) => { + const mdbtable = tableData; + const newFields = mdbtable.cols.filter( + (f2, i4) => f2.name != column2.name + ); + const newTable = { + ...mdbtable, + cols: newFields ?? [] + }; + saveFrame(newTable); + }; + const newProperty = (col) => { + return saveProperty(col); + }; + const saveProperty = (newColumn, oldColumn) => { + const column2 = { + ...newColumn, + name: sanitizeColumnName(newColumn.name) + }; + const mdbtable = tableData; + if (column2.name == "") { + props.superstate.ui.notify(i18n_default.notice.noPropertyName); + return false; } - let actions = this.tokens.getActions(stack); - for (let i4 = 0; i4 < actions.length; ) { - let action = actions[i4++], term = actions[i4++], end = actions[i4++]; - let last = i4 == actions.length || !split; - let localStack = last ? stack : stack.split(); - localStack.apply(action, term, end); - if (verbose) - console.log(base2 + this.stackID(localStack) + ` (via ${(action & 65536) == 0 ? "shift" : `reduce of ${parser3.getName(action & 65535)}`} for ${parser3.getName(term)} @ ${start}${localStack == stack ? "" : ", split"})`); - if (last) - return true; - else if (localStack.pos > start) - stacks.push(localStack); - else - split.push(localStack); + if (!oldColumn && mdbtable.cols.find( + (f2) => f2.name.toLowerCase() == column2.name.toLowerCase() + ) || oldColumn && oldColumn.name != column2.name && mdbtable.cols.find( + (f2) => f2.name.toLowerCase() == column2.name.toLowerCase() + )) { + props.superstate.ui.notify(i18n_default.notice.duplicatePropertyName); + return false; } - return false; - } - advanceFully(stack, newStacks) { - let pos = stack.pos; - for (; ; ) { - if (!this.advanceStack(stack, null, null)) - return false; - if (stack.pos > pos) { - pushStackDedup(stack, newStacks); - return true; - } + const oldFieldIndex = oldColumn ? mdbtable.cols.findIndex((f2) => f2.name == oldColumn.name) : -1; + const newFields = oldFieldIndex == -1 ? [...mdbtable.cols, column2] : mdbtable.cols.map((f2, i4) => i4 == oldFieldIndex ? column2 : f2); + const newTable = { + ...mdbtable, + cols: newFields ?? [] + }; + saveFrame(newTable); + return true; + }; + return /* @__PURE__ */ import_react19.default.createElement(FramesMDBContext.Provider, { + value: { + frames, + tableData, + saveFrame, + frameSchemas: schemas, + saveSchema, + deleteSchema, + saveProperty, + newProperty, + delProperty, + frameSchema, + setFrameSchema, + getMDBData, + undoLastAction, + redoAction } - } - runRecovery(stacks, tokens, newStacks) { - let finished = null, restarted = false; - for (let i4 = 0; i4 < stacks.length; i4++) { - let stack = stacks[i4], token = tokens[i4 << 1], tokenEnd = tokens[(i4 << 1) + 1]; - let base2 = verbose ? this.stackID(stack) + " -> " : ""; - if (stack.deadEnd) { - if (restarted) - continue; - restarted = true; - stack.restart(); - if (verbose) - console.log(base2 + this.stackID(stack) + " (restarted)"); - let done = this.advanceFully(stack, newStacks); - if (done) - continue; - } - let force = stack.split(), forceBase = base2; - for (let j = 0; force.forceReduce() && j < 10; j++) { - if (verbose) - console.log(forceBase + this.stackID(force) + " (via force-reduce)"); - let done = this.advanceFully(force, newStacks); - if (done) - break; - if (verbose) - forceBase = this.stackID(force) + " -> "; - } - for (let insert2 of stack.recoverByInsert(token)) { - if (verbose) - console.log(base2 + this.stackID(insert2) + " (via recover-insert)"); - this.advanceFully(insert2, newStacks); - } - if (this.stream.end > stack.pos) { - if (tokenEnd == stack.pos) { - tokenEnd++; - token = 0; - } - stack.recoverByDelete(token, tokenEnd); - if (verbose) - console.log(base2 + this.stackID(stack) + ` (via recover-delete ${this.parser.getName(token)})`); - pushStackDedup(stack, newStacks); - } else if (!finished || finished.score < stack.score) { - finished = stack; - } + }, props.children); +}; + +// src/core/react/context/ContextEditorContext.tsx +var ContextEditorContext = (0, import_react20.createContext)({ + dbSchema: null, + views: [], + source: "", + sortedColumns: [], + filteredData: [], + contextTable: {}, + editMode: 0, + setEditMode: () => null, + selectedRows: [], + selectRows: () => null, + setContextTable: () => null, + predicate: null, + savePredicate: () => null, + saveDB: () => null, + hideColumn: () => null, + saveColumn: () => false, + newColumn: () => false, + sortColumn: () => null, + delColumn: () => null, + searchString: "", + setSearchString: () => null, + updateValue: () => null, + updateFieldValue: () => null, + tableData: null, + cols: [] +}); +var ContextEditorProvider = (props) => { + const { frameSchemas, saveSchema, frameSchema } = (0, import_react20.useContext)(FramesMDBContext); + const { + spaceInfo, + readMode, + spaceState: spaceCache + } = (0, import_react20.useContext)(SpaceContext); + const [schemaTable, setSchemaTable] = (0, import_react20.useState)(null); + const [contextTable, setContextTable] = (0, import_react20.useState)({}); + const [tableData, setTableData] = (0, import_react20.useState)(null); + const [searchString, setSearchString] = (0, import_react20.useState)(null); + const [predicate, setPredicate] = (0, import_react20.useState)(null); + const [selectedRows, setSelectedRows] = (0, import_react20.useState)([]); + const [editMode, setEditMode] = (0, import_react20.useState)(0); + const contextPath = frameSchema?.def?.context ?? spaceInfo?.path; + const dbSchema = (0, import_react20.useMemo)(() => { + if (frameSchema) { + if (schemaTable) + return schemaTable?.rows.find( + (f2) => f2.id == frameSchema.def.db + ); + return { + id: frameSchema.def.db, + ...defaultContextDBSchema + }; } - return finished; - } - stackToTree(stack) { - stack.close(); - return Tree.build({ - buffer: StackBufferCursor.create(stack), - nodeSet: this.parser.nodeSet, - topID: this.topTerm, - maxBufferLength: this.parser.bufferLength, - reused: this.reused, - start: this.ranges[0].from, - length: stack.pos - this.ranges[0].from, - minRepeatType: this.parser.minRepeatTerm + return null; + }, [frameSchema, schemaTable]); + const views = (0, import_react20.useMemo)(() => { + const _views = frameSchemas.filter( + (f2) => f2.type == "view" && f2.def.db == dbSchema?.id + ); + return _views.length > 0 ? _views : frameSchema ? [frameSchema] : []; + }, [frameSchemas, frameSchema, dbSchema]); + const defaultSchema = defaultContextTable; + const contexts = spaceCache?.contexts ?? []; + const loadTables = async () => { + const schemas = await props.superstate.spaceManager.tablesForSpace( + contextPath + ); + if (schemas) + setSchemaTable(() => ({ + ...defaultSchema, + rows: schemas + })); + }; + (0, import_react20.useEffect)(() => { + if (dbSchema) + retrieveCachedTable(dbSchema); + }, [dbSchema]); + const loadContextFields = (0, import_react20.useCallback)(async (tag2) => { + props.superstate.spaceManager.contextForSpace(tagSpacePathFromTag(tag2)).then((f2) => { + setContextTable((t5) => ({ + ...t5, + [tag2]: f2 + })); }); - } - stackID(stack) { - let id3 = (stackIDs || (stackIDs = /* @__PURE__ */ new WeakMap())).get(stack); - if (!id3) - stackIDs.set(stack, id3 = String.fromCodePoint(this.nextStackID++)); - return id3 + stack; - } -}; -function pushStackDedup(stack, newStacks) { - for (let i4 = 0; i4 < newStacks.length; i4++) { - let other = newStacks[i4]; - if (other.pos == stack.pos && other.sameState(stack)) { - if (newStacks[i4].score < stack.score) - newStacks[i4] = stack; + }, []); + const retrieveCachedTable = (newSchema) => { + const f2 = props.superstate.contextsIndex?.get(contextPath)?.tables[newSchema.id]; + if (f2) { + if (newSchema.primary) { + for (const c3 of contexts) { + loadContextFields(c3); + } + } + updateTable(f2); return; } - } - newStacks.push(stack); -} -var Dialect = class { - constructor(source, flags, disabled) { - this.source = source; - this.flags = flags; - this.disabled = disabled; - } - allows(term) { - return !this.disabled || this.disabled[term] == 0; - } -}; -var id = (x2) => x2; -var ContextTracker = class { - constructor(spec) { - this.start = spec.start; - this.shift = spec.shift || id; - this.reduce = spec.reduce || id; - this.reuse = spec.reuse || id; - this.hash = spec.hash || (() => 0); - this.strict = spec.strict !== false; - } -}; -var LRParser = class extends Parser4 { - constructor(spec) { - super(); - this.wrappers = []; - if (spec.version != 14) - throw new RangeError(`Parser version (${spec.version}) doesn't match runtime version (${14})`); - let nodeNames = spec.nodeNames.split(" "); - this.minRepeatTerm = nodeNames.length; - for (let i4 = 0; i4 < spec.repeatNodeCount; i4++) - nodeNames.push(""); - let topTerms = Object.keys(spec.topRules).map((r2) => spec.topRules[r2][1]); - let nodeProps = []; - for (let i4 = 0; i4 < nodeNames.length; i4++) - nodeProps.push([]); - function setProp(nodeID, prop2, value) { - nodeProps[nodeID].push([prop2, prop2.deserialize(String(value))]); - } - if (spec.nodeProps) - for (let propSpec of spec.nodeProps) { - let prop2 = propSpec[0]; - if (typeof prop2 == "string") - prop2 = NodeProp[prop2]; - for (let i4 = 1; i4 < propSpec.length; ) { - let next = propSpec[i4++]; - if (next >= 0) { - setProp(next, prop2, propSpec[i4++]); - } else { - let value = propSpec[i4 + -next]; - for (let j = -next; j > 0; j--) - setProp(propSpec[i4++], prop2, value); - i4++; + props.superstate.spaceManager.readTable(contextPath, newSchema.id).then((f3) => { + if (f3) { + if (newSchema.primary) { + for (const c3 of contexts) { + loadContextFields(c3); } } + updateTable(f3); } - this.nodeSet = new NodeSet(nodeNames.map((name317, i4) => NodeType.define({ - name: i4 >= this.minRepeatTerm ? void 0 : name317, - id: i4, - props: nodeProps[i4], - top: topTerms.indexOf(i4) > -1, - error: i4 == 0, - skipped: spec.skippedNodes && spec.skippedNodes.indexOf(i4) > -1 - }))); - if (spec.propSources) - this.nodeSet = this.nodeSet.extend(...spec.propSources); - this.strict = false; - this.bufferLength = DefaultBufferLength; - let tokenArray = decodeArray(spec.tokenData); - this.context = spec.context; - this.specialized = new Uint16Array(spec.specialized ? spec.specialized.length : 0); - this.specializers = []; - if (spec.specialized) - for (let i4 = 0; i4 < spec.specialized.length; i4++) { - this.specialized[i4] = spec.specialized[i4].term; - this.specializers[i4] = spec.specialized[i4].get; - } - this.states = decodeArray(spec.states, Uint32Array); - this.data = decodeArray(spec.stateData); - this.goto = decodeArray(spec.goto); - this.maxTerm = spec.maxTerm; - this.tokenizers = spec.tokenizers.map((value) => typeof value == "number" ? new TokenGroup(tokenArray, value) : value); - this.topRules = spec.topRules; - this.dialects = spec.dialects || {}; - this.dynamicPrecedences = spec.dynamicPrecedences || null; - this.tokenPrecTable = spec.tokenPrec; - this.termNames = spec.termNames || null; - this.maxNode = this.nodeSet.types.length - 1; - this.dialect = this.parseDialect(); - this.top = this.topRules[Object.keys(this.topRules)[0]]; - } - createParse(input, fragments, ranges) { - let parse7 = new Parse(this, input, fragments, ranges); - for (let w2 of this.wrappers) - parse7 = w2(parse7, input, fragments, ranges); - return parse7; - } - getGoto(state, term, loose = false) { - let table = this.goto; - if (term >= table[0]) - return -1; - for (let pos = table[term + 1]; ; ) { - let groupTag = table[pos++], last = groupTag & 1; - let target = table[pos++]; - if (last && loose) - return target; - for (let end = pos + (groupTag >> 1); pos < end; pos++) - if (table[pos] == state) - return target; - if (last) - return -1; - } - } - hasAction(state, terminal) { - let data2 = this.data; - for (let set = 0; set < 2; set++) { - for (let i4 = this.stateSlot(state, set ? 2 : 1), next; ; i4 += 3) { - if ((next = data2[i4]) == 65535) { - if (data2[i4 + 1] == 1) - next = data2[i4 = pair(data2, i4 + 2)]; - else if (data2[i4 + 1] == 2) - return pair(data2, i4 + 2); - else - break; + }); + }; + const updateTable = (newTable) => { + setTableData(newTable); + }; + (0, import_react20.useEffect)(() => { + const refreshMDB = (payload) => { + if (payload.path == contextPath) { + if (dbSchema) { + retrieveCachedTable(dbSchema); } - if (next == terminal || next == 0) - return pair(data2, i4 + 1); + } else { + const tag2 = Object.keys(contextTable).find( + (t5) => props.superstate.spaceManager.spaceInfoForPath(t5)?.path == payload.path + ); + if (tag2) + loadContextFields(tag2); } - } - return 0; - } - stateSlot(state, slot) { - return this.states[state * 6 + slot]; - } - stateFlag(state, flag) { - return (this.stateSlot(state, 0) & flag) > 0; - } - validAction(state, action) { - if (action == this.stateSlot(state, 4)) - return true; - for (let i4 = this.stateSlot(state, 1); ; i4 += 3) { - if (this.data[i4] == 65535) { - if (this.data[i4 + 1] == 1) - i4 = pair(this.data, i4 + 2); - else - return false; + }; + const refreshPath = (payload) => { + if (payload.path == contextPath && dbSchema) { + retrieveCachedTable(dbSchema); + } else if (dbSchema?.primary == "true" && tableData?.rows.some((f2) => f2[PathPropertyName] == payload.path)) { + retrieveCachedTable(dbSchema); } - if (action == pair(this.data, i4 + 1)) - return true; - } - } - nextStates(state) { - let result = []; - for (let i4 = this.stateSlot(state, 1); ; i4 += 3) { - if (this.data[i4] == 65535) { - if (this.data[i4 + 1] == 1) - i4 = pair(this.data, i4 + 2); - else - break; + }; + props.superstate.eventsDispatcher.addListener( + "contextStateUpdated", + refreshMDB + ); + props.superstate.eventsDispatcher.addListener( + "pathStateUpdated", + refreshPath + ); + return () => { + props.superstate.eventsDispatcher.removeListener( + "contextStateUpdated", + refreshMDB + ); + props.superstate.eventsDispatcher.removeListener( + "pathStateUpdated", + refreshPath + ); + }; + }, [contextTable, dbSchema, retrieveCachedTable, spaceInfo, tableData]); + (0, import_react20.useEffect)(() => { + loadTables(); + }, [spaceInfo, frameSchema]); + const saveDB = async (newTable) => { + if (spaceInfo.readOnly) + return; + await props.superstate.spaceManager.saveTable(contextPath, newTable, true).then((f2) => { + updateTable(newTable); + }); + }; + const cols = (0, import_react20.useMemo)( + () => tableData ? [ + ...tableData.cols.map((f2) => ({ ...f2, table: "" })) ?? [], + ...dbSchema?.primary == "true" ? contexts.reduce( + (p, c3) => [ + ...p, + ...contextTable[c3]?.cols.filter((f2) => f2.primary != "true").map((f2) => ({ ...f2, table: c3 })) ?? [] + ], + [] + ) : [] + ] : [], + [tableData, contextTable, contexts, dbSchema] + ); + const data2 = (0, import_react20.useMemo)( + () => tableData?.rows.map((r2, index2) => ({ + _index: index2.toString(), + ...r2, + ...r2[PathPropertyName] ? { + [PathPropertyName]: props.superstate.spaceManager.resolvePath( + r2[PathPropertyName], + spaceCache?.path + ) + } : {}, + ...contexts.reduce((p, c3) => { + const contextRowIndexByPath = contextTable[c3]?.rows.findIndex( + (f2) => f2[PathPropertyName] == r2[PathPropertyName] + ) ?? -1; + const contextRowsByPath = contextTable[c3]?.rows[contextRowIndexByPath] ?? {}; + const contextRowsWithKeysAppended = Object.keys( + contextRowsByPath + ).reduce((pa, ca) => ({ ...pa, [ca + c3]: contextRowsByPath[ca] }), { + ["_index" + c3]: contextRowIndexByPath.toString() + }); + return { ...p, ...contextRowsWithKeysAppended }; + }, {}) + })) ?? [], + [tableData, contextTable, cols, dbSchema, spaceCache] + ); + (0, import_react20.useEffect)(() => { + if (tableData) { + for (const c3 of contexts) { + loadContextFields(c3); } - if ((this.data[i4 + 2] & 65536 >> 16) == 0) { - let value = this.data[i4 + 1]; - if (!result.some((v2, i5) => i5 & 1 && v2 == value)) - result.push(this.data[i4], value); + } + }, [tableData]); + const saveContextDB = async (newTable, tag2) => { + await props.superstate.spaceManager.saveTable(tagSpacePathFromTag(tag2), newTable, true).then((f2) => { + setContextTable((t5) => ({ + ...t5, + [tag2]: newTable + })); + }); + }; + const sortedColumns = (0, import_react20.useMemo)(() => { + return cols.filter( + (f2) => f2.hidden != "true" && !(predicate?.colsHidden ?? []).some((c3) => c3 == f2.name + f2.table) + ).sort( + (a4, b2) => (predicate?.colsOrder ?? []).findIndex((x2) => x2 == a4.name + a4.table) - (predicate?.colsOrder ?? []).findIndex((x2) => x2 == b2.name + b2.table) + ); + }, [cols, predicate]); + const filteredData = (0, import_react20.useMemo)( + () => data2.filter((f2) => { + return (predicate?.filters ?? []).reduce((p, c3) => { + return p ? filterReturnForCol( + cols.find((col) => col.name + col.table == c3.field), + c3, + f2, + spaceCache.properties + ) : p; + }, true); + }).filter( + (f2) => searchString?.length > 0 ? matchAny(searchString).test( + Object.keys(f2).filter((g) => g.charAt(0) != "_").map((g) => f2[g]).join("|") + ) : true + ).sort((a4, b2) => { + return (predicate?.sort ?? []).reduce((p, c3) => { + return p == 0 ? sortReturnForCol( + cols.find((col) => col.name + col.table == c3.field), + c3, + a4, + b2 + ) : p; + }, 0); + }), + [predicate, data2, cols, searchString] + ); + const updateValue2 = (column2, value, table, index2, path2) => { + const col = (table == "" ? tableData : contextTable[table])?.cols.find( + (f2) => f2.name == column2 + ); + if (col) + saveProperties( + props.superstate, + path2 ?? tableData.rows[index2]?.[PathPropertyName], + { [column2]: parseMDBValue(col.type, value) } + ); + if (table == "") { + saveDB({ + ...tableData, + rows: tableData.rows.map( + (r2, i4) => i4 == index2 ? { + ...r2, + [column2]: value + } : r2 + ) + }); + } else if (contextTable[table]) { + const path3 = tableData.rows[index2][PathPropertyName]; + saveContextDB( + { + ...contextTable[table], + rows: contextTable[table].rows.map( + (r2, i4) => r2[PathPropertyName] == path3 ? { + ...r2, + [column2]: value + } : r2 + ) + }, + table + ); + } + }; + const sortColumn = (sort2) => { + savePredicate({ + sort: [sort2] + }); + }; + const hideColumn = (col, hidden) => { + savePredicate({ + colsHidden: hidden ? [ + ...predicate.colsHidden.filter((s4) => s4 != col.name + col.table), + col.name + col.table + ] : predicate.colsHidden.filter((s4) => s4 != col.name + col.table) + }); + }; + const updateFieldValue = (column2, fieldValue, value, table, index2, path2) => { + const col = tableData.cols.find((f2) => f2.name == column2); + saveProperties( + props.superstate, + path2 ?? tableData.rows[index2]?.[PathPropertyName], + { [column2]: parseMDBValue(col.type, value) } + ); + if (table == "") { + const newTable = { + ...tableData, + cols: tableData.cols.map( + (m4) => m4.name == column2 ? { + ...m4, + value: fieldValue + } : m4 + ), + rows: tableData.rows.map( + (r2, i4) => i4 == index2 ? { + ...r2, + [column2]: value + } : r2 + ) + }; + saveDB(newTable); + } else if (contextTable[table]) { + const path3 = tableData.rows[index2][PathPropertyName]; + saveContextDB( + { + ...contextTable[table], + cols: contextTable[table].cols.map( + (m4) => m4.name == column2 ? { + ...m4, + value: fieldValue + } : m4 + ), + rows: contextTable[table].rows.map( + (r2, i4) => path3 == r2[PathPropertyName] ? { + ...r2, + [column2]: value + } : r2 + ) + }, + table + ); + } + }; + const syncAllProperties = async (f2) => { + const paths = f2.rows.map((f3) => f3[PathPropertyName]); + const getPathProperties2 = async (paths2, fmKeys) => { + let rows = { uniques: [], cols: fmKeys, rows: [] }; + for (const c3 of paths2) { + const properties3 = props.superstate.pathsIndex.get(c3)?.metadata.property; + rows = { + uniques: [], + cols: fmKeys, + rows: [ + ...rows.rows, + { + [PathPropertyName]: c3, + ...properties3 ? fmKeys.reduce((p, c4) => { + const value = parseProperty(c4, properties3[c4]); + if (value?.length > 0) + return { ...p, [c4]: value }; + return p; + }, {}) : {} + } + ] + }; + } + return rows; + }; + const pathPropertiesTable = await getPathProperties2( + paths, + f2.cols.filter((f3) => !f3.type.includes("file")).map((f3) => f3.name) + ); + const newRows = f2.rows.map((r2) => { + const fmRow = pathPropertiesTable.rows.find( + (f3) => f3[PathPropertyName] == r2[PathPropertyName] + ); + if (fmRow) { + return { + ...r2, + ...fmRow + }; } + return r2; + }); + const rowsChanged = !import_lodash9.default.isEqual(newRows, tableData?.rows); + const colsChanged = !import_lodash9.default.isEqual(tableData?.cols, f2.cols); + if (rowsChanged || colsChanged) { + saveDB({ + ...f2, + rows: newRows + }); } - return result; - } - overrides(token, prev) { - let iPrev = findOffset(this.data, this.tokenPrecTable, prev); - return iPrev < 0 || findOffset(this.data, this.tokenPrecTable, token) < iPrev; - } - configure(config4) { - let copy = Object.assign(Object.create(LRParser.prototype), this); - if (config4.props) - copy.nodeSet = this.nodeSet.extend(...config4.props); - if (config4.top) { - let info = this.topRules[config4.top]; - if (!info) - throw new RangeError(`Invalid top rule name ${config4.top}`); - copy.top = info; + }; + (0, import_react20.useEffect)(() => { + if (frameSchema) { + parsePredicate(frameSchema.predicate); } - if (config4.tokenizers) - copy.tokenizers = this.tokenizers.map((t5) => { - let found = config4.tokenizers.find((r2) => r2.from == t5); - return found ? found.to : t5; + }, [frameSchema]); + const selectRows = (lastSelected, rows) => { + setSelectedRows(rows); + if (!(dbSchema?.primary == "true")) + return; + if (lastSelected) { + const path2 = tableData.rows[parseInt(lastSelected)]?.[PathPropertyName]; + if (path2) + props.superstate.ui.setActivePath(path2); + } else { + props.superstate.ui.setActivePath(contextPath); + } + }; + const savePredicate = (newPredicate) => { + const defPredicate = defaultPredicateForSchema(dbSchema); + const pred = { + ...predicate ?? defPredicate, + ...newPredicate + }; + const cleanedPredicate = validatePredicate(pred, defPredicate); + if (frameSchema) { + saveSchema({ + ...frameSchema, + predicate: JSON.stringify(cleanedPredicate) }); - if (config4.contextTracker) - copy.context = config4.contextTracker; - if (config4.dialect) - copy.dialect = this.parseDialect(config4.dialect); - if (config4.strict != null) - copy.strict = config4.strict; - if (config4.wrap) - copy.wrappers = copy.wrappers.concat(config4.wrap); - if (config4.bufferLength != null) - copy.bufferLength = config4.bufferLength; - return copy; - } - hasWrappers() { - return this.wrappers.length > 0; - } - getName(term) { - return this.termNames ? this.termNames[term] : String(term <= this.maxNode && this.nodeSet.types[term].name || term); - } - get eofTerm() { - return this.maxNode + 1; - } - get topNode() { - return this.nodeSet.types[this.top[1]]; - } - dynamicPrecedence(term) { - let prec = this.dynamicPrecedences; - return prec == null ? 0 : prec[term] || 0; - } - parseDialect(dialect) { - let values2 = Object.keys(this.dialects), flags = values2.map(() => false); - if (dialect) - for (let part of dialect.split(" ")) { - let id3 = values2.indexOf(part); - if (id3 >= 0) - flags[id3] = true; - } - let disabled = null; - for (let i4 = 0; i4 < values2.length; i4++) - if (!flags[i4]) { - for (let j = this.dialects[values2[i4]], id3; (id3 = this.data[j++]) != 65535; ) - (disabled || (disabled = new Uint8Array(this.maxTerm + 1)))[id3] = 1; + } else { + saveSchema({ + id: uniqueNameFromString( + dbSchema.id + "View", + frameSchemas.map((f2) => f2.id) + ), + name: dbSchema.name + " View", + type: "view", + def: { db: dbSchema.id }, + predicate: JSON.stringify(cleanedPredicate) + }); + } + setPredicate(cleanedPredicate); + }; + (0, import_react20.useEffect)(() => { + if (predicate) + setPredicate((p) => ({ + ...p, + colsOrder: uniq([ + ...p.colsOrder, + ...cols.filter((f2) => f2.hidden != "true").map((c3) => c3.name + c3.table) + ]) + })); + }, [cols]); + const parsePredicate = (predicateStr) => { + const defPredicate = defaultPredicateForSchema(dbSchema); + const newPredicate = validatePredicate( + safelyParseJSON(predicateStr), + defPredicate + ); + setPredicate({ + ...newPredicate, + colsOrder: uniq([ + ...newPredicate.colsOrder, + ...cols.filter((f2) => f2.hidden != "true").map((c3) => c3.name + c3.table) + ]) + }); + }; + const delColumn = (column2) => { + let mdbtable; + const table = column2.table; + if (table == "") { + mdbtable = tableData; + } else if (contextTable[table]) { + mdbtable = contextTable[table]; + } + const newFields = mdbtable.cols.filter( + (f2, i4) => f2.name != column2.name + ); + const newTable = { + ...mdbtable, + cols: newFields, + rows: mdbtable.rows.map((r2) => { + const { [column2.name]: val, ...rest } = r2; + return rest; + }) + }; + if (table == "") { + saveDB(newTable); + } else if (contextTable[table]) { + saveContextDB(newTable, table); + } + }; + const newColumn = (col) => { + return saveColumn(col); + }; + const saveColumn = (newColumn2, oldColumn) => { + let mdbtable; + const column2 = { + ...newColumn2, + name: sanitizeColumnName(newColumn2.name) + }; + const table = column2.table; + if (table == "" || table == contextPath) { + mdbtable = tableData; + } else if (contextTable[table]) { + mdbtable = contextTable[table]; + } + if (column2.name == "") { + props.superstate.ui.notify(i18n_default.notice.noPropertyName); + return false; + } + if (!oldColumn && mdbtable.cols.find( + (f2) => f2.name.toLowerCase() == column2.name.toLowerCase() + ) || oldColumn && oldColumn.name != column2.name && mdbtable.cols.find( + (f2) => f2.name.toLowerCase() == column2.name.toLowerCase() + )) { + props.superstate.ui.notify(i18n_default.notice.duplicatePropertyName); + return false; + } + const oldFieldIndex = oldColumn ? mdbtable.cols.findIndex((f2) => f2.name == oldColumn.name) : -1; + const newFields = oldFieldIndex == -1 ? [...mdbtable.cols, column2] : mdbtable.cols.map((f2, i4) => i4 == oldFieldIndex ? column2 : f2); + const newTable = { + ...mdbtable, + cols: newFields, + rows: mdbtable.rows.map( + (f2) => oldColumn ? { + ...f2, + [column2.name]: f2[oldColumn.name], + oldColumn: void 0 + } : f2 + ) + }; + if (oldColumn) + savePredicate({ + filters: (predicate?.filters ?? []).map( + (f2) => f2.field == oldColumn.name + oldColumn.table ? { ...f2, field: column2.name + column2.table } : f2 + ), + sort: (predicate?.sort ?? []).map( + (f2) => f2.field == oldColumn.name + oldColumn.table ? { ...f2, field: column2.name + column2.table } : f2 + ), + groupBy: (predicate?.groupBy ?? []).map( + (f2) => f2 == oldColumn.name + oldColumn.table ? column2.name + column2.table : f2 + ), + colsHidden: (predicate?.colsHidden ?? []).map( + (f2) => f2 == oldColumn.name + oldColumn.table ? column2.name + column2.table : f2 + ), + colsOrder: (predicate?.colsOrder ?? []).map( + (f2) => f2 == oldColumn.name + oldColumn.table ? column2.name + column2.table : f2 + ), + colsSize: { + ...predicate?.colsSize ?? {}, + [column2.name + column2.table]: predicate?.colsSize?.[oldColumn.name + oldColumn.table], + [oldColumn.name + oldColumn.table]: void 0 + } + }); + if (table == "") { + if (dbSchema.id == defaultContextSchemaID) { + syncAllProperties(newTable); + } else { + saveDB(newTable); } - return new Dialect(dialect, flags, disabled); - } - static deserialize(spec) { - return new LRParser(spec); - } + } else if (contextTable[table]) { + saveContextDB(newTable, table); + } + return true; + }; + return /* @__PURE__ */ import_react20.default.createElement(ContextEditorContext.Provider, { + value: { + source: contextPath, + views, + cols, + saveDB, + filteredData, + dbSchema, + tableData, + selectedRows, + selectRows, + sortedColumns, + contextTable, + setContextTable, + predicate, + savePredicate, + saveColumn, + hideColumn, + sortColumn, + delColumn, + newColumn, + searchString, + setSearchString, + updateValue: updateValue2, + updateFieldValue, + editMode, + setEditMode + } + }, props.children); }; -function pair(data2, off) { - return data2[off] | data2[off + 1] << 16; -} -function findOffset(data2, start, term) { - for (let i4 = start, next; (next = data2[i4]) != 65535; i4++) - if (next == term) - return i4 - start; - return -1; -} -function findFinished(stacks) { - let best = null; - for (let stack of stacks) { - let stopped = stack.p.stoppedAt; - if ((stack.pos == stack.p.stream.end || stopped != null && stack.pos > stopped) && stack.p.parser.stateFlag(stack.state, 2) && (!best || best.score < stack.score)) - best = stack; - } - return best; -} -// node_modules/@lezer/javascript/node_modules/@lezer/highlight/dist/index.js -var nextTagID = 0; -var Tag = class { - constructor(set, base2, modified) { - this.set = set; - this.base = base2; - this.modified = modified; - this.id = nextTagID++; - } - static define(parent) { - if (parent === null || parent === void 0 ? void 0 : parent.base) - throw new Error("Can not derive from a modified tag"); - let tag2 = new Tag([], null, []); - tag2.set.push(tag2); - if (parent) - for (let t5 of parent.set) - tag2.set.push(t5); - return tag2; - } - static defineModifier() { - let mod3 = new Modifier(); - return (tag2) => { - if (tag2.modified.indexOf(mod3) > -1) - return tag2; - return Modifier.get(tag2.base || tag2, tag2.modified.concat(mod3).sort((a4, b2) => a4.id - b2.id)); - }; - } -}; -var nextModifierID = 0; -var Modifier = class { - constructor() { - this.instances = []; - this.id = nextModifierID++; - } - static get(base2, mods) { - if (!mods.length) - return base2; - let exists = mods[0].instances.find((t5) => t5.base == base2 && sameArray(mods, t5.modified)); - if (exists) - return exists; - let set = [], tag2 = new Tag(set, base2, mods); - for (let m4 of mods) - m4.instances.push(tag2); - let configs = permute(mods); - for (let parent of base2.set) - for (let config4 of configs) - set.push(Modifier.get(parent, config4)); - return tag2; - } -}; -function sameArray(a4, b2) { - return a4.length == b2.length && a4.every((x2, i4) => x2 == b2[i4]); +// src/core/react/hooks/useCombinedRef.tsx +var import_react21 = __toESM(require_react()); +function useCombinedRefs2(...refs) { + return (0, import_react21.useMemo)( + () => (node) => { + refs.forEach((ref2) => ref2(node)); + }, + refs + ); } -function permute(array) { - let result = [array]; - for (let i4 = 0; i4 < array.length; i4++) { - for (let a4 of permute(array.slice(0, i4).concat(array.slice(i4 + 1)))) - result.push(a4); + +// src/core/react/components/SpaceView/Contexts/TableView/ColumnHeader.tsx +var import_react22 = __toESM(require_react()); +var filePropTypes = [ + { + name: i18n_default.properties.fileProperty.name, + value: "name" + }, + { + name: i18n_default.properties.fileProperty.createdTime, + value: "ctime" + }, + { + name: i18n_default.properties.fileProperty.modifiedTime, + value: "mtime" + }, + { + name: i18n_default.properties.fileProperty.sticker, + value: "sticker" + }, + { + name: i18n_default.properties.fileProperty.extension, + value: "extension" + }, + { + name: i18n_default.properties.fileProperty.size, + value: "size" + }, + { + name: i18n_default.properties.fileProperty.parentFolder, + value: "folder" + }, + { + name: i18n_default.properties.fileProperty.links, + value: "inlinks" + }, + { + name: i18n_default.properties.fileProperty.tags, + value: "tags" + }, + { + name: i18n_default.properties.fileProperty.spaces, + value: "spaces" } - return result; -} -function styleTags(spec) { - let byName = /* @__PURE__ */ Object.create(null); - for (let prop2 in spec) { - let tags3 = spec[prop2]; - if (!Array.isArray(tags3)) - tags3 = [tags3]; - for (let part of prop2.split(" ")) - if (part) { - let pieces = [], mode2 = 2, rest = part; - for (let pos = 0; ; ) { - if (rest == "..." && pos > 0 && pos + 3 == part.length) { - mode2 = 1; - break; - } - let m4 = /^"(?:[^"\\]|\\.)*?"|[^\/!]+/.exec(rest); - if (!m4) - throw new RangeError("Invalid path: " + part); - pieces.push(m4[0] == "*" ? "" : m4[0][0] == '"' ? JSON.parse(m4[0]) : m4[0]); - pos += m4[0].length; - if (pos == part.length) - break; - let next = part[pos++]; - if (pos == part.length && next == "!") { - mode2 = 0; - break; +]; +var ColumnHeader = (props) => { + const [field, setField] = (0, import_react22.useState)(props.column); + const menuRef = (0, import_react22.useRef)(null); + const { spaceInfo, spaceState: spaceCache } = (0, import_react22.useContext)(SpaceContext); + const { + predicate, + tableData, + contextTable, + cols, + newColumn, + saveColumn, + hideColumn, + sortColumn, + delColumn + } = (0, import_react22.useContext)(ContextEditorContext); + (0, import_react22.useEffect)(() => { + setField(props.column); + }, [props.column]); + const { + attributes, + listeners, + setNodeRef: setDraggableNodeRef, + transform + } = useDraggable({ + id: field.name + field.table, + data: { name: field.name } + }); + const { setNodeRef: setDroppableNodeRef } = useDroppable({ + id: field.name + field.table, + data: { name: field.name } + }); + const saveField = (field2) => { + if (field2.name.length > 0) { + if (field2.name != props.column.name || field2.type != props.column.type || field2.value != props.column.value || field2.attrs != props.column.attrs) { + const saveResult = saveColumn(field2, props.column); + if (saveResult) { + if (props.isNew) { + setField(props.column); } - if (next != "/") - throw new RangeError("Invalid path: " + part); - rest = part.slice(pos); } - let last = pieces.length - 1, inner = pieces[last]; - if (!inner) - throw new RangeError("Invalid path: " + part); - let rule = new Rule(tags3, mode2, last > 0 ? pieces.slice(0, last) : null); - byName[inner] = rule.sort(byName[inner]); } - } - return ruleNodeProp.add(byName); -} -var ruleNodeProp = new NodeProp(); -var Rule = class { - constructor(tags3, mode2, context, next) { - this.tags = tags3; - this.mode = mode2; - this.context = context; - this.next = next; - } - sort(other) { - if (!other || other.depth < this.depth) { - this.next = other; - return this; } - other.next = this.sort(other.next); - return other; - } - get depth() { - return this.context ? this.context.length : 0; - } + }; + const showNewMenu = (e5) => { + const offset2 = ref2.current.getBoundingClientRect(); + showNewPropertyMenu( + props.superstate, + offset2, + spaceCache?.contexts ?? [], + cols, + (source, field2) => newColumn({ ...field2, table: source }), + tableData.schema.id, + spaceInfo.path, + false + ); + }; + const toggleMenu = (e5) => { + if (props.isNew) { + showNewMenu(e5); + } else { + const offset2 = e5.target.getBoundingClientRect(); + const options = optionValuesForColumn( + field.name, + field.table == "" ? tableData : contextTable[field.table] + ); + showPropertyMenu({ + superstate: props.superstate, + rect: offset2, + editable: props.editable, + options, + field, + fields: cols, + contextPath: spaceInfo.path, + saveField, + hide: hideColumn, + deleteColumn: delColumn, + sortColumn, + hidden: predicate?.colsHidden.includes(field.name + field.table) + }); + } + }; + const ref2 = (0, import_react22.useRef)(null); + const setNodeRef = useCombinedRefs2(setDroppableNodeRef, setDraggableNodeRef); + return /* @__PURE__ */ import_react22.default.createElement("div", { + ref: setNodeRef, + ...listeners, + ...attributes, + className: "mk-col-header", + onClick: (e5) => { + toggleMenu(e5); + } + }, /* @__PURE__ */ import_react22.default.createElement("div", { + ref: ref2 + }, props.column.name.length > 0 ? /* @__PURE__ */ import_react22.default.createElement(import_react22.default.Fragment, null, /* @__PURE__ */ import_react22.default.createElement("div", { + className: "mk-path-context-field-icon", + dangerouslySetInnerHTML: { + __html: props.superstate.ui.getSticker( + stickerForField(props.column) + ) + } + }), /* @__PURE__ */ import_react22.default.createElement("div", { + className: "mk-path-context-field-key" + }, field.name)) : "+", /* @__PURE__ */ import_react22.default.createElement("span", { + className: "mk-col-header-context", + "aria-label": props.column.table.length > 0 ? props.column.table : "" + }, props.column.table.length > 0 ? "#" : ""))); }; -function tagHighlighter(tags3, options) { - let map4 = /* @__PURE__ */ Object.create(null); - for (let style of tags3) { - if (!Array.isArray(style.tag)) - map4[style.tag.id] = style.class; - else - for (let tag2 of style.tag) - map4[tag2.id] = style.class; + +// src/core/utils/properties/allProperties.ts +var allCacheTypesForPaths = (superstate, paths) => { + if (!superstate.settings.experimental) + return []; + ; + const properties3 = {}; + for (const path2 of paths) { + const f2 = superstate.pathsIndex.get(path2)?.metadata; + if (f2) { + Object.keys(f2).forEach((k2) => { + const type = detectPropertyType(f2[k2], k2); + if (type != "unknown" && type != "object") + properties3[k2] = [...properties3[k2] ?? [], type]; + }); + } } - let { scope, all: all2 = null } = options || {}; - return { - style: (tags4) => { - let cls = all2; - for (let tag2 of tags4) { - for (let sub2 of tag2.set) { - let tagClass = map4[sub2.id]; - if (tagClass) { - cls = cls ? cls + " " + tagClass : tagClass; - break; + return Object.keys(properties3).reduce((p, c3) => { + return [...p, { name: c3, type: properties3[c3][0] }]; + }, []); +}; + +// src/core/react/components/UI/Menus/contexts/PropertyValue.tsx +var import_react23 = __toESM(require_react()); +var PropertyValueComponent = (props) => { + const showOptions = (e5, value, options, field, saveProperty) => { + props.superstate.ui.openMenu( + e5.target.getBoundingClientRect(), + { + ui: props.superstate.ui, + multi: false, + editable: true, + searchable: true, + saveOptions: (_15, v2) => { + if (saveProperty) { + saveProperty(v2[0]); + } else { + saveParsedValue(field, v2[0]); } - } + }, + placeholder: i18n_default.labels.propertyValueSpace, + value: [value ?? ""], + options } - return cls; - }, - scope + ); }; -} -var t2 = Tag.define; -var comment = t2(); -var name315 = t2(); -var typeName2 = t2(name315); -var propertyName = t2(name315); -var literal2 = t2(); -var string2 = t2(literal2); -var number2 = t2(literal2); -var content = t2(); -var heading = t2(content); -var keyword = t2(); -var operator = t2(); -var punctuation = t2(); -var bracket = t2(punctuation); -var meta = t2(); -var tags = { - comment, - lineComment: t2(comment), - blockComment: t2(comment), - docComment: t2(comment), - name: name315, - variableName: t2(name315), - typeName: typeName2, - tagName: t2(typeName2), - propertyName, - attributeName: t2(propertyName), - className: t2(name315), - labelName: t2(name315), - namespace: t2(name315), - macroName: t2(name315), - literal: literal2, - string: string2, - docString: t2(string2), - character: t2(string2), - attributeValue: t2(string2), - number: number2, - integer: t2(number2), - float: t2(number2), - bool: t2(literal2), - regexp: t2(literal2), - escape: t2(literal2), - color: t2(literal2), - url: t2(literal2), - keyword, - self: t2(keyword), - null: t2(keyword), - atom: t2(keyword), - unit: t2(keyword), - modifier: t2(keyword), - operatorKeyword: t2(keyword), - controlKeyword: t2(keyword), - definitionKeyword: t2(keyword), - moduleKeyword: t2(keyword), - operator, - derefOperator: t2(operator), - arithmeticOperator: t2(operator), - logicOperator: t2(operator), - bitwiseOperator: t2(operator), - compareOperator: t2(operator), - updateOperator: t2(operator), - definitionOperator: t2(operator), - typeOperator: t2(operator), - controlOperator: t2(operator), - punctuation, - separator: t2(punctuation), - bracket, - angleBracket: t2(bracket), - squareBracket: t2(bracket), - paren: t2(bracket), - brace: t2(bracket), - content, - heading, - heading1: t2(heading), - heading2: t2(heading), - heading3: t2(heading), - heading4: t2(heading), - heading5: t2(heading), - heading6: t2(heading), - contentSeparator: t2(content), - list: t2(content), - quote: t2(content), - emphasis: t2(content), - strong: t2(content), - link: t2(content), - monospace: t2(content), - strikethrough: t2(content), - inserted: t2(), - deleted: t2(), - changed: t2(), - invalid: t2(), - meta, - documentMeta: t2(meta), - annotation: t2(meta), - processingInstruction: t2(meta), - definition: Tag.defineModifier(), - constant: Tag.defineModifier(), - function: Tag.defineModifier(), - standard: Tag.defineModifier(), - local: Tag.defineModifier(), - special: Tag.defineModifier() -}; -var classHighlighter = tagHighlighter([ - { tag: tags.link, class: "tok-link" }, - { tag: tags.heading, class: "tok-heading" }, - { tag: tags.emphasis, class: "tok-emphasis" }, - { tag: tags.strong, class: "tok-strong" }, - { tag: tags.keyword, class: "tok-keyword" }, - { tag: tags.atom, class: "tok-atom" }, - { tag: tags.bool, class: "tok-bool" }, - { tag: tags.url, class: "tok-url" }, - { tag: tags.labelName, class: "tok-labelName" }, - { tag: tags.inserted, class: "tok-inserted" }, - { tag: tags.deleted, class: "tok-deleted" }, - { tag: tags.literal, class: "tok-literal" }, - { tag: tags.string, class: "tok-string" }, - { tag: tags.number, class: "tok-number" }, - { tag: [tags.regexp, tags.escape, tags.special(tags.string)], class: "tok-string2" }, - { tag: tags.variableName, class: "tok-variableName" }, - { tag: tags.local(tags.variableName), class: "tok-variableName tok-local" }, - { tag: tags.definition(tags.variableName), class: "tok-variableName tok-definition" }, - { tag: tags.special(tags.variableName), class: "tok-variableName2" }, - { tag: tags.definition(tags.propertyName), class: "tok-propertyName tok-definition" }, - { tag: tags.typeName, class: "tok-typeName" }, - { tag: tags.namespace, class: "tok-namespace" }, - { tag: tags.className, class: "tok-className" }, - { tag: tags.macroName, class: "tok-macroName" }, - { tag: tags.propertyName, class: "tok-propertyName" }, - { tag: tags.operator, class: "tok-operator" }, - { tag: tags.comment, class: "tok-comment" }, - { tag: tags.meta, class: "tok-meta" }, - { tag: tags.invalid, class: "tok-invalid" }, - { tag: tags.punctuation, class: "tok-punctuation" } -]); - -// node_modules/@lezer/javascript/dist/index.es.js -var noSemi = 281; -var incdec = 1; -var incdecPrefix = 2; -var templateContent = 282; -var InterpolationStart = 3; -var templateEnd = 283; -var insertSemi = 284; -var TSExtends = 4; -var spaces = 286; -var newline = 287; -var LineComment = 5; -var BlockComment = 6; -var Dialect_ts = 1; -var space = [ - 9, - 10, - 11, - 12, - 13, - 32, - 133, - 160, - 5760, - 8192, - 8193, - 8194, - 8195, - 8196, - 8197, - 8198, - 8199, - 8200, - 8201, - 8202, - 8232, - 8233, - 8239, - 8287, - 12288 -]; -var braceR = 125; -var braceL = 123; -var semicolon = 59; -var slash = 47; -var star = 42; -var plus = 43; -var minus = 45; -var dollar = 36; -var backtick = 96; -var backslash = 92; -var trackNewline = new ContextTracker({ - start: false, - shift(context, term) { - return term == LineComment || term == BlockComment || term == spaces ? context : term == newline; - }, - strict: false -}); -var insertSemicolon = new ExternalTokenizer((input, stack) => { - let { next } = input; - if ((next == braceR || next == -1 || stack.context) && stack.canShift(insertSemi)) - input.acceptToken(insertSemi); -}, { contextual: true, fallback: true }); -var noSemicolon = new ExternalTokenizer((input, stack) => { - let { next } = input, after; - if (space.indexOf(next) > -1) - return; - if (next == slash && ((after = input.peek(1)) == slash || after == star)) - return; - if (next != braceR && next != semicolon && next != -1 && !stack.context && stack.canShift(noSemi)) - input.acceptToken(noSemi); -}, { contextual: true }); -var incdecToken = new ExternalTokenizer((input, stack) => { - let { next } = input; - if (next == plus || next == minus) { - input.advance(); - if (next == input.next) { - input.advance(); - let mayPostfix = !stack.context && stack.canShift(incdec); - input.acceptToken(mayPostfix ? incdec : incdecPrefix); - } - } -}, { contextual: true }); -var template = new ExternalTokenizer((input) => { - for (let afterDollar = false, i4 = 0; ; i4++) { - let { next } = input; - if (next < 0) { - if (i4) - input.acceptToken(templateContent); - break; - } else if (next == backtick) { - if (i4) - input.acceptToken(templateContent); - else - input.acceptToken(templateEnd, 1); - break; - } else if (next == braceL && afterDollar) { - if (i4 == 1) - input.acceptToken(InterpolationStart, 1); - else - input.acceptToken(templateContent, -1); - break; - } else if (next == 10 && i4) { - input.advance(); - input.acceptToken(templateContent); - break; - } else if (next == backslash) { - input.advance(); + const selectType = (e5) => { + props.superstate.ui.openMenu( + e5.target.getBoundingClientRect(), + { + ui: props.superstate.ui, + multi: false, + editable: false, + searchable: false, + saveOptions: (_15, v2) => saveParsedValue("type", v2[0]), + value: [], + showAll: true, + options: fieldTypes.filter((f2) => f2.primative).map((f2, i4) => ({ + id: i4 + 1, + name: f2.label, + value: f2.type, + icon: f2.icon + })) + } + ); + }; + const parsedValue = (0, import_react23.useMemo)( + () => parseFieldValue(props.value, props.fieldType, props.superstate), + [props.value, props.fieldType] + ); + const saveParsedValue = (field, value) => { + props.saveValue(JSON.stringify({ ...parsedValue, [field]: value })); + }; + const saveSpaceProperty = (field) => { + const colExists = props.superstate.contextsIndex.get(parsedValue.space)?.cols?.some((f2) => f2.name == field); + if (!colExists) { + props.superstate.spaceManager.addSpaceProperty(parsedValue.space, { + name: field, + schemaId: defaultContextSchemaID, + type: "context", + value: props.name + }); } - afterDollar = next == dollar; - input.advance(); - } -}); -function tsExtends(value, stack) { - return value == "extends" && stack.dialectEnabled(Dialect_ts) ? TSExtends : -1; -} -var jsHighlight = styleTags({ - "get set async static": tags.modifier, - "for while do if else switch try catch finally return throw break continue default case": tags.controlKeyword, - "in of await yield void typeof delete instanceof": tags.operatorKeyword, - "let var const function class extends": tags.definitionKeyword, - "import export from": tags.moduleKeyword, - "with debugger as new": tags.keyword, - TemplateString: tags.special(tags.string), - Super: tags.atom, - BooleanLiteral: tags.bool, - this: tags.self, - null: tags.null, - Star: tags.modifier, - VariableName: tags.variableName, - "CallExpression/VariableName TaggedTemplateExpression/VariableName": tags.function(tags.variableName), - VariableDefinition: tags.definition(tags.variableName), - Label: tags.labelName, - PropertyName: tags.propertyName, - PrivatePropertyName: tags.special(tags.propertyName), - "CallExpression/MemberExpression/PropertyName": tags.function(tags.propertyName), - "FunctionDeclaration/VariableDefinition": tags.function(tags.definition(tags.variableName)), - "ClassDeclaration/VariableDefinition": tags.definition(tags.className), - PropertyDefinition: tags.definition(tags.propertyName), - PrivatePropertyDefinition: tags.definition(tags.special(tags.propertyName)), - UpdateOp: tags.updateOperator, - LineComment: tags.lineComment, - BlockComment: tags.blockComment, - Number: tags.number, - String: tags.string, - ArithOp: tags.arithmeticOperator, - LogicOp: tags.logicOperator, - BitOp: tags.bitwiseOperator, - CompareOp: tags.compareOperator, - RegExp: tags.regexp, - Equals: tags.definitionOperator, - "Arrow : Spread": tags.punctuation, - "( )": tags.paren, - "[ ]": tags.squareBracket, - "{ }": tags.brace, - "InterpolationStart InterpolationEnd": tags.special(tags.brace), - ".": tags.derefOperator, - ", ;": tags.separator, - TypeName: tags.typeName, - TypeDefinition: tags.definition(tags.typeName), - "type enum interface implements namespace module declare": tags.definitionKeyword, - "abstract global Privacy readonly override": tags.modifier, - "is keyof unique infer": tags.operatorKeyword, - JSXAttributeValue: tags.attributeValue, - JSXText: tags.content, - "JSXStartTag JSXStartCloseTag JSXSelfCloseEndTag JSXEndTag": tags.angleBracket, - "JSXIdentifier JSXNameSpacedName": tags.tagName, - "JSXAttribute/JSXIdentifier JSXAttribute/JSXNameSpacedName": tags.attributeName -}); -var spec_identifier = { __proto__: null, export: 18, as: 23, from: 29, default: 32, async: 37, function: 38, this: 48, true: 56, false: 56, void: 66, typeof: 70, null: 86, super: 88, new: 122, await: 139, yield: 141, delete: 142, class: 152, extends: 154, public: 197, private: 197, protected: 197, readonly: 199, instanceof: 220, in: 222, const: 224, import: 256, keyof: 307, unique: 311, infer: 317, is: 351, abstract: 371, implements: 373, type: 375, let: 378, var: 380, interface: 387, enum: 391, namespace: 397, module: 399, declare: 403, global: 407, for: 428, of: 437, while: 440, with: 444, do: 448, if: 452, else: 454, switch: 458, case: 464, try: 470, catch: 474, finally: 478, return: 482, throw: 486, break: 490, continue: 494, debugger: 498 }; -var spec_word = { __proto__: null, async: 109, get: 111, set: 113, public: 161, private: 161, protected: 161, static: 163, abstract: 165, override: 167, readonly: 173, new: 355 }; -var spec_LessThan = { __proto__: null, "<": 129 }; -var parser2 = LRParser.deserialize({ - version: 14, - states: "$4|O`QYOOO'QQ$IfO'#ChO'XOSO'#DVO)dQYO'#D]O)tQYO'#DhO){QYO'#DrO-xQYO'#DxOOQO'#E]'#E]O.]QWO'#E[O.bQWO'#E[OOQ$IU'#Ef'#EfO0aQ$IfO'#ItO2wQ$IfO'#IuO3eQWO'#EzO3jQpO'#FaOOQ$IU'#FS'#FSO3rO!bO'#FSO4QQWO'#FhO5_QWO'#FgOOQ$IU'#Iu'#IuOOQ$IS'#It'#ItOOQQ'#J^'#J^O5dQWO'#HpO5iQ$I[O'#HqOOQQ'#Ih'#IhOOQQ'#Hr'#HrQ`QYOOO){QYO'#DjO5qQWO'#G[O5vQ#tO'#CmO6UQWO'#EZO6aQWO'#EgO6fQ#tO'#FRO7QQWO'#G[O7VQWO'#G`O7bQWO'#G`O7pQWO'#GcO7pQWO'#GdO7pQWO'#GfO5qQWO'#GiO8aQWO'#GlO9oQWO'#CdO:PQWO'#GyO:XQWO'#HPO:XQWO'#HRO`QYO'#HTO:XQWO'#HVO:XQWO'#HYO:^QWO'#H`O:cQ$I]O'#HfO){QYO'#HhO:nQ$I]O'#HjO:yQ$I]O'#HlO5iQ$I[O'#HnO){QYO'#DWOOOS'#Ht'#HtO;UOSO,59qOOQ$IU,59q,59qO=gQbO'#ChO=qQYO'#HuO>UQWO'#IvO@TQbO'#IvO'dQYO'#IvO@[QWO,59wO@rQ&jO'#DbOAkQWO'#E]OAxQWO'#JROBTQWO'#JQOBTQWO'#JQOB]QWO,5:yOBbQWO'#JPOBiQWO'#DyO5vQ#tO'#EZOBwQWO'#EZOCSQ`O'#FROOQ$IU,5:S,5:SOC[QYO,5:SOEYQ$IfO,5:^OEvQWO,5:dOFaQ$I[O'#JOO7VQWO'#I}OFhQWO'#I}OFpQWO,5:xOFuQWO'#I}OGTQYO,5:vOITQWO'#EWOJ_QWO,5:vOKnQWO'#DlOKuQYO'#DqOLPQ&jO,5;PO){QYO,5;POOQQ'#Er'#ErOOQQ'#Et'#EtO){QYO,5;RO){QYO,5;RO){QYO,5;RO){QYO,5;RO){QYO,5;RO){QYO,5;RO){QYO,5;RO){QYO,5;RO){QYO,5;RO){QYO,5;RO){QYO,5;ROOQQ'#Ex'#ExOLXQYO,5;cOOQ$IU,5;h,5;hOOQ$IU,5;i,5;iONXQWO,5;iOOQ$IU,5;j,5;jO){QYO'#IPON^Q$I[O,5[OOQQ'#Ik'#IkOOQQ,5>],5>]OOQQ-E;p-E;pO!+VQ$IfO,5:UOOQ$IS'#Cp'#CpO!+vQ#tO,5Q,5>QO){QYO,5>QO5iQ$I[O,5>SOOQQ,5>U,5>UO!8VQWO,5>UOOQQ,5>W,5>WO!8VQWO,5>WOOQQ,5>Y,5>YO!8[Q`O,59rOOOS-E;r-E;rOOQ$IU1G/]1G/]O!8aQbO,5>aO'dQYO,5>aOOQO,5>f,5>fO!8kQYO'#HuOOQO-E;s-E;sO!8xQWO,5?bO!9QQbO,5?bO!9XQWO,5?lOOQ$IU1G/c1G/cO!9aQpO'#DTOOQO'#Ix'#IxO){QYO'#IxO!:OQpO'#IxO!:mQpO'#DcO!;OQ&jO'#DcO!=ZQYO'#DcO!=bQWO'#IwO!=jQWO,59|O!=oQWO'#EaO!=}QWO'#JSO!>VQWO,5:zO!>mQ&jO'#DcO){QYO,5?mO!>wQWO'#HzOOQO-E;x-E;xO!9XQWO,5?lOOQ$IS1G0e1G0eO!@TQ&jO'#D|OOQ$IU,5:e,5:eO){QYO,5:eOITQWO,5:eO!@[QWO,5:eO:^QWO,5:uO!,rQpO,5:uO!,zQ#tO,5:uO5vQ#tO,5:uOOQ$IU1G/n1G/nOOQ$IU1G0O1G0OOOQ$IS'#EV'#EVO){QYO,5?jO!@gQ$I[O,5?jO!@xQ$I[O,5?jO!APQWO,5?iO!AXQWO'#H|O!APQWO,5?iOOQ$IS1G0d1G0dO7VQWO,5?iOOQ$IU1G0b1G0bO!AsQ$IfO1G0bO!BdQ$IdO,5:rOOQ$IU'#Fq'#FqO!CQQ$IfO'#IqOGTQYO1G0bO!EPQ#tO'#IyO!EZQWO,5:WO!E`QbO'#IzO){QYO'#IzO!EjQWO,5:]OOQ$IU'#DT'#DTOOQ$IU1G0k1G0kO!EoQWO1G0kO!HQQ$IfO1G0mO!HXQ$IfO1G0mO!JlQ$IfO1G0mO!JsQ$IfO1G0mO!LzQ$IfO1G0mO!M_Q$IfO1G0mO#!OQ$IfO1G0mO#!VQ$IfO1G0mO#$jQ$IfO1G0mO#$qQ$IfO1G0mO#&fQ$IfO1G0mO#)`Q7^O'#ChO#+ZQ7^O1G0}O#-UQ7^O'#IuOOQ$IU1G1T1G1TO#-iQ$IfO,5>kOOQ$IS-E;}-E;}O#.YQ$IfO1G0mOOQ$IU1G0m1G0mO#0[Q$IfO1G1QO#0{QpO,5;sO#1QQpO,5;tO#1VQpO'#F[O#1kQWO'#FZOOQO'#JW'#JWOOQO'#H}'#H}O#1pQpO1G1]OOQ$IU1G1]1G1]OOOO1G1f1G1fO#2OQ7^O'#ItO#2YQWO,5;}OLXQYO,5;}OOOO-E;|-E;|OOQ$IU1G1Y1G1YOOQ$IU,5WQWO1G2iOOQQ1G2j1G2jOITQWO1G2jO#>]QWO1G2jO#>eQ&jO'#GhOOQQ1G2l1G2lO!&tQ&jO'#IYO!0OQ`O1G2oOOQQ1G2o1G2oOOQQ,5=Y,5=YO#>mQ#tO,5=[O5qQWO,5=[O#5YQWO,5=_O5_QWO,5=_O!,rQpO,5=_O!,zQ#tO,5=_O5vQ#tO,5=_O#?OQWO'#JaO#?ZQWO,5=`OOQQ1G.j1G.jO#?`Q$I[O1G.jO#?kQWO1G.jO#?pQWO1G.jO5iQ$I[O1G.jO#?xQbO,5@OO#@SQWO,5@OO#@_QYO,5=gO#@fQWO,5=gO7VQWO,5@OOOQQ1G3P1G3PO`QYO1G3POOQQ1G3V1G3VOOQQ1G3X1G3XO:XQWO1G3ZO#@kQYO1G3]O#DfQYO'#H[OOQQ1G3`1G3`O#DsQWO'#HbO:^QWO'#HdOOQQ1G3f1G3fO#D{QYO1G3fO5iQ$I[O1G3lOOQQ1G3n1G3nOOQ$IS'#Fx'#FxO5iQ$I[O1G3pO5iQ$I[O1G3rOOOS1G/^1G/^O#HyQ`O,5aO#I]QWO1G4|O#IeQWO1G5WO#ImQWO,5?dOLXQYO,5:{O7VQWO,5:{O:^QWO,59}OLXQYO,59}O!,rQpO,59}O#IrQ7^O,59}OOQO,5:{,5:{O#I|Q&jO'#HvO#JdQWO,5?cOOQ$IU1G/h1G/hO#JlQ&jO'#H{O#KQQWO,5?nOOQ$IS1G0f1G0fO!;OQ&jO,59}O#KYQbO1G5XO7VQWO,5>fOOQ$IS'#ES'#ESO#KdQ$ItO'#ETO!?{Q&jO'#D}OOQO'#Hy'#HyO#LOQ&jO,5:hOOQ$IU,5:h,5:hO#LVQ&jO'#D}O#LhQ&jO'#D}O#LoQ&jO'#EYO#LrQ&jO'#ETO#MPQ&jO'#ETO!?{Q&jO'#ETO#MdQWO1G0PO#MiQ`O1G0POOQ$IU1G0P1G0PO){QYO1G0POITQWO1G0POOQ$IU1G0a1G0aO:^QWO1G0aO!,rQpO1G0aO!,zQ#tO1G0aO#MpQ$IfO1G5UO){QYO1G5UO#NQQ$I[O1G5UO#NcQWO1G5TO7VQWO,5>hOOQO,5>h,5>hO#NkQWO,5>hOOQO-E;z-E;zO#NcQWO1G5TO#NyQ$IfO,59jO$!xQ$IfO,5m,5>mO$,iQWO,5>mOOQ$IU1G2P1G2PP$,nQWO'#IRPOQ$IU-Eo,5>oOOQO-Ep,5>pOOQO-Ex,5>xOOQO-E<[-E<[OOQ$IU7+&q7+&qO$4uQWO7+(iO5iQ$I[O7+(iO5qQWO7+(iO$4zQWO7+(iO$5PQWO7+'|OOQ$IS,5>r,5>rOOQ$IS-Et,5>tOOQO-EO,5>OOOQQ7+)Q7+)QOOQQ7+)W7+)WOOQQ7+)[7+)[OOQQ7+)^7+)^OOQO1G5O1G5OO$9eQ7^O1G0gO$9oQWO1G0gOOQO1G/i1G/iO$9zQ7^O1G/iO:^QWO1G/iOLXQYO'#DcOOQO,5>b,5>bOOQO-E;t-E;tOOQO,5>g,5>gOOQO-E;y-E;yO!,rQpO1G/iO:^QWO,5:iOOQO,5:o,5:oO){QYO,5:oO$:UQ$I[O,5:oO$:aQ$I[O,5:oO!,rQpO,5:iOOQO-E;w-E;wOOQ$IU1G0S1G0SO!?{Q&jO,5:iO$:oQ&jO,5:iO$;QQ$ItO,5:oO$;lQ&jO,5:iO!?{Q&jO,5:oOOQO,5:t,5:tO$;sQ&jO,5:oO$cOOQO-E;u-E;uO$CfQbO,5>dO){QYO,5>dOOQO-E;v-E;vO$CpQWO1G5QO$CxQ7^O1G0bO$FPQ7^O1G0mO$FWQ7^O1G0mO$HXQ7^O1G0mO$H`Q7^O1G0mO$JTQ7^O1G0mO$JhQ7^O1G0mO$LuQ7^O1G0mO$L|Q7^O1G0mO$N}Q7^O1G0mO% UQ7^O1G0mO%!yQ7^O1G0mO%#^Q$IfO<kOOOO7+'T7+'TOOOS1G/R1G/ROOQ$IU1G4X1G4XOJdQWO7+'zO%([QWO,5>lO5qQWO,5>lOOQO-EnO%)XQWO,5>nOITQWO,5>nOOQO-Ew,5>wO%,kQWO,5>wO%,pQWO,5>wOOQO-EvOOQO-EWQ7^O7+'WO%>eQ7^O7+'XO%>rQWO,5;xOOQO7+&{7+&{O%>wQ#tO<qOOQO-EsOOQO-E{AN>{OOQOAN>uAN>uO%1gQ$IfOAN>{O:^QWOAN>uO){QYOAN>{O!,rQpOAN>uO&%SQ$I[OAN>{O&%_Q7^O<^O!O&OO~Ox&RO!W&]O!X&UO!Y&UO'^$bO~O]&SOk&SO!Q&VO'g&PO!S'kP!S'vP~P@aO!O'sX!R'sX!]'sX!c'sX'p'sX~O!{'sX#W#PX!S'sX~PAYO!{&^O!O'uX!R'uX~O!R&_O!O'tX~O!O&bO~O!{#eO~PAYOS&fO!T&cO!o&eO']$`O~Oc&kO!d$XO']$`O~Ou$nO!d$mO~O!S&lO~P`Ou!{Ov!{Ox!|O!b!yO!d!zO'fQOP!faZ!faj!fa!R!fa!a!fa!j!fa#[!fa#]!fa#^!fa#_!fa#`!fa#a!fa#b!fa#c!fa#e!fa#g!fa#i!fa#j!fa'p!fa'w!fa'x!fa~O_!fa'W!fa!O!fa!c!fan!fa!T!fa%Q!fa!]!fa~PCcO!c&mO~O!]!wO!{&oO'p&nO!R'rX_'rX'W'rX~O!c'rX~PE{O!R&sO!c'qX~O!c&uO~Ox$tO!T$uO#V&vO']$`O~OPTOQTO]cOb!kOc!jOhcOjTOkcOlcOqTOsTOxRO{cO|cO}cO!TSO!_kO!dUO!gTO!hTO!iTO!jTO!kTO!n!iO#t!lO#x^O']9WO'fQO'oYO'|aO~O]#qOh$OOj#rOk#qOl#qOq$POs9kOx#xO!T#yO!_;RO!d#vO#V9tO#t$TO$_9nO$a9qO$d$UO']&zO'f#sO~O#W&|O~O]#qOh$OOj#rOk#qOl#qOq$POs$QOx#xO!T#yO!_$VO!d#vO#V$WO#t$TO$_$RO$a$SO$d$UO']&zO'f#sO~O'a'mP~PJdO!Q'QO!c'nP~P){O'g'SO'oYO~OP9TOQ9TO]cOb;POc!jOhcOj9TOkcOlcOq9TOs9TOxRO{cO|cO}cO!T!bO!_9VO!dUO!g9TO!h9TO!i9TO!j9TO!k9TO!n!iO#t!lO#x^O']'bO'fQO'oYO'|:}O~O!d!zO~O!R#bO_$]a'W$]a!c$]a!O$]a!T$]a%Q$]a!]$]a~O#d'iO~PITO!]'kO!T'yX#w'yX#z'yX$R'yX~Ou'lO~P! POu'lO!T'yX#w'yX#z'yX$R'yX~O!T'nO#w'rO#z'mO$R'sO~O!Q'vO~PLXO#z#fO$R'yO~Ou$eXx$eX!b$eX'p$eX'w$eX'x$eX~OSfX!RfX!{fX'afX'a$eX~P!!iOk'{O~OR'|O'U'}O'V(PO~Ou(ROx(SO'p#[O'w(UO'x(WO~O'a(QO~P!#rO'a(ZO~O]#qOh$OOj#rOk#qOl#qOq$POs9kOx#xO!T#yO!_;RO!d#vO#V9tO#t$TO$_9nO$a9qO$d$UO'f#sO~O!Q(_O']([O!c'}P~P!$aO#W(aO~O!Q(eO'](bO!O(OP~P!$aOj(sOx(kO!W(qO!X(jO!Y(jO!d(hO!x(rO$w(mO'^$bO'g(gO~O!S(pO~P!&XO!b!yOu'eXx'eX'p'eX'w'eX'x'eX!R'eX!{'eX~O'a'eX#m'eX~P!'QOS(vO!{(uO!R'dX'a'dX~O!R(wO'a'cX~O'](yO~O!d)OO~O']&zO~O!d(hO~Ox$tO!Q!rO!T$uO#U!uO#V!rO']$`O!c'qP~O!]!wO#W)SO~OP#^OZ#dOj#ROu!{Ov!{Ox!|O!a#TO!b!yO!d!zO!j#^O#[#PO#]#QO#^#QO#_#QO#`#SO#a#TO#b#TO#c#TO#e#UO#g#WO#i#YO#j#ZO'fQO'p#[O'w!}O'x#OO~O_!^a!R!^a'W!^a!O!^a!c!^an!^a!T!^a%Q!^a!]!^a~P!)cOS)[O!T&cO!o)ZO%Q)YO'b$cO~O']$zO'a'cP~O!])_O!T'`X_'`X!R'`X'W'`X~O!d$XO'b$cO~O!d$XO']$`O'b$cO~O!]!wO#W&|O~O])jO%R)kO'])gO!S(VP~O!R)lO^(UX~O'g'SO~OZ)pO~O^)qO~O!T$kO']$`O'^$bO^(UP~Ox$tO!Q)vO!R&_O!T$uO']$`O!O'tP~O]&YOk&YO!Q)wO'g'SO!S'vP~O!R)xO_(RX'W(RX~O!{)|O'b$cO~OS*PO!T#yO'b$cO~O!T*RO~Ou*TO!TSO~O!n*YO~Oc*_O~O'](yO!S(TP~Oc$iO~O%RtO']$zO~P8tOZ*eO^*dO~OPTOQTO]cObnOcmOhcOjTOkcOlcOqTOsTOxRO{cO|cO}cO!_kO!dUO!gTO!hTO!iTO!jTO!kTO!nlO#x^O%PqO'fQO'oYO'|aO~O!T!bO#t!lO']9WO~P!1RO^*dO_$[O'W$[O~O_*iO#d*kO%T*kO%U*kO~P){O!d%_O~O%t*pO~O!T*rO~O&V*tO&X*uOP&SaQ&SaX&Sa]&Sa_&Sab&Sac&Sah&Saj&Sak&Sal&Saq&Sas&Sax&Sa{&Sa|&Sa}&Sa!T&Sa!_&Sa!d&Sa!g&Sa!h&Sa!i&Sa!j&Sa!k&Sa!n&Sa#d&Sa#t&Sa#x&Sa%P&Sa%R&Sa%T&Sa%U&Sa%X&Sa%Z&Sa%^&Sa%_&Sa%a&Sa%n&Sa%t&Sa%v&Sa%x&Sa%z&Sa%}&Sa&T&Sa&Z&Sa&]&Sa&_&Sa&a&Sa&c&Sa'S&Sa']&Sa'f&Sa'o&Sa'|&Sa!S&Sa%{&Sa`&Sa&Q&Sa~O']*zO~On*}O~O!O&ia!R&ia~P!)cO!Q+RO!O&iX!R&iX~P){O!R%yO!O'ja~O!O'ja~P>^O!R&_O!O'ta~O!RwX!R!ZX!SwX!S!ZX!]wX!]!ZX!d!ZX!{wX'b!ZX~O!]+WO!{+VO!R#TX!R'lX!S#TX!S'lX!]'lX!d'lX'b'lX~O!]+YO!d$XO'b$cO!R!VX!S!VX~O]&QOk&QOx&RO'g(gO~OP9TOQ9TO]cOb;POc!jOhcOj9TOkcOlcOq9TOs9TOxRO{cO|cO}cO!T!bO!_9VO!dUO!g9TO!h9TO!i9TO!j9TO!k9TO!n!iO#t!lO#x^O'fQO'oYO'|:}O~O']9yO~P!;^O!R+^O!S'kX~O!S+`O~O!]+WO!{+VO!R#TX!S#TX~O!R+aO!S'vX~O!S+cO~O]&QOk&QOx&RO'^$bO'g(gO~O!X+dO!Y+dO~P!>[Ox$tO!Q+fO!T$uO']$`O!O&nX!R&nX~O_+jO!W+mO!X+iO!Y+iO!r+qO!s+oO!t+pO!u+nO!x+rO'^$bO'g(gO'o+gO~O!S+lO~P!?]OS+wO!T&cO!o+vO~O!{+}O!R'ra!c'ra_'ra'W'ra~O!]!wO~P!@gO!R&sO!c'qa~Ox$tO!Q,QO!T$uO#U,SO#V,QO']$`O!R&pX!c&pX~O_#Oi!R#Oi'W#Oi!O#Oi!c#Oin#Oi!T#Oi%Q#Oi!]#Oi~P!)cO#W!za!R!za!c!za!{!za!T!za_!za'W!za!O!za~P!#rO#W'eXP'eXZ'eX_'eXj'eXv'eX!a'eX!d'eX!j'eX#['eX#]'eX#^'eX#_'eX#`'eX#a'eX#b'eX#c'eX#e'eX#g'eX#i'eX#j'eX'W'eX'f'eX!c'eX!O'eX!T'eXn'eX%Q'eX!]'eX~P!'QO!R,]O'a'mX~P!#rO'a,_O~O!R,`O!c'nX~P!)cO!c,cO~O!O,dO~OP#^Ou!{Ov!{Ox!|O!b!yO!d!zO!j#^O'fQOZ#Zi_#Zij#Zi!R#Zi!a#Zi#]#Zi#^#Zi#_#Zi#`#Zi#a#Zi#b#Zi#c#Zi#e#Zi#g#Zi#i#Zi#j#Zi'W#Zi'p#Zi'w#Zi'x#Zi!O#Zi!c#Zin#Zi!T#Zi%Q#Zi!]#Zi~O#[#Zi~P!EtO#[#PO~P!EtOP#^Ou!{Ov!{Ox!|O!b!yO!d!zO!j#^O#[#PO#]#QO#^#QO#_#QO'fQOZ#Zi_#Zi!R#Zi!a#Zi#`#Zi#a#Zi#b#Zi#c#Zi#e#Zi#g#Zi#i#Zi#j#Zi'W#Zi'p#Zi'w#Zi'x#Zi!O#Zi!c#Zin#Zi!T#Zi%Q#Zi!]#Zi~Oj#Zi~P!H`Oj#RO~P!H`OP#^Oj#ROu!{Ov!{Ox!|O!b!yO!d!zO!j#^O#[#PO#]#QO#^#QO#_#QO#`#SO'fQO_#Zi!R#Zi#e#Zi#g#Zi#i#Zi#j#Zi'W#Zi'p#Zi'w#Zi'x#Zi!O#Zi!c#Zin#Zi!T#Zi%Q#Zi!]#Zi~OZ#Zi!a#Zi#a#Zi#b#Zi#c#Zi~P!JzOZ#dO!a#TO#a#TO#b#TO#c#TO~P!JzOP#^OZ#dOj#ROu!{Ov!{Ox!|O!a#TO!b!yO!d!zO!j#^O#[#PO#]#QO#^#QO#_#QO#`#SO#a#TO#b#TO#c#TO#e#UO'fQO_#Zi!R#Zi#g#Zi#i#Zi#j#Zi'W#Zi'p#Zi'x#Zi!O#Zi!c#Zin#Zi!T#Zi%Q#Zi!]#Zi~O'w#Zi~P!MrO'w!}O~P!MrOP#^OZ#dOj#ROu!{Ov!{Ox!|O!a#TO!b!yO!d!zO!j#^O#[#PO#]#QO#^#QO#_#QO#`#SO#a#TO#b#TO#c#TO#e#UO#g#WO'fQO'w!}O_#Zi!R#Zi#i#Zi#j#Zi'W#Zi'p#Zi!O#Zi!c#Zin#Zi!T#Zi%Q#Zi!]#Zi~O'x#Zi~P#!^O'x#OO~P#!^OP#^OZ#dOj#ROu!{Ov!{Ox!|O!a#TO!b!yO!d!zO!j#^O#[#PO#]#QO#^#QO#_#QO#`#SO#a#TO#b#TO#c#TO#e#UO#g#WO#i#YO'fQO'w!}O'x#OO~O_#Zi!R#Zi#j#Zi'W#Zi'p#Zi!O#Zi!c#Zin#Zi!T#Zi%Q#Zi!]#Zi~P#$xOP[XZ[Xj[Xu[Xv[Xx[X!a[X!b[X!d[X!j[X!{[X#WdX#[[X#][X#^[X#_[X#`[X#a[X#b[X#c[X#e[X#g[X#i[X#j[X#o[X'f[X'p[X'w[X'x[X!R[X!S[X~O#m[X~P#']OP#^OZ9iOj9^Ou!{Ov!{Ox!|O!a9`O!b!yO!d!zO!j#^O#[9[O#]9]O#^9]O#_9]O#`9_O#a9`O#b9`O#c9`O#e9aO#g9cO#i9eO#j9fO'fQO'p#[O'w!}O'x#OO~O#m,fO~P#)gOP'iXZ'iXj'iXu'iXv'iXx'iX!a'iX!b'iX!d'iX!j'iX#['iX#]'iX#^'iX#_'iX#`'iX#a'iX#b'iX#e'iX#g'iX#i'iX#j'iX'f'iX'p'iX'w'iX'x'iX!R'iX~O!{9jO#o9jO#c'iX#m'iX!S'iX~P#+bO_&sa!R&sa'W&sa!c&san&sa!O&sa!T&sa%Q&sa!]&sa~P!)cOP#ZiZ#Zi_#Zij#Ziv#Zi!R#Zi!a#Zi!b#Zi!d#Zi!j#Zi#[#Zi#]#Zi#^#Zi#_#Zi#`#Zi#a#Zi#b#Zi#c#Zi#e#Zi#g#Zi#i#Zi#j#Zi'W#Zi'f#Zi!O#Zi!c#Zin#Zi!T#Zi%Q#Zi!]#Zi~P!#rO_#ni!R#ni'W#ni!O#ni!c#nin#ni!T#ni%Q#ni!]#ni~P!)cO#z,hO~O#z,iO~O!]'kO!{,jO!T$OX#w$OX#z$OX$R$OX~O!Q,kO~O!T'nO#w,mO#z'mO$R,nO~O!R9gO!S'hX~P#)gO!S,oO~O$R,qO~OR'|O'U'}O'V,tO~O],wOk,wO!O,xO~O!RdX!]dX!cdX!c$eX'pdX~P!!iO!c-OO~P!#rO!R-PO!]!wO'p&nO!c'}X~O!c-UO~O!O$eX!R$eX!]$lX~P!!iO!R-WO!O(OX~P!#rO!]-YO~O!O-[O~O!Q(_O']$`O!c'}P~Oj-`O!]!wO!d$XO'b$cO'p&nO~O!])_O~O_$[O!R-eO'W$[O~O!S-gO~P!&XO!X-hO!Y-hO'^$bO'g(gO~Ox-jO'g(gO~O!x-kO~O']$zO!R&xX'a&xX~O!R(wO'a'ca~Ou-pOv-pOx-qO'pra'wra'xra!Rra!{ra~O'ara#mra~P#6qOu(ROx(SO'p$^a'w$^a'x$^a!R$^a!{$^a~O'a$^a#m$^a~P#7gOu(ROx(SO'p$`a'w$`a'x$`a!R$`a!{$`a~O'a$`a#m$`a~P#8YO]-rO~O#W-sO~O'a$na!R$na#m$na!{$na~P!#rO#W-vO~OS.PO!T&cO!o.OO%Q-}O~O'a.QO~O]#qOj#rOk#qOl#qOq$POs9kOx#xO!T#yO!_;RO!d#vO#V9tO#t$TO$_9nO$a9qO$d$UO'f#sO~Oh.SO'].RO~P#:PO!])_O!T'`a_'`a!R'`a'W'`a~O#W.YO~OZ[X!RdX!SdX~O!R.ZO!S(VX~O!S.]O~OZ.^O~O].`O'])gO~O!T$kO']$`O^'QX!R'QX~O!R)lO^(Ua~O!c.cO~P!)cO].eO~OZ.fO~O^.gO~OS.PO!T&cO!o.OO%Q-}O'b$cO~O!R)xO_(Ra'W(Ra~O!{.mO~OS.pO!T#yO~O'g'SO!S(SP~OS.zO!T.vO!o.yO%Q.xO'b$cO~OZ/UO!R/SO!S(TX~O!S/VO~O^/XO_$[O'W$[O~O]/YO~O]/ZO'](yO~O#c/[O%r/]O~P0zO!{#eO#c/[O%r/]O~O_/^O~P){O_/`O~O%{/dOP%yiQ%yiX%yi]%yi_%yib%yic%yih%yij%yik%yil%yiq%yis%yix%yi{%yi|%yi}%yi!T%yi!_%yi!d%yi!g%yi!h%yi!i%yi!j%yi!k%yi!n%yi#d%yi#t%yi#x%yi%P%yi%R%yi%T%yi%U%yi%X%yi%Z%yi%^%yi%_%yi%a%yi%n%yi%t%yi%v%yi%x%yi%z%yi%}%yi&T%yi&Z%yi&]%yi&_%yi&a%yi&c%yi'S%yi']%yi'f%yi'o%yi'|%yi!S%yi`%yi&Q%yi~O`/jO!S/hO&Q/iO~P`O!TSO!d/lO~O&X*uOP&SiQ&SiX&Si]&Si_&Sib&Sic&Sih&Sij&Sik&Sil&Siq&Sis&Six&Si{&Si|&Si}&Si!T&Si!_&Si!d&Si!g&Si!h&Si!i&Si!j&Si!k&Si!n&Si#d&Si#t&Si#x&Si%P&Si%R&Si%T&Si%U&Si%X&Si%Z&Si%^&Si%_&Si%a&Si%n&Si%t&Si%v&Si%x&Si%z&Si%}&Si&T&Si&Z&Si&]&Si&_&Si&a&Si&c&Si'S&Si']&Si'f&Si'o&Si'|&Si!S&Si%{&Si`&Si&Q&Si~O!R#bOn$]a~O!O&ii!R&ii~P!)cO!R%yO!O'ji~O!R&_O!O'ti~O!O/rO~O!R!Va!S!Va~P#)gO]&QOk&QO!Q/xO'g(gO!R&jX!S&jX~P@aO!R+^O!S'ka~O]&YOk&YO!Q)wO'g'SO!R&oX!S&oX~O!R+aO!S'va~O!O'ui!R'ui~P!)cO_$[O!]!wO!d$XO!j0SO!{0QO'W$[O'b$cO'p&nO~O!S0VO~P!?]O!X0WO!Y0WO'^$bO'g(gO'o+gO~O!W0XO~P#LVO!TSO!W0XO!u0ZO!x0[O~P#LVO!W0XO!s0^O!t0^O!u0ZO!x0[O~P#LVO!T&cO~O!T&cO~P!#rO!R'ri!c'ri_'ri'W'ri~P!)cO!{0gO!R'ri!c'ri_'ri'W'ri~O!R&sO!c'qi~Ox$tO!T$uO#V0iO']$`O~O#WraPraZra_rajra!ara!bra!dra!jra#[ra#]ra#^ra#_ra#`ra#ara#bra#cra#era#gra#ira#jra'Wra'fra!cra!Ora!Tranra%Qra!]ra~P#6qO#W$^aP$^aZ$^a_$^aj$^av$^a!a$^a!b$^a!d$^a!j$^a#[$^a#]$^a#^$^a#_$^a#`$^a#a$^a#b$^a#c$^a#e$^a#g$^a#i$^a#j$^a'W$^a'f$^a!c$^a!O$^a!T$^an$^a%Q$^a!]$^a~P#7gO#W$`aP$`aZ$`a_$`aj$`av$`a!a$`a!b$`a!d$`a!j$`a#[$`a#]$`a#^$`a#_$`a#`$`a#a$`a#b$`a#c$`a#e$`a#g$`a#i$`a#j$`a'W$`a'f$`a!c$`a!O$`a!T$`an$`a%Q$`a!]$`a~P#8YO#W$naP$naZ$na_$naj$nav$na!R$na!a$na!b$na!d$na!j$na#[$na#]$na#^$na#_$na#`$na#a$na#b$na#c$na#e$na#g$na#i$na#j$na'W$na'f$na!c$na!O$na!T$na!{$nan$na%Q$na!]$na~P!#rO_#Oq!R#Oq'W#Oq!O#Oq!c#Oqn#Oq!T#Oq%Q#Oq!]#Oq~P!)cO!R&kX'a&kX~PJdO!R,]O'a'ma~O!Q0qO!R&lX!c&lX~P){O!R,`O!c'na~O!R,`O!c'na~P!)cO#m!fa!S!fa~PCcO#m!^a!R!^a!S!^a~P#)gO!T1UO#x^O$P1VO~O!S1ZO~On1[O~P!#rO_$Yq!R$Yq'W$Yq!O$Yq!c$Yqn$Yq!T$Yq%Q$Yq!]$Yq~P!)cO!O1]O~O],wOk,wO~Ou(ROx(SO'x(WO'p$xi'w$xi!R$xi!{$xi~O'a$xi#m$xi~P$,vOu(ROx(SO'p$zi'w$zi'x$zi!R$zi!{$zi~O'a$zi#m$zi~P$-iO#m1^O~P!#rO!Q1`O']$`O!R&tX!c&tX~O!R-PO!c'}a~O!R-PO!]!wO!c'}a~O!R-PO!]!wO'p&nO!c'}a~O'a$gi!R$gi#m$gi!{$gi~P!#rO!Q1gO'](bO!O&vX!R&vX~P!$aO!R-WO!O(Oa~O!R-WO!O(Oa~P!#rO!]!wO~O!]!wO#c1oO~Oj1rO!]!wO'p&nO~O!R'di'a'di~P!#rO!{1uO!R'di'a'di~P!#rO!c1xO~O_$Zq!R$Zq'W$Zq!O$Zq!c$Zqn$Zq!T$Zq%Q$Zq!]$Zq~P!)cO!R1|O!T(PX~P!#rO!T&cO%Q2PO~O!T&cO%Q2PO~P!#rO!T$eX$u[X_$eX!R$eX'W$eX~P!!iO$u2TOugXxgX!TgX'pgX'wgX'xgX_gX!RgX'WgX~O$u2TO~O]2ZO%R2[O'])gO!R'PX!S'PX~O!R.ZO!S(Va~OZ2`O~O^2aO~O]2dO~OS2fO!T&cO!o2eO%Q2PO~O_$[O'W$[O~P!#rO!T#yO~P!#rO!R2kO!{2mO!S(SX~O!S2nO~Ox;]O!W2wO!X2pO!Y2pO!r2vO!s2uO!t2uO!x2tO'^$bO'g(gO'o+gO~O!S2sO~P$6QOS3OO!T.vO!o2}O%Q2|O~OS3OO!T.vO!o2}O%Q2|O'b$cO~O'](yO!R'OX!S'OX~O!R/SO!S(Ta~O]3YO'g3XO~O]3ZO~O^3]O~O!c3`O~P){O_3bO~O_3bO~P){O#c3dO%r3eO~PE{O`/jO!S3iO&Q/iO~P`O!]3kO~O!R#Ti!S#Ti~P#)gO!{3mO!R#Ti!S#Ti~O!R!Vi!S!Vi~P#)gO_$[O!{3tO'W$[O~O_$[O!]!wO!{3tO'W$[O~O!X3xO!Y3xO'^$bO'g(gO'o+gO~O_$[O!]!wO!d$XO!j3yO!{3tO'W$[O'b$cO'p&nO~O!W3zO~P$:oO!W3zO!u3}O!x4OO~P$:oO_$[O!]!wO!j3yO!{3tO'W$[O'p&nO~O!R'rq!c'rq_'rq'W'rq~P!)cO!R&sO!c'qq~O#W$xiP$xiZ$xi_$xij$xiv$xi!a$xi!b$xi!d$xi!j$xi#[$xi#]$xi#^$xi#_$xi#`$xi#a$xi#b$xi#c$xi#e$xi#g$xi#i$xi#j$xi'W$xi'f$xi!c$xi!O$xi!T$xin$xi%Q$xi!]$xi~P$,vO#W$ziP$ziZ$zi_$zij$ziv$zi!a$zi!b$zi!d$zi!j$zi#[$zi#]$zi#^$zi#_$zi#`$zi#a$zi#b$zi#c$zi#e$zi#g$zi#i$zi#j$zi'W$zi'f$zi!c$zi!O$zi!T$zin$zi%Q$zi!]$zi~P$-iO#W$giP$giZ$gi_$gij$giv$gi!R$gi!a$gi!b$gi!d$gi!j$gi#[$gi#]$gi#^$gi#_$gi#`$gi#a$gi#b$gi#c$gi#e$gi#g$gi#i$gi#j$gi'W$gi'f$gi!c$gi!O$gi!T$gi!{$gin$gi%Q$gi!]$gi~P!#rO!R&ka'a&ka~P!#rO!R&la!c&la~P!)cO!R,`O!c'ni~O#m#Oi!R#Oi!S#Oi~P#)gOP#^Ou!{Ov!{Ox!|O!b!yO!d!zO!j#^O'fQOZ#Zij#Zi!a#Zi#]#Zi#^#Zi#_#Zi#`#Zi#a#Zi#b#Zi#c#Zi#e#Zi#g#Zi#i#Zi#j#Zi#m#Zi'p#Zi'w#Zi'x#Zi!R#Zi!S#Zi~O#[#Zi~P$DVO#[9[O~P$DVOP#^Ou!{Ov!{Ox!|O!b!yO!d!zO!j#^O#[9[O#]9]O#^9]O#_9]O'fQOZ#Zi!a#Zi#`#Zi#a#Zi#b#Zi#c#Zi#e#Zi#g#Zi#i#Zi#j#Zi#m#Zi'p#Zi'w#Zi'x#Zi!R#Zi!S#Zi~Oj#Zi~P$F_Oj9^O~P$F_OP#^Oj9^Ou!{Ov!{Ox!|O!b!yO!d!zO!j#^O#[9[O#]9]O#^9]O#_9]O#`9_O'fQO#e#Zi#g#Zi#i#Zi#j#Zi#m#Zi'p#Zi'w#Zi'x#Zi!R#Zi!S#Zi~OZ#Zi!a#Zi#a#Zi#b#Zi#c#Zi~P$HgOZ9iO!a9`O#a9`O#b9`O#c9`O~P$HgOP#^OZ9iOj9^Ou!{Ov!{Ox!|O!a9`O!b!yO!d!zO!j#^O#[9[O#]9]O#^9]O#_9]O#`9_O#a9`O#b9`O#c9`O#e9aO'fQO#g#Zi#i#Zi#j#Zi#m#Zi'p#Zi'x#Zi!R#Zi!S#Zi~O'w#Zi~P$J{O'w!}O~P$J{OP#^OZ9iOj9^Ou!{Ov!{Ox!|O!a9`O!b!yO!d!zO!j#^O#[9[O#]9]O#^9]O#_9]O#`9_O#a9`O#b9`O#c9`O#e9aO#g9cO'fQO'w!}O#i#Zi#j#Zi#m#Zi'p#Zi!R#Zi!S#Zi~O'x#Zi~P$MTO'x#OO~P$MTOP#^OZ9iOj9^Ou!{Ov!{Ox!|O!a9`O!b!yO!d!zO!j#^O#[9[O#]9]O#^9]O#_9]O#`9_O#a9`O#b9`O#c9`O#e9aO#g9cO#i9eO'fQO'w!}O'x#OO~O#j#Zi#m#Zi'p#Zi!R#Zi!S#Zi~P% ]O_#ky!R#ky'W#ky!O#ky!c#kyn#ky!T#ky%Q#ky!]#ky~P!)cOP#ZiZ#Zij#Ziv#Zi!a#Zi!b#Zi!d#Zi!j#Zi#[#Zi#]#Zi#^#Zi#_#Zi#`#Zi#a#Zi#b#Zi#c#Zi#e#Zi#g#Zi#i#Zi#j#Zi#m#Zi'f#Zi!R#Zi!S#Zi~P!#rO!b!yOu'eXx'eX'p'eX'w'eX'x'eX!S'eX~OP'eXZ'eXj'eXv'eX!a'eX!d'eX!j'eX#['eX#]'eX#^'eX#_'eX#`'eX#a'eX#b'eX#c'eX#e'eX#g'eX#i'eX#j'eX#m'eX'f'eX!R'eX~P%%mO#m#ni!R#ni!S#ni~P#)gO!S4`O~O!R&sa!S&sa~P#)gO!]!wO'p&nO!R&ta!c&ta~O!R-PO!c'}i~O!R-PO!]!wO!c'}i~O!O&va!R&va~P!#rO!]4gO~O!R-WO!O(Oi~P!#rO!R-WO!O(Oi~O!O4kO~O!]!wO#c4pO~Oj4qO!]!wO'p&nO~O!O4sO~O'a$iq!R$iq#m$iq!{$iq~P!#rO_$Zy!R$Zy'W$Zy!O$Zy!c$Zyn$Zy!T$Zy%Q$Zy!]$Zy~P!)cO!R1|O!T(Pa~O!T&cO%Q4xO~O!T&cO%Q4xO~P!#rO_#Oy!R#Oy'W#Oy!O#Oy!c#Oyn#Oy!T#Oy%Q#Oy!]#Oy~P!)cOZ4{O~O]4}O'])gO~O!R.ZO!S(Vi~O]5QO~O^5RO~O'g'SO!R&{X!S&{X~O!R2kO!S(Sa~O!S5`O~P$6QOx;^O'g(gO'o+gO~O!W5cO!X5bO!Y5bO!x0[O'^$bO'g(gO'o+gO~O!s5dO!t5dO~P%.RO!X5bO!Y5bO'^$bO'g(gO'o+gO~O!T.vO~O!T.vO%Q5fO~O!T.vO%Q5fO~P!#rOS5kO!T.vO!o5jO%Q5fO~OZ5pO!R'Oa!S'Oa~O!R/SO!S(Ti~O]5sO~O!c5tO~O!c5uO~O!c5vO~O!c5vO~P){O_5xO~O!]5{O~O!c5|O~O!R'ui!S'ui~P#)gO_$[O'W$[O~P!)cO_$[O!{6RO'W$[O~O_$[O!]!wO!{6RO'W$[O~O!X6WO!Y6WO'^$bO'g(gO'o+gO~O_$[O!]!wO!j6XO!{6RO'W$[O'p&nO~O!d$XO'b$cO~P%2mO!W6YO~P%2[O!R'ry!c'ry_'ry'W'ry~P!)cO#W$iqP$iqZ$iq_$iqj$iqv$iq!R$iq!a$iq!b$iq!d$iq!j$iq#[$iq#]$iq#^$iq#_$iq#`$iq#a$iq#b$iq#c$iq#e$iq#g$iq#i$iq#j$iq'W$iq'f$iq!c$iq!O$iq!T$iq!{$iqn$iq%Q$iq!]$iq~P!#rO!R&li!c&li~P!)cO#m#Oq!R#Oq!S#Oq~P#)gOu-pOv-pOx-qO'pra'wra'xra!Sra~OPraZrajra!ara!bra!dra!jra#[ra#]ra#^ra#_ra#`ra#ara#bra#cra#era#gra#ira#jra#mra'fra!Rra~P%6eOu(ROx(SO'p$^a'w$^a'x$^a!S$^a~OP$^aZ$^aj$^av$^a!a$^a!b$^a!d$^a!j$^a#[$^a#]$^a#^$^a#_$^a#`$^a#a$^a#b$^a#c$^a#e$^a#g$^a#i$^a#j$^a#m$^a'f$^a!R$^a~P%8fOu(ROx(SO'p$`a'w$`a'x$`a!S$`a~OP$`aZ$`aj$`av$`a!a$`a!b$`a!d$`a!j$`a#[$`a#]$`a#^$`a#_$`a#`$`a#a$`a#b$`a#c$`a#e$`a#g$`a#i$`a#j$`a#m$`a'f$`a!R$`a~P%:gOP$naZ$naj$nav$na!a$na!b$na!d$na!j$na#[$na#]$na#^$na#_$na#`$na#a$na#b$na#c$na#e$na#g$na#i$na#j$na#m$na'f$na!R$na!S$na~P!#rO#m$Yq!R$Yq!S$Yq~P#)gO#m$Zq!R$Zq!S$Zq~P#)gO!S6dO~O'a$|y!R$|y#m$|y!{$|y~P!#rO!]!wO!R&ti!c&ti~O!]!wO'p&nO!R&ti!c&ti~O!R-PO!c'}q~O!O&vi!R&vi~P!#rO!R-WO!O(Oq~O!O6jO~P!#rO!O6jO~O!R'dy'a'dy~P!#rO!R&ya!T&ya~P!#rO!T$tq_$tq!R$tq'W$tq~P!#rOZ6qO~O!R.ZO!S(Vq~O]6tO~O!T&cO%Q6uO~O!T&cO%Q6uO~P!#rO!{6vO!R&{a!S&{a~O!R2kO!S(Si~P#)gO!X6|O!Y6|O'^$bO'g(gO'o+gO~O!W7OO!x4OO~P%BkO!T.vO%Q7RO~O!T.vO%Q7RO~P!#rO]7YO'g7XO~O!R/SO!S(Tq~O!c7[O~O!c7[O~P){O!c7^O~O!c7_O~O!R#Ty!S#Ty~P#)gO_$[O!{7eO'W$[O~O_$[O!]!wO!{7eO'W$[O~O!X7hO!Y7hO'^$bO'g(gO'o+gO~O_$[O!]!wO!j7iO!{7eO'W$[O'p&nO~O#W$|yP$|yZ$|y_$|yj$|yv$|y!R$|y!a$|y!b$|y!d$|y!j$|y#[$|y#]$|y#^$|y#_$|y#`$|y#a$|y#b$|y#c$|y#e$|y#g$|y#i$|y#j$|y'W$|y'f$|y!c$|y!O$|y!T$|y!{$|yn$|y%Q$|y!]$|y~P!#rO#m#ky!R#ky!S#ky~P#)gOP$giZ$gij$giv$gi!a$gi!b$gi!d$gi!j$gi#[$gi#]$gi#^$gi#_$gi#`$gi#a$gi#b$gi#c$gi#e$gi#g$gi#i$gi#j$gi#m$gi'f$gi!R$gi!S$gi~P!#rOu(ROx(SO'x(WO'p$xi'w$xi!S$xi~OP$xiZ$xij$xiv$xi!a$xi!b$xi!d$xi!j$xi#[$xi#]$xi#^$xi#_$xi#`$xi#a$xi#b$xi#c$xi#e$xi#g$xi#i$xi#j$xi#m$xi'f$xi!R$xi~P%JROu(ROx(SO'p$zi'w$zi'x$zi!S$zi~OP$ziZ$zij$ziv$zi!a$zi!b$zi!d$zi!j$zi#[$zi#]$zi#^$zi#_$zi#`$zi#a$zi#b$zi#c$zi#e$zi#g$zi#i$zi#j$zi#m$zi'f$zi!R$zi~P%LSO#m$Zy!R$Zy!S$Zy~P#)gO#m#Oy!R#Oy!S#Oy~P#)gO!]!wO!R&tq!c&tq~O!R-PO!c'}y~O!O&vq!R&vq~P!#rO!O7mO~P!#rO!R.ZO!S(Vy~O!R2kO!S(Sq~O!X7yO!Y7yO'^$bO'g(gO'o+gO~O!T.vO%Q7|O~O!T.vO%Q7|O~P!#rO!c8PO~O_$[O!{8UO'W$[O~O_$[O!]!wO!{8UO'W$[O~OP$iqZ$iqj$iqv$iq!a$iq!b$iq!d$iq!j$iq#[$iq#]$iq#^$iq#_$iq#`$iq#a$iq#b$iq#c$iq#e$iq#g$iq#i$iq#j$iq#m$iq'f$iq!R$iq!S$iq~P!#rO!R&{q!S&{q~P#)gO_$[O!{8hO'W$[O~OP$|yZ$|yj$|yv$|y!a$|y!b$|y!d$|y!j$|y#[$|y#]$|y#^$|y#_$|y#`$|y#a$|y#b$|y#c$|y#e$|y#g$|y#i$|y#j$|y#m$|y'f$|y!R$|y!S$|y~P!#rO!S!za!W!za!X!za!Y!za!r!za!s!za!t!za!x!za'^!za'g!za'o!za~P!#rO!W'eX!X'eX!Y'eX!r'eX!s'eX!t'eX!x'eX'^'eX'g'eX'o'eX~P%%mO!Wra!Xra!Yra!rra!sra!tra!xra'^ra'gra'ora~P%6eO!W$^a!X$^a!Y$^a!r$^a!s$^a!t$^a!x$^a'^$^a'g$^a'o$^a~P%8fO!W$`a!X$`a!Y$`a!r$`a!s$`a!t$`a!x$`a'^$`a'g$`a'o$`a~P%:gO!S$na!W$na!X$na!Y$na!r$na!s$na!t$na!x$na'^$na'g$na'o$na~P!#rO!W$xi!X$xi!Y$xi!r$xi!s$xi!t$xi!x$xi'^$xi'g$xi'o$xi~P%JRO!W$zi!X$zi!Y$zi!r$zi!s$zi!t$zi!x$zi'^$zi'g$zi'o$zi~P%LSO!S$gi!W$gi!X$gi!Y$gi!r$gi!s$gi!t$gi!x$gi'^$gi'g$gi'o$gi~P!#rO!S$iq!W$iq!X$iq!Y$iq!r$iq!s$iq!t$iq!x$iq'^$iq'g$iq'o$iq~P!#rO!S$|y!W$|y!X$|y!Y$|y!r$|y!s$|y!t$|y!x$|y'^$|y'g$|y'o$|y~P!#rOn'hX~P.jOn[X!O[X!c[X%r[X!T[X%Q[X!][X~P$zO!]dX!c[X!cdX'pdX~P;aOP9TOQ9TO]cOb;POc!jOhcOj9TOkcOlcOq9TOs9TOxRO{cO|cO}cO!TSO!_9VO!dUO!g9TO!h9TO!i9TO!j9TO!k9TO!n!iO#t!lO#x^O']'bO'fQO'oYO'|:}O~O]#qOh$OOj#rOk#qOl#qOq$POs9lOx#xO!T#yO!_;SO!d#vO#V9uO#t$TO$_9oO$a9rO$d$UO']&zO'f#sO~O!R9gO!S$]a~O]#qOh$OOj#rOk#qOl#qOq$POs9mOx#xO!T#yO!_;TO!d#vO#V9vO#t$TO$_9pO$a9sO$d$UO']&zO'f#sO~O#d'iO~P&3xO!S[X!SdX~P;aO!]9ZO~O#W9YO~O!]!wO#W9YO~O!{9jO~O#c9`O~O!{9wO!R'uX!S'uX~O!{9jO!R'sX!S'sX~O#W9xO~O'a9zO~P!#rO#W:RO~O#W:SO~O#W:TO~O!]!wO#W:UO~O!]!wO#W9xO~O#m:VO~P#)gO#W:WO~O#W:XO~O#W:YO~O#W:ZO~O#W:[O~O#m:]O~P!#rO#m:^O~P!#rO#m:_O~P!#rO!O:`O~O!O:aO~P!#rO!O:aO~O!O:bO~P!#rO!]!wO#c;YO~O!]!wO#c;[O~O#x~!b!r!t!u#U#V'|$_$a$d$u%P%Q%R%X%Z%^%_%a%c~UT#x'|#]}'Y'Z#z'Y']'g~", - goto: "#Hc(ZPPPPPPPP([P(lP*`PPPP-zPP.a3s5g5zP5zPPP5zP7t5zP5zP7xPP8OP8dk|}?O}!O>k!O!P?`!P!QCl!Q!R!0[!R![!1q![!]!7s!]!^!8V!^!_!8g!_!`!9d!`!a!:[!a!b!U#R#S2`#S#T!>i#T#o2`#o#p!>y#p#q!?O#q#r!?f#r#s!?x#s$f%T$f$g%c$g#BY2`#BY#BZ!@Y#BZ$IS2`$IS$I_!@Y$I_$I|2`$I|$I}!Bq$I}$JO!Bq$JO$JT2`$JT$JU!@Y$JU$KV2`$KV$KW!@Y$KW&FU2`&FU&FV!@Y&FV?HT2`?HT?HU!@Y?HU~2`W%YR$UWO!^%T!_#o%T#p~%T7Z%jg$UW'Y7ROX%TXY%cYZ%TZ[%c[p%Tpq%cq!^%T!_#o%T#p$f%T$f$g%c$g#BY%T#BY#BZ%c#BZ$IS%T$IS$I_%c$I_$JT%T$JT$JU%c$JU$KV%T$KV$KW%c$KW&FU%T&FU&FV%c&FV?HT%T?HT?HU%c?HU~%T7Z'YR$UW'Z7RO!^%T!_#o%T#p~%T$T'jS$UW!j#{O!^%T!_!`'v!`#o%T#p~%T$O'}S#e#v$UWO!^%T!_!`(Z!`#o%T#p~%T$O(bR#e#v$UWO!^%T!_#o%T#p~%T'u(rZ$UW]!ROY(kYZ)eZr(krs*rs!^(k!^!_+U!_#O(k#O#P-b#P#o(k#o#p+U#p~(k&r)jV$UWOr)ers*Ps!^)e!^!_*a!_#o)e#o#p*a#p~)e&r*WR$P&j$UWO!^%T!_#o%T#p~%T&j*dROr*ars*ms~*a&j*rO$P&j'u*{R$P&j$UW]!RO!^%T!_#o%T#p~%T'm+ZV]!ROY+UYZ*aZr+Urs+ps#O+U#O#P+w#P~+U'm+wO$P&j]!R'm+zROr+Urs,Ts~+U'm,[U$P&j]!ROY,nZr,nrs-Vs#O,n#O#P-[#P~,n!R,sU]!ROY,nZr,nrs-Vs#O,n#O#P-[#P~,n!R-[O]!R!R-_PO~,n'u-gV$UWOr(krs-|s!^(k!^!_+U!_#o(k#o#p+U#p~(k'u.VZ$P&j$UW]!ROY.xYZ%TZr.xrs/rs!^.x!^!_,n!_#O.x#O#P0S#P#o.x#o#p,n#p~.x!Z/PZ$UW]!ROY.xYZ%TZr.xrs/rs!^.x!^!_,n!_#O.x#O#P0S#P#o.x#o#p,n#p~.x!Z/yR$UW]!RO!^%T!_#o%T#p~%T!Z0XT$UWO!^.x!^!_,n!_#o.x#o#p,n#p~.x2k0mZ$UWOt%Ttu1`u!^%T!_!c%T!c!}1`!}#R%T#R#S1`#S#T%T#T#o1`#p$g%T$g~1`2k1g]$UW'o2cOt%Ttu1`u!Q%T!Q![1`![!^%T!_!c%T!c!}1`!}#R%T#R#S1`#S#T%T#T#o1`#p$g%T$g~1`7Z2k_$UW#zS']%k'g2bOt%Ttu2`u}%T}!O3j!O!Q%T!Q![2`![!^%T!_!c%T!c!}2`!}#R%T#R#S2`#S#T%T#T#o2`#p$g%T$g~2`[3q_$UW#zSOt%Ttu3ju}%T}!O3j!O!Q%T!Q![3j![!^%T!_!c%T!c!}3j!}#R%T#R#S3j#S#T%T#T#o3j#p$g%T$g~3j$O4wS#^#v$UWO!^%T!_!`5T!`#o%T#p~%T$O5[R$UW#o#vO!^%T!_#o%T#p~%T6d5lU'x6[$UWOv%Tvw6Ow!^%T!_!`5T!`#o%T#p~%T$O6VS$UW#i#vO!^%T!_!`5T!`#o%T#p~%T'u6jZ$UW]!ROY6cYZ7]Zw6cwx*rx!^6c!^!_8T!_#O6c#O#P:T#P#o6c#o#p8T#p~6c&r7bV$UWOw7]wx*Px!^7]!^!_7w!_#o7]#o#p7w#p~7]&j7zROw7wwx*mx~7w'm8YV]!ROY8TYZ7wZw8Twx+px#O8T#O#P8o#P~8T'm8rROw8Twx8{x~8T'm9SU$P&j]!ROY9fZw9fwx-Vx#O9f#O#P9}#P~9f!R9kU]!ROY9fZw9fwx-Vx#O9f#O#P9}#P~9f!R:QPO~9f'u:YV$UWOw6cwx:ox!^6c!^!_8T!_#o6c#o#p8T#p~6c'u:xZ$P&j$UW]!ROY;kYZ%TZw;kwx/rx!^;k!^!_9f!_#O;k#O#PW{!^%T!_!`5T!`#o%T#p~%T$O>_S#[#v$UWO!^%T!_!`5T!`#o%T#p~%T$u>rSj$m$UWO!^%T!_!`5T!`#o%T#p~%T&i?VR!R&a$UWO!^%T!_#o%T#p~%T7Z?gVu6`$UWO!O%T!O!P?|!P!Q%T!Q![@r![!^%T!_#o%T#p~%Ty@RT$UWO!O%T!O!P@b!P!^%T!_#o%T#p~%Ty@iR!Qq$UWO!^%T!_#o%T#p~%Ty@yZ$UWkqO!Q%T!Q![@r![!^%T!_!g%T!g!hAl!h#R%T#R#S@r#S#X%T#X#YAl#Y#o%T#p~%TyAqZ$UWO{%T{|Bd|}%T}!OBd!O!Q%T!Q![CO![!^%T!_#R%T#R#SCO#S#o%T#p~%TyBiV$UWO!Q%T!Q![CO![!^%T!_#R%T#R#SCO#S#o%T#p~%TyCVV$UWkqO!Q%T!Q![CO![!^%T!_#R%T#R#SCO#S#o%T#p~%T7ZCs`$UW#]#vOYDuYZ%TZzDuz{Jl{!PDu!P!Q!-e!Q!^Du!^!_Fx!_!`!.^!`!a!/]!a!}Du!}#OHq#O#PJQ#P#oDu#o#pFx#p~DuXD|[$UW}POYDuYZ%TZ!PDu!P!QEr!Q!^Du!^!_Fx!_!}Du!}#OHq#O#PJQ#P#oDu#o#pFx#p~DuXEy_$UW}PO!^%T!_#Z%T#Z#[Er#[#]%T#]#^Er#^#a%T#a#bEr#b#g%T#g#hEr#h#i%T#i#jEr#j#m%T#m#nEr#n#o%T#p~%TPF}V}POYFxZ!PFx!P!QGd!Q!}Fx!}#OG{#O#PHh#P~FxPGiU}P#Z#[Gd#]#^Gd#a#bGd#g#hGd#i#jGd#m#nGdPHOTOYG{Z#OG{#O#PH_#P#QFx#Q~G{PHbQOYG{Z~G{PHkQOYFxZ~FxXHvY$UWOYHqYZ%TZ!^Hq!^!_G{!_#OHq#O#PIf#P#QDu#Q#oHq#o#pG{#p~HqXIkV$UWOYHqYZ%TZ!^Hq!^!_G{!_#oHq#o#pG{#p~HqXJVV$UWOYDuYZ%TZ!^Du!^!_Fx!_#oDu#o#pFx#p~Du7ZJs^$UW}POYJlYZKoZzJlz{NQ{!PJl!P!Q!,R!Q!^Jl!^!_!!]!_!}Jl!}#O!'|#O#P!+a#P#oJl#o#p!!]#p~Jl7ZKtV$UWOzKoz{LZ{!^Ko!^!_M]!_#oKo#o#pM]#p~Ko7ZL`X$UWOzKoz{LZ{!PKo!P!QL{!Q!^Ko!^!_M]!_#oKo#o#pM]#p~Ko7ZMSR$UWU7RO!^%T!_#o%T#p~%T7RM`ROzM]z{Mi{~M]7RMlTOzM]z{Mi{!PM]!P!QM{!Q~M]7RNQOU7R7ZNX^$UW}POYJlYZKoZzJlz{NQ{!PJl!P!Q! T!Q!^Jl!^!_!!]!_!}Jl!}#O!'|#O#P!+a#P#oJl#o#p!!]#p~Jl7Z! ^_$UWU7R}PO!^%T!_#Z%T#Z#[Er#[#]%T#]#^Er#^#a%T#a#bEr#b#g%T#g#hEr#h#i%T#i#jEr#j#m%T#m#nEr#n#o%T#p~%T7R!!bY}POY!!]YZM]Zz!!]z{!#Q{!P!!]!P!Q!&x!Q!}!!]!}#O!$`#O#P!&f#P~!!]7R!#VY}POY!!]YZM]Zz!!]z{!#Q{!P!!]!P!Q!#u!Q!}!!]!}#O!$`#O#P!&f#P~!!]7R!#|UU7R}P#Z#[Gd#]#^Gd#a#bGd#g#hGd#i#jGd#m#nGd7R!$cWOY!$`YZM]Zz!$`z{!${{#O!$`#O#P!&S#P#Q!!]#Q~!$`7R!%OYOY!$`YZM]Zz!$`z{!${{!P!$`!P!Q!%n!Q#O!$`#O#P!&S#P#Q!!]#Q~!$`7R!%sTU7ROYG{Z#OG{#O#PH_#P#QFx#Q~G{7R!&VTOY!$`YZM]Zz!$`z{!${{~!$`7R!&iTOY!!]YZM]Zz!!]z{!#Q{~!!]7R!&}_}POzM]z{Mi{#ZM]#Z#[!&x#[#]M]#]#^!&x#^#aM]#a#b!&x#b#gM]#g#h!&x#h#iM]#i#j!&x#j#mM]#m#n!&x#n~M]7Z!(R[$UWOY!'|YZKoZz!'|z{!(w{!^!'|!^!_!$`!_#O!'|#O#P!*o#P#QJl#Q#o!'|#o#p!$`#p~!'|7Z!(|^$UWOY!'|YZKoZz!'|z{!(w{!P!'|!P!Q!)x!Q!^!'|!^!_!$`!_#O!'|#O#P!*o#P#QJl#Q#o!'|#o#p!$`#p~!'|7Z!*PY$UWU7ROYHqYZ%TZ!^Hq!^!_G{!_#OHq#O#PIf#P#QDu#Q#oHq#o#pG{#p~Hq7Z!*tX$UWOY!'|YZKoZz!'|z{!(w{!^!'|!^!_!$`!_#o!'|#o#p!$`#p~!'|7Z!+fX$UWOYJlYZKoZzJlz{NQ{!^Jl!^!_!!]!_#oJl#o#p!!]#p~Jl7Z!,Yc$UW}POzKoz{LZ{!^Ko!^!_M]!_#ZKo#Z#[!,R#[#]Ko#]#^!,R#^#aKo#a#b!,R#b#gKo#g#h!,R#h#iKo#i#j!,R#j#mKo#m#n!,R#n#oKo#o#pM]#p~Ko7Z!-lV$UWT7ROY!-eYZ%TZ!^!-e!^!_!.R!_#o!-e#o#p!.R#p~!-e7R!.WQT7ROY!.RZ~!.R$P!.g[$UW#o#v}POYDuYZ%TZ!PDu!P!QEr!Q!^Du!^!_Fx!_!}Du!}#OHq#O#PJQ#P#oDu#o#pFx#p~Du]!/f[#wS$UW}POYDuYZ%TZ!PDu!P!QEr!Q!^Du!^!_Fx!_!}Du!}#OHq#O#PJQ#P#oDu#o#pFx#p~Duy!0cd$UWkqO!O%T!O!P@r!P!Q%T!Q![!1q![!^%T!_!g%T!g!hAl!h#R%T#R#S!1q#S#U%T#U#V!3X#V#X%T#X#YAl#Y#b%T#b#c!2w#c#d!4m#d#l%T#l#m!5{#m#o%T#p~%Ty!1x_$UWkqO!O%T!O!P@r!P!Q%T!Q![!1q![!^%T!_!g%T!g!hAl!h#R%T#R#S!1q#S#X%T#X#YAl#Y#b%T#b#c!2w#c#o%T#p~%Ty!3OR$UWkqO!^%T!_#o%T#p~%Ty!3^W$UWO!Q%T!Q!R!3v!R!S!3v!S!^%T!_#R%T#R#S!3v#S#o%T#p~%Ty!3}Y$UWkqO!Q%T!Q!R!3v!R!S!3v!S!^%T!_#R%T#R#S!3v#S#b%T#b#c!2w#c#o%T#p~%Ty!4rV$UWO!Q%T!Q!Y!5X!Y!^%T!_#R%T#R#S!5X#S#o%T#p~%Ty!5`X$UWkqO!Q%T!Q!Y!5X!Y!^%T!_#R%T#R#S!5X#S#b%T#b#c!2w#c#o%T#p~%Ty!6QZ$UWO!Q%T!Q![!6s![!^%T!_!c%T!c!i!6s!i#R%T#R#S!6s#S#T%T#T#Z!6s#Z#o%T#p~%Ty!6z]$UWkqO!Q%T!Q![!6s![!^%T!_!c%T!c!i!6s!i#R%T#R#S!6s#S#T%T#T#Z!6s#Z#b%T#b#c!2w#c#o%T#p~%T%w!7|R!]V$UW#m%hO!^%T!_#o%T#p~%T!P!8^R_w$UWO!^%T!_#o%T#p~%T6i!8rR'bd!a0`#x&s'|P!P!Q!8{!^!_!9Q!_!`!9_W!9QO$WW#v!9VP#`#v!_!`!9Y#v!9_O#o#v#v!9dO#a#v%w!9kT!{%o$UWO!^%T!_!`'v!`!a!9z!a#o%T#p~%T$P!:RR#W#w$UWO!^%T!_#o%T#p~%T%w!:gT'a!s#a#v$RS$UWO!^%T!_!`!:v!`!a!;W!a#o%T#p~%T$O!:}R#a#v$UWO!^%T!_#o%T#p~%T$O!;_T#`#v$UWO!^%T!_!`5T!`!a!;n!a#o%T#p~%T$O!;uS#`#v$UWO!^%T!_!`5T!`#o%T#p~%T6i!]S#g#v$UWO!^%T!_!`5T!`#o%T#p~%T$P!>pR$UW'f#wO!^%T!_#o%T#p~%T~!?OO!T~6d!?VT'w6[$UWO!^%T!_!`5T!`#o%T#p#q!=P#q~%T5g!?oR!S5]nQ$UWO!^%T!_#o%T#p~%TX!@PR!kP$UWO!^%T!_#o%T#p~%T7Z!@gr$UW'Y7R#zS']%k'g2bOX%TXY%cYZ%TZ[%c[p%Tpq%cqt%Ttu2`u}%T}!O3j!O!Q%T!Q![2`![!^%T!_!c%T!c!}2`!}#R%T#R#S2`#S#T%T#T#o2`#p$f%T$f$g%c$g#BY2`#BY#BZ!@Y#BZ$IS2`$IS$I_!@Y$I_$JT2`$JT$JU!@Y$JU$KV2`$KV$KW!@Y$KW&FU2`&FU&FV!@Y&FV?HT2`?HT?HU!@Y?HU~2`7Z!CO_$UW'Z7R#zS']%k'g2bOt%Ttu2`u}%T}!O3j!O!Q%T!Q![2`![!^%T!_!c%T!c!}2`!}#R%T#R#S2`#S#T%T#T#o2`#p$g%T$g~2`", - tokenizers: [noSemicolon, incdecToken, template, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, insertSemicolon], - topRules: { "Script": [0, 7] }, - dialects: { jsx: 11707, ts: 11709 }, - dynamicPrecedences: { "149": 1, "176": 1 }, - specialized: [{ term: 289, get: (value, stack) => tsExtends(value, stack) << 1 }, { term: 289, get: (value) => spec_identifier[value] || -1 }, { term: 299, get: (value) => spec_word[value] || -1 }, { term: 63, get: (value) => spec_LessThan[value] || -1 }], - tokenPrec: 11730 -}); - -// node_modules/@codemirror/lang-javascript/dist/index.js -var import_language2 = require("@codemirror/language"); -var import_state3 = require("@codemirror/state"); -var import_view2 = require("@codemirror/view"); -var import_autocomplete = require("@codemirror/autocomplete"); - -// node_modules/@codemirror/lang-javascript/node_modules/@lezer/common/dist/index.js -var DefaultBufferLength2 = 1024; -var nextPropID2 = 0; -var NodeProp2 = class { - constructor(config4 = {}) { - this.id = nextPropID2++; - this.perNode = !!config4.perNode; - this.deserialize = config4.deserialize || (() => { - throw new Error("This node type doesn't define a deserialize function"); - }); - } - add(match2) { - if (this.perNode) - throw new RangeError("Can't add per-node props to node types"); - if (typeof match2 != "function") - match2 = NodeType2.match(match2); - return (type) => { - let result = match2(type); - return result === void 0 ? null : [this, result]; + saveParsedValue("field", field); + }; + const selectContext = (e5) => { + showOptions( + e5, + parsedValue.space, + props.superstate.allSpaces().filter((f2) => f2.type != "default").map((m4) => ({ name: m4.name, value: m4.path, description: m4.path })), + "space" + ); + }; + const selectSpaceProperty = (e5) => { + showOptions( + e5, + parsedValue.property, + props.superstate.contextsIndex.get(parsedValue.space)?.cols.filter((f2) => { + return f2.type?.startsWith("context") && parseFieldValue(f2.value, f2.type, props.superstate)["space"] == props.contextPath ? true : false; + }).map((m4) => ({ name: m4.name, value: m4.name })) ?? [], + "field", + saveSpaceProperty + ); + }; + const selectProperty = (e5) => { + const properties3 = props.fields.filter( + (f2) => f2.type == "file" || f2.type == "link" || f2.type == "context" + ).map((f2) => ({ + name: f2.name, + value: f2.name + })) ?? []; + showOptions(e5, null, properties3, "field"); + }; + const selectPathProp = (e5) => { + const property = props.fields.find((f2) => f2.name == parsedValue.field); + const allPaths = props.superstate.spaceManager.allPaths(); + const fileProps = property ? property.type == "file" || property.type == "link" ? filePropTypes.map((f2) => ({ + name: f2.name, + value: f2.value + })) : props.superstate.contextsIndex.get( + parseFieldValue(property.value, "context", props.superstate).space + )?.cols.filter((f2) => f2.hidden != "true").map((f2) => ({ + name: f2.name, + value: f2.name + })) ?? [] : []; + const cacheTypes = allCacheTypesForPaths(props.superstate, allPaths).map( + (f2) => ({ name: f2.name, value: f2.name }) + ); + showOptions(e5, null, [...fileProps, ...cacheTypes], "value"); + }; + const editFormula = (e5) => { + const _props = { + superstate: props.superstate, + saveFormula: (value) => saveParsedValue("value", value), + formula: parsedValue.value, + value: {}, + fields: props.fields, + path: "" }; - } -}; -NodeProp2.closedBy = new NodeProp2({ deserialize: (str) => str.split(" ") }); -NodeProp2.openedBy = new NodeProp2({ deserialize: (str) => str.split(" ") }); -NodeProp2.group = new NodeProp2({ deserialize: (str) => str.split(" ") }); -NodeProp2.contextHash = new NodeProp2({ perNode: true }); -NodeProp2.lookAhead = new NodeProp2({ perNode: true }); -NodeProp2.mounted = new NodeProp2({ perNode: true }); -var noProps2 = /* @__PURE__ */ Object.create(null); -var NodeType2 = class { - constructor(name317, props, id3, flags = 0) { - this.name = name317; - this.props = props; - this.id = id3; - this.flags = flags; - } - static define(spec) { - let props = spec.props && spec.props.length ? /* @__PURE__ */ Object.create(null) : noProps2; - let flags = (spec.top ? 1 : 0) | (spec.skipped ? 2 : 0) | (spec.error ? 4 : 0) | (spec.name == null ? 8 : 0); - let type = new NodeType2(spec.name || "", props, spec.id, flags); - if (spec.props) - for (let src of spec.props) { - if (!Array.isArray(src)) - src = src(type); - if (src) { - if (src[0].perNode) - throw new RangeError("Can't store a per-node prop on a node type"); - props[src[0].id] = src[1]; - } + props.superstate.ui.openCustomMenu( + e5.target.getBoundingClientRect(), + /* @__PURE__ */ import_react23.default.createElement(FormulaEditor, { + ..._props + }), + { ..._props }, + "bottom" + ); + }; + const selectDateFormat = (e5) => { + const formats = [ + { + name: "2020-04-21", + value: "yyyy-MM-dd" + }, + { + name: "Apr 21, 2020", + value: "MMM d, yyyy" + }, + { + name: "Tue Apr 21, 2020", + value: "EEE MMM d, yyyy" } - return type; - } - prop(prop2) { - return this.props[prop2.id]; - } - get isTop() { - return (this.flags & 1) > 0; - } - get isSkipped() { - return (this.flags & 2) > 0; - } - get isError() { - return (this.flags & 4) > 0; - } - get isAnonymous() { - return (this.flags & 8) > 0; - } - is(name317) { - if (typeof name317 == "string") { - if (this.name == name317) - return true; - let group = this.prop(NodeProp2.group); - return group ? group.indexOf(name317) > -1 : false; + ]; + showOptions(e5, null, formats, "format"); + }; + return props.fieldType?.startsWith("date") ? /* @__PURE__ */ import_react23.default.createElement("div", { + className: "mk-menu-option", + onClick: (e5) => selectDateFormat(e5) + }, /* @__PURE__ */ import_react23.default.createElement("span", null, i18n_default.labels.dateFormat), /* @__PURE__ */ import_react23.default.createElement("span", null, parsedValue.format)) : props.fieldType?.startsWith("context") ? /* @__PURE__ */ import_react23.default.createElement(import_react23.default.Fragment, null, /* @__PURE__ */ import_react23.default.createElement("div", { + className: "mk-menu-option", + onClick: (e5) => selectContext(e5) + }, /* @__PURE__ */ import_react23.default.createElement("span", null, i18n_default.labels.propertyValueSpace), /* @__PURE__ */ import_react23.default.createElement("span", null, spaceNameFromSpacePath(parsedValue.space, props.superstate))), parsedValue.space?.length > 0 && props.contextPath && /* @__PURE__ */ import_react23.default.createElement("div", { + className: "mk-menu-option", + onClick: (e5) => selectSpaceProperty(e5) + }, /* @__PURE__ */ import_react23.default.createElement("span", null, i18n_default.labels.propertyValueProperty), /* @__PURE__ */ import_react23.default.createElement("span", null, parsedValue.field))) : props.fieldType == "number" ? /* @__PURE__ */ import_react23.default.createElement(import_react23.default.Fragment, null) : props.fieldType == "fileprop" ? /* @__PURE__ */ import_react23.default.createElement(import_react23.default.Fragment, null, /* @__PURE__ */ import_react23.default.createElement("div", { + className: "mk-menu-option", + onClick: (e5) => editFormula(e5) + }, /* @__PURE__ */ import_react23.default.createElement("span", null, i18n_default.labels.propertyLookup)), /* @__PURE__ */ import_react23.default.createElement("div", { + className: "mk-menu-option", + onClick: (e5) => selectType(e5) + }, /* @__PURE__ */ import_react23.default.createElement("span", null, i18n_default.labels.propertyType), /* @__PURE__ */ import_react23.default.createElement("span", null, fieldTypeForType(parsedValue.type)?.label))) : props.fieldType == "object" ? /* @__PURE__ */ import_react23.default.createElement("div", { + className: "mk-menu-option", + onClick: (e5) => { + props.superstate.ui.openModal( + "Object Name", + (_props) => /* @__PURE__ */ import_react23.default.createElement(InputModal, { + value: parsedValue.typeName, + saveLabel: "Rename Object", + saveValue: (value) => { + saveParsedValue("typeName", value); + }, + hide: _props.hide + }) + ); } - return this.id == name317; - } - static match(map4) { - let direct = /* @__PURE__ */ Object.create(null); - for (let prop2 in map4) - for (let name317 of prop2.split(" ")) - direct[name317] = map4[prop2]; - return (node) => { - for (let groups = node.prop(NodeProp2.group), i4 = -1; i4 < (groups ? groups.length : 0); i4++) { - let found = direct[i4 < 0 ? node.name : groups[i4]]; - if (found) - return found; - } - }; - } + }, /* @__PURE__ */ import_react23.default.createElement("span", null, "Name"), /* @__PURE__ */ import_react23.default.createElement("span", null, parsedValue.typeName)) : props.fieldType == "super" ? /* @__PURE__ */ import_react23.default.createElement(import_react23.default.Fragment, null, /* @__PURE__ */ import_react23.default.createElement("div", { + className: "mk-menu-option" + }, /* @__PURE__ */ import_react23.default.createElement("span", null, i18n_default.labels.propertyDynamic), /* @__PURE__ */ import_react23.default.createElement("input", { + type: "checkbox", + checked: parsedValue.dynamic == true, + onChange: () => saveParsedValue("dynamic", !parsedValue.dynamic) + })), /* @__PURE__ */ import_react23.default.createElement("div", { + className: "mk-menu-option", + onClick: (e5) => selectProperty(e5) + }, /* @__PURE__ */ import_react23.default.createElement("span", null, i18n_default.labels.propertyFileProp), /* @__PURE__ */ import_react23.default.createElement("span", null, parsedValue.field))) : /* @__PURE__ */ import_react23.default.createElement(import_react23.default.Fragment, null); }; -NodeType2.none = new NodeType2("", /* @__PURE__ */ Object.create(null), 0, 8); -var CachedNode2 = /* @__PURE__ */ new WeakMap(); -var CachedInnerNode2 = /* @__PURE__ */ new WeakMap(); -var IterMode2; -(function(IterMode4) { - IterMode4[IterMode4["ExcludeBuffers"] = 1] = "ExcludeBuffers"; - IterMode4[IterMode4["IncludeAnonymous"] = 2] = "IncludeAnonymous"; - IterMode4[IterMode4["IgnoreMounts"] = 4] = "IgnoreMounts"; - IterMode4[IterMode4["IgnoreOverlays"] = 8] = "IgnoreOverlays"; -})(IterMode2 || (IterMode2 = {})); -var Tree2 = class { - constructor(type, children, positions, length, props) { - this.type = type; - this.children = children; - this.positions = positions; - this.length = length; - this.props = null; - if (props && props.length) { - this.props = /* @__PURE__ */ Object.create(null); - for (let [prop2, value] of props) - this.props[typeof prop2 == "number" ? prop2 : prop2.id] = value; + +// src/core/react/components/UI/Menus/contexts/newSpacePropertyMenu.tsx +var NewPropertyMenuComponent = (props) => { + const [fieldName, setFieldName] = (0, import_react24.useState)(""); + const [fieldSource, setFieldSource] = (0, import_react24.useState)( + props.fileMetadata ? "$fm" : "" + ); + const spaceCaches = (0, import_react24.useMemo)( + () => props.spaces.map((f2) => props.superstate.spacesIndex.get(f2)).filter((f2) => f2), + [props.spaces] + ); + const [fieldValue, setFieldValue] = (0, import_react24.useState)(""); + const [fieldType, setFieldType] = (0, import_react24.useState)("text"); + const options = (0, import_react24.useMemo)(() => { + const options2 = []; + if (props.fileMetadata) { + options2.push({ + name: i18n_default.menu.setNone, + value: "$fm" + }); } - } - toString() { - let mounted = this.prop(NodeProp2.mounted); - if (mounted && !mounted.overlay) - return mounted.tree.toString(); - let children = ""; - for (let ch of this.children) { - let str = ch.toString(); - if (str) { - if (children) - children += ","; - children += str; - } + if (props.contextPath) { + options2.push({ + name: folderPathToString(props.contextPath), + value: "" + }); } - return !this.type.name ? children : (/\W/.test(this.type.name) && !this.type.isError ? JSON.stringify(this.type.name) : this.type.name) + (children.length ? "(" + children + ")" : ""); - } - cursor(mode2 = 0) { - return new TreeCursor2(this.topNode, mode2); - } - cursorAt(pos, side = 0, mode2 = 0) { - let scope = CachedNode2.get(this) || this.topNode; - let cursor2 = new TreeCursor2(scope); - cursor2.moveTo(pos, side); - CachedNode2.set(this, cursor2._tree); - return cursor2; - } - get topNode() { - return new TreeNode3(this, 0, 0, null); - } - resolve(pos, side = 0) { - let node = resolveNode2(CachedNode2.get(this) || this.topNode, pos, side, false); - CachedNode2.set(this, node); - return node; - } - resolveInner(pos, side = 0) { - let node = resolveNode2(CachedInnerNode2.get(this) || this.topNode, pos, side, true); - CachedInnerNode2.set(this, node); - return node; - } - iterate(spec) { - let { enter, leave, from = 0, to: to2 = this.length } = spec; - for (let c3 = this.cursor((spec.mode || 0) | IterMode2.IncludeAnonymous); ; ) { - let entered = false; - if (c3.from <= to2 && c3.to >= from && (c3.type.isAnonymous || enter(c3) !== false)) { - if (c3.firstChild()) - continue; - entered = true; + options2.push( + ...(spaceCaches ?? []).map((f2) => ({ + name: f2.name, + value: f2.path + })) + ); + return options2; + }, [spaceCaches]); + const selectedType = (_15, value) => { + setFieldType(value[0]); + }; + const selectedValue = (value) => { + setFieldValue(value); + }; + const selectedSource = (_15, value) => { + setFieldSource(value[0]); + }; + const toggleMulti = () => { + const field = fieldTypes.find( + (f2) => f2.type == fieldType || f2.multiType == fieldType + ); + setFieldType(field.type == fieldType ? field.multiType : field.type); + }; + const selectType = (e5) => { + props.superstate.ui.openMenu( + e5.target.getBoundingClientRect(), + { + ui: props.superstate.ui, + multi: false, + editable: false, + searchable: true, + saveOptions: selectedType, + value: [], + showAll: true, + options: fieldTypes.filter( + (f2) => fieldSource == "$fm" && !props.isSpace ? f2.metadata : !f2.restricted + ).map((f2, i4) => ({ + id: i4 + 1, + name: f2.label, + value: f2.type, + icon: f2.icon, + description: f2.description + })) } - for (; ; ) { - if (entered && leave && !c3.type.isAnonymous) - leave(c3); - if (c3.nextSibling()) - break; - if (!c3.parent()) - return; - entered = true; + ); + }; + const selectedContext = (value) => { + setFieldValue(value); + }; + const type = (0, import_react24.useMemo)( + () => fieldTypeForType(fieldType, fieldName) ?? fieldTypes[0], + [fieldType, fieldName] + ); + const selectSource = (e5) => { + e5.stopPropagation(); + props.superstate.ui.openMenu( + e5.target.getBoundingClientRect(), + { + ui: props.superstate.ui, + multi: false, + editable: false, + searchable: false, + saveOptions: selectedSource, + value: [], + showAll: true, + options } + ); + }; + const saveField = () => { + if (fieldName.length == 0) { + props.superstate.ui.notify(i18n_default.notice.noPropertyName); + return; } - } - prop(prop2) { - return !prop2.perNode ? this.type.prop(prop2) : this.props ? this.props[prop2.id] : void 0; - } - get propValues() { - let result = []; - if (this.props) - for (let id3 in this.props) - result.push([+id3, this.props[id3]]); - return result; - } - balance(config4 = {}) { - return this.children.length <= 8 ? this : balanceRange2(NodeType2.none, this.children, this.positions, 0, this.children.length, 0, this.length, (children, positions, length) => new Tree2(this.type, children, positions, length, this.propValues), config4.makeTree || ((children, positions, length) => new Tree2(NodeType2.none, children, positions, length))); - } - static build(data2) { - return buildTree2(data2); - } + props.saveField(fieldSource, { + name: fieldName, + type: fieldType, + value: fieldValue, + schemaId: props.schemaId + }); + props.hide(); + }; + const onKeyDown = (e5) => { + if (e5.key == "Enter") { + saveField(); + } + }; + (0, import_react24.useEffect)(() => { + setTimeout(() => { + input.current?.focus(); + }, 50); + }, []); + const input = (0, import_react24.useRef)(null); + return /* @__PURE__ */ import_react24.default.createElement("div", { + className: "mk-menu-container" + }, /* @__PURE__ */ import_react24.default.createElement("div", { + className: "mk-menu-suggestions" + }, /* @__PURE__ */ import_react24.default.createElement("div", { + className: "mk-menu-input" + }, /* @__PURE__ */ import_react24.default.createElement("input", { + type: "text", + ref: input, + placeholder: "Name", + onKeyDown, + onChange: (e5) => setFieldName(e5.target.value), + onMouseDown: (e5) => e5.stopPropagation(), + value: fieldName + })), /* @__PURE__ */ import_react24.default.createElement("div", { + className: "mk-menu-separator" + }), options.length > 1 && /* @__PURE__ */ import_react24.default.createElement("div", { + className: "mk-menu-option", + onClick: (e5) => selectSource(e5) + }, /* @__PURE__ */ import_react24.default.createElement("div", { + className: "mk-menu-options-inner" + }, i18n_default.labels.propertyValueSpace), /* @__PURE__ */ import_react24.default.createElement("span", null, fieldSource == "$fm" ? "None" : fieldSource == "" ? props.contextPath : fieldSource)), /* @__PURE__ */ import_react24.default.createElement("div", { + className: "mk-menu-option", + onClick: (e5) => selectType(e5) + }, /* @__PURE__ */ import_react24.default.createElement("div", { + className: "mk-menu-options-inner" + }, i18n_default.labels.propertyValueProperty), /* @__PURE__ */ import_react24.default.createElement("span", null, type.label)), type.multi ? /* @__PURE__ */ import_react24.default.createElement("div", { + className: "mk-menu-option" + }, /* @__PURE__ */ import_react24.default.createElement("span", null, i18n_default.labels.multiple), /* @__PURE__ */ import_react24.default.createElement("input", { + type: "checkbox", + checked: fieldType == type.multiType, + onChange: () => toggleMulti() + })) : /* @__PURE__ */ import_react24.default.createElement(import_react24.default.Fragment, null), /* @__PURE__ */ import_react24.default.createElement("div", { + className: "mk-menu-separator" + }), fieldSource != "$fm" || props.isSpace ? /* @__PURE__ */ import_react24.default.createElement(PropertyValueComponent, { + superstate: props.superstate, + table: fieldSource, + fields: props.fields, + fieldType, + value: fieldValue, + contextPath: props.contextPath, + saveValue: selectedValue + }) : /* @__PURE__ */ import_react24.default.createElement(import_react24.default.Fragment, null), /* @__PURE__ */ import_react24.default.createElement("div", { + className: "mk-menu-separator" + }), /* @__PURE__ */ import_react24.default.createElement("div", { + className: "mk-menu-option", + onClick: (e5) => saveField() + }, /* @__PURE__ */ import_react24.default.createElement("span", null, i18n_default.buttons.saveProperty)), /* @__PURE__ */ import_react24.default.createElement("div", { + className: "mk-menu-option", + onClick: (e5) => props.hide() + }, /* @__PURE__ */ import_react24.default.createElement("span", null, i18n_default.buttons.cancel)))); }; -Tree2.empty = new Tree2(NodeType2.none, [], [], 0); -var FlatBufferCursor2 = class { - constructor(buffer, index2) { - this.buffer = buffer; - this.index = index2; - } - get id() { - return this.buffer[this.index - 4]; - } - get start() { - return this.buffer[this.index - 3]; - } - get end() { - return this.buffer[this.index - 2]; - } - get size() { - return this.buffer[this.index - 1]; - } - get pos() { - return this.index; - } - next() { - this.index -= 4; - } - fork() { - return new FlatBufferCursor2(this.buffer, this.index); - } +var showNewPropertyMenu = (superstate, rect, spaces2, fields, saveField, schemaId, contextPath, fileMetadata, isSpace) => { + return superstate.ui.openCustomMenu( + rect, + /* @__PURE__ */ import_react24.default.createElement(NewPropertyMenuComponent, { + superstate, + spaces: spaces2, + schemaId, + contextPath, + fields, + saveField, + fileMetadata, + isSpace + }), + {}, + "bottom" + ); }; -var TreeBuffer2 = class { - constructor(buffer, length, set) { - this.buffer = buffer; - this.length = length; - this.set = set; - } - get type() { - return NodeType2.none; - } - toString() { - let result = []; - for (let index2 = 0; index2 < this.buffer.length; ) { - result.push(this.childString(index2)); - index2 = this.buffer[index2 + 3]; + +// src/core/react/components/SpaceEditor/SpacePropertyEditor.tsx +var import_react_dom2 = __toESM(require_react_dom()); +var SpacePropertyEditor = (props) => { + const [activeId, setActiveId] = (0, import_react25.useState)(""); + const items = props.columns.map((f2) => ({ ...f2, table: "", id: f2.name })); + const [openNodes, setOpenNodes] = (0, import_react25.useState)([]); + const [overId, setOverId] = (0, import_react25.useState)(""); + const contextProperties = (0, import_react25.useMemo)(() => { + return props.contexts.reduce((p, c3) => { + return { + ...p, + [c3]: { + path: props.superstate.pathsIndex.get(tagSpacePathFromTag(c3)), + space: props.superstate.spacesIndex.get(tagSpacePathFromTag(c3)), + cols: props.superstate.contextsIndex.get(tagSpacePathFromTag(c3))?.cols ?? [].map((f2) => ({ ...f2, table: c3 })) + } + }; + }, {}); + }, [props.contexts]); + const sensors = useSensors( + useSensor(MouseSensor, { + activationConstraint: { + distance: 10 + } + }), + useSensor(TouchSensor, { + activationConstraint: { + delay: 250, + tolerance: 5 + } + }), + useSensor(KeyboardSensor, { + coordinateGetter: sortableKeyboardCoordinates + }) + ); + const resetState = () => { + setActiveId(null); + setOverId(null); + }; + const saveNewField = (source, field) => { + props.saveColumn({ ...field, table: "" }); + }; + const newProperty = (e5) => { + const offset2 = e5.target.getBoundingClientRect(); + showNewPropertyMenu( + props.superstate, + offset2, + props.contexts ?? [], + [], + saveNewField, + defaultContextSchemaID, + null, + false + ); + }; + const newContexts = (e5) => { + const offset2 = e5.target.getBoundingClientRect(); + const f2 = props.superstate.spaceManager.readTags(); + const addTag2 = async (tag2) => { + const newTag = ensureTag(tag2); + props.saveContexts([ + ...props.contexts.filter((f3) => f3 != newTag), + newTag + ]); + }; + props.superstate.ui.openMenu(offset2, { + ui: props.superstate.ui, + multi: false, + editable: true, + value: [], + options: f2.map((m4) => ({ name: m4, value: m4 })), + saveOptions: (_15, value) => addTag2(value[0]), + placeholder: i18n_default.labels.contextItemSelectPlaceholder, + searchable: true, + showAll: true + }); + }; + return /* @__PURE__ */ import_react25.default.createElement(DndContext, { + sensors, + collisionDetection: closestCenter, + measuring: { + droppable: { + strategy: MeasuringStrategy.Always + } + }, + onDragStart: ({ active }) => { + setActiveId(active.data.current.id); + }, + onDragOver: ({ active, over }) => { + const overId2 = over?.data.current?.id; + if (overId2) + setOverId(overId2); + }, + onDragEnd: ({ active, over }) => { + const overId2 = over?.data.current?.id; + if (!overId2) { + resetState(); + return; + } + props.setColumnOrder( + arrayMove( + props.colsOrder, + props.colsOrder.findIndex((f2) => f2 == activeId), + props.colsOrder.findIndex((f2) => f2 == overId2) + ) + ); + resetState(); + }, + onDragCancel: resetState + }, /* @__PURE__ */ import_react25.default.createElement("div", { + className: "mk-space-editor" + }, /* @__PURE__ */ import_react25.default.createElement("div", { + className: "mk-space-editor-header" + }, /* @__PURE__ */ import_react25.default.createElement("div", { + className: "mk-space-editor-header-title" + }, /* @__PURE__ */ import_react25.default.createElement("div", { + className: "mk-space-editor-title" + }, i18n_default.labels.properties), /* @__PURE__ */ import_react25.default.createElement("div", { + className: "mk-space-editor-description" + }, i18n_default.descriptions.spaceProperties)), /* @__PURE__ */ import_react25.default.createElement("span", null), /* @__PURE__ */ import_react25.default.createElement("button", { + className: "mk-toolbar-button", + dangerouslySetInnerHTML: { + __html: props.superstate.ui.getSticker("ui//combine") + }, + onClick: (e5) => { + newContexts(e5); } - return result.join(","); - } - childString(index2) { - let id3 = this.buffer[index2], endIndex = this.buffer[index2 + 3]; - let type = this.set.types[id3], result = type.name; - if (/\W/.test(result) && !type.isError) - result = JSON.stringify(result); - index2 += 4; - if (endIndex == index2) - return result; - let children = []; - while (index2 < endIndex) { - children.push(this.childString(index2)); - index2 = this.buffer[index2 + 3]; + }), /* @__PURE__ */ import_react25.default.createElement("button", { + className: "mk-button-new", + "aria-label": i18n_default.buttons.addItem, + onClick: (e5) => newProperty(e5), + dangerouslySetInnerHTML: { + __html: props.superstate.ui.getSticker("ui//plus") } - return result + "(" + children.join(",") + ")"; - } - findChild(startIndex, endIndex, dir, pos, side) { - let { buffer } = this, pick = -1; - for (let i4 = startIndex; i4 != endIndex; i4 = buffer[i4 + 3]) { - if (checkSide2(side, pos, buffer[i4 + 1], buffer[i4 + 2])) { - pick = i4; - if (dir > 0) - break; - } + })), /* @__PURE__ */ import_react25.default.createElement("div", { + className: "mk-space-editor-contents" + }, /* @__PURE__ */ import_react25.default.createElement("div", { + className: "mk-space-editor-context-list" + }, props.contexts.map((f2, i4) => /* @__PURE__ */ import_react25.default.createElement("div", { + key: i4, + className: "mk-props-contexts-space-name", + style: contextProperties[f2].path?.label?.color?.length > 0 ? { + "--tag-background": contextProperties[f2].path?.label?.color, + "--tag-color": "var(--color-white)" + } : {} + }, /* @__PURE__ */ import_react25.default.createElement("div", { + className: `mk-icon-xsmall`, + dangerouslySetInnerHTML: { + __html: props.superstate.ui.getSticker( + contextProperties[f2].path?.label?.sticker + ) } - return pick; - } - slice(startI, endI, from, to2) { - let b2 = this.buffer; - let copy = new Uint16Array(endI - startI); - for (let i4 = startI, j = 0; i4 < endI; ) { - copy[j++] = b2[i4++]; - copy[j++] = b2[i4++] - from; - copy[j++] = b2[i4++] - from; - copy[j++] = b2[i4++] - startI; + }), f2, /* @__PURE__ */ import_react25.default.createElement("div", { + className: "mk-icon-small", + dangerouslySetInnerHTML: { + __html: props.superstate.ui.getSticker("ui//close") + }, + onClick: (e5) => { + props.saveContexts(props.contexts.filter((g) => g != f2)); } - return new TreeBuffer2(copy, to2 - from, this.set); - } + })))), /* @__PURE__ */ import_react25.default.createElement("div", { + className: "mk-space-editor-contents" + }, /* @__PURE__ */ import_react25.default.createElement(SortableContext, { + items, + strategy: verticalListSortingStrategy + }, items.map((value, index2) => { + return /* @__PURE__ */ import_react25.default.createElement(SortableItem, { + key: index2, + id: value.id, + field: value, + superstate: props.superstate, + saveColumn: (field) => props.saveColumn(field, value), + cols: items, + colsHidden: props.colsHidden, + hideColumn: props.hideColumn, + delColumn: props.delColumn + }); + }))), props.contexts.map((f2, i4) => /* @__PURE__ */ import_react25.default.createElement("div", { + key: i4, + className: "mk-property-editor-context" + }, /* @__PURE__ */ import_react25.default.createElement("div", { + className: "mk-property-editor-list" + }, contextProperties[f2]?.cols.filter((f3) => f3.primary != "true").map((g, h3) => /* @__PURE__ */ import_react25.default.createElement(SortableItem, { + key: h3, + id: g.name + "#" + f2, + field: g, + superstate: props.superstate, + saveColumn: (field) => props.saveColumn(field, g), + cols: contextProperties[f2].cols, + colsHidden: props.colsHidden, + hideColumn: props.hideColumn, + delColumn: props.delColumn + }))))))), (0, import_react_dom2.createPortal)( + /* @__PURE__ */ import_react25.default.createElement(DragOverlay, { + adjustScale: false + }, activeId ? /* @__PURE__ */ import_react25.default.createElement(SortableItem, { + id: items.find((f2) => f2.id == activeId).id, + field: items.find((f2) => f2.id == activeId), + superstate: props.superstate, + cols: items, + colsHidden: props.colsHidden + }) : null), + document.body + )); }; -function checkSide2(side, pos, from, to2) { - switch (side) { - case -2: - return from < pos; - case -1: - return to2 >= pos && from < pos; - case 0: - return from < pos && to2 > pos; - case 1: - return from <= pos && to2 > pos; - case 2: - return to2 > pos; - case 4: - return true; - } -} -function enterUnfinishedNodesBefore2(node, pos) { - let scan = node.childBefore(pos); - while (scan) { - let last = scan.lastChild; - if (!last || last.to != scan.to) - break; - if (last.type.isError && last.from == last.to) { - node = scan; - scan = last.prevSibling; - } else { - scan = last; +function SortableItem(props) { + const { spaceInfo } = (0, import_react25.useContext)(SpaceContext); + const { field } = props; + const saveField = (field2, oldField) => { + if (field2.name.length > 0) { + if (field2.name != oldField.name || field2.type != oldField.type || field2.value != oldField.value || field2.attrs != oldField.attrs) { + const saveResult = props.saveColumn(field2, oldField); + } } - } - return node; -} -function resolveNode2(node, pos, side, overlays) { - var _a; - while (node.from == node.to || (side < 1 ? node.from >= pos : node.from > pos) || (side > -1 ? node.to <= pos : node.to < pos)) { - let parent = !overlays && node instanceof TreeNode3 && node.index < 0 ? null : node.parent; - if (!parent) - return node; - node = parent; - } - let mode2 = overlays ? 0 : IterMode2.IgnoreOverlays; - if (overlays) - for (let scan = node, parent = scan.parent; parent; scan = parent, parent = scan.parent) { - if (scan instanceof TreeNode3 && scan.index < 0 && ((_a = parent.enter(pos, side, mode2)) === null || _a === void 0 ? void 0 : _a.from) != scan.from) - node = parent; + }; + const { attributes, listeners, setNodeRef, transform, transition } = useSortable({ id: props.id }); + const style = { + transform: CSS.Transform.toString(transform), + transition + }; + const icon = stickerForField(props.field); + const selectedType = (_15, value) => { + const newField = { + ...props.field, + type: value[0] + }; + props.saveColumn(newField); + }; + return /* @__PURE__ */ import_react25.default.createElement("div", { + className: "mk-property-editor-property", + ref: setNodeRef, + style, + ...attributes, + ...listeners + }, /* @__PURE__ */ import_react25.default.createElement("div", { + className: "mk-path-context-field-icon", + dangerouslySetInnerHTML: { + __html: props.superstate.ui.getSticker(icon) + }, + onClick: (e5) => { + selectPropertyTypeMenu(e5, props.superstate.ui, selectedType); } - for (; ; ) { - let inner = node.enter(pos, side, mode2); - if (!inner) - return node; - node = inner; - } + }), props.field.name, /* @__PURE__ */ import_react25.default.createElement("span", null), /* @__PURE__ */ import_react25.default.createElement("div", { + className: "mk-icon-small", + dangerouslySetInnerHTML: { + __html: props.superstate.ui.getSticker("ui//options") + }, + onClick: (e5) => { + const offset2 = e5.target.getBoundingClientRect(); + showPropertyMenu({ + superstate: props.superstate, + rect: offset2, + editable: true, + options: [], + field, + fields: props.cols, + contextPath: spaceInfo?.path, + saveField: (newField) => saveField(newField, field), + hide: props.hideColumn, + deleteColumn: props.delColumn, + hidden: props.colsHidden.includes(field.name + field.table) + }); + } + })); } -var TreeNode3 = class { - constructor(_tree, from, index2, _parent) { - this._tree = _tree; - this.from = from; - this.index = index2; - this._parent = _parent; + +// src/core/react/components/UI/Modals/ContextEditor.tsx +var import_react46 = __toESM(require_react()); + +// src/core/react/components/SpaceEditor/SpaceEditor.tsx +var import_react45 = __toESM(require_react()); + +// src/core/utils/contexts/embed.ts +var framePathForSpace = (space2, schema) => { + if (space2.type == "folder") { + return `${space2.path}/#*${schema}`; } - get type() { - return this._tree.type; + if (space2.type == "vault") { + return `/#*${schema}`; } - get name() { - return this._tree.type.name; + return `${space2.path}/#*${schema}`; +}; +var actionPathForSpace = (space2, schema) => { + if (space2.type == "folder") { + return `${space2.path}/#;${schema}`; } - get to() { - return this.from + this._tree.length; + if (space2.type == "vault") { + return `/#;${schema}`; } - nextChild(i4, dir, pos, side, mode2 = 0) { - for (let parent = this; ; ) { - for (let { children, positions } = parent._tree, e5 = dir > 0 ? children.length : -1; i4 != e5; i4 += dir) { - let next = children[i4], start = positions[i4] + parent.from; - if (!checkSide2(side, pos, start, start + next.length)) - continue; - if (next instanceof TreeBuffer2) { - if (mode2 & IterMode2.ExcludeBuffers) - continue; - let index2 = next.findChild(0, next.buffer.length, dir, pos - start, side); - if (index2 > -1) - return new BufferNode2(new BufferContext2(parent, next, i4, start), null, index2); - } else if (mode2 & IterMode2.IncludeAnonymous || (!next.type.isAnonymous || hasChild2(next))) { - let mounted; - if (!(mode2 & IterMode2.IgnoreMounts) && next.props && (mounted = next.prop(NodeProp2.mounted)) && !mounted.overlay) - return new TreeNode3(mounted.tree, start, i4, parent); - let inner = new TreeNode3(next, start, i4, parent); - return mode2 & IterMode2.IncludeAnonymous || !inner.type.isAnonymous ? inner : inner.nextChild(dir < 0 ? next.children.length - 1 : 0, dir, pos, side); + return `${space2.path}/#;${schema}`; +}; +var contextPathForSpace = (space2, schema) => { + if (space2.type == "folder") { + return `${space2.path}/#^${schema}`; + } + if (space2.type == "vault") { + return `/#^${schema}`; + } + return `${space2.path}/#^${schema}`; +}; +var contextViewEmbedStringFromContext = (space2, schema) => `![![${framePathForSpace(space2, schema)}]]`; +var contextEmbedStringFromContext = (space2, schema) => `![![${contextPathForSpace(space2, schema)}]]`; + +// src/core/react/components/SpaceEditor/ActionsList.tsx +var import_react26 = __toESM(require_react()); +var ActionsList = (props) => { + const { pathState } = (0, import_react26.useContext)(PathContext); + const { spaceState } = (0, import_react26.useContext)(SpaceContext); + const [actions, setActions] = import_react26.default.useState([]); + (0, import_react26.useEffect)(() => { + refreshData({ path: pathState.path }); + }, []); + const refreshData = (payload) => { + if (payload.path == pathState?.path) + props.superstate.spaceManager.commandsForSpace(pathState.path).then((f2) => setActions(f2)); + }; + (0, import_react26.useEffect)(() => { + props.superstate.eventsDispatcher.addListener( + "actionStateUpdated", + refreshData + ); + return () => { + props.superstate.eventsDispatcher.removeListener( + "actionStateUpdated", + refreshData + ); + }; + }, [pathState]); + const newAction = (e5) => { + props.superstate.ui.openModal( + i18n_default.labels.newAction, + (_props) => /* @__PURE__ */ import_react26.default.createElement(InputModal, { + value: "", + saveLabel: i18n_default.buttons.save, + hide: _props.hide, + saveValue: (value) => { + props.superstate.spaceManager.createCommand(spaceState.path, { + id: value, + name: value, + type: "actions" + }); } + }) + ); + }; + return /* @__PURE__ */ import_react26.default.createElement("div", { + className: "mk-space-editor" + }, /* @__PURE__ */ import_react26.default.createElement("div", { + className: "mk-space-editor-header" + }, /* @__PURE__ */ import_react26.default.createElement("div", { + className: "mk-space-editor-header-title" + }, /* @__PURE__ */ import_react26.default.createElement("div", { + className: "mk-space-editor-title" + }, i18n_default.subViews.spaceActions), /* @__PURE__ */ import_react26.default.createElement("div", { + className: "mk-space-editor-description" + }, i18n_default.descriptions.spaceActions)), /* @__PURE__ */ import_react26.default.createElement("span", null), /* @__PURE__ */ import_react26.default.createElement("button", { + className: "mk-button-new", + "aria-label": i18n_default.labels.newAction, + onClick: (e5) => newAction(e5), + dangerouslySetInnerHTML: { + __html: props.superstate.ui.getSticker("ui//plus") + } + })), /* @__PURE__ */ import_react26.default.createElement("div", { + className: "mk-space-editor-contents" + }, actions.map((f2, i4) => /* @__PURE__ */ import_react26.default.createElement("div", { + key: i4, + className: "mk-action" + }, /* @__PURE__ */ import_react26.default.createElement("div", { + className: "mk-path" + }, /* @__PURE__ */ import_react26.default.createElement("div", { + className: "mk-path-icon", + dangerouslySetInnerHTML: { + __html: props.superstate.ui.getSticker( + stickerForSchema(f2.schema) + ) + } + }), /* @__PURE__ */ import_react26.default.createElement("div", { + onClick: (e5) => { + props.superstate.ui.openPath( + actionPathForSpace(spaceState, f2.schema.id), + e5.metaKey + ); + props.close(); + } + }, f2.schema.name)), /* @__PURE__ */ import_react26.default.createElement("span", null), /* @__PURE__ */ import_react26.default.createElement("button", { + className: "mk-toolbar-button", + onClick: () => props.superstate.cli.runCommand( + actionPathForSpace(spaceState, f2.schema.id), + { iterations: 0, instanceProps: {}, props: {} } + ), + dangerouslySetInnerHTML: { + __html: props.superstate.ui.getSticker("lucide//play") + } + }), /* @__PURE__ */ import_react26.default.createElement("button", { + className: "mk-toolbar-button", + onClick: () => props.superstate.spaceManager.deleteCommand( + spaceState.path, + f2.schema.id + ), + dangerouslySetInnerHTML: { + __html: props.superstate.ui.getSticker("ui//trash") + } + }))))); +}; + +// src/core/react/components/UI/Menus/properties/linkMenu.tsx +var showLinkMenu = (offset2, superstate, saveLink, options) => { + const suggestions = [...superstate.pathsIndex.values()].filter((f2) => !f2.hidden).map((f2) => ({ + name: f2.displayName, + value: f2.path, + description: f2.path, + icon: f2.label?.sticker, + section: f2.type + })); + const sections = Array.from( + new Set(suggestions.map((f2) => f2.section)) + ).map((f2) => { + return { + name: f2, + value: f2 + }; + }); + return superstate.ui.openMenu(offset2, { + ui: superstate.ui, + multi: false, + editable: true, + value: [], + options: suggestions, + saveOptions: (_15, value) => { + saveLink(value[0]); + }, + placeholder: i18n_default.labels.linkItemSelectPlaceholder, + detail: true, + searchable: true, + showAll: true, + sections, + showSections: true, + ...options ?? {} + }); +}; + +// src/core/react/components/SpaceEditor/SpaceItems.tsx +var import_react40 = __toESM(require_react()); + +// src/core/react/components/UI/Crumbs/PathCrumb.tsx +var import_react28 = __toESM(require_react()); + +// src/core/react/components/UI/Stickers/PathSticker/PathSticker.tsx +var import_react27 = __toESM(require_react()); +var PathStickerView = (props) => { + const { pathState } = props; + const sticker = pathState?.label?.sticker; + const color2 = pathState?.label?.color; + const extension = pathState?.type; + const triggerStickerContextMenu = (e5) => { + if (!pathState) + return; + e5.preventDefault(); + const menuOptions = []; + menuOptions.push({ + name: i18n_default.buttons.changeIcon, + icon: "ui//sticker", + onClick: () => { + props.superstate.ui.openPalette((_props) => /* @__PURE__ */ import_react27.default.createElement(StickerModal_default, { + ui: props.superstate.ui, + hide: _props.hide, + selectedSticker: (emoji) => savePathSticker(props.superstate, pathState?.path, emoji) + })); } - if (mode2 & IterMode2.IncludeAnonymous || !parent.type.isAnonymous) - return null; - if (parent.index >= 0) - i4 = parent.index + dir; - else - i4 = dir < 0 ? -1 : parent._parent._tree.children.length; - parent = parent._parent; - if (!parent) - return null; + }); + menuOptions.push({ + name: i18n_default.buttons.removeIcon, + icon: "ui//file-minus", + onClick: () => { + removeIconsForPaths(props.superstate, [pathState.path]); + } + }); + props.superstate.ui.openMenu( + e5.target.getBoundingClientRect(), + defaultMenu(props.superstate.ui, menuOptions) + ); + return false; + }; + const triggerStickerMenu = (e5) => { + if (pathState?.type == "space") { + props.superstate.ui.openPalette((_props) => /* @__PURE__ */ import_react27.default.createElement(StickerModal_default, { + ui: props.superstate.ui, + hide: _props.hide, + selectedSticker: (emoji) => savePathSticker(props.superstate, pathState.path, emoji) + })); + return; } - } - get firstChild() { - return this.nextChild(0, 1, 0, 4); - } - get lastChild() { - return this.nextChild(this._tree.children.length - 1, -1, 0, 4); - } - childAfter(pos) { - return this.nextChild(0, 1, pos, 2); - } - childBefore(pos) { - return this.nextChild(this._tree.children.length - 1, -1, pos, -2); - } - enter(pos, side, mode2 = 0) { - let mounted; - if (!(mode2 & IterMode2.IgnoreOverlays) && (mounted = this._tree.prop(NodeProp2.mounted)) && mounted.overlay) { - let rPos = pos - this.from; - for (let { from, to: to2 } of mounted.overlay) { - if ((side > 0 ? from <= rPos : from < rPos) && (side < 0 ? to2 >= rPos : to2 > rPos)) - return new TreeNode3(mounted.tree, mounted.overlay[0].from + this.from, -1, this); + props.superstate.ui.openPalette((_props) => /* @__PURE__ */ import_react27.default.createElement(StickerModal_default, { + ui: props.superstate.ui, + hide: _props.hide, + selectedSticker: (emoji) => savePathSticker(props.superstate, pathState.path, emoji) + })); + }; + const [stickerType, stickerPath] = parseStickerString(sticker); + return /* @__PURE__ */ import_react27.default.createElement("div", { + className: `mk-path-icon ${sticker ? "" : "mk-path-icon-placeholder"}` + }, stickerType == "image" ? /* @__PURE__ */ import_react27.default.createElement("img", { + src: props.superstate.ui.getUIPath( + props.superstate.imagesCache.get(stickerPath) + ) + }) : /* @__PURE__ */ import_react27.default.createElement("button", { + "aria-label": i18n_default.buttons.changeIcon, + onContextMenu: triggerStickerContextMenu, + style: color2?.length > 0 ? { + "--label-color": `${color2}`, + "--icon-color": `#ffffff` + } : { + "--icon-color": `var(--mk-ui-text-secondary)` + }, + dangerouslySetInnerHTML: { + __html: props.superstate.ui.getSticker(sticker) + }, + onClick: (e5) => props.editable && triggerStickerMenu(e5) + })); +}; +var PathStickerContainer = (props) => { + const [cache2, setCache] = (0, import_react27.useState)(null); + const reloadCache = () => { + setCache(props.superstate.pathsIndex.get(props.path)); + }; + const reloadIcon = (payload) => { + if (payload.path == props.path) { + reloadCache(); + } + }; + (0, import_react27.useEffect)(() => { + reloadCache(); + props.superstate.eventsDispatcher.addListener( + "pathStateUpdated", + reloadIcon + ); + return () => { + props.superstate.eventsDispatcher.removeListener( + "pathStateUpdated", + reloadIcon + ); + }; + }, [props.path]); + return cache2 ? /* @__PURE__ */ import_react27.default.createElement(PathStickerView, { + superstate: props.superstate, + pathState: cache2, + editable: true + }) : /* @__PURE__ */ import_react27.default.createElement(import_react27.default.Fragment, null); +}; + +// src/core/react/components/UI/Crumbs/PathCrumb.tsx +var PathCrumb = (props) => { + const path2 = (0, import_react28.useMemo)( + () => props.source && props.path ? props.superstate.spaceManager.resolvePath(props.path, props.source) : props.path, + [props.source, props.path] + ); + const [cache2, setCache] = (0, import_react28.useState)( + props.superstate.pathsIndex.get(path2) + ); + const reloadCache = () => { + setCache(props.superstate.pathsIndex.get(path2)); + }; + const reloadIcon = (payload) => { + if (payload.path == path2) { + reloadCache(); + } + }; + (0, import_react28.useEffect)(() => { + props.superstate.eventsDispatcher.addListener( + "pathStateUpdated", + reloadIcon + ); + reloadCache(); + return () => { + props.superstate.eventsDispatcher.removeListener( + "pathStateUpdated", + reloadIcon + ); + }; + }, [path2]); + return /* @__PURE__ */ import_react28.default.createElement("div", { + className: "mk-path", + "aria-label": path2, + onClick: () => props.superstate.ui.openPath(cache2?.path ?? path2, false), + onContextMenu: (e5) => cache2 && showPathContextMenu(props.superstate, cache2.path, null, { + x: e5.clientX, + y: e5.clientY, + width: 0, + height: 0 + }) + }, cache2 && /* @__PURE__ */ import_react28.default.createElement(PathStickerView, { + superstate: props.superstate, + pathState: cache2 + }), /* @__PURE__ */ import_react28.default.createElement("span", null, (!props.hideName && cache2?.displayName) ?? path2), props.children); +}; + +// src/core/react/components/UI/Menus/properties/datePickerMenu.tsx +var import_react30 = __toESM(require_react()); + +// node_modules/react-day-picker/dist/index.esm.js +var import_react29 = __toESM(require_react()); +var __assign = function() { + __assign = Object.assign || function __assign4(t5) { + for (var s4, i4 = 1, n3 = arguments.length; i4 < n3; i4++) { + s4 = arguments[i4]; + for (var p in s4) + if (Object.prototype.hasOwnProperty.call(s4, p)) + t5[p] = s4[p]; + } + return t5; + }; + return __assign.apply(this, arguments); +}; +function __rest(s4, e5) { + var t5 = {}; + for (var p in s4) + if (Object.prototype.hasOwnProperty.call(s4, p) && e5.indexOf(p) < 0) + t5[p] = s4[p]; + if (s4 != null && typeof Object.getOwnPropertySymbols === "function") + for (var i4 = 0, p = Object.getOwnPropertySymbols(s4); i4 < p.length; i4++) { + if (e5.indexOf(p[i4]) < 0 && Object.prototype.propertyIsEnumerable.call(s4, p[i4])) + t5[p[i4]] = s4[p[i4]]; + } + return t5; +} +function __spreadArray(to2, from, pack) { + if (pack || arguments.length === 2) + for (var i4 = 0, l2 = from.length, ar; i4 < l2; i4++) { + if (ar || !(i4 in from)) { + if (!ar) + ar = Array.prototype.slice.call(from, 0, i4); + ar[i4] = from[i4]; } } - return this.nextChild(0, 1, pos, side, mode2); - } - nextSignificantParent() { - let val = this; - while (val.type.isAnonymous && val._parent) - val = val._parent; - return val; + return to2.concat(ar || Array.prototype.slice.call(from)); +} +var jsxRuntime = { exports: {} }; +var reactJsxRuntime_production_min = {}; +var hasRequiredReactJsxRuntime_production_min; +function requireReactJsxRuntime_production_min() { + if (hasRequiredReactJsxRuntime_production_min) + return reactJsxRuntime_production_min; + hasRequiredReactJsxRuntime_production_min = 1; + var f2 = import_react29.default, k2 = Symbol.for("react.element"), l2 = Symbol.for("react.fragment"), m4 = Object.prototype.hasOwnProperty, n3 = f2.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.ReactCurrentOwner, p = { key: true, ref: true, __self: true, __source: true }; + function q2(c3, a4, g) { + var b2, d4 = {}, e5 = null, h3 = null; + void 0 !== g && (e5 = "" + g); + void 0 !== a4.key && (e5 = "" + a4.key); + void 0 !== a4.ref && (h3 = a4.ref); + for (b2 in a4) + m4.call(a4, b2) && !p.hasOwnProperty(b2) && (d4[b2] = a4[b2]); + if (c3 && c3.defaultProps) + for (b2 in a4 = c3.defaultProps, a4) + void 0 === d4[b2] && (d4[b2] = a4[b2]); + return { $$typeof: k2, type: c3, key: e5, ref: h3, props: d4, _owner: n3.current }; } - get parent() { - return this._parent ? this._parent.nextSignificantParent() : null; + reactJsxRuntime_production_min.Fragment = l2; + reactJsxRuntime_production_min.jsx = q2; + reactJsxRuntime_production_min.jsxs = q2; + return reactJsxRuntime_production_min; +} +if (true) { + jsxRuntime.exports = requireReactJsxRuntime_production_min(); +} else { + jsxRuntime.exports = requireReactJsxRuntime_development(); +} +var jsxRuntimeExports = jsxRuntime.exports; +function isDayPickerMultiple(props) { + return props.mode === "multiple"; +} +function isDayPickerRange(props) { + return props.mode === "range"; +} +function isDayPickerSingle(props) { + return props.mode === "single"; +} +var defaultClassNames = { + root: "rdp", + multiple_months: "rdp-multiple_months", + with_weeknumber: "rdp-with_weeknumber", + vhidden: "rdp-vhidden", + button_reset: "rdp-button_reset", + button: "rdp-button", + caption: "rdp-caption", + caption_start: "rdp-caption_start", + caption_end: "rdp-caption_end", + caption_between: "rdp-caption_between", + caption_label: "rdp-caption_label", + caption_dropdowns: "rdp-caption_dropdowns", + dropdown: "rdp-dropdown", + dropdown_month: "rdp-dropdown_month", + dropdown_year: "rdp-dropdown_year", + dropdown_icon: "rdp-dropdown_icon", + months: "rdp-months", + month: "rdp-month", + table: "rdp-table", + tbody: "rdp-tbody", + tfoot: "rdp-tfoot", + head: "rdp-head", + head_row: "rdp-head_row", + head_cell: "rdp-head_cell", + nav: "rdp-nav", + nav_button: "rdp-nav_button", + nav_button_previous: "rdp-nav_button_previous", + nav_button_next: "rdp-nav_button_next", + nav_icon: "rdp-nav_icon", + row: "rdp-row", + weeknumber: "rdp-weeknumber", + cell: "rdp-cell", + day: "rdp-day", + day_today: "rdp-day_today", + day_outside: "rdp-day_outside", + day_selected: "rdp-day_selected", + day_disabled: "rdp-day_disabled", + day_hidden: "rdp-day_hidden", + day_range_start: "rdp-day_range_start", + day_range_end: "rdp-day_range_end", + day_range_middle: "rdp-day_range_middle" +}; +function formatCaption(month, options) { + return format(month, "LLLL y", options); +} +function formatDay(day, options) { + return format(day, "d", options); +} +function formatMonthCaption(month, options) { + return format(month, "LLLL", options); +} +function formatWeekNumber(weekNumber) { + return "".concat(weekNumber); +} +function formatWeekdayName(weekday, options) { + return format(weekday, "cccccc", options); +} +function formatYearCaption(year, options) { + return format(year, "yyyy", options); +} +var formatters3 = /* @__PURE__ */ Object.freeze({ + __proto__: null, + formatCaption, + formatDay, + formatMonthCaption, + formatWeekNumber, + formatWeekdayName, + formatYearCaption +}); +var labelDay = function(day, activeModifiers, options) { + return format(day, "do MMMM (EEEE)", options); +}; +var labelMonthDropdown = function() { + return "Month: "; +}; +var labelNext = function() { + return "Go to next month"; +}; +var labelPrevious = function() { + return "Go to previous month"; +}; +var labelWeekday = function(day, options) { + return format(day, "cccc", options); +}; +var labelWeekNumber = function(n3) { + return "Week n. ".concat(n3); +}; +var labelYearDropdown = function() { + return "Year: "; +}; +var labels = /* @__PURE__ */ Object.freeze({ + __proto__: null, + labelDay, + labelMonthDropdown, + labelNext, + labelPrevious, + labelWeekNumber, + labelWeekday, + labelYearDropdown +}); +function getDefaultContextValues() { + var captionLayout = "buttons"; + var classNames13 = defaultClassNames; + var locale2 = en_US_default; + var modifiersClassNames = {}; + var modifiers = {}; + var numberOfMonths = 1; + var styles2 = {}; + var today = new Date(); + return { + captionLayout, + classNames: classNames13, + formatters: formatters3, + labels, + locale: locale2, + modifiersClassNames, + modifiers, + numberOfMonths, + styles: styles2, + today, + mode: "default" + }; +} +function parseFromToProps(props) { + var fromYear = props.fromYear, toYear = props.toYear, fromMonth = props.fromMonth, toMonth = props.toMonth; + var fromDate = props.fromDate, toDate2 = props.toDate; + if (fromMonth) { + fromDate = startOfMonth(fromMonth); + } else if (fromYear) { + fromDate = new Date(fromYear, 0, 1); } - get nextSibling() { - return this._parent && this.index >= 0 ? this._parent.nextChild(this.index + 1, 1, 0, 4) : null; + if (toMonth) { + toDate2 = endOfMonth(toMonth); + } else if (toYear) { + toDate2 = new Date(toYear, 11, 31); } - get prevSibling() { - return this._parent && this.index >= 0 ? this._parent.nextChild(this.index - 1, -1, 0, 4) : null; + return { + fromDate: fromDate ? startOfDay(fromDate) : void 0, + toDate: toDate2 ? startOfDay(toDate2) : void 0 + }; +} +var DayPickerContext = (0, import_react29.createContext)(void 0); +function DayPickerProvider(props) { + var _a; + var initialProps = props.initialProps; + var defaultContextValues = getDefaultContextValues(); + var _b = parseFromToProps(initialProps), fromDate = _b.fromDate, toDate2 = _b.toDate; + var captionLayout = (_a = initialProps.captionLayout) !== null && _a !== void 0 ? _a : defaultContextValues.captionLayout; + if (captionLayout !== "buttons" && (!fromDate || !toDate2)) { + captionLayout = "buttons"; } - cursor(mode2 = 0) { - return new TreeCursor2(this, mode2); + var onSelect; + if (isDayPickerSingle(initialProps) || isDayPickerMultiple(initialProps) || isDayPickerRange(initialProps)) { + onSelect = initialProps.onSelect; } - get tree() { - return this._tree; + var value = __assign(__assign(__assign({}, defaultContextValues), initialProps), { captionLayout, classNames: __assign(__assign({}, defaultContextValues.classNames), initialProps.classNames), components: __assign({}, initialProps.components), formatters: __assign(__assign({}, defaultContextValues.formatters), initialProps.formatters), fromDate, labels: __assign(__assign({}, defaultContextValues.labels), initialProps.labels), mode: initialProps.mode || defaultContextValues.mode, modifiers: __assign(__assign({}, defaultContextValues.modifiers), initialProps.modifiers), modifiersClassNames: __assign(__assign({}, defaultContextValues.modifiersClassNames), initialProps.modifiersClassNames), onSelect, styles: __assign(__assign({}, defaultContextValues.styles), initialProps.styles), toDate: toDate2 }); + return jsxRuntimeExports.jsx(DayPickerContext.Provider, { value, children: props.children }); +} +function useDayPicker() { + var context = (0, import_react29.useContext)(DayPickerContext); + if (!context) { + throw new Error("useDayPicker must be used within a DayPickerProvider."); } - toTree() { - return this._tree; + return context; +} +function CaptionLabel(props) { + var _a = useDayPicker(), locale2 = _a.locale, classNames13 = _a.classNames, styles2 = _a.styles, formatCaption2 = _a.formatters.formatCaption; + return jsxRuntimeExports.jsx("div", { className: classNames13.caption_label, style: styles2.caption_label, "aria-live": "polite", role: "presentation", id: props.id, children: formatCaption2(props.displayMonth, { locale: locale2 }) }); +} +function IconDropdown(props) { + return jsxRuntimeExports.jsx("svg", __assign({ width: "8px", height: "8px", viewBox: "0 0 120 120", "data-testid": "iconDropdown" }, props, { children: jsxRuntimeExports.jsx("path", { d: "M4.22182541,48.2218254 C8.44222828,44.0014225 15.2388494,43.9273804 19.5496459,47.9996989 L19.7781746,48.2218254 L60,88.443 L100.221825,48.2218254 C104.442228,44.0014225 111.238849,43.9273804 115.549646,47.9996989 L115.778175,48.2218254 C119.998577,52.4422283 120.07262,59.2388494 116.000301,63.5496459 L115.778175,63.7781746 L67.7781746,111.778175 C63.5577717,115.998577 56.7611506,116.07262 52.4503541,112.000301 L52.2218254,111.778175 L4.22182541,63.7781746 C-0.0739418023,59.4824074 -0.0739418023,52.5175926 4.22182541,48.2218254 Z", fill: "currentColor", fillRule: "nonzero" }) })); +} +function Dropdown(props) { + var _a, _b; + var onChange = props.onChange, value = props.value, children = props.children, caption = props.caption, className = props.className, style = props.style; + var dayPicker = useDayPicker(); + var IconDropdownComponent = (_b = (_a = dayPicker.components) === null || _a === void 0 ? void 0 : _a.IconDropdown) !== null && _b !== void 0 ? _b : IconDropdown; + return jsxRuntimeExports.jsxs("div", { className, style, children: [jsxRuntimeExports.jsx("span", { className: dayPicker.classNames.vhidden, children: props["aria-label"] }), jsxRuntimeExports.jsx("select", { name: props.name, "aria-label": props["aria-label"], className: dayPicker.classNames.dropdown, style: dayPicker.styles.dropdown, value, onChange, children }), jsxRuntimeExports.jsxs("div", { className: dayPicker.classNames.caption_label, style: dayPicker.styles.caption_label, "aria-hidden": "true", children: [caption, jsxRuntimeExports.jsx(IconDropdownComponent, { className: dayPicker.classNames.dropdown_icon, style: dayPicker.styles.dropdown_icon })] })] }); +} +function MonthsDropdown(props) { + var _a; + var _b = useDayPicker(), fromDate = _b.fromDate, toDate2 = _b.toDate, styles2 = _b.styles, locale2 = _b.locale, formatMonthCaption2 = _b.formatters.formatMonthCaption, classNames13 = _b.classNames, components = _b.components, labelMonthDropdown2 = _b.labels.labelMonthDropdown; + if (!fromDate) + return jsxRuntimeExports.jsx(jsxRuntimeExports.Fragment, {}); + if (!toDate2) + return jsxRuntimeExports.jsx(jsxRuntimeExports.Fragment, {}); + var dropdownMonths = []; + if (isSameYear(fromDate, toDate2)) { + var date = startOfMonth(fromDate); + for (var month = fromDate.getMonth(); month <= toDate2.getMonth(); month++) { + dropdownMonths.push(setMonth(date, month)); + } + } else { + var date = startOfMonth(new Date()); + for (var month = 0; month <= 11; month++) { + dropdownMonths.push(setMonth(date, month)); + } } - resolve(pos, side = 0) { - return resolveNode2(this, pos, side, false); + var handleChange = function(e5) { + var selectedMonth = Number(e5.target.value); + var newMonth = setMonth(startOfMonth(props.displayMonth), selectedMonth); + props.onChange(newMonth); + }; + var DropdownComponent2 = (_a = components === null || components === void 0 ? void 0 : components.Dropdown) !== null && _a !== void 0 ? _a : Dropdown; + return jsxRuntimeExports.jsx(DropdownComponent2, { name: "months", "aria-label": labelMonthDropdown2(), className: classNames13.dropdown_month, style: styles2.dropdown_month, onChange: handleChange, value: props.displayMonth.getMonth(), caption: formatMonthCaption2(props.displayMonth, { locale: locale2 }), children: dropdownMonths.map(function(m4) { + return jsxRuntimeExports.jsx("option", { value: m4.getMonth(), children: formatMonthCaption2(m4, { locale: locale2 }) }, m4.getMonth()); + }) }); +} +function YearsDropdown(props) { + var _a; + var displayMonth = props.displayMonth; + var _b = useDayPicker(), fromDate = _b.fromDate, toDate2 = _b.toDate, locale2 = _b.locale, styles2 = _b.styles, classNames13 = _b.classNames, components = _b.components, formatYearCaption2 = _b.formatters.formatYearCaption, labelYearDropdown2 = _b.labels.labelYearDropdown; + var years = []; + if (!fromDate) + return jsxRuntimeExports.jsx(jsxRuntimeExports.Fragment, {}); + if (!toDate2) + return jsxRuntimeExports.jsx(jsxRuntimeExports.Fragment, {}); + var fromYear = fromDate.getFullYear(); + var toYear = toDate2.getFullYear(); + for (var year = fromYear; year <= toYear; year++) { + years.push(setYear(startOfYear(new Date()), year)); } - resolveInner(pos, side = 0) { - return resolveNode2(this, pos, side, true); + var handleChange = function(e5) { + var newMonth = setYear(startOfMonth(displayMonth), Number(e5.target.value)); + props.onChange(newMonth); + }; + var DropdownComponent2 = (_a = components === null || components === void 0 ? void 0 : components.Dropdown) !== null && _a !== void 0 ? _a : Dropdown; + return jsxRuntimeExports.jsx(DropdownComponent2, { name: "years", "aria-label": labelYearDropdown2(), className: classNames13.dropdown_year, style: styles2.dropdown_year, onChange: handleChange, value: displayMonth.getFullYear(), caption: formatYearCaption2(displayMonth, { locale: locale2 }), children: years.map(function(year2) { + return jsxRuntimeExports.jsx("option", { value: year2.getFullYear(), children: formatYearCaption2(year2, { locale: locale2 }) }, year2.getFullYear()); + }) }); +} +function useControlledValue(defaultValue2, controlledValue) { + var _a = (0, import_react29.useState)(defaultValue2), uncontrolledValue = _a[0], setValue = _a[1]; + var value = controlledValue === void 0 ? uncontrolledValue : controlledValue; + return [value, setValue]; +} +function getInitialMonth(context) { + var month = context.month, defaultMonth = context.defaultMonth, today = context.today; + var initialMonth = month || defaultMonth || today || new Date(); + var toDate2 = context.toDate, fromDate = context.fromDate, _a = context.numberOfMonths, numberOfMonths = _a === void 0 ? 1 : _a; + if (toDate2 && differenceInCalendarMonths(toDate2, initialMonth) < 0) { + var offset2 = -1 * (numberOfMonths - 1); + initialMonth = addMonths(toDate2, offset2); } - enterUnfinishedNodesBefore(pos) { - return enterUnfinishedNodesBefore2(this, pos); + if (fromDate && differenceInCalendarMonths(initialMonth, fromDate) < 0) { + initialMonth = fromDate; } - getChild(type, before = null, after = null) { - let r2 = getChildren2(this, type, before, after); - return r2.length ? r2[0] : null; + return startOfMonth(initialMonth); +} +function useNavigationState() { + var context = useDayPicker(); + var initialMonth = getInitialMonth(context); + var _a = useControlledValue(initialMonth, context.month), month = _a[0], setMonth2 = _a[1]; + var goToMonth = function(date) { + var _a2; + if (context.disableNavigation) + return; + var month2 = startOfMonth(date); + setMonth2(month2); + (_a2 = context.onMonthChange) === null || _a2 === void 0 ? void 0 : _a2.call(context, month2); + }; + return [month, goToMonth]; +} +function getDisplayMonths(month, _a) { + var reverseMonths = _a.reverseMonths, numberOfMonths = _a.numberOfMonths; + var start = startOfMonth(month); + var end = startOfMonth(addMonths(start, numberOfMonths)); + var monthsDiff = differenceInCalendarMonths(end, start); + var months = []; + for (var i4 = 0; i4 < monthsDiff; i4++) { + var nextMonth = addMonths(start, i4); + months.push(nextMonth); } - getChildren(type, before = null, after = null) { - return getChildren2(this, type, before, after); + if (reverseMonths) + months = months.reverse(); + return months; +} +function getNextMonth(startingMonth, options) { + if (options.disableNavigation) { + return void 0; } - toString() { - return this._tree.toString(); + var toDate2 = options.toDate, pagedNavigation = options.pagedNavigation, _a = options.numberOfMonths, numberOfMonths = _a === void 0 ? 1 : _a; + var offset2 = pagedNavigation ? numberOfMonths : 1; + var month = startOfMonth(startingMonth); + if (!toDate2) { + return addMonths(month, offset2); } - get node() { - return this; + var monthsDiff = differenceInCalendarMonths(toDate2, startingMonth); + if (monthsDiff < numberOfMonths) { + return void 0; } - matchContext(context) { - return matchNodeContext2(this, context); + return addMonths(month, offset2); +} +function getPreviousMonth(startingMonth, options) { + if (options.disableNavigation) { + return void 0; } -}; -function getChildren2(node, type, before, after) { - let cur = node.cursor(), result = []; - if (!cur.firstChild()) - return result; - if (before != null) { - while (!cur.type.is(before)) - if (!cur.nextSibling()) - return result; + var fromDate = options.fromDate, pagedNavigation = options.pagedNavigation, _a = options.numberOfMonths, numberOfMonths = _a === void 0 ? 1 : _a; + var offset2 = pagedNavigation ? numberOfMonths : 1; + var month = startOfMonth(startingMonth); + if (!fromDate) { + return addMonths(month, -offset2); } - for (; ; ) { - if (after != null && cur.type.is(after)) - return result; - if (cur.type.is(type)) - result.push(cur.node); - if (!cur.nextSibling()) - return after == null ? result : []; + var monthsDiff = differenceInCalendarMonths(month, fromDate); + if (monthsDiff <= 0) { + return void 0; } + return addMonths(month, -offset2); } -function matchNodeContext2(node, context, i4 = context.length - 1) { - for (let p = node.parent; i4 >= 0; p = p.parent) { - if (!p) - return false; - if (!p.type.isAnonymous) { - if (context[i4] && context[i4] != p.name) - return false; - i4--; +var NavigationContext = (0, import_react29.createContext)(void 0); +function NavigationProvider(props) { + var dayPicker = useDayPicker(); + var _a = useNavigationState(), currentMonth = _a[0], goToMonth = _a[1]; + var displayMonths = getDisplayMonths(currentMonth, dayPicker); + var nextMonth = getNextMonth(currentMonth, dayPicker); + var previousMonth = getPreviousMonth(currentMonth, dayPicker); + var isDateDisplayed = function(date) { + return displayMonths.some(function(displayMonth) { + return isSameMonth(date, displayMonth); + }); + }; + var goToDate = function(date, refDate) { + if (isDateDisplayed(date)) { + return; } - } - return true; + if (refDate && isBefore(date, refDate)) { + goToMonth(addMonths(date, 1 + dayPicker.numberOfMonths * -1)); + } else { + goToMonth(date); + } + }; + var value = { + currentMonth, + displayMonths, + goToMonth, + goToDate, + previousMonth, + nextMonth, + isDateDisplayed + }; + return jsxRuntimeExports.jsx(NavigationContext.Provider, { value, children: props.children }); } -var BufferContext2 = class { - constructor(parent, buffer, index2, start) { - this.parent = parent; - this.buffer = buffer; - this.index = index2; - this.start = start; - } -}; -var BufferNode2 = class { - constructor(context, _parent, index2) { - this.context = context; - this._parent = _parent; - this.index = index2; - this.type = context.buffer.set.types[context.buffer.buffer[index2]]; +function useNavigation() { + var context = (0, import_react29.useContext)(NavigationContext); + if (!context) { + throw new Error("useNavigation must be used within a NavigationProvider"); } - get name() { - return this.type.name; + return context; +} +function CaptionDropdowns(props) { + var _a; + var _b = useDayPicker(), classNames13 = _b.classNames, styles2 = _b.styles, components = _b.components; + var goToMonth = useNavigation().goToMonth; + var handleMonthChange = function(newMonth) { + goToMonth(addMonths(newMonth, props.displayIndex ? -props.displayIndex : 0)); + }; + var CaptionLabelComponent = (_a = components === null || components === void 0 ? void 0 : components.CaptionLabel) !== null && _a !== void 0 ? _a : CaptionLabel; + var captionLabel = jsxRuntimeExports.jsx(CaptionLabelComponent, { id: props.id, displayMonth: props.displayMonth }); + return jsxRuntimeExports.jsxs("div", { className: classNames13.caption_dropdowns, style: styles2.caption_dropdowns, children: [jsxRuntimeExports.jsx("div", { className: classNames13.vhidden, children: captionLabel }), jsxRuntimeExports.jsx(MonthsDropdown, { onChange: handleMonthChange, displayMonth: props.displayMonth }), jsxRuntimeExports.jsx(YearsDropdown, { onChange: handleMonthChange, displayMonth: props.displayMonth })] }); +} +function IconLeft(props) { + return jsxRuntimeExports.jsx("svg", __assign({ width: "16px", height: "16px", viewBox: "0 0 120 120" }, props, { children: jsxRuntimeExports.jsx("path", { d: "M69.490332,3.34314575 C72.6145263,0.218951416 77.6798462,0.218951416 80.8040405,3.34314575 C83.8617626,6.40086786 83.9268205,11.3179931 80.9992143,14.4548388 L80.8040405,14.6568542 L35.461,60 L80.8040405,105.343146 C83.8617626,108.400868 83.9268205,113.317993 80.9992143,116.454839 L80.8040405,116.656854 C77.7463184,119.714576 72.8291931,119.779634 69.6923475,116.852028 L69.490332,116.656854 L18.490332,65.6568542 C15.4326099,62.5991321 15.367552,57.6820069 18.2951583,54.5451612 L18.490332,54.3431458 L69.490332,3.34314575 Z", fill: "currentColor", fillRule: "nonzero" }) })); +} +function IconRight(props) { + return jsxRuntimeExports.jsx("svg", __assign({ width: "16px", height: "16px", viewBox: "0 0 120 120" }, props, { children: jsxRuntimeExports.jsx("path", { d: "M49.8040405,3.34314575 C46.6798462,0.218951416 41.6145263,0.218951416 38.490332,3.34314575 C35.4326099,6.40086786 35.367552,11.3179931 38.2951583,14.4548388 L38.490332,14.6568542 L83.8333725,60 L38.490332,105.343146 C35.4326099,108.400868 35.367552,113.317993 38.2951583,116.454839 L38.490332,116.656854 C41.5480541,119.714576 46.4651794,119.779634 49.602025,116.852028 L49.8040405,116.656854 L100.804041,65.6568542 C103.861763,62.5991321 103.926821,57.6820069 100.999214,54.5451612 L100.804041,54.3431458 L49.8040405,3.34314575 Z", fill: "currentColor" }) })); +} +var Button = (0, import_react29.forwardRef)(function(props, ref2) { + var _a = useDayPicker(), classNames13 = _a.classNames, styles2 = _a.styles; + var classNamesArr = [classNames13.button_reset, classNames13.button]; + if (props.className) { + classNamesArr.push(props.className); } - get from() { - return this.context.start + this.context.buffer.buffer[this.index + 1]; + var className = classNamesArr.join(" "); + var style = __assign(__assign({}, styles2.button_reset), styles2.button); + if (props.style) { + Object.assign(style, props.style); } - get to() { - return this.context.start + this.context.buffer.buffer[this.index + 2]; + return jsxRuntimeExports.jsx("button", __assign({}, props, { ref: ref2, type: "button", className, style })); +}); +function Navigation(props) { + var _a, _b; + var _c = useDayPicker(), dir = _c.dir, locale2 = _c.locale, classNames13 = _c.classNames, styles2 = _c.styles, _d = _c.labels, labelPrevious2 = _d.labelPrevious, labelNext2 = _d.labelNext, components = _c.components; + if (!props.nextMonth && !props.previousMonth) { + return jsxRuntimeExports.jsx(jsxRuntimeExports.Fragment, {}); } - child(dir, pos, side) { - let { buffer } = this.context; - let index2 = buffer.findChild(this.index + 4, buffer.buffer[this.index + 3], dir, pos - this.context.start, side); - return index2 < 0 ? null : new BufferNode2(this.context, this, index2); + var previousLabel = labelPrevious2(props.previousMonth, { locale: locale2 }); + var previousClassName = [ + classNames13.nav_button, + classNames13.nav_button_previous + ].join(" "); + var nextLabel = labelNext2(props.nextMonth, { locale: locale2 }); + var nextClassName = [ + classNames13.nav_button, + classNames13.nav_button_next + ].join(" "); + var IconRightComponent = (_a = components === null || components === void 0 ? void 0 : components.IconRight) !== null && _a !== void 0 ? _a : IconRight; + var IconLeftComponent = (_b = components === null || components === void 0 ? void 0 : components.IconLeft) !== null && _b !== void 0 ? _b : IconLeft; + return jsxRuntimeExports.jsxs("div", { className: classNames13.nav, style: styles2.nav, children: [!props.hidePrevious && jsxRuntimeExports.jsx(Button, { name: "previous-month", "aria-label": previousLabel, className: previousClassName, style: styles2.nav_button_previous, disabled: !props.previousMonth, onClick: props.onPreviousClick, children: dir === "rtl" ? jsxRuntimeExports.jsx(IconRightComponent, { className: classNames13.nav_icon, style: styles2.nav_icon }) : jsxRuntimeExports.jsx(IconLeftComponent, { className: classNames13.nav_icon, style: styles2.nav_icon }) }), !props.hideNext && jsxRuntimeExports.jsx(Button, { name: "next-month", "aria-label": nextLabel, className: nextClassName, style: styles2.nav_button_next, disabled: !props.nextMonth, onClick: props.onNextClick, children: dir === "rtl" ? jsxRuntimeExports.jsx(IconLeftComponent, { className: classNames13.nav_icon, style: styles2.nav_icon }) : jsxRuntimeExports.jsx(IconRightComponent, { className: classNames13.nav_icon, style: styles2.nav_icon }) })] }); +} +function CaptionNavigation(props) { + var numberOfMonths = useDayPicker().numberOfMonths; + var _a = useNavigation(), previousMonth = _a.previousMonth, nextMonth = _a.nextMonth, goToMonth = _a.goToMonth, displayMonths = _a.displayMonths; + var displayIndex = displayMonths.findIndex(function(month) { + return isSameMonth(props.displayMonth, month); + }); + var isFirst = displayIndex === 0; + var isLast = displayIndex === displayMonths.length - 1; + var hideNext = numberOfMonths > 1 && (isFirst || !isLast); + var hidePrevious = numberOfMonths > 1 && (isLast || !isFirst); + var handlePreviousClick = function() { + if (!previousMonth) + return; + goToMonth(previousMonth); + }; + var handleNextClick = function() { + if (!nextMonth) + return; + goToMonth(nextMonth); + }; + return jsxRuntimeExports.jsx(Navigation, { displayMonth: props.displayMonth, hideNext, hidePrevious, nextMonth, previousMonth, onPreviousClick: handlePreviousClick, onNextClick: handleNextClick }); +} +function Caption(props) { + var _a; + var _b = useDayPicker(), classNames13 = _b.classNames, disableNavigation = _b.disableNavigation, styles2 = _b.styles, captionLayout = _b.captionLayout, components = _b.components; + var CaptionLabelComponent = (_a = components === null || components === void 0 ? void 0 : components.CaptionLabel) !== null && _a !== void 0 ? _a : CaptionLabel; + var caption; + if (disableNavigation) { + caption = jsxRuntimeExports.jsx(CaptionLabelComponent, { id: props.id, displayMonth: props.displayMonth }); + } else if (captionLayout === "dropdown") { + caption = jsxRuntimeExports.jsx(CaptionDropdowns, { displayMonth: props.displayMonth, id: props.id }); + } else if (captionLayout === "dropdown-buttons") { + caption = jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment, { children: [jsxRuntimeExports.jsx(CaptionDropdowns, { displayMonth: props.displayMonth, displayIndex: props.displayIndex, id: props.id }), jsxRuntimeExports.jsx(CaptionNavigation, { displayMonth: props.displayMonth, displayIndex: props.displayIndex, id: props.id })] }); + } else { + caption = jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment, { children: [jsxRuntimeExports.jsx(CaptionLabelComponent, { id: props.id, displayMonth: props.displayMonth, displayIndex: props.displayIndex }), jsxRuntimeExports.jsx(CaptionNavigation, { displayMonth: props.displayMonth, id: props.id })] }); } - get firstChild() { - return this.child(1, 0, 4); + return jsxRuntimeExports.jsx("div", { className: classNames13.caption, style: styles2.caption, children: caption }); +} +function Footer(props) { + var _a = useDayPicker(), footer = _a.footer, styles2 = _a.styles, tfoot = _a.classNames.tfoot; + if (!footer) + return jsxRuntimeExports.jsx(jsxRuntimeExports.Fragment, {}); + return jsxRuntimeExports.jsx("tfoot", { className: tfoot, style: styles2.tfoot, children: jsxRuntimeExports.jsx("tr", { children: jsxRuntimeExports.jsx("td", { colSpan: 8, children: footer }) }) }); +} +function getWeekdays(locale2, weekStartsOn, ISOWeek) { + var start = ISOWeek ? startOfISOWeek(new Date()) : startOfWeek(new Date(), { locale: locale2, weekStartsOn }); + var days = []; + for (var i4 = 0; i4 < 7; i4++) { + var day = addDays(start, i4); + days.push(day); } - get lastChild() { - return this.child(-1, 0, 4); + return days; +} +function HeadRow() { + var _a = useDayPicker(), classNames13 = _a.classNames, styles2 = _a.styles, showWeekNumber = _a.showWeekNumber, locale2 = _a.locale, weekStartsOn = _a.weekStartsOn, ISOWeek = _a.ISOWeek, formatWeekdayName2 = _a.formatters.formatWeekdayName, labelWeekday2 = _a.labels.labelWeekday; + var weekdays = getWeekdays(locale2, weekStartsOn, ISOWeek); + return jsxRuntimeExports.jsxs("tr", { style: styles2.head_row, className: classNames13.head_row, children: [showWeekNumber && jsxRuntimeExports.jsx("td", { style: styles2.head_cell, className: classNames13.head_cell }), weekdays.map(function(weekday, i4) { + return jsxRuntimeExports.jsx("th", { scope: "col", className: classNames13.head_cell, style: styles2.head_cell, "aria-label": labelWeekday2(weekday, { locale: locale2 }), children: formatWeekdayName2(weekday, { locale: locale2 }) }, i4); + })] }); +} +function Head() { + var _a; + var _b = useDayPicker(), classNames13 = _b.classNames, styles2 = _b.styles, components = _b.components; + var HeadRowComponent = (_a = components === null || components === void 0 ? void 0 : components.HeadRow) !== null && _a !== void 0 ? _a : HeadRow; + return jsxRuntimeExports.jsx("thead", { style: styles2.head, className: classNames13.head, children: jsxRuntimeExports.jsx(HeadRowComponent, {}) }); +} +function DayContent(props) { + var _a = useDayPicker(), locale2 = _a.locale, formatDay2 = _a.formatters.formatDay; + return jsxRuntimeExports.jsx(jsxRuntimeExports.Fragment, { children: formatDay2(props.date, { locale: locale2 }) }); +} +var SelectMultipleContext = (0, import_react29.createContext)(void 0); +function SelectMultipleProvider(props) { + if (!isDayPickerMultiple(props.initialProps)) { + var emptyContextValue = { + selected: void 0, + modifiers: { + disabled: [] + } + }; + return jsxRuntimeExports.jsx(SelectMultipleContext.Provider, { value: emptyContextValue, children: props.children }); } - childAfter(pos) { - return this.child(1, pos, 2); + return jsxRuntimeExports.jsx(SelectMultipleProviderInternal, { initialProps: props.initialProps, children: props.children }); +} +function SelectMultipleProviderInternal(_a) { + var initialProps = _a.initialProps, children = _a.children; + var selected = initialProps.selected, min5 = initialProps.min, max5 = initialProps.max; + var onDayClick = function(day, activeModifiers, e5) { + var _a2, _b; + (_a2 = initialProps.onDayClick) === null || _a2 === void 0 ? void 0 : _a2.call(initialProps, day, activeModifiers, e5); + var isMinSelected = Boolean(activeModifiers.selected && min5 && (selected === null || selected === void 0 ? void 0 : selected.length) === min5); + if (isMinSelected) { + return; + } + var isMaxSelected = Boolean(!activeModifiers.selected && max5 && (selected === null || selected === void 0 ? void 0 : selected.length) === max5); + if (isMaxSelected) { + return; + } + var selectedDays = selected ? __spreadArray([], selected, true) : []; + if (activeModifiers.selected) { + var index2 = selectedDays.findIndex(function(selectedDay) { + return isSameDay(day, selectedDay); + }); + selectedDays.splice(index2, 1); + } else { + selectedDays.push(day); + } + (_b = initialProps.onSelect) === null || _b === void 0 ? void 0 : _b.call(initialProps, selectedDays, day, activeModifiers, e5); + }; + var modifiers = { + disabled: [] + }; + if (selected) { + modifiers.disabled.push(function(day) { + var isMaxSelected = max5 && selected.length > max5 - 1; + var isSelected = selected.some(function(selectedDay) { + return isSameDay(selectedDay, day); + }); + return Boolean(isMaxSelected && !isSelected); + }); } - childBefore(pos) { - return this.child(-1, pos, -2); + var contextValue = { + selected, + onDayClick, + modifiers + }; + return jsxRuntimeExports.jsx(SelectMultipleContext.Provider, { value: contextValue, children }); +} +function useSelectMultiple() { + var context = (0, import_react29.useContext)(SelectMultipleContext); + if (!context) { + throw new Error("useSelectMultiple must be used within a SelectMultipleProvider"); } - enter(pos, side, mode2 = 0) { - if (mode2 & IterMode2.ExcludeBuffers) - return null; - let { buffer } = this.context; - let index2 = buffer.findChild(this.index + 4, buffer.buffer[this.index + 3], side > 0 ? 1 : -1, pos - this.context.start, side); - return index2 < 0 ? null : new BufferNode2(this.context, this, index2); + return context; +} +function addToRange(day, range2) { + var _a = range2 || {}, from = _a.from, to2 = _a.to; + if (from && to2) { + if (isSameDay(to2, day) && isSameDay(from, day)) { + return void 0; + } + if (isSameDay(to2, day)) { + return { from: to2, to: void 0 }; + } + if (isSameDay(from, day)) { + return void 0; + } + if (isAfter(from, day)) { + return { from: day, to: to2 }; + } + return { from, to: day }; } - get parent() { - return this._parent || this.context.parent.nextSignificantParent(); + if (to2) { + if (isAfter(day, to2)) { + return { from: to2, to: day }; + } + return { from: day, to: to2 }; } - externalSibling(dir) { - return this._parent ? null : this.context.parent.nextChild(this.context.index + dir, dir, 0, 4); + if (from) { + if (isBefore(day, from)) { + return { from: day, to: from }; + } + return { from, to: day }; } - get nextSibling() { - let { buffer } = this.context; - let after = buffer.buffer[this.index + 3]; - if (after < (this._parent ? buffer.buffer[this._parent.index + 3] : buffer.buffer.length)) - return new BufferNode2(this.context, this._parent, after); - return this.externalSibling(1); - } - get prevSibling() { - let { buffer } = this.context; - let parentStart = this._parent ? this._parent.index + 4 : 0; - if (this.index == parentStart) - return this.externalSibling(-1); - return new BufferNode2(this.context, this._parent, buffer.findChild(parentStart, this.index, -1, 0, 4)); - } - cursor(mode2 = 0) { - return new TreeCursor2(this, mode2); - } - get tree() { - return null; - } - toTree() { - let children = [], positions = []; - let { buffer } = this.context; - let startI = this.index + 4, endI = buffer.buffer[this.index + 3]; - if (endI > startI) { - let from = buffer.buffer[this.index + 1], to2 = buffer.buffer[this.index + 2]; - children.push(buffer.slice(startI, endI, from, to2)); - positions.push(0); - } - return new Tree2(this.type, children, positions, this.to - this.from); - } - resolve(pos, side = 0) { - return resolveNode2(this, pos, side, false); - } - resolveInner(pos, side = 0) { - return resolveNode2(this, pos, side, true); - } - enterUnfinishedNodesBefore(pos) { - return enterUnfinishedNodesBefore2(this, pos); - } - toString() { - return this.context.buffer.childString(this.index); - } - getChild(type, before = null, after = null) { - let r2 = getChildren2(this, type, before, after); - return r2.length ? r2[0] : null; - } - getChildren(type, before = null, after = null) { - return getChildren2(this, type, before, after); - } - get node() { - return this; - } - matchContext(context) { - return matchNodeContext2(this, context); + return { from: day, to: void 0 }; +} +var SelectRangeContext = (0, import_react29.createContext)(void 0); +function SelectRangeProvider(props) { + if (!isDayPickerRange(props.initialProps)) { + var emptyContextValue = { + selected: void 0, + modifiers: { + range_start: [], + range_end: [], + range_middle: [], + disabled: [] + } + }; + return jsxRuntimeExports.jsx(SelectRangeContext.Provider, { value: emptyContextValue, children: props.children }); } -}; -var TreeCursor2 = class { - constructor(node, mode2 = 0) { - this.mode = mode2; - this.buffer = null; - this.stack = []; - this.index = 0; - this.bufferNode = null; - if (node instanceof TreeNode3) { - this.yieldNode(node); + return jsxRuntimeExports.jsx(SelectRangeProviderInternal, { initialProps: props.initialProps, children: props.children }); +} +function SelectRangeProviderInternal(_a) { + var initialProps = _a.initialProps, children = _a.children; + var selected = initialProps.selected; + var _b = selected || {}, selectedFrom = _b.from, selectedTo = _b.to; + var min5 = initialProps.min; + var max5 = initialProps.max; + var onDayClick = function(day, activeModifiers, e5) { + var _a2, _b2; + (_a2 = initialProps.onDayClick) === null || _a2 === void 0 ? void 0 : _a2.call(initialProps, day, activeModifiers, e5); + var newRange = addToRange(day, selected); + (_b2 = initialProps.onSelect) === null || _b2 === void 0 ? void 0 : _b2.call(initialProps, newRange, day, activeModifiers, e5); + }; + var modifiers = { + range_start: [], + range_end: [], + range_middle: [], + disabled: [] + }; + if (selectedFrom) { + modifiers.range_start = [selectedFrom]; + if (!selectedTo) { + modifiers.range_end = [selectedFrom]; } else { - this._tree = node.context.parent; - this.buffer = node.context; - for (let n3 = node._parent; n3; n3 = n3._parent) - this.stack.unshift(n3.index); - this.bufferNode = node; - this.yieldBuf(node.index); + modifiers.range_end = [selectedTo]; + if (!isSameDay(selectedFrom, selectedTo)) { + modifiers.range_middle = [ + { + after: selectedFrom, + before: selectedTo + } + ]; + } } + } else if (selectedTo) { + modifiers.range_start = [selectedTo]; + modifiers.range_end = [selectedTo]; } - get name() { - return this.type.name; - } - yieldNode(node) { - if (!node) - return false; - this._tree = node; - this.type = node.type; - this.from = node.from; - this.to = node.to; - return true; - } - yieldBuf(index2, type) { - this.index = index2; - let { start, buffer } = this.buffer; - this.type = type || buffer.set.types[buffer.buffer[index2]]; - this.from = start + buffer.buffer[index2 + 1]; - this.to = start + buffer.buffer[index2 + 2]; - return true; - } - yield(node) { - if (!node) - return false; - if (node instanceof TreeNode3) { - this.buffer = null; - return this.yieldNode(node); + if (min5) { + if (selectedFrom && !selectedTo) { + modifiers.disabled.push({ + after: subDays(selectedFrom, min5 - 1), + before: addDays(selectedFrom, min5 - 1) + }); + } + if (selectedFrom && selectedTo) { + modifiers.disabled.push({ + after: selectedFrom, + before: addDays(selectedFrom, min5 - 1) + }); + } + if (!selectedFrom && selectedTo) { + modifiers.disabled.push({ + after: subDays(selectedTo, min5 - 1), + before: addDays(selectedTo, min5 - 1) + }); } - this.buffer = node.context; - return this.yieldBuf(node.index, node.type); - } - toString() { - return this.buffer ? this.buffer.buffer.childString(this.index) : this._tree.toString(); } - enterChild(dir, pos, side) { - if (!this.buffer) - return this.yield(this._tree.nextChild(dir < 0 ? this._tree._tree.children.length - 1 : 0, dir, pos, side, this.mode)); - let { buffer } = this.buffer; - let index2 = buffer.findChild(this.index + 4, buffer.buffer[this.index + 3], dir, pos - this.buffer.start, side); - if (index2 < 0) - return false; - this.stack.push(this.index); - return this.yieldBuf(index2); + if (max5) { + if (selectedFrom && !selectedTo) { + modifiers.disabled.push({ + before: addDays(selectedFrom, -max5 + 1) + }); + modifiers.disabled.push({ + after: addDays(selectedFrom, max5 - 1) + }); + } + if (selectedFrom && selectedTo) { + var selectedCount = differenceInCalendarDays(selectedTo, selectedFrom) + 1; + var offset2 = max5 - selectedCount; + modifiers.disabled.push({ + before: subDays(selectedFrom, offset2) + }); + modifiers.disabled.push({ + after: addDays(selectedTo, offset2) + }); + } + if (!selectedFrom && selectedTo) { + modifiers.disabled.push({ + before: addDays(selectedTo, -max5 + 1) + }); + modifiers.disabled.push({ + after: addDays(selectedTo, max5 - 1) + }); + } } - firstChild() { - return this.enterChild(1, 0, 4); + return jsxRuntimeExports.jsx(SelectRangeContext.Provider, { value: { selected, onDayClick, modifiers }, children }); +} +function useSelectRange() { + var context = (0, import_react29.useContext)(SelectRangeContext); + if (!context) { + throw new Error("useSelectRange must be used within a SelectRangeProvider"); } - lastChild() { - return this.enterChild(-1, 0, 4); + return context; +} +function matcherToArray(matcher) { + if (Array.isArray(matcher)) { + return __spreadArray([], matcher, true); + } else if (matcher !== void 0) { + return [matcher]; + } else { + return []; } - childAfter(pos) { - return this.enterChild(1, pos, 2); +} +function getCustomModifiers(dayModifiers) { + var customModifiers = {}; + Object.entries(dayModifiers).forEach(function(_a) { + var modifier = _a[0], matcher = _a[1]; + customModifiers[modifier] = matcherToArray(matcher); + }); + return customModifiers; +} +var InternalModifier; +(function(InternalModifier2) { + InternalModifier2["Outside"] = "outside"; + InternalModifier2["Disabled"] = "disabled"; + InternalModifier2["Selected"] = "selected"; + InternalModifier2["Hidden"] = "hidden"; + InternalModifier2["Today"] = "today"; + InternalModifier2["RangeStart"] = "range_start"; + InternalModifier2["RangeEnd"] = "range_end"; + InternalModifier2["RangeMiddle"] = "range_middle"; +})(InternalModifier || (InternalModifier = {})); +var Selected = InternalModifier.Selected; +var Disabled = InternalModifier.Disabled; +var Hidden = InternalModifier.Hidden; +var Today = InternalModifier.Today; +var RangeEnd = InternalModifier.RangeEnd; +var RangeMiddle = InternalModifier.RangeMiddle; +var RangeStart = InternalModifier.RangeStart; +var Outside2 = InternalModifier.Outside; +function getInternalModifiers(dayPicker, selectMultiple, selectRange2) { + var _a; + var internalModifiers = (_a = {}, _a[Selected] = matcherToArray(dayPicker.selected), _a[Disabled] = matcherToArray(dayPicker.disabled), _a[Hidden] = matcherToArray(dayPicker.hidden), _a[Today] = [dayPicker.today], _a[RangeEnd] = [], _a[RangeMiddle] = [], _a[RangeStart] = [], _a[Outside2] = [], _a); + if (dayPicker.fromDate) { + internalModifiers[Disabled].push({ before: dayPicker.fromDate }); } - childBefore(pos) { - return this.enterChild(-1, pos, -2); + if (dayPicker.toDate) { + internalModifiers[Disabled].push({ after: dayPicker.toDate }); } - enter(pos, side, mode2 = this.mode) { - if (!this.buffer) - return this.yield(this._tree.enter(pos, side, mode2)); - return mode2 & IterMode2.ExcludeBuffers ? false : this.enterChild(1, pos, side); + if (isDayPickerMultiple(dayPicker)) { + internalModifiers[Disabled] = internalModifiers[Disabled].concat(selectMultiple.modifiers[Disabled]); + } else if (isDayPickerRange(dayPicker)) { + internalModifiers[Disabled] = internalModifiers[Disabled].concat(selectRange2.modifiers[Disabled]); + internalModifiers[RangeStart] = selectRange2.modifiers[RangeStart]; + internalModifiers[RangeMiddle] = selectRange2.modifiers[RangeMiddle]; + internalModifiers[RangeEnd] = selectRange2.modifiers[RangeEnd]; } - parent() { - if (!this.buffer) - return this.yieldNode(this.mode & IterMode2.IncludeAnonymous ? this._tree._parent : this._tree.parent); - if (this.stack.length) - return this.yieldBuf(this.stack.pop()); - let parent = this.mode & IterMode2.IncludeAnonymous ? this.buffer.parent : this.buffer.parent.nextSignificantParent(); - this.buffer = null; - return this.yieldNode(parent); + return internalModifiers; +} +var ModifiersContext = (0, import_react29.createContext)(void 0); +function ModifiersProvider(props) { + var dayPicker = useDayPicker(); + var selectMultiple = useSelectMultiple(); + var selectRange2 = useSelectRange(); + var internalModifiers = getInternalModifiers(dayPicker, selectMultiple, selectRange2); + var customModifiers = getCustomModifiers(dayPicker.modifiers); + var modifiers = __assign(__assign({}, internalModifiers), customModifiers); + return jsxRuntimeExports.jsx(ModifiersContext.Provider, { value: modifiers, children: props.children }); +} +function useModifiers() { + var context = (0, import_react29.useContext)(ModifiersContext); + if (!context) { + throw new Error("useModifiers must be used within a ModifiersProvider"); } - sibling(dir) { - if (!this.buffer) - return !this._tree._parent ? false : this.yield(this._tree.index < 0 ? null : this._tree._parent.nextChild(this._tree.index + dir, dir, 0, 4, this.mode)); - let { buffer } = this.buffer, d4 = this.stack.length - 1; - if (dir < 0) { - let parentStart = d4 < 0 ? 0 : this.stack[d4] + 4; - if (this.index != parentStart) - return this.yieldBuf(buffer.findChild(parentStart, this.index, -1, 0, 4)); - } else { - let after = buffer.buffer[this.index + 3]; - if (after < (d4 < 0 ? buffer.buffer.length : buffer.buffer[this.stack[d4] + 3])) - return this.yieldBuf(after); + return context; +} +function isDateInterval(matcher) { + return Boolean(matcher && typeof matcher === "object" && "before" in matcher && "after" in matcher); +} +function isDateRange(value) { + return Boolean(value && typeof value === "object" && "from" in value); +} +function isDateAfterType(value) { + return Boolean(value && typeof value === "object" && "after" in value); +} +function isDateBeforeType(value) { + return Boolean(value && typeof value === "object" && "before" in value); +} +function isDayOfWeekType(value) { + return Boolean(value && typeof value === "object" && "dayOfWeek" in value); +} +function isDateInRange(date, range2) { + var _a; + var from = range2.from, to2 = range2.to; + if (from && to2) { + var isRangeInverted = differenceInCalendarDays(to2, from) < 0; + if (isRangeInverted) { + _a = [to2, from], from = _a[0], to2 = _a[1]; } - return d4 < 0 ? this.yield(this.buffer.parent.nextChild(this.buffer.index + dir, dir, 0, 4, this.mode)) : false; + var isInRange = differenceInCalendarDays(date, from) >= 0 && differenceInCalendarDays(to2, date) >= 0; + return isInRange; } - nextSibling() { - return this.sibling(1); + if (to2) { + return isSameDay(to2, date); } - prevSibling() { - return this.sibling(-1); + if (from) { + return isSameDay(from, date); } - atLastNode(dir) { - let index2, parent, { buffer } = this; - if (buffer) { - if (dir > 0) { - if (this.index < buffer.buffer.buffer.length) - return false; - } else { - for (let i4 = 0; i4 < this.index; i4++) - if (buffer.buffer.buffer[i4 + 3] < this.index) - return false; - } - ({ index: index2, parent } = buffer); - } else { - ({ index: index2, _parent: parent } = this._tree); + return false; +} +function isDateType(value) { + return isDate(value); +} +function isArrayOfDates(value) { + return Array.isArray(value) && value.every(isDate); +} +function isMatch(day, matchers) { + return matchers.some(function(matcher) { + if (typeof matcher === "boolean") { + return matcher; } - for (; parent; { index: index2, _parent: parent } = parent) { - if (index2 > -1) - for (let i4 = index2 + dir, e5 = dir < 0 ? -1 : parent._tree.children.length; i4 != e5; i4 += dir) { - let child = parent._tree.children[i4]; - if (this.mode & IterMode2.IncludeAnonymous || child instanceof TreeBuffer2 || !child.type.isAnonymous || hasChild2(child)) - return false; - } + if (isDateType(matcher)) { + return isSameDay(day, matcher); } - return true; - } - move(dir, enter) { - if (enter && this.enterChild(dir, 0, 4)) - return true; - for (; ; ) { - if (this.sibling(dir)) - return true; - if (this.atLastNode(dir) || !this.parent()) - return false; + if (isArrayOfDates(matcher)) { + return matcher.includes(day); } - } - next(enter = true) { - return this.move(1, enter); - } - prev(enter = true) { - return this.move(-1, enter); - } - moveTo(pos, side = 0) { - while (this.from == this.to || (side < 1 ? this.from >= pos : this.from > pos) || (side > -1 ? this.to <= pos : this.to < pos)) - if (!this.parent()) - break; - while (this.enterChild(1, pos, side)) { + if (isDateRange(matcher)) { + return isDateInRange(day, matcher); } - return this; - } - get node() { - if (!this.buffer) - return this._tree; - let cache2 = this.bufferNode, result = null, depth = 0; - if (cache2 && cache2.context == this.buffer) { - scan: - for (let index2 = this.index, d4 = this.stack.length; d4 >= 0; ) { - for (let c3 = cache2; c3; c3 = c3._parent) - if (c3.index == index2) { - if (index2 == this.index) - return c3; - result = c3; - depth = d4 + 1; - break scan; - } - index2 = this.stack[--d4]; - } + if (isDayOfWeekType(matcher)) { + return matcher.dayOfWeek.includes(day.getDay()); } - for (let i4 = depth; i4 < this.stack.length; i4++) - result = new BufferNode2(this.buffer, result, this.stack[i4]); - return this.bufferNode = new BufferNode2(this.buffer, result, this.index); - } - get tree() { - return this.buffer ? null : this._tree._tree; - } - iterate(enter, leave) { - for (let depth = 0; ; ) { - let mustLeave = false; - if (this.type.isAnonymous || enter(this) !== false) { - if (this.firstChild()) { - depth++; - continue; - } - if (!this.type.isAnonymous) - mustLeave = true; - } - for (; ; ) { - if (mustLeave && leave) - leave(this); - mustLeave = this.type.isAnonymous; - if (this.nextSibling()) - break; - if (!depth) - return; - this.parent(); - depth--; - mustLeave = true; + if (isDateInterval(matcher)) { + var diffBefore = differenceInCalendarDays(matcher.before, day); + var diffAfter = differenceInCalendarDays(matcher.after, day); + var isDayBefore = diffBefore > 0; + var isDayAfter = diffAfter < 0; + var isClosedInterval = isAfter(matcher.before, matcher.after); + if (isClosedInterval) { + return isDayAfter && isDayBefore; + } else { + return isDayBefore || isDayAfter; } } - } - matchContext(context) { - if (!this.buffer) - return matchNodeContext2(this.node, context); - let { buffer } = this.buffer, { types: types2 } = buffer.set; - for (let i4 = context.length - 1, d4 = this.stack.length - 1; i4 >= 0; d4--) { - if (d4 < 0) - return matchNodeContext2(this.node, context, i4); - let type = types2[buffer.buffer[this.stack[d4]]]; - if (!type.isAnonymous) { - if (context[i4] && context[i4] != type.name) - return false; - i4--; - } + if (isDateAfterType(matcher)) { + return differenceInCalendarDays(day, matcher.after) > 0; } - return true; - } -}; -function hasChild2(tree) { - return tree.children.some((ch) => ch instanceof TreeBuffer2 || !ch.type.isAnonymous || hasChild2(ch)); -} -function buildTree2(data2) { - var _a; - let { buffer, nodeSet, maxBufferLength = DefaultBufferLength2, reused = [], minRepeatType = nodeSet.types.length } = data2; - let cursor2 = Array.isArray(buffer) ? new FlatBufferCursor2(buffer, buffer.length) : buffer; - let types2 = nodeSet.types; - let contextHash = 0, lookAhead = 0; - function takeNode(parentStart, minPos, children2, positions2, inRepeat) { - let { id: id3, start, end, size: size2 } = cursor2; - let lookAheadAtStart = lookAhead; - while (size2 < 0) { - cursor2.next(); - if (size2 == -1) { - let node2 = reused[id3]; - children2.push(node2); - positions2.push(start - parentStart); - return; - } else if (size2 == -3) { - contextHash = id3; - return; - } else if (size2 == -4) { - lookAhead = id3; - return; - } else { - throw new RangeError(`Unrecognized record size: ${size2}`); - } + if (isDateBeforeType(matcher)) { + return differenceInCalendarDays(matcher.before, day) > 0; } - let type = types2[id3], node, buffer2; - let startPos = start - parentStart; - if (end - start <= maxBufferLength && (buffer2 = findBufferSize(cursor2.pos - minPos, inRepeat))) { - let data3 = new Uint16Array(buffer2.size - buffer2.skip); - let endPos = cursor2.pos - buffer2.size, index2 = data3.length; - while (cursor2.pos > endPos) - index2 = copyToBuffer(buffer2.start, data3, index2); - node = new TreeBuffer2(data3, end - buffer2.start, nodeSet); - startPos = buffer2.start - parentStart; - } else { - let endPos = cursor2.pos - size2; - cursor2.next(); - let localChildren = [], localPositions = []; - let localInRepeat = id3 >= minRepeatType ? id3 : -1; - let lastGroup = 0, lastEnd = end; - while (cursor2.pos > endPos) { - if (localInRepeat >= 0 && cursor2.id == localInRepeat && cursor2.size >= 0) { - if (cursor2.end <= lastEnd - maxBufferLength) { - makeRepeatLeaf(localChildren, localPositions, start, lastGroup, cursor2.end, lastEnd, localInRepeat, lookAheadAtStart); - lastGroup = localChildren.length; - lastEnd = cursor2.end; - } - cursor2.next(); - } else { - takeNode(start, endPos, localChildren, localPositions, localInRepeat); - } - } - if (localInRepeat >= 0 && lastGroup > 0 && lastGroup < localChildren.length) - makeRepeatLeaf(localChildren, localPositions, start, lastGroup, start, lastEnd, localInRepeat, lookAheadAtStart); - localChildren.reverse(); - localPositions.reverse(); - if (localInRepeat > -1 && lastGroup > 0) { - let make = makeBalanced(type); - node = balanceRange2(type, localChildren, localPositions, 0, localChildren.length, 0, end - start, make, make); - } else { - node = makeTree(type, localChildren, localPositions, end - start, lookAheadAtStart - end); - } + if (typeof matcher === "function") { + return matcher(day); } - children2.push(node); - positions2.push(startPos); - } - function makeBalanced(type) { - return (children2, positions2, length2) => { - let lookAhead2 = 0, lastI = children2.length - 1, last, lookAheadProp; - if (lastI >= 0 && (last = children2[lastI]) instanceof Tree2) { - if (!lastI && last.type == type && last.length == length2) - return last; - if (lookAheadProp = last.prop(NodeProp2.lookAhead)) - lookAhead2 = positions2[lastI] + last.length + lookAheadProp; - } - return makeTree(type, children2, positions2, length2, lookAhead2); - }; - } - function makeRepeatLeaf(children2, positions2, base2, i4, from, to2, type, lookAhead2) { - let localChildren = [], localPositions = []; - while (children2.length > i4) { - localChildren.push(children2.pop()); - localPositions.push(positions2.pop() + base2 - from); + return false; + }); +} +function getActiveModifiers(day, modifiers, displayMonth) { + var matchedModifiers = Object.keys(modifiers).reduce(function(result, key2) { + var modifier = modifiers[key2]; + if (isMatch(day, modifier)) { + result.push(key2); } - children2.push(makeTree(nodeSet.types[type], localChildren, localPositions, to2 - from, lookAhead2 - to2)); - positions2.push(from - base2); + return result; + }, []); + var activeModifiers = {}; + matchedModifiers.forEach(function(modifier) { + return activeModifiers[modifier] = true; + }); + if (displayMonth && !isSameMonth(day, displayMonth)) { + activeModifiers.outside = true; } - function makeTree(type, children2, positions2, length2, lookAhead2 = 0, props) { - if (contextHash) { - let pair2 = [NodeProp2.contextHash, contextHash]; - props = props ? [pair2].concat(props) : [pair2]; + return activeModifiers; +} +function getInitialFocusTarget(displayMonths, modifiers) { + var firstDayInMonth = startOfMonth(displayMonths[0]); + var lastDayInMonth = endOfMonth(displayMonths[displayMonths.length - 1]); + var firstFocusableDay; + var today; + var date = firstDayInMonth; + while (date <= lastDayInMonth) { + var activeModifiers = getActiveModifiers(date, modifiers); + var isFocusable = !activeModifiers.disabled && !activeModifiers.hidden; + if (!isFocusable) { + date = addDays(date, 1); + continue; } - if (lookAhead2 > 25) { - let pair2 = [NodeProp2.lookAhead, lookAhead2]; - props = props ? [pair2].concat(props) : [pair2]; + if (activeModifiers.selected) { + return date; } - return new Tree2(type, children2, positions2, length2, props); - } - function findBufferSize(maxSize, inRepeat) { - let fork = cursor2.fork(); - let size2 = 0, start = 0, skip = 0, minStart = fork.end - maxBufferLength; - let result = { size: 0, start: 0, skip: 0 }; - scan: - for (let minPos = fork.pos - maxSize; fork.pos > minPos; ) { - let nodeSize4 = fork.size; - if (fork.id == inRepeat && nodeSize4 >= 0) { - result.size = size2; - result.start = start; - result.skip = skip; - skip += 4; - size2 += 4; - fork.next(); - continue; - } - let startPos = fork.pos - nodeSize4; - if (nodeSize4 < 0 || startPos < minPos || fork.start < minStart) - break; - let localSkipped = fork.id >= minRepeatType ? 4 : 0; - let nodeStart = fork.start; - fork.next(); - while (fork.pos > startPos) { - if (fork.size < 0) { - if (fork.size == -3) - localSkipped += 4; - else - break scan; - } else if (fork.id >= minRepeatType) { - localSkipped += 4; - } - fork.next(); - } - start = nodeStart; - size2 += nodeSize4; - skip += localSkipped; - } - if (inRepeat < 0 || size2 == maxSize) { - result.size = size2; - result.start = start; - result.skip = skip; + if (activeModifiers.today && !today) { + today = date; } - return result.size > 4 ? result : void 0; - } - function copyToBuffer(bufferStart, buffer2, index2) { - let { id: id3, start, end, size: size2 } = cursor2; - cursor2.next(); - if (size2 >= 0 && id3 < minRepeatType) { - let startIndex = index2; - if (size2 > 4) { - let endPos = cursor2.pos - (size2 - 4); - while (cursor2.pos > endPos) - index2 = copyToBuffer(bufferStart, buffer2, index2); - } - buffer2[--index2] = startIndex; - buffer2[--index2] = end - bufferStart; - buffer2[--index2] = start - bufferStart; - buffer2[--index2] = id3; - } else if (size2 == -3) { - contextHash = id3; - } else if (size2 == -4) { - lookAhead = id3; + if (!firstFocusableDay) { + firstFocusableDay = date; } - return index2; + date = addDays(date, 1); } - let children = [], positions = []; - while (cursor2.pos > 0) - takeNode(data2.start || 0, data2.bufferStart || 0, children, positions, -1); - let length = (_a = data2.length) !== null && _a !== void 0 ? _a : children.length ? positions[0] + children[0].length : 0; - return new Tree2(types2[data2.topID], children.reverse(), positions.reverse(), length); -} -var nodeSizeCache2 = /* @__PURE__ */ new WeakMap(); -function nodeSize2(balanceType, node) { - if (!balanceType.isAnonymous || node instanceof TreeBuffer2 || node.type != balanceType) - return 1; - let size2 = nodeSizeCache2.get(node); - if (size2 == null) { - size2 = 1; - for (let child of node.children) { - if (child.type != balanceType || !(child instanceof Tree2)) { - size2 = 1; - break; - } - size2 += nodeSize2(balanceType, child); - } - nodeSizeCache2.set(node, size2); + if (today) { + return today; + } else { + return firstFocusableDay; } - return size2; } -function balanceRange2(balanceType, children, positions, from, to2, start, length, mkTop, mkTree) { - let total = 0; - for (let i4 = from; i4 < to2; i4++) - total += nodeSize2(balanceType, children[i4]); - let maxChild = Math.ceil(total * 1.5 / 8); - let localChildren = [], localPositions = []; - function divide3(children2, positions2, from2, to3, offset2) { - for (let i4 = from2; i4 < to3; ) { - let groupFrom = i4, groupStart = positions2[i4], groupSize = nodeSize2(balanceType, children2[i4]); - i4++; - for (; i4 < to3; i4++) { - let nextSize = nodeSize2(balanceType, children2[i4]); - if (groupSize + nextSize >= maxChild) - break; - groupSize += nextSize; - } - if (i4 == groupFrom + 1) { - if (groupSize > maxChild) { - let only = children2[groupFrom]; - divide3(only.children, only.positions, 0, only.children.length, positions2[groupFrom] + offset2); - continue; - } - localChildren.push(children2[groupFrom]); - } else { - let length2 = positions2[i4 - 1] + children2[i4 - 1].length - groupStart; - localChildren.push(balanceRange2(balanceType, children2, positions2, groupFrom, i4, groupStart, length2, null, mkTree)); - } - localPositions.push(groupStart + offset2 - start); +var MAX_RETRY = 365; +function getNextFocus(focusedDay, options) { + var moveBy = options.moveBy, direction = options.direction, context = options.context, modifiers = options.modifiers, _a = options.retry, retry = _a === void 0 ? { count: 0, lastFocused: focusedDay } : _a; + var weekStartsOn = context.weekStartsOn, fromDate = context.fromDate, toDate2 = context.toDate, locale2 = context.locale; + var moveFns = { + day: addDays, + week: addWeeks, + month: addMonths, + year: addYears, + startOfWeek: function(date) { + return context.ISOWeek ? startOfISOWeek(date) : startOfWeek(date, { locale: locale2, weekStartsOn }); + }, + endOfWeek: function(date) { + return context.ISOWeek ? endOfISOWeek(date) : endOfWeek(date, { locale: locale2, weekStartsOn }); } + }; + var newFocusedDay = moveFns[moveBy](focusedDay, direction === "after" ? 1 : -1); + if (direction === "before" && fromDate) { + newFocusedDay = max([fromDate, newFocusedDay]); + } else if (direction === "after" && toDate2) { + newFocusedDay = min([toDate2, newFocusedDay]); } - divide3(children, positions, from, to2, 0); - return (mkTop || mkTree)(localChildren, localPositions, length); -} -var NodeWeakMap = class { - constructor() { - this.map = /* @__PURE__ */ new WeakMap(); - } - setBuffer(buffer, index2, value) { - let inner = this.map.get(buffer); - if (!inner) - this.map.set(buffer, inner = /* @__PURE__ */ new Map()); - inner.set(index2, value); - } - getBuffer(buffer, index2) { - let inner = this.map.get(buffer); - return inner && inner.get(index2); - } - set(node, value) { - if (node instanceof BufferNode2) - this.setBuffer(node.context.buffer, node.index, value); - else if (node instanceof TreeNode3) - this.map.set(node.tree, value); - } - get(node) { - return node instanceof BufferNode2 ? this.getBuffer(node.context.buffer, node.index) : node instanceof TreeNode3 ? this.map.get(node.tree) : void 0; - } - cursorSet(cursor2, value) { - if (cursor2.buffer) - this.setBuffer(cursor2.buffer.buffer, cursor2.index, value); - else - this.map.set(cursor2.tree, value); + var isFocusable = true; + if (modifiers) { + var activeModifiers = getActiveModifiers(newFocusedDay, modifiers); + isFocusable = !activeModifiers.disabled && !activeModifiers.hidden; } - cursorGet(cursor2) { - return cursor2.buffer ? this.getBuffer(cursor2.buffer.buffer, cursor2.index) : this.map.get(cursor2.tree); + if (isFocusable) { + return newFocusedDay; + } else { + if (retry.count > MAX_RETRY) { + return retry.lastFocused; + } + return getNextFocus(newFocusedDay, { + moveBy, + direction, + context, + modifiers, + retry: __assign(__assign({}, retry), { count: retry.count + 1 }) + }); } -}; -var stoppedInner2 = new NodeProp2({ perNode: true }); - -// node_modules/@codemirror/lang-javascript/dist/index.js -var snippets = [ - /* @__PURE__ */ (0, import_autocomplete.snippetCompletion)("function ${name}(${params}) {\n ${}\n}", { - label: "function", - detail: "definition", - type: "keyword" - }), - /* @__PURE__ */ (0, import_autocomplete.snippetCompletion)("for (let ${index} = 0; ${index} < ${bound}; ${index}++) {\n ${}\n}", { - label: "for", - detail: "loop", - type: "keyword" - }), - /* @__PURE__ */ (0, import_autocomplete.snippetCompletion)("for (let ${name} of ${collection}) {\n ${}\n}", { - label: "for", - detail: "of loop", - type: "keyword" - }), - /* @__PURE__ */ (0, import_autocomplete.snippetCompletion)("try {\n ${}\n} catch (${error}) {\n ${}\n}", { - label: "try", - detail: "block", - type: "keyword" - }), - /* @__PURE__ */ (0, import_autocomplete.snippetCompletion)("class ${name} {\n constructor(${params}) {\n ${}\n }\n}", { - label: "class", - detail: "definition", - type: "keyword" - }), - /* @__PURE__ */ (0, import_autocomplete.snippetCompletion)('import {${names}} from "${module}"\n${}', { - label: "import", - detail: "named", - type: "keyword" - }), - /* @__PURE__ */ (0, import_autocomplete.snippetCompletion)('import ${name} from "${module}"\n${}', { - label: "import", - detail: "default", - type: "keyword" - }) -]; -var cache = /* @__PURE__ */ new NodeWeakMap(); -var ScopeNodes = /* @__PURE__ */ new Set([ - "Script", - "Block", - "FunctionExpression", - "FunctionDeclaration", - "ArrowFunction", - "MethodDeclaration", - "ForStatement" -]); -function defID(type) { - return (node, def) => { - let id3 = node.node.getChild("VariableDefinition"); - if (id3) - def(id3, type); - return true; +} +var FocusContext = (0, import_react29.createContext)(void 0); +function FocusProvider(props) { + var navigation = useNavigation(); + var modifiers = useModifiers(); + var _a = (0, import_react29.useState)(), focusedDay = _a[0], setFocusedDay = _a[1]; + var _b = (0, import_react29.useState)(), lastFocused = _b[0], setLastFocused = _b[1]; + var initialFocusTarget = getInitialFocusTarget(navigation.displayMonths, modifiers); + var focusTarget = (focusedDay !== null && focusedDay !== void 0 ? focusedDay : lastFocused && navigation.isDateDisplayed(lastFocused)) ? lastFocused : initialFocusTarget; + var blur = function() { + setLastFocused(focusedDay); + setFocusedDay(void 0); + }; + var focus = function(date) { + setFocusedDay(date); + }; + var context = useDayPicker(); + var moveFocus = function(moveBy, direction) { + if (!focusedDay) + return; + var nextFocused = getNextFocus(focusedDay, { + moveBy, + direction, + context, + modifiers + }); + if (isSameDay(focusedDay, nextFocused)) + return void 0; + navigation.goToDate(nextFocused, focusedDay); + focus(nextFocused); + }; + var value = { + focusedDay, + focusTarget, + blur, + focus, + focusDayAfter: function() { + return moveFocus("day", "after"); + }, + focusDayBefore: function() { + return moveFocus("day", "before"); + }, + focusWeekAfter: function() { + return moveFocus("week", "after"); + }, + focusWeekBefore: function() { + return moveFocus("week", "before"); + }, + focusMonthBefore: function() { + return moveFocus("month", "before"); + }, + focusMonthAfter: function() { + return moveFocus("month", "after"); + }, + focusYearBefore: function() { + return moveFocus("year", "before"); + }, + focusYearAfter: function() { + return moveFocus("year", "after"); + }, + focusStartOfWeek: function() { + return moveFocus("startOfWeek", "before"); + }, + focusEndOfWeek: function() { + return moveFocus("endOfWeek", "after"); + } }; + return jsxRuntimeExports.jsx(FocusContext.Provider, { value, children: props.children }); } -var functionContext = ["FunctionDeclaration"]; -var gatherCompletions = { - FunctionDeclaration: /* @__PURE__ */ defID("function"), - ClassDeclaration: /* @__PURE__ */ defID("class"), - ClassExpression: () => true, - EnumDeclaration: /* @__PURE__ */ defID("constant"), - TypeAliasDeclaration: /* @__PURE__ */ defID("type"), - NamespaceDeclaration: /* @__PURE__ */ defID("namespace"), - VariableDefinition(node, def) { - if (!node.matchContext(functionContext)) - def(node, "variable"); - }, - TypeDefinition(node, def) { - def(node, "type"); - }, - __proto__: null -}; -function getScope(doc, node) { - let cached = cache.get(node); - if (cached) - return cached; - let completions = [], top = true; - function def(node2, type) { - let name317 = doc.sliceString(node2.from, node2.to); - completions.push({ label: name317, type }); +function useFocusContext() { + var context = (0, import_react29.useContext)(FocusContext); + if (!context) { + throw new Error("useFocusContext must be used within a FocusProvider"); } - node.cursor(IterMode2.IncludeAnonymous).iterate((node2) => { - if (top) { - top = false; - } else if (node2.name) { - let gather = gatherCompletions[node2.name]; - if (gather && gather(node2, def) || ScopeNodes.has(node2.name)) - return false; - } else if (node2.to - node2.from > 8192) { - for (let c3 of getScope(doc, node2.node)) - completions.push(c3); - return false; - } - }); - cache.set(node, completions); - return completions; + return context; } -var Identifier = /^[\w$\xa1-\uffff][\w$\d\xa1-\uffff]*$/; -function localCompletionSource(context) { - let inner = (0, import_language2.syntaxTree)(context.state).resolve(context.pos, -1); - if (inner.name == "TemplateString" || inner.name == "String" || inner.name == "LineComment" || inner.name == "BlockComment") - return null; - let isWord = inner.to - inner.from < 20 && Identifier.test(context.state.sliceDoc(inner.from, inner.to)); - if (!isWord && !context.explicit) - return null; - let options = []; - for (let pos = inner; pos; pos = pos.parent) { - if (ScopeNodes.has(pos.name)) - options = options.concat(getScope(context.state.doc, pos)); +function useActiveModifiers(day, displayMonth) { + var modifiers = useModifiers(); + var activeModifiers = getActiveModifiers(day, modifiers, displayMonth); + return activeModifiers; +} +var SelectSingleContext = (0, import_react29.createContext)(void 0); +function SelectSingleProvider(props) { + if (!isDayPickerSingle(props.initialProps)) { + var emptyContextValue = { + selected: void 0 + }; + return jsxRuntimeExports.jsx(SelectSingleContext.Provider, { value: emptyContextValue, children: props.children }); } - return { - options, - from: isWord ? inner.from : context.pos, - validFor: Identifier + return jsxRuntimeExports.jsx(SelectSingleProviderInternal, { initialProps: props.initialProps, children: props.children }); +} +function SelectSingleProviderInternal(_a) { + var initialProps = _a.initialProps, children = _a.children; + var onDayClick = function(day, activeModifiers, e5) { + var _a2, _b, _c; + (_a2 = initialProps.onDayClick) === null || _a2 === void 0 ? void 0 : _a2.call(initialProps, day, activeModifiers, e5); + if (activeModifiers.selected && !initialProps.required) { + (_b = initialProps.onSelect) === null || _b === void 0 ? void 0 : _b.call(initialProps, void 0, day, activeModifiers, e5); + return; + } + (_c = initialProps.onSelect) === null || _c === void 0 ? void 0 : _c.call(initialProps, day, day, activeModifiers, e5); }; + var contextValue = { + selected: initialProps.selected, + onDayClick + }; + return jsxRuntimeExports.jsx(SelectSingleContext.Provider, { value: contextValue, children }); } -var javascriptLanguage = /* @__PURE__ */ import_language2.LRLanguage.define({ - parser: /* @__PURE__ */ parser2.configure({ - props: [ - /* @__PURE__ */ import_language2.indentNodeProp.add({ - IfStatement: /* @__PURE__ */ (0, import_language2.continuedIndent)({ except: /^\s*({|else\b)/ }), - TryStatement: /* @__PURE__ */ (0, import_language2.continuedIndent)({ except: /^\s*({|catch\b|finally\b)/ }), - LabeledStatement: import_language2.flatIndent, - SwitchBody: (context) => { - let after = context.textAfter, closed = /^\s*\}/.test(after), isCase = /^\s*(case|default)\b/.test(after); - return context.baseIndent + (closed ? 0 : isCase ? 1 : 2) * context.unit; - }, - Block: /* @__PURE__ */ (0, import_language2.delimitedIndent)({ closing: "}" }), - ArrowFunction: (cx) => cx.baseIndent + cx.unit, - "TemplateString BlockComment": () => -1, - "Statement Property": /* @__PURE__ */ (0, import_language2.continuedIndent)({ except: /^{/ }), - JSXElement(context) { - let closed = /^\s*<\//.test(context.textAfter); - return context.lineIndent(context.node.from) + (closed ? 0 : context.unit); - }, - JSXEscape(context) { - let closed = /\s*\}/.test(context.textAfter); - return context.lineIndent(context.node.from) + (closed ? 0 : context.unit); - }, - "JSXOpenTag JSXSelfClosingTag"(context) { - return context.column(context.node.from) + context.unit; - } - }), - /* @__PURE__ */ import_language2.foldNodeProp.add({ - "Block ClassBody SwitchBody EnumBody ObjectExpression ArrayExpression": import_language2.foldInside, - BlockComment(tree) { - return { from: tree.from + 2, to: tree.to - 2 }; - } - }) - ] - }), - languageData: { - closeBrackets: { brackets: ["(", "[", "{", "'", '"', "`"] }, - commentTokens: { line: "//", block: { open: "/*", close: "*/" } }, - indentOnInput: /^\s*(?:case |default:|\{|\}|<\/)$/, - wordChars: "$" +function useSelectSingle() { + var context = (0, import_react29.useContext)(SelectSingleContext); + if (!context) { + throw new Error("useSelectSingle must be used within a SelectSingleProvider"); } -}); -var typescriptLanguage = /* @__PURE__ */ javascriptLanguage.configure({ dialect: "ts" }); -var jsxLanguage = /* @__PURE__ */ javascriptLanguage.configure({ dialect: "jsx" }); -var tsxLanguage = /* @__PURE__ */ javascriptLanguage.configure({ dialect: "jsx ts" }); -function javascript(config4 = {}) { - let lang = config4.jsx ? config4.typescript ? tsxLanguage : jsxLanguage : config4.typescript ? typescriptLanguage : javascriptLanguage; - return new import_language2.LanguageSupport(lang, [ - javascriptLanguage.data.of({ - autocomplete: (0, import_autocomplete.ifNotIn)(["LineComment", "BlockComment", "String"], (0, import_autocomplete.completeFromList)(snippets)) - }), - javascriptLanguage.data.of({ - autocomplete: localCompletionSource - }), - config4.jsx ? autoCloseTags : [] - ]); + return context; } -function elementName(doc, tree, max5 = doc.length) { - if (!tree) - return ""; - let name317 = tree.getChild("JSXIdentifier"); - return name317 ? doc.sliceString(name317.from, Math.min(name317.to, max5)) : ""; +function useDayEventHandlers(date, activeModifiers) { + var dayPicker = useDayPicker(); + var single = useSelectSingle(); + var multiple = useSelectMultiple(); + var range2 = useSelectRange(); + var _a = useFocusContext(), focusDayAfter = _a.focusDayAfter, focusDayBefore = _a.focusDayBefore, focusWeekAfter = _a.focusWeekAfter, focusWeekBefore = _a.focusWeekBefore, blur = _a.blur, focus = _a.focus, focusMonthBefore = _a.focusMonthBefore, focusMonthAfter = _a.focusMonthAfter, focusYearBefore = _a.focusYearBefore, focusYearAfter = _a.focusYearAfter, focusStartOfWeek = _a.focusStartOfWeek, focusEndOfWeek = _a.focusEndOfWeek; + var onClick = function(e5) { + var _a2, _b, _c, _d; + if (isDayPickerSingle(dayPicker)) { + (_a2 = single.onDayClick) === null || _a2 === void 0 ? void 0 : _a2.call(single, date, activeModifiers, e5); + } else if (isDayPickerMultiple(dayPicker)) { + (_b = multiple.onDayClick) === null || _b === void 0 ? void 0 : _b.call(multiple, date, activeModifiers, e5); + } else if (isDayPickerRange(dayPicker)) { + (_c = range2.onDayClick) === null || _c === void 0 ? void 0 : _c.call(range2, date, activeModifiers, e5); + } else { + (_d = dayPicker.onDayClick) === null || _d === void 0 ? void 0 : _d.call(dayPicker, date, activeModifiers, e5); + } + }; + var onFocus = function(e5) { + var _a2; + focus(date); + (_a2 = dayPicker.onDayFocus) === null || _a2 === void 0 ? void 0 : _a2.call(dayPicker, date, activeModifiers, e5); + }; + var onBlur = function(e5) { + var _a2; + blur(); + (_a2 = dayPicker.onDayBlur) === null || _a2 === void 0 ? void 0 : _a2.call(dayPicker, date, activeModifiers, e5); + }; + var onMouseEnter = function(e5) { + var _a2; + (_a2 = dayPicker.onDayMouseEnter) === null || _a2 === void 0 ? void 0 : _a2.call(dayPicker, date, activeModifiers, e5); + }; + var onMouseLeave = function(e5) { + var _a2; + (_a2 = dayPicker.onDayMouseLeave) === null || _a2 === void 0 ? void 0 : _a2.call(dayPicker, date, activeModifiers, e5); + }; + var onPointerEnter = function(e5) { + var _a2; + (_a2 = dayPicker.onDayPointerEnter) === null || _a2 === void 0 ? void 0 : _a2.call(dayPicker, date, activeModifiers, e5); + }; + var onPointerLeave = function(e5) { + var _a2; + (_a2 = dayPicker.onDayPointerLeave) === null || _a2 === void 0 ? void 0 : _a2.call(dayPicker, date, activeModifiers, e5); + }; + var onTouchCancel = function(e5) { + var _a2; + (_a2 = dayPicker.onDayTouchCancel) === null || _a2 === void 0 ? void 0 : _a2.call(dayPicker, date, activeModifiers, e5); + }; + var onTouchEnd = function(e5) { + var _a2; + (_a2 = dayPicker.onDayTouchEnd) === null || _a2 === void 0 ? void 0 : _a2.call(dayPicker, date, activeModifiers, e5); + }; + var onTouchMove = function(e5) { + var _a2; + (_a2 = dayPicker.onDayTouchMove) === null || _a2 === void 0 ? void 0 : _a2.call(dayPicker, date, activeModifiers, e5); + }; + var onTouchStart = function(e5) { + var _a2; + (_a2 = dayPicker.onDayTouchStart) === null || _a2 === void 0 ? void 0 : _a2.call(dayPicker, date, activeModifiers, e5); + }; + var onKeyUp = function(e5) { + var _a2; + (_a2 = dayPicker.onDayKeyUp) === null || _a2 === void 0 ? void 0 : _a2.call(dayPicker, date, activeModifiers, e5); + }; + var onKeyDown = function(e5) { + var _a2; + switch (e5.key) { + case "ArrowLeft": + e5.preventDefault(); + e5.stopPropagation(); + dayPicker.dir === "rtl" ? focusDayAfter() : focusDayBefore(); + break; + case "ArrowRight": + e5.preventDefault(); + e5.stopPropagation(); + dayPicker.dir === "rtl" ? focusDayBefore() : focusDayAfter(); + break; + case "ArrowDown": + e5.preventDefault(); + e5.stopPropagation(); + focusWeekAfter(); + break; + case "ArrowUp": + e5.preventDefault(); + e5.stopPropagation(); + focusWeekBefore(); + break; + case "PageUp": + e5.preventDefault(); + e5.stopPropagation(); + e5.shiftKey ? focusYearBefore() : focusMonthBefore(); + break; + case "PageDown": + e5.preventDefault(); + e5.stopPropagation(); + e5.shiftKey ? focusYearAfter() : focusMonthAfter(); + break; + case "Home": + e5.preventDefault(); + e5.stopPropagation(); + focusStartOfWeek(); + break; + case "End": + e5.preventDefault(); + e5.stopPropagation(); + focusEndOfWeek(); + break; + } + (_a2 = dayPicker.onDayKeyDown) === null || _a2 === void 0 ? void 0 : _a2.call(dayPicker, date, activeModifiers, e5); + }; + var eventHandlers = { + onClick, + onFocus, + onBlur, + onKeyDown, + onKeyUp, + onMouseEnter, + onMouseLeave, + onPointerEnter, + onPointerLeave, + onTouchCancel, + onTouchEnd, + onTouchMove, + onTouchStart + }; + return eventHandlers; } -var android = typeof navigator == "object" && /* @__PURE__ */ /Android\b/.test(navigator.userAgent); -var autoCloseTags = /* @__PURE__ */ import_view2.EditorView.inputHandler.of((view, from, to2, text2) => { - if ((android ? view.composing : view.compositionStarted) || view.state.readOnly || from != to2 || text2 != ">" && text2 != "/" || !javascriptLanguage.isActiveAt(view.state, from, -1)) - return false; - let { state } = view; - let changes = state.changeByRange((range2) => { - var _a, _b, _c; - let { head } = range2, around2 = (0, import_language2.syntaxTree)(state).resolveInner(head, -1), name317; - if (around2.name == "JSXStartTag") - around2 = around2.parent; - if (text2 == ">" && around2.name == "JSXFragmentTag") { - return { range: import_state3.EditorSelection.cursor(head + 1), changes: { from: head, insert: `><>` } }; - } else if (text2 == ">" && around2.name == "JSXIdentifier") { - if (((_b = (_a = around2.parent) === null || _a === void 0 ? void 0 : _a.lastChild) === null || _b === void 0 ? void 0 : _b.name) != "JSXEndTag" && (name317 = elementName(state.doc, around2.parent, head))) - return { range: import_state3.EditorSelection.cursor(head + 1), changes: { from: head, insert: `>` } }; - } else if (text2 == "/" && around2.name == "JSXFragmentTag") { - let empty3 = around2.parent, base2 = empty3 === null || empty3 === void 0 ? void 0 : empty3.parent; - if (empty3.from == head - 1 && ((_c = base2.lastChild) === null || _c === void 0 ? void 0 : _c.name) != "JSXEndTag" && (name317 = elementName(state.doc, base2 === null || base2 === void 0 ? void 0 : base2.firstChild, head))) { - let insert2 = `/${name317}>`; - return { range: import_state3.EditorSelection.cursor(head + insert2.length), changes: { from: head, insert: insert2 } }; +function useSelectedDays() { + var dayPicker = useDayPicker(); + var single = useSelectSingle(); + var multiple = useSelectMultiple(); + var range2 = useSelectRange(); + var selectedDays = isDayPickerSingle(dayPicker) ? single.selected : isDayPickerMultiple(dayPicker) ? multiple.selected : isDayPickerRange(dayPicker) ? range2.selected : void 0; + return selectedDays; +} +function isInternalModifier(modifier) { + return Object.values(InternalModifier).includes(modifier); +} +function getDayClassNames(dayPicker, activeModifiers) { + var classNames13 = [dayPicker.classNames.day]; + Object.keys(activeModifiers).forEach(function(modifier) { + var customClassName = dayPicker.modifiersClassNames[modifier]; + if (customClassName) { + classNames13.push(customClassName); + } else if (isInternalModifier(modifier)) { + var internalClassName = dayPicker.classNames["day_".concat(modifier)]; + if (internalClassName) { + classNames13.push(internalClassName); } } - return { range: range2 }; }); - if (changes.changes.empty) - return false; - view.dispatch(changes, { userEvent: "input.type", scrollIntoView: true }); - return true; -}); - -// node_modules/@lezer/common/dist/index.js -var DefaultBufferLength3 = 1024; -var nextPropID3 = 0; -var NodeProp3 = class { - constructor(config4 = {}) { - this.id = nextPropID3++; - this.perNode = !!config4.perNode; - this.deserialize = config4.deserialize || (() => { - throw new Error("This node type doesn't define a deserialize function"); - }); - } - add(match2) { - if (this.perNode) - throw new RangeError("Can't add per-node props to node types"); - if (typeof match2 != "function") - match2 = NodeType3.match(match2); - return (type) => { - let result = match2(type); - return result === void 0 ? null : [this, result]; - }; - } -}; -NodeProp3.closedBy = new NodeProp3({ deserialize: (str) => str.split(" ") }); -NodeProp3.openedBy = new NodeProp3({ deserialize: (str) => str.split(" ") }); -NodeProp3.group = new NodeProp3({ deserialize: (str) => str.split(" ") }); -NodeProp3.isolate = new NodeProp3({ deserialize: (value) => { - if (value && value != "rtl" && value != "ltr" && value != "auto") - throw new RangeError("Invalid value for isolate: " + value); - return value || "auto"; -} }); -NodeProp3.contextHash = new NodeProp3({ perNode: true }); -NodeProp3.lookAhead = new NodeProp3({ perNode: true }); -NodeProp3.mounted = new NodeProp3({ perNode: true }); -var MountedTree = class { - constructor(tree, overlay, parser3) { - this.tree = tree; - this.overlay = overlay; - this.parser = parser3; - } - static get(tree) { - return tree && tree.props && tree.props[NodeProp3.mounted.id]; - } -}; -var noProps3 = /* @__PURE__ */ Object.create(null); -var NodeType3 = class { - constructor(name317, props, id3, flags = 0) { - this.name = name317; - this.props = props; - this.id = id3; - this.flags = flags; - } - static define(spec) { - let props = spec.props && spec.props.length ? /* @__PURE__ */ Object.create(null) : noProps3; - let flags = (spec.top ? 1 : 0) | (spec.skipped ? 2 : 0) | (spec.error ? 4 : 0) | (spec.name == null ? 8 : 0); - let type = new NodeType3(spec.name || "", props, spec.id, flags); - if (spec.props) - for (let src of spec.props) { - if (!Array.isArray(src)) - src = src(type); - if (src) { - if (src[0].perNode) - throw new RangeError("Can't store a per-node prop on a node type"); - props[src[0].id] = src[1]; - } - } - return type; - } - prop(prop2) { - return this.props[prop2.id]; + return classNames13; +} +function getDayStyle(dayPicker, activeModifiers) { + var style = __assign({}, dayPicker.styles.day); + Object.keys(activeModifiers).forEach(function(modifier) { + var _a; + style = __assign(__assign({}, style), (_a = dayPicker.modifiersStyles) === null || _a === void 0 ? void 0 : _a[modifier]); + }); + return style; +} +function useDayRender(day, displayMonth, buttonRef) { + var _a; + var _b, _c; + var dayPicker = useDayPicker(); + var focusContext = useFocusContext(); + var activeModifiers = useActiveModifiers(day, displayMonth); + var eventHandlers = useDayEventHandlers(day, activeModifiers); + var selectedDays = useSelectedDays(); + var isButton = Boolean(dayPicker.onDayClick || dayPicker.mode !== "default"); + (0, import_react29.useEffect)(function() { + var _a2; + if (activeModifiers.outside) + return; + if (!focusContext.focusedDay) + return; + if (!isButton) + return; + if (isSameDay(focusContext.focusedDay, day)) { + (_a2 = buttonRef.current) === null || _a2 === void 0 ? void 0 : _a2.focus(); + } + }, [ + focusContext.focusedDay, + day, + buttonRef, + isButton, + activeModifiers.outside + ]); + var className = getDayClassNames(dayPicker, activeModifiers).join(" "); + var style = getDayStyle(dayPicker, activeModifiers); + var isHidden = Boolean(activeModifiers.outside && !dayPicker.showOutsideDays || activeModifiers.hidden); + var DayContentComponent = (_c = (_b = dayPicker.components) === null || _b === void 0 ? void 0 : _b.DayContent) !== null && _c !== void 0 ? _c : DayContent; + var children = jsxRuntimeExports.jsx(DayContentComponent, { date: day, displayMonth, activeModifiers }); + var divProps = { + style, + className, + children, + role: "gridcell" + }; + var isFocusTarget = focusContext.focusTarget && isSameDay(focusContext.focusTarget, day) && !activeModifiers.outside; + var isFocused = focusContext.focusedDay && isSameDay(focusContext.focusedDay, day); + var buttonProps = __assign(__assign(__assign({}, divProps), (_a = { disabled: activeModifiers.disabled, role: "gridcell" }, _a["aria-selected"] = activeModifiers.selected, _a.tabIndex = isFocused || isFocusTarget ? 0 : -1, _a)), eventHandlers); + var dayRender = { + isButton, + isHidden, + activeModifiers, + selectedDays, + buttonProps, + divProps + }; + return dayRender; +} +function Day(props) { + var buttonRef = (0, import_react29.useRef)(null); + var dayRender = useDayRender(props.date, props.displayMonth, buttonRef); + if (dayRender.isHidden) { + return jsxRuntimeExports.jsx("div", { role: "gridcell" }); } - get isTop() { - return (this.flags & 1) > 0; + if (!dayRender.isButton) { + return jsxRuntimeExports.jsx("div", __assign({}, dayRender.divProps)); } - get isSkipped() { - return (this.flags & 2) > 0; + return jsxRuntimeExports.jsx(Button, __assign({ name: "day", ref: buttonRef }, dayRender.buttonProps)); +} +function WeekNumber(props) { + var weekNumber = props.number, dates = props.dates; + var _a = useDayPicker(), onWeekNumberClick = _a.onWeekNumberClick, styles2 = _a.styles, classNames13 = _a.classNames, locale2 = _a.locale, labelWeekNumber2 = _a.labels.labelWeekNumber, formatWeekNumber2 = _a.formatters.formatWeekNumber; + var content3 = formatWeekNumber2(Number(weekNumber), { locale: locale2 }); + if (!onWeekNumberClick) { + return jsxRuntimeExports.jsx("span", { className: classNames13.weeknumber, style: styles2.weeknumber, children: content3 }); } - get isError() { - return (this.flags & 4) > 0; + var label = labelWeekNumber2(Number(weekNumber), { locale: locale2 }); + var handleClick = function(e5) { + onWeekNumberClick(weekNumber, dates, e5); + }; + return jsxRuntimeExports.jsx(Button, { name: "week-number", "aria-label": label, className: classNames13.weeknumber, style: styles2.weeknumber, onClick: handleClick, children: content3 }); +} +function Row(props) { + var _a, _b; + var _c = useDayPicker(), styles2 = _c.styles, classNames13 = _c.classNames, showWeekNumber = _c.showWeekNumber, components = _c.components; + var DayComponent = (_a = components === null || components === void 0 ? void 0 : components.Day) !== null && _a !== void 0 ? _a : Day; + var WeeknumberComponent = (_b = components === null || components === void 0 ? void 0 : components.WeekNumber) !== null && _b !== void 0 ? _b : WeekNumber; + var weekNumberCell; + if (showWeekNumber) { + weekNumberCell = jsxRuntimeExports.jsx("td", { className: classNames13.cell, style: styles2.cell, children: jsxRuntimeExports.jsx(WeeknumberComponent, { number: props.weekNumber, dates: props.dates }) }); } - get isAnonymous() { - return (this.flags & 8) > 0; + return jsxRuntimeExports.jsxs("tr", { className: classNames13.row, style: styles2.row, children: [weekNumberCell, props.dates.map(function(date) { + return jsxRuntimeExports.jsx("td", { className: classNames13.cell, style: styles2.cell, role: "presentation", children: jsxRuntimeExports.jsx(DayComponent, { displayMonth: props.displayMonth, date }) }, getUnixTime(date)); + })] }); +} +function daysToMonthWeeks(fromDate, toDate2, options) { + var toWeek = (options === null || options === void 0 ? void 0 : options.ISOWeek) ? endOfISOWeek(toDate2) : endOfWeek(toDate2, options); + var fromWeek = (options === null || options === void 0 ? void 0 : options.ISOWeek) ? startOfISOWeek(fromDate) : startOfWeek(fromDate, options); + var nOfDays = differenceInCalendarDays(toWeek, fromWeek); + var days = []; + for (var i4 = 0; i4 <= nOfDays; i4++) { + days.push(addDays(fromWeek, i4)); } - is(name317) { - if (typeof name317 == "string") { - if (this.name == name317) - return true; - let group = this.prop(NodeProp3.group); - return group ? group.indexOf(name317) > -1 : false; + var weeksInMonth = days.reduce(function(result, date) { + var weekNumber = (options === null || options === void 0 ? void 0 : options.ISOWeek) ? getISOWeek(date) : getWeek(date, options); + var existingWeek = result.find(function(value) { + return value.weekNumber === weekNumber; + }); + if (existingWeek) { + existingWeek.dates.push(date); + return result; } - return this.id == name317; - } - static match(map4) { - let direct = /* @__PURE__ */ Object.create(null); - for (let prop2 in map4) - for (let name317 of prop2.split(" ")) - direct[name317] = map4[prop2]; - return (node) => { - for (let groups = node.prop(NodeProp3.group), i4 = -1; i4 < (groups ? groups.length : 0); i4++) { - let found = direct[i4 < 0 ? node.name : groups[i4]]; - if (found) - return found; - } - }; - } -}; -NodeType3.none = new NodeType3("", /* @__PURE__ */ Object.create(null), 0, 8); -var CachedNode3 = /* @__PURE__ */ new WeakMap(); -var CachedInnerNode3 = /* @__PURE__ */ new WeakMap(); -var IterMode3; -(function(IterMode4) { - IterMode4[IterMode4["ExcludeBuffers"] = 1] = "ExcludeBuffers"; - IterMode4[IterMode4["IncludeAnonymous"] = 2] = "IncludeAnonymous"; - IterMode4[IterMode4["IgnoreMounts"] = 4] = "IgnoreMounts"; - IterMode4[IterMode4["IgnoreOverlays"] = 8] = "IgnoreOverlays"; -})(IterMode3 || (IterMode3 = {})); -var Tree3 = class { - constructor(type, children, positions, length, props) { - this.type = type; - this.children = children; - this.positions = positions; - this.length = length; - this.props = null; - if (props && props.length) { - this.props = /* @__PURE__ */ Object.create(null); - for (let [prop2, value] of props) - this.props[typeof prop2 == "number" ? prop2 : prop2.id] = value; + result.push({ + weekNumber, + dates: [date] + }); + return result; + }, []); + return weeksInMonth; +} +function getMonthWeeks(month, options) { + var weeksInMonth = daysToMonthWeeks(startOfMonth(month), endOfMonth(month), options); + if (options === null || options === void 0 ? void 0 : options.useFixedWeeks) { + var nrOfMonthWeeks = getWeeksInMonth(month, options); + if (nrOfMonthWeeks < 6) { + var lastWeek = weeksInMonth[weeksInMonth.length - 1]; + var lastDate = lastWeek.dates[lastWeek.dates.length - 1]; + var toDate2 = addWeeks(lastDate, 6 - nrOfMonthWeeks); + var extraWeeks = daysToMonthWeeks(addWeeks(lastDate, 1), toDate2, options); + weeksInMonth.push.apply(weeksInMonth, extraWeeks); } } - toString() { - let mounted = MountedTree.get(this); - if (mounted && !mounted.overlay) - return mounted.tree.toString(); - let children = ""; - for (let ch of this.children) { - let str = ch.toString(); - if (str) { - if (children) - children += ","; - children += str; - } + return weeksInMonth; +} +function Table(props) { + var _a, _b, _c; + var _d = useDayPicker(), locale2 = _d.locale, classNames13 = _d.classNames, styles2 = _d.styles, hideHead = _d.hideHead, fixedWeeks = _d.fixedWeeks, components = _d.components, weekStartsOn = _d.weekStartsOn, firstWeekContainsDate = _d.firstWeekContainsDate, ISOWeek = _d.ISOWeek; + var weeks = getMonthWeeks(props.displayMonth, { + useFixedWeeks: Boolean(fixedWeeks), + ISOWeek, + locale: locale2, + weekStartsOn, + firstWeekContainsDate + }); + var HeadComponent = (_a = components === null || components === void 0 ? void 0 : components.Head) !== null && _a !== void 0 ? _a : Head; + var RowComponent = (_b = components === null || components === void 0 ? void 0 : components.Row) !== null && _b !== void 0 ? _b : Row; + var FooterComponent = (_c = components === null || components === void 0 ? void 0 : components.Footer) !== null && _c !== void 0 ? _c : Footer; + return jsxRuntimeExports.jsxs("table", { id: props.id, className: classNames13.table, style: styles2.table, role: "grid", "aria-labelledby": props["aria-labelledby"], children: [!hideHead && jsxRuntimeExports.jsx(HeadComponent, {}), jsxRuntimeExports.jsx("tbody", { className: classNames13.tbody, style: styles2.tbody, children: weeks.map(function(week) { + return jsxRuntimeExports.jsx(RowComponent, { displayMonth: props.displayMonth, dates: week.dates, weekNumber: week.weekNumber }, week.weekNumber); + }) }), jsxRuntimeExports.jsx(FooterComponent, { displayMonth: props.displayMonth })] }); +} +function canUseDOM2() { + return !!(typeof window !== "undefined" && window.document && window.document.createElement); +} +var useIsomorphicLayoutEffect2 = canUseDOM2() ? import_react29.useLayoutEffect : import_react29.useEffect; +var serverHandoffComplete = false; +var id2 = 0; +function genId2() { + return "react-day-picker-".concat(++id2); +} +function useId(providedId) { + var _a; + var initialId = providedId !== null && providedId !== void 0 ? providedId : serverHandoffComplete ? genId2() : null; + var _b = (0, import_react29.useState)(initialId), id3 = _b[0], setId = _b[1]; + useIsomorphicLayoutEffect2(function() { + if (id3 === null) { + setId(genId2()); } - return !this.type.name ? children : (/\W/.test(this.type.name) && !this.type.isError ? JSON.stringify(this.type.name) : this.type.name) + (children.length ? "(" + children + ")" : ""); - } - cursor(mode2 = 0) { - return new TreeCursor3(this.topNode, mode2); - } - cursorAt(pos, side = 0, mode2 = 0) { - let scope = CachedNode3.get(this) || this.topNode; - let cursor2 = new TreeCursor3(scope); - cursor2.moveTo(pos, side); - CachedNode3.set(this, cursor2._tree); - return cursor2; - } - get topNode() { - return new TreeNode4(this, 0, 0, null); - } - resolve(pos, side = 0) { - let node = resolveNode3(CachedNode3.get(this) || this.topNode, pos, side, false); - CachedNode3.set(this, node); - return node; - } - resolveInner(pos, side = 0) { - let node = resolveNode3(CachedInnerNode3.get(this) || this.topNode, pos, side, true); - CachedInnerNode3.set(this, node); - return node; - } - resolveStack(pos, side = 0) { - return stackIterator(this, pos, side); - } - iterate(spec) { - let { enter, leave, from = 0, to: to2 = this.length } = spec; - let mode2 = spec.mode || 0, anon = (mode2 & IterMode3.IncludeAnonymous) > 0; - for (let c3 = this.cursor(mode2 | IterMode3.IncludeAnonymous); ; ) { - let entered = false; - if (c3.from <= to2 && c3.to >= from && (!anon && c3.type.isAnonymous || enter(c3) !== false)) { - if (c3.firstChild()) - continue; - entered = true; - } - for (; ; ) { - if (entered && leave && (anon || !c3.type.isAnonymous)) - leave(c3); - if (c3.nextSibling()) - break; - if (!c3.parent()) - return; - entered = true; - } + }, []); + (0, import_react29.useEffect)(function() { + if (serverHandoffComplete === false) { + serverHandoffComplete = true; } + }, []); + return (_a = providedId !== null && providedId !== void 0 ? providedId : id3) !== null && _a !== void 0 ? _a : void 0; +} +function Month(props) { + var _a; + var _b; + var dayPicker = useDayPicker(); + var dir = dayPicker.dir, classNames13 = dayPicker.classNames, styles2 = dayPicker.styles, components = dayPicker.components; + var displayMonths = useNavigation().displayMonths; + var captionId = useId(dayPicker.id ? "".concat(dayPicker.id, "-").concat(props.displayIndex) : void 0); + var tableId = dayPicker.id ? "".concat(dayPicker.id, "-grid-").concat(props.displayIndex) : void 0; + var className = [classNames13.month]; + var style = styles2.month; + var isStart = props.displayIndex === 0; + var isEnd = props.displayIndex === displayMonths.length - 1; + var isCenter = !isStart && !isEnd; + if (dir === "rtl") { + _a = [isStart, isEnd], isEnd = _a[0], isStart = _a[1]; } - prop(prop2) { - return !prop2.perNode ? this.type.prop(prop2) : this.props ? this.props[prop2.id] : void 0; - } - get propValues() { - let result = []; - if (this.props) - for (let id3 in this.props) - result.push([+id3, this.props[id3]]); - return result; - } - balance(config4 = {}) { - return this.children.length <= 8 ? this : balanceRange3(NodeType3.none, this.children, this.positions, 0, this.children.length, 0, this.length, (children, positions, length) => new Tree3(this.type, children, positions, length, this.propValues), config4.makeTree || ((children, positions, length) => new Tree3(NodeType3.none, children, positions, length))); - } - static build(data2) { - return buildTree3(data2); - } -}; -Tree3.empty = new Tree3(NodeType3.none, [], [], 0); -var FlatBufferCursor3 = class { - constructor(buffer, index2) { - this.buffer = buffer; - this.index = index2; - } - get id() { - return this.buffer[this.index - 4]; - } - get start() { - return this.buffer[this.index - 3]; - } - get end() { - return this.buffer[this.index - 2]; + if (isStart) { + className.push(classNames13.caption_start); + style = __assign(__assign({}, style), styles2.caption_start); } - get size() { - return this.buffer[this.index - 1]; + if (isEnd) { + className.push(classNames13.caption_end); + style = __assign(__assign({}, style), styles2.caption_end); } - get pos() { - return this.index; + if (isCenter) { + className.push(classNames13.caption_between); + style = __assign(__assign({}, style), styles2.caption_between); } - next() { - this.index -= 4; + var CaptionComponent = (_b = components === null || components === void 0 ? void 0 : components.Caption) !== null && _b !== void 0 ? _b : Caption; + return jsxRuntimeExports.jsxs("div", { className: className.join(" "), style, children: [jsxRuntimeExports.jsx(CaptionComponent, { id: captionId, displayMonth: props.displayMonth, displayIndex: props.displayIndex }), jsxRuntimeExports.jsx(Table, { id: tableId, "aria-labelledby": captionId, displayMonth: props.displayMonth })] }, props.displayIndex); +} +function Months(props) { + var _a = useDayPicker(), classNames13 = _a.classNames, styles2 = _a.styles; + return jsxRuntimeExports.jsx("div", { className: classNames13.months, style: styles2.months, children: props.children }); +} +function Root(_a) { + var _b, _c; + var initialProps = _a.initialProps; + var dayPicker = useDayPicker(); + var focusContext = useFocusContext(); + var navigation = useNavigation(); + var _d = (0, import_react29.useState)(false), hasInitialFocus = _d[0], setHasInitialFocus = _d[1]; + (0, import_react29.useEffect)(function() { + if (!dayPicker.initialFocus) + return; + if (!focusContext.focusTarget) + return; + if (hasInitialFocus) + return; + focusContext.focus(focusContext.focusTarget); + setHasInitialFocus(true); + }, [ + dayPicker.initialFocus, + hasInitialFocus, + focusContext.focus, + focusContext.focusTarget, + focusContext + ]); + var classNames13 = [dayPicker.classNames.root, dayPicker.className]; + if (dayPicker.numberOfMonths > 1) { + classNames13.push(dayPicker.classNames.multiple_months); } - fork() { - return new FlatBufferCursor3(this.buffer, this.index); + if (dayPicker.showWeekNumber) { + classNames13.push(dayPicker.classNames.with_weeknumber); } + var style = __assign(__assign({}, dayPicker.styles.root), dayPicker.style); + var dataAttributes = Object.keys(initialProps).filter(function(key2) { + return key2.startsWith("data-"); + }).reduce(function(attrs, key2) { + var _a2; + return __assign(__assign({}, attrs), (_a2 = {}, _a2[key2] = initialProps[key2], _a2)); + }, {}); + var MonthsComponent = (_c = (_b = initialProps.components) === null || _b === void 0 ? void 0 : _b.Months) !== null && _c !== void 0 ? _c : Months; + return jsxRuntimeExports.jsx("div", __assign({ className: classNames13.join(" "), style, dir: dayPicker.dir, id: dayPicker.id, nonce: initialProps.nonce, title: initialProps.title, lang: initialProps.lang }, dataAttributes, { children: jsxRuntimeExports.jsx(MonthsComponent, { children: navigation.displayMonths.map(function(month, i4) { + return jsxRuntimeExports.jsx(Month, { displayIndex: i4, displayMonth: month }, i4); + }) }) })); +} +function RootProvider(props) { + var children = props.children, initialProps = __rest(props, ["children"]); + return jsxRuntimeExports.jsx(DayPickerProvider, { initialProps, children: jsxRuntimeExports.jsx(NavigationProvider, { children: jsxRuntimeExports.jsx(SelectSingleProvider, { initialProps, children: jsxRuntimeExports.jsx(SelectMultipleProvider, { initialProps, children: jsxRuntimeExports.jsx(SelectRangeProvider, { initialProps, children: jsxRuntimeExports.jsx(ModifiersProvider, { children: jsxRuntimeExports.jsx(FocusProvider, { children }) }) }) }) }) }) }); +} +function DayPicker(props) { + return jsxRuntimeExports.jsx(RootProvider, __assign({}, props, { children: jsxRuntimeExports.jsx(Root, { initialProps: props }) })); +} + +// src/core/react/components/UI/Menus/properties/datePickerMenu.tsx +var showDatePickerMenu = (ui, rect, value, setValue, time, format8, anchor) => { + return ui.openCustomMenu( + rect, + /* @__PURE__ */ import_react30.default.createElement(DatePicker, { + ui, + value, + setValue, + time + }), + {}, + anchor + ); }; -var TreeBuffer3 = class { - constructor(buffer, length, set) { - this.buffer = buffer; - this.length = length; - this.set = set; - } - get type() { - return NodeType3.none; - } - toString() { - let result = []; - for (let index2 = 0; index2 < this.buffer.length; ) { - result.push(this.childString(index2)); - index2 = this.buffer[index2 + 3]; +var DatePickerHeader = (props) => { + const { goToMonth, nextMonth, previousMonth } = useNavigation(); + return /* @__PURE__ */ import_react30.default.createElement("div", { + className: "mk-date-picker-header" + }, /* @__PURE__ */ import_react30.default.createElement("button", { + disabled: !previousMonth, + onClick: () => previousMonth && goToMonth(previousMonth), + dangerouslySetInnerHTML: { + __html: props.ui.getSticker("ui//chevron-left") } - return result.join(","); - } - childString(index2) { - let id3 = this.buffer[index2], endIndex = this.buffer[index2 + 3]; - let type = this.set.types[id3], result = type.name; - if (/\W/.test(result) && !type.isError) - result = JSON.stringify(result); - index2 += 4; - if (endIndex == index2) - return result; - let children = []; - while (index2 < endIndex) { - children.push(this.childString(index2)); - index2 = this.buffer[index2 + 3]; + }), format(props.displayMonth, "MMM yyy"), /* @__PURE__ */ import_react30.default.createElement("button", { + disabled: !nextMonth, + onClick: () => nextMonth && goToMonth(nextMonth), + dangerouslySetInnerHTML: { + __html: props.ui.getSticker("ui//chevron-right") } - return result + "(" + children.join(",") + ")"; - } - findChild(startIndex, endIndex, dir, pos, side) { - let { buffer } = this, pick = -1; - for (let i4 = startIndex; i4 != endIndex; i4 = buffer[i4 + 3]) { - if (checkSide3(side, pos, buffer[i4 + 1], buffer[i4 + 2])) { - pick = i4; - if (dir > 0) - break; - } + })); +}; +var DatePicker = (props) => { + const [hour, setHour] = (0, import_react30.useState)(0); + const [minutes, setMinutes] = (0, import_react30.useState)(0); + const [seconds, setSeconds] = (0, import_react30.useState)(0); + const [date, setDate] = (0, import_react30.useState)(props.value); + (0, import_react30.useEffect)(() => { + const date2 = props.value ?? new Date(); + setHour(date2.getHours()); + setMinutes(date2.getMinutes()); + setSeconds(date2.getSeconds()); + setDate(date2); + }, [props.value]); + const updateDate = () => { + const newDate = new Date(date); + if (props.time) { + newDate.setHours(hour); + newDate.setMinutes(minutes); + newDate.setSeconds(seconds); } - return pick; - } - slice(startI, endI, from) { - let b2 = this.buffer; - let copy = new Uint16Array(endI - startI), len = 0; - for (let i4 = startI, j = 0; i4 < endI; ) { - copy[j++] = b2[i4++]; - copy[j++] = b2[i4++] - from; - let to2 = copy[j++] = b2[i4++] - from; - copy[j++] = b2[i4++] - startI; - len = Math.max(len, to2); + props.setValue(newDate); + }; + return /* @__PURE__ */ import_react30.default.createElement("div", { + className: "mk-date-picker-container" + }, /* @__PURE__ */ import_react30.default.createElement(DayPicker, { + defaultMonth: date, + mode: "single", + selected: date, + classNames: { + root: "mk-date-picker", + day: "mk-date-picker-day", + cell: "mk-date-picker-cell", + months: "mk-date-picker-months", + month: "mk-date-picker-month", + day_today: "mk-date-picker-today", + day_selected: "mk-date-picker-selected" + }, + components: { + Caption: (_props) => DatePickerHeader({ ui: props.ui, ..._props }) + }, + labels: { + labelMonthDropdown: () => void 0, + labelYearDropdown: () => void 0, + labelNext: () => void 0, + labelPrevious: () => void 0, + labelDay: () => void 0, + labelWeekday: () => void 0, + labelWeekNumber: () => void 0 + }, + onSelect: (date2, s4, a4, e5) => { + setDate(date2); + props.setValue(date2); + e5.stopPropagation(); } - return new TreeBuffer3(copy, len, this.set); - } -}; -function checkSide3(side, pos, from, to2) { - switch (side) { - case -2: - return from < pos; - case -1: - return to2 >= pos && from < pos; - case 0: - return from < pos && to2 > pos; - case 1: - return from <= pos && to2 > pos; - case 2: - return to2 > pos; - case 4: - return true; - } -} -function resolveNode3(node, pos, side, overlays) { - var _a; - while (node.from == node.to || (side < 1 ? node.from >= pos : node.from > pos) || (side > -1 ? node.to <= pos : node.to < pos)) { - let parent = !overlays && node instanceof TreeNode4 && node.index < 0 ? null : node.parent; - if (!parent) - return node; - node = parent; - } - let mode2 = overlays ? 0 : IterMode3.IgnoreOverlays; - if (overlays) - for (let scan = node, parent = scan.parent; parent; scan = parent, parent = scan.parent) { - if (scan instanceof TreeNode4 && scan.index < 0 && ((_a = parent.enter(pos, side, mode2)) === null || _a === void 0 ? void 0 : _a.from) != scan.from) - node = parent; + }), props.time != 0 /* None */ && /* @__PURE__ */ import_react30.default.createElement("div", { + className: "mk-date-picker-time" + }, /* @__PURE__ */ import_react30.default.createElement("div", { + dangerouslySetInnerHTML: { + __html: props.ui.getSticker("ui//clock") } - for (; ; ) { - let inner = node.enter(pos, side, mode2); - if (!inner) - return node; - node = inner; - } -} -var BaseNode = class { - cursor(mode2 = 0) { - return new TreeCursor3(this, mode2); - } - getChild(type, before = null, after = null) { - let r2 = getChildren3(this, type, before, after); - return r2.length ? r2[0] : null; - } - getChildren(type, before = null, after = null) { - return getChildren3(this, type, before, after); - } - resolve(pos, side = 0) { - return resolveNode3(this, pos, side, false); - } - resolveInner(pos, side = 0) { - return resolveNode3(this, pos, side, true); - } - matchContext(context) { - return matchNodeContext3(this, context); - } - enterUnfinishedNodesBefore(pos) { - let scan = this.childBefore(pos), node = this; - while (scan) { - let last = scan.lastChild; - if (!last || last.to != scan.to) - break; - if (last.type.isError && last.from == last.to) { - node = scan; - scan = last.prevSibling; - } else { - scan = last; + }), /* @__PURE__ */ import_react30.default.createElement("input", { + type: "text", + value: hour.toString().padStart(2, "0"), + onKeyDown: (e5) => { + if (e5.key === "ArrowUp") { + setHour((hour + 1) % 24); + updateDate(); + } else if (e5.key === "ArrowDown") { + setHour((hour + 23) % 24); + updateDate(); } + }, + onChange: (e5) => { + setHour(+e5.target.value); + updateDate(); } - return node; - } - get node() { - return this; - } - get next() { - return this.parent; - } -}; -var TreeNode4 = class extends BaseNode { - constructor(_tree, from, index2, _parent) { - super(); - this._tree = _tree; - this.from = from; - this.index = index2; - this._parent = _parent; - } - get type() { - return this._tree.type; - } - get name() { - return this._tree.type.name; - } - get to() { - return this.from + this._tree.length; - } - nextChild(i4, dir, pos, side, mode2 = 0) { - for (let parent = this; ; ) { - for (let { children, positions } = parent._tree, e5 = dir > 0 ? children.length : -1; i4 != e5; i4 += dir) { - let next = children[i4], start = positions[i4] + parent.from; - if (!checkSide3(side, pos, start, start + next.length)) - continue; - if (next instanceof TreeBuffer3) { - if (mode2 & IterMode3.ExcludeBuffers) - continue; - let index2 = next.findChild(0, next.buffer.length, dir, pos - start, side); - if (index2 > -1) - return new BufferNode3(new BufferContext3(parent, next, i4, start), null, index2); - } else if (mode2 & IterMode3.IncludeAnonymous || (!next.type.isAnonymous || hasChild3(next))) { - let mounted; - if (!(mode2 & IterMode3.IgnoreMounts) && (mounted = MountedTree.get(next)) && !mounted.overlay) - return new TreeNode4(mounted.tree, start, i4, parent); - let inner = new TreeNode4(next, start, i4, parent); - return mode2 & IterMode3.IncludeAnonymous || !inner.type.isAnonymous ? inner : inner.nextChild(dir < 0 ? next.children.length - 1 : 0, dir, pos, side); - } + }), ":", /* @__PURE__ */ import_react30.default.createElement("input", { + type: "text", + value: minutes.toString().padStart(2, "0"), + onKeyDown: (e5) => { + if (e5.key === "ArrowUp") { + setMinutes((minutes + 1) % 60); + updateDate(); + } else if (e5.key === "ArrowDown") { + setMinutes((minutes + 59) % 60); + updateDate(); } - if (mode2 & IterMode3.IncludeAnonymous || !parent.type.isAnonymous) - return null; - if (parent.index >= 0) - i4 = parent.index + dir; - else - i4 = dir < 0 ? -1 : parent._parent._tree.children.length; - parent = parent._parent; - if (!parent) - return null; + }, + onChange: (e5) => { + setMinutes(+e5.target.value); + updateDate(); } - } - get firstChild() { - return this.nextChild(0, 1, 0, 4); - } - get lastChild() { - return this.nextChild(this._tree.children.length - 1, -1, 0, 4); - } - childAfter(pos) { - return this.nextChild(0, 1, pos, 2); - } - childBefore(pos) { - return this.nextChild(this._tree.children.length - 1, -1, pos, -2); - } - enter(pos, side, mode2 = 0) { - let mounted; - if (!(mode2 & IterMode3.IgnoreOverlays) && (mounted = MountedTree.get(this._tree)) && mounted.overlay) { - let rPos = pos - this.from; - for (let { from, to: to2 } of mounted.overlay) { - if ((side > 0 ? from <= rPos : from < rPos) && (side < 0 ? to2 >= rPos : to2 > rPos)) - return new TreeNode4(mounted.tree, mounted.overlay[0].from + this.from, -1, this); - } + }), /* @__PURE__ */ import_react30.default.createElement("button", { + className: "mk-date-picker-meridiem", + onClick: () => { + setHour((hour + 12) % 24); + updateDate(); } - return this.nextChild(0, 1, pos, side, mode2); - } - nextSignificantParent() { - let val = this; - while (val.type.isAnonymous && val._parent) - val = val._parent; - return val; - } - get parent() { - return this._parent ? this._parent.nextSignificantParent() : null; - } - get nextSibling() { - return this._parent && this.index >= 0 ? this._parent.nextChild(this.index + 1, 1, 0, 4) : null; - } - get prevSibling() { - return this._parent && this.index >= 0 ? this._parent.nextChild(this.index - 1, -1, 0, 4) : null; - } - get tree() { - return this._tree; - } - toTree() { - return this._tree; - } - toString() { - return this._tree.toString(); - } + }, hour < 12 ? "AM" : "PM"), /* @__PURE__ */ import_react30.default.createElement("button", { + onClick: () => updateDate(), + dangerouslySetInnerHTML: { + __html: props.ui.getSticker("ui//close") + } + }))); }; -function getChildren3(node, type, before, after) { - let cur = node.cursor(), result = []; - if (!cur.firstChild()) - return result; - if (before != null) - for (let found = false; !found; ) { - found = cur.type.is(before); - if (!cur.nextSibling()) - return result; - } - for (; ; ) { - if (after != null && cur.type.is(after)) - return result; - if (cur.type.is(type)) - result.push(cur.node); - if (!cur.nextSibling()) - return after == null ? result : []; - } -} -function matchNodeContext3(node, context, i4 = context.length - 1) { - for (let p = node.parent; i4 >= 0; p = p.parent) { - if (!p) - return false; - if (!p.type.isAnonymous) { - if (context[i4] && context[i4] != p.name) - return false; - i4--; - } - } - return true; -} -var BufferContext3 = class { - constructor(parent, buffer, index2, start) { - this.parent = parent; - this.buffer = buffer; - this.index = index2; - this.start = start; - } + +// src/core/utils/contexts/predicate/filterFns/filterFnLabels.ts +var filterFnLabels = { + isEmpty: i18n_default.filterTypes.isEmpty, + isNotEmpty: i18n_default.filterTypes.isNotEmpty, + include: i18n_default.filterTypes.contains, + notInclude: i18n_default.filterTypes.notContains, + is: i18n_default.filterTypes.is, + isNot: i18n_default.filterTypes.isNot, + isLink: i18n_default.filterTypes.is, + isNotLink: i18n_default.filterTypes.isNot, + equal: "=", + isGreatThan: ">", + isLessThan: "<", + isLessThanOrEqual: "\u2264", + isGreatThanOrEqual: "\u2265", + dateBefore: i18n_default.filterTypes.before, + dateAfter: i18n_default.filterTypes.after, + isSameDate: i18n_default.filterTypes.isSameDate, + isSameDateAsToday: i18n_default.filterTypes.isSameDateAsToday, + isExactList: i18n_default.filterTypes.is, + isAnyInList: i18n_default.filterTypes.anyOf, + isNoneInList: i18n_default.filterTypes.noneOf, + isTrue: i18n_default.filterTypes.checked, + isFalse: i18n_default.filterTypes.unchecked }; -var BufferNode3 = class extends BaseNode { - get name() { - return this.type.name; - } - get from() { - return this.context.start + this.context.buffer.buffer[this.index + 1]; - } - get to() { - return this.context.start + this.context.buffer.buffer[this.index + 2]; - } - constructor(context, _parent, index2) { - super(); - this.context = context; - this._parent = _parent; - this.index = index2; - this.type = context.buffer.set.types[context.buffer.buffer[index2]]; - } - child(dir, pos, side) { - let { buffer } = this.context; - let index2 = buffer.findChild(this.index + 4, buffer.buffer[this.index + 3], dir, pos - this.context.start, side); - return index2 < 0 ? null : new BufferNode3(this.context, this, index2); - } - get firstChild() { - return this.child(1, 0, 4); - } - get lastChild() { - return this.child(-1, 0, 4); - } - childAfter(pos) { - return this.child(1, pos, 2); - } - childBefore(pos) { - return this.child(-1, pos, -2); - } - enter(pos, side, mode2 = 0) { - if (mode2 & IterMode3.ExcludeBuffers) - return null; - let { buffer } = this.context; - let index2 = buffer.findChild(this.index + 4, buffer.buffer[this.index + 3], side > 0 ? 1 : -1, pos - this.context.start, side); - return index2 < 0 ? null : new BufferNode3(this.context, this, index2); - } - get parent() { - return this._parent || this.context.parent.nextSignificantParent(); - } - externalSibling(dir) { - return this._parent ? null : this.context.parent.nextChild(this.context.index + dir, dir, 0, 4); - } - get nextSibling() { - let { buffer } = this.context; - let after = buffer.buffer[this.index + 3]; - if (after < (this._parent ? buffer.buffer[this._parent.index + 3] : buffer.buffer.length)) - return new BufferNode3(this.context, this._parent, after); - return this.externalSibling(1); - } - get prevSibling() { - let { buffer } = this.context; - let parentStart = this._parent ? this._parent.index + 4 : 0; - if (this.index == parentStart) - return this.externalSibling(-1); - return new BufferNode3(this.context, this._parent, buffer.findChild(parentStart, this.index, -1, 0, 4)); - } - get tree() { - return null; - } - toTree() { - let children = [], positions = []; - let { buffer } = this.context; - let startI = this.index + 4, endI = buffer.buffer[this.index + 3]; - if (endI > startI) { - let from = buffer.buffer[this.index + 1]; - children.push(buffer.slice(startI, endI, from)); - positions.push(0); + +// src/core/react/components/SpaceEditor/SpaceQuery.tsx +var import_react39 = __toESM(require_react()); + +// src/core/react/components/UI/Menus/navigator/showSpaceAddMenu.tsx +var import_react31 = __toESM(require_react()); +var defaultAddAction = (superstate, space2, location) => { + if (space2?.path == "spaces://$tags") { + superstate.ui.openModal("New Tag", (props) => { + return /* @__PURE__ */ import_react31.default.createElement(InputModal, { + value: "", + saveLabel: i18n_default.labels.saveView, + hide: props.hide, + saveValue: (value) => addTag(superstate, value) + }); + }); + } else if (space2) { + if (space2?.metadata.template?.length > 0) { + newTemplateInSpace(superstate, space2, space2.metadata.template, location); + return; + } else { + newPathInSpace(superstate, space2, "md", null, false, null, location); } - return new Tree3(this.type, children, positions, this.to - this.from); - } - toString() { - return this.context.buffer.childString(this.index); + } else { + defaultSpace( + superstate, + superstate.pathsIndex.get(superstate.ui.activePath) + ).then((f2) => { + if (f2) + newPathInSpace(superstate, f2, "md", null, false, null, location); + }); } }; -function iterStack(heads) { - if (!heads.length) - return null; - let pick = 0, picked = heads[0]; - for (let i4 = 1; i4 < heads.length; i4++) { - let node = heads[i4]; - if (node.from > picked.from || node.to < picked.to) { - picked = node; - pick = i4; +var showSpaceAddMenu = (superstate, offset2, space2, dontOpen) => { + const menuOptions = []; + if (space2.type == "default") { + menuOptions.push({ + name: "New Tag", + icon: "ui//tags", + onClick: (e5) => { + superstate.ui.openModal("New Tag", (props) => { + return /* @__PURE__ */ import_react31.default.createElement(InputModal, { + value: "", + saveLabel: i18n_default.labels.saveView, + hide: props.hide, + saveValue: (value) => addTag(superstate, value) + }); + }); + } + }); + } else { + menuOptions.push({ + name: i18n_default.labels.createNote, + icon: "ui//edit", + onClick: (e5) => { + newPathInSpace( + superstate, + space2, + "md", + superstate.settings.newNotePlaceholder, + dontOpen + ); + } + }); + menuOptions.push({ + name: i18n_default.buttons.createCanvas, + icon: "ui//layout-dashboard", + onClick: (e5) => { + newPathInSpace(superstate, space2, "canvas", null, dontOpen); + } + }); + menuOptions.push({ + name: i18n_default.labels.createSection, + icon: "ui//folder-plus", + onClick: (e5) => { + superstate.ui.openModal( + i18n_default.labels.createSection, + (props) => /* @__PURE__ */ import_react31.default.createElement(InputModal, { + saveLabel: i18n_default.buttons.createFolder, + value: "", + hide: props.hide, + saveValue: (v2) => { + let pathState = superstate.pathsIndex.get(space2?.path); + if (!pathState) { + pathState = superstate.pathsIndex.get("/"); + } + const newName = v2.replace(/\//g, ""); + const parentPath = pathState?.subtype == "folder" ? pathState.path : pathState.parent ? pathState.parent : "/"; + const newPath = !parentPath || parentPath == "/" ? newName : parentPath + "/" + newName; + if (newName.length == 0) { + superstate.ui.notify(i18n_default.notice.newSpaceName); + return; + } + if (superstate.spacesIndex.has(newPath)) { + superstate.ui.notify(i18n_default.notice.duplicateSpaceName); + return; + } + createSpace(superstate, newPath, {}); + } + }) + ); + } + }); + if (space2.templates.length > 0) { + menuOptions.push(menuSeparator); + for (const template2 of space2.templates) { + menuOptions.push({ + name: template2, + icon: "ui//clipboard-pen", + onClick: (e5) => { + newTemplateInSpace(superstate, space2, template2); + } + }); + } } } - let next = picked instanceof TreeNode4 && picked.index < 0 ? null : picked.parent; - let newHeads = heads.slice(); - if (next) - newHeads[pick] = next; - else - newHeads.splice(pick, 1); - return new StackIterator(newHeads, picked); -} -var StackIterator = class { - constructor(heads, node) { - this.heads = heads; - this.node = node; - } - get next() { - return iterStack(this.heads); - } + return superstate.ui.openMenu( + offset2, + defaultMenu(superstate.ui, menuOptions) + ); }; -function stackIterator(tree, pos, side) { - let inner = tree.resolveInner(pos, side), layers = null; - for (let scan = inner instanceof TreeNode4 ? inner : inner.context.parent; scan; scan = scan.parent) { - if (scan.index < 0) { - let parent = scan.parent; - (layers || (layers = [inner])).push(parent.resolve(pos, side)); - scan = parent; - } else { - let mount = MountedTree.get(scan.tree); - if (mount && mount.overlay && mount.overlay[0].from <= pos && mount.overlay[mount.overlay.length - 1].to >= pos) { - let root = new TreeNode4(mount.tree, mount.overlay[0].from + scan.from, -1, scan); - (layers || (layers = [inner])).push(resolveNode3(root, pos, side, false)); + +// src/core/react/components/UI/Menus/properties/propertyMenu.tsx +var showSetValueMenu = (rect, superstate, property, onChangeValue, path2) => { + if (!property) + return; + if (property.type == "text") { + } else if (property.type == "number") { + const input = menuInput("", (value) => onChangeValue(value)); + superstate.ui.openMenu(rect, { + ...defaultMenu(superstate.ui, [input]) + }); + } else if (property.type == "date") { + showDatePickerMenu( + superstate.ui, + rect, + new Date(), + (date) => onChangeValue(date.toISOString()), + 0 /* None */ + ); + } else if (property.type == "option") { + const options = parseFieldValue(property.value, property.type, superstate, path2)?.options ?? []; + superstate.ui.openMenu(rect, { + ...defaultMenu(superstate.ui, options), + saveOptions: (options2, value) => { + onChangeValue(value[0]); } - } - } - return layers ? iterStack(layers) : inner; -} -var TreeCursor3 = class { - get name() { - return this.type.name; - } - constructor(node, mode2 = 0) { - this.mode = mode2; - this.buffer = null; - this.stack = []; - this.index = 0; - this.bufferNode = null; - if (node instanceof TreeNode4) { - this.yieldNode(node); - } else { - this._tree = node.context.parent; - this.buffer = node.context; - for (let n3 = node._parent; n3; n3 = n3._parent) - this.stack.unshift(n3.index); - this.bufferNode = node; - this.yieldBuf(node.index); - } - } - yieldNode(node) { - if (!node) - return false; - this._tree = node; - this.type = node.type; - this.from = node.from; - this.to = node.to; - return true; - } - yieldBuf(index2, type) { - this.index = index2; - let { start, buffer } = this.buffer; - this.type = type || buffer.set.types[buffer.buffer[index2]]; - this.from = start + buffer.buffer[index2 + 1]; - this.to = start + buffer.buffer[index2 + 2]; - return true; - } - yield(node) { - if (!node) - return false; - if (node instanceof TreeNode4) { - this.buffer = null; - return this.yieldNode(node); - } - this.buffer = node.context; - return this.yieldBuf(node.index, node.type); - } - toString() { - return this.buffer ? this.buffer.buffer.childString(this.index) : this._tree.toString(); - } - enterChild(dir, pos, side) { - if (!this.buffer) - return this.yield(this._tree.nextChild(dir < 0 ? this._tree._tree.children.length - 1 : 0, dir, pos, side, this.mode)); - let { buffer } = this.buffer; - let index2 = buffer.findChild(this.index + 4, buffer.buffer[this.index + 3], dir, pos - this.buffer.start, side); - if (index2 < 0) - return false; - this.stack.push(this.index); - return this.yieldBuf(index2); - } - firstChild() { - return this.enterChild(1, 0, 4); - } - lastChild() { - return this.enterChild(-1, 0, 4); - } - childAfter(pos) { - return this.enterChild(1, pos, 2); - } - childBefore(pos) { - return this.enterChild(-1, pos, -2); - } - enter(pos, side, mode2 = this.mode) { - if (!this.buffer) - return this.yield(this._tree.enter(pos, side, mode2)); - return mode2 & IterMode3.ExcludeBuffers ? false : this.enterChild(1, pos, side); - } - parent() { - if (!this.buffer) - return this.yieldNode(this.mode & IterMode3.IncludeAnonymous ? this._tree._parent : this._tree.parent); - if (this.stack.length) - return this.yieldBuf(this.stack.pop()); - let parent = this.mode & IterMode3.IncludeAnonymous ? this.buffer.parent : this.buffer.parent.nextSignificantParent(); - this.buffer = null; - return this.yieldNode(parent); - } - sibling(dir) { - if (!this.buffer) - return !this._tree._parent ? false : this.yield(this._tree.index < 0 ? null : this._tree._parent.nextChild(this._tree.index + dir, dir, 0, 4, this.mode)); - let { buffer } = this.buffer, d4 = this.stack.length - 1; - if (dir < 0) { - let parentStart = d4 < 0 ? 0 : this.stack[d4] + 4; - if (this.index != parentStart) - return this.yieldBuf(buffer.findChild(parentStart, this.index, -1, 0, 4)); - } else { - let after = buffer.buffer[this.index + 3]; - if (after < (d4 < 0 ? buffer.buffer.length : buffer.buffer[this.stack[d4] + 3])) - return this.yieldBuf(after); - } - return d4 < 0 ? this.yield(this.buffer.parent.nextChild(this.buffer.index + dir, dir, 0, 4, this.mode)) : false; - } - nextSibling() { - return this.sibling(1); - } - prevSibling() { - return this.sibling(-1); - } - atLastNode(dir) { - let index2, parent, { buffer } = this; - if (buffer) { - if (dir > 0) { - if (this.index < buffer.buffer.buffer.length) - return false; - } else { - for (let i4 = 0; i4 < this.index; i4++) - if (buffer.buffer.buffer[i4 + 3] < this.index) - return false; + }); + } else if (property.type == "boolean") { + const options = [ + { name: "Yes", value: "true" }, + { name: "No", value: "false" } + ]; + superstate.ui.openMenu(rect, { + ...defaultMenu(superstate.ui, options), + saveOptions: (options2, value) => { + onChangeValue(value[0]); } - ({ index: index2, parent } = buffer); - } else { - ({ index: index2, _parent: parent } = this._tree); - } - for (; parent; { index: index2, _parent: parent } = parent) { - if (index2 > -1) - for (let i4 = index2 + dir, e5 = dir < 0 ? -1 : parent._tree.children.length; i4 != e5; i4 += dir) { - let child = parent._tree.children[i4]; - if (this.mode & IterMode3.IncludeAnonymous || child instanceof TreeBuffer3 || !child.type.isAnonymous || hasChild3(child)) - return false; - } - } - return true; + }); } - move(dir, enter) { - if (enter && this.enterChild(dir, 0, 4)) - return true; - for (; ; ) { - if (this.sibling(dir)) - return true; - if (this.atLastNode(dir) || !this.parent()) - return false; +}; + +// src/core/react/components/SpaceView/Contexts/FilterBar/FilterBar.tsx +var import_react38 = __toESM(require_react()); + +// src/core/react/components/UI/Stickers/Sticker.tsx +var import_react32 = __toESM(require_react()); +var Sticker = (props) => { + return /* @__PURE__ */ import_react32.default.createElement("div", { + className: "mk-sticker", + dangerouslySetInnerHTML: { + __html: props.ui.getSticker(props.sticker) } - } - next(enter = true) { - return this.move(1, enter); - } - prev(enter = true) { - return this.move(-1, enter); - } - moveTo(pos, side = 0) { - while (this.from == this.to || (side < 1 ? this.from >= pos : this.from > pos) || (side > -1 ? this.to <= pos : this.to < pos)) - if (!this.parent()) - break; - while (this.enterChild(1, pos, side)) { + }); +}; + +// src/core/react/components/SpaceView/Contexts/FilterBar/CustomVIewOption.tsx +var import_react33 = __toESM(require_react()); +var CustomViewOption = (props) => { + return /* @__PURE__ */ import_react33.default.createElement("div", { + className: "mk-menu-option", + onClick: () => { + props.onSelect(); + props.hide(); } - return this; - } - get node() { - if (!this.buffer) - return this._tree; - let cache2 = this.bufferNode, result = null, depth = 0; - if (cache2 && cache2.context == this.buffer) { - scan: - for (let index2 = this.index, d4 = this.stack.length; d4 >= 0; ) { - for (let c3 = cache2; c3; c3 = c3._parent) - if (c3.index == index2) { - if (index2 == this.index) - return c3; - result = c3; - depth = d4 + 1; - break scan; - } - index2 = this.stack[--d4]; - } + }, /* @__PURE__ */ import_react33.default.createElement(Sticker, { + ui: props.ui, + sticker: props.icon + }), /* @__PURE__ */ import_react33.default.createElement("div", { + className: "mk-menu-options-inner" + }, /* @__PURE__ */ import_react33.default.createElement("span", null, props.type)), props.selected && /* @__PURE__ */ import_react33.default.createElement("div", { + dangerouslySetInnerHTML: { + __html: props.ui.getSticker("ui//check") } - for (let i4 = depth; i4 < this.stack.length; i4++) - result = new BufferNode3(this.buffer, result, this.stack[i4]); - return this.bufferNode = new BufferNode3(this.buffer, result, this.index); - } - get tree() { - return this.buffer ? null : this._tree._tree; - } - iterate(enter, leave) { - for (let depth = 0; ; ) { - let mustLeave = false; - if (this.type.isAnonymous || enter(this) !== false) { - if (this.firstChild()) { - depth++; - continue; - } - if (!this.type.isAnonymous) - mustLeave = true; - } - for (; ; ) { - if (mustLeave && leave) - leave(this); - mustLeave = this.type.isAnonymous; - if (this.nextSibling()) - break; - if (!depth) - return; - this.parent(); - depth--; - mustLeave = true; - } + }), /* @__PURE__ */ import_react33.default.createElement("button", { + onClick: (e5) => { + e5.preventDefault(); + props.hide(); + props.onCustomize(); + }, + "aria-label": "Customize", + className: "mk-icon-small mk-inline-button", + dangerouslySetInnerHTML: { + __html: props.ui.getSticker("ui//brush") } - } - matchContext(context) { - if (!this.buffer) - return matchNodeContext3(this.node, context); - let { buffer } = this.buffer, { types: types2 } = buffer.set; - for (let i4 = context.length - 1, d4 = this.stack.length - 1; i4 >= 0; d4--) { - if (d4 < 0) - return matchNodeContext3(this.node, context, i4); - let type = types2[buffer.buffer[this.stack[d4]]]; - if (!type.isAnonymous) { - if (context[i4] && context[i4] != type.name) - return false; - i4--; - } + })); +}; + +// src/core/react/components/UI/Crumbs/ContextViewCrumb.tsx +var import_react34 = __toESM(require_react()); +var ContextViewCrumb = (props) => { + return /* @__PURE__ */ import_react34.default.createElement("div", { + onClick: (e5) => props.onSelect(e5), + onContextMenu: (e5) => props.onContextMenu(e5, props.schema), + className: "mk-context" + }, /* @__PURE__ */ import_react34.default.createElement("div", { + className: "mk-path-icon", + dangerouslySetInnerHTML: { + __html: props.superstate.ui.getSticker( + stickerForSchema(props.schema) + ) } - return true; - } + }), defaultString(props.schema.name, "Untitled"), props.children); }; -function hasChild3(tree) { - return tree.children.some((ch) => ch instanceof TreeBuffer3 || !ch.type.isAnonymous || hasChild3(ch)); -} -function buildTree3(data2) { - var _a; - let { buffer, nodeSet, maxBufferLength = DefaultBufferLength3, reused = [], minRepeatType = nodeSet.types.length } = data2; - let cursor2 = Array.isArray(buffer) ? new FlatBufferCursor3(buffer, buffer.length) : buffer; - let types2 = nodeSet.types; - let contextHash = 0, lookAhead = 0; - function takeNode(parentStart, minPos, children2, positions2, inRepeat, depth) { - let { id: id3, start, end, size: size2 } = cursor2; - let lookAheadAtStart = lookAhead; - while (size2 < 0) { - cursor2.next(); - if (size2 == -1) { - let node2 = reused[id3]; - children2.push(node2); - positions2.push(start - parentStart); - return; - } else if (size2 == -3) { - contextHash = id3; - return; - } else if (size2 == -4) { - lookAhead = id3; + +// src/core/react/components/UI/Toggles/CollapseToggle.tsx +var import_react35 = __toESM(require_react()); +var CollapseToggle = (props) => { + return /* @__PURE__ */ import_react35.default.createElement("button", { + className: `mk-collapse ${props.collapsed ? "mk-collapsed" : ""}`, + onClick: (e5) => { + if (!props.onToggle) return; - } else { - throw new RangeError(`Unrecognized record size: ${size2}`); - } + e5.stopPropagation(); + props.onToggle(!props.collapsed, e5); + }, + dangerouslySetInnerHTML: { + __html: props.superstate.ui.getSticker("ui//collapse") } - let type = types2[id3], node, buffer2; - let startPos = start - parentStart; - if (end - start <= maxBufferLength && (buffer2 = findBufferSize(cursor2.pos - minPos, inRepeat))) { - let data3 = new Uint16Array(buffer2.size - buffer2.skip); - let endPos = cursor2.pos - buffer2.size, index2 = data3.length; - while (cursor2.pos > endPos) - index2 = copyToBuffer(buffer2.start, data3, index2); - node = new TreeBuffer3(data3, end - buffer2.start, nodeSet); - startPos = buffer2.start - parentStart; - } else { - let endPos = cursor2.pos - size2; - cursor2.next(); - let localChildren = [], localPositions = []; - let localInRepeat = id3 >= minRepeatType ? id3 : -1; - let lastGroup = 0, lastEnd = end; - while (cursor2.pos > endPos) { - if (localInRepeat >= 0 && cursor2.id == localInRepeat && cursor2.size >= 0) { - if (cursor2.end <= lastEnd - maxBufferLength) { - makeRepeatLeaf(localChildren, localPositions, start, lastGroup, cursor2.end, lastEnd, localInRepeat, lookAheadAtStart); - lastGroup = localChildren.length; - lastEnd = cursor2.end; - } - cursor2.next(); - } else if (depth > 2500) { - takeFlatNode(start, endPos, localChildren, localPositions); - } else { - takeNode(start, endPos, localChildren, localPositions, localInRepeat, depth + 1); - } + }); +}; + +// src/core/react/components/SpaceView/Contexts/FilterBar/ListSelector.tsx +var import_react36 = __toESM(require_react()); +var ListSelector = (props) => { + const { views, dbSchema, source } = (0, import_react36.useContext)(ContextEditorContext); + const { spaceState } = (0, import_react36.useContext)(SpaceContext); + const { + frameSchema: schema, + setFrameSchema: setSchema, + saveSchema, + deleteSchema + } = (0, import_react36.useContext)(FramesMDBContext); + const viewContextMenu = (e5, _schema) => { + const menuOptions = []; + menuOptions.push({ + name: i18n_default.menu.copyEmbedLink, + icon: "ui//link", + onClick: (e6) => { + navigator.clipboard.writeText( + contextViewEmbedStringFromContext(spaceState, _schema.id) + ); } - if (localInRepeat >= 0 && lastGroup > 0 && lastGroup < localChildren.length) - makeRepeatLeaf(localChildren, localPositions, start, lastGroup, start, lastEnd, localInRepeat, lookAheadAtStart); - localChildren.reverse(); - localPositions.reverse(); - if (localInRepeat > -1 && lastGroup > 0) { - let make = makeBalanced(type); - node = balanceRange3(type, localChildren, localPositions, 0, localChildren.length, 0, end - start, make, make); - } else { - node = makeTree(type, localChildren, localPositions, end - start, lookAheadAtStart - end); + }); + menuOptions.push({ + name: i18n_default.buttons.renameView, + icon: "ui//edit", + onClick: (e6) => { + props.superstate.ui.openModal( + i18n_default.labels.renameView, + (props2) => /* @__PURE__ */ import_react36.default.createElement(InputModal, { + value: _schema.name, + saveLabel: i18n_default.labels.renameView, + hide: props2.hide, + saveValue: (value) => saveSchema({ + ..._schema, + name: value + }) + }) + ); } - } - children2.push(node); - positions2.push(startPos); - } - function takeFlatNode(parentStart, minPos, children2, positions2) { - let nodes = []; - let nodeCount = 0, stopAt = -1; - while (cursor2.pos > minPos) { - let { id: id3, start, end, size: size2 } = cursor2; - if (size2 > 4) { - cursor2.next(); - } else if (stopAt > -1 && start < stopAt) { - break; - } else { - if (stopAt < 0) - stopAt = end - maxBufferLength; - nodes.push(id3, start, end); - nodeCount++; - cursor2.next(); + }); + menuOptions.push({ + name: i18n_default.buttons.delete, + icon: "ui//trash", + onClick: (e6) => { + deleteSchema(_schema); } + }); + props.superstate.ui.openMenu( + e5.target.getBoundingClientRect(), + defaultMenu(props.superstate.ui, menuOptions) + ); + }; + const selectView = (value) => { + setSchema(views.find((f2) => f2.id == value)); + if (props.setView) + props.setView(value); + }; + const ref2 = (0, import_react36.useRef)(null); + const showSaveViewModal = () => { + props.superstate.ui.openModal( + i18n_default.labels.saveView, + (props2) => /* @__PURE__ */ import_react36.default.createElement(InputModal, { + value: "", + saveLabel: i18n_default.labels.saveView, + hide: props2.hide, + saveValue: (value) => { + const newSchema = { + ...schema ?? { + name: dbSchema.name, + def: { + db: dbSchema.id + }, + type: "view" + }, + id: value.replace(/ /g, "_"), + name: value + }; + saveSchema(newSchema).then((f2) => selectView(newSchema.id)); + } + }) + ); + }; + const selectViewMenu = (e5) => { + const options = []; + (views ?? []).forEach((f2) => { + options.push({ + name: defaultString(f2.name, "Untitled"), + value: f2.id, + icon: stickerForSchema(f2), + onClick: () => selectView(f2.id), + onMoreOptions: (e6) => viewContextMenu(e6, f2) + }); + }); + options.push(menuSeparator); + options.push({ + name: i18n_default.menu.newView, + icon: "ui//plus", + value: "", + onClick: () => showSaveViewModal() + }); + props.superstate.ui.openMenu( + e5.target.getBoundingClientRect(), + defaultMenu(props.superstate.ui, options), + "bottom" + ); + }; + return dbSchema && (schema ? /* @__PURE__ */ import_react36.default.createElement(import_react36.default.Fragment, null, /* @__PURE__ */ import_react36.default.createElement("div", { + className: "mk-view-selector", + ref: ref2 + }, props.expanded ? /* @__PURE__ */ import_react36.default.createElement(import_react36.default.Fragment, null, views.map((f2, i4) => /* @__PURE__ */ import_react36.default.createElement(ContextViewCrumb, { + key: i4, + superstate: props.superstate, + schema: f2, + onSelect: () => setSchema(views.find((g) => g.id == f2.id)), + onContextMenu: viewContextMenu + })), /* @__PURE__ */ import_react36.default.createElement("button", { + onClick: (e5) => showSaveViewModal() + }, "+")) : /* @__PURE__ */ import_react36.default.createElement(ContextViewCrumb, { + superstate: props.superstate, + schema, + onSelect: (e5) => selectViewMenu(e5), + onContextMenu: viewContextMenu + }, /* @__PURE__ */ import_react36.default.createElement(CollapseToggle, { + collapsed: false, + onToggle: null, + superstate: props.superstate + })))) : /* @__PURE__ */ import_react36.default.createElement("div", { + onClick: (e5) => selectViewMenu(e5), + className: "mk-context" + }, /* @__PURE__ */ import_react36.default.createElement("div", { + className: "mk-path-icon", + dangerouslySetInnerHTML: { + __html: props.superstate.ui.getSticker("ui//table") } - if (nodeCount) { - let buffer2 = new Uint16Array(nodeCount * 4); - let start = nodes[nodes.length - 2]; - for (let i4 = nodes.length - 3, j = 0; i4 >= 0; i4 -= 3) { - buffer2[j++] = nodes[i4]; - buffer2[j++] = nodes[i4 + 1] - start; - buffer2[j++] = nodes[i4 + 2] - start; - buffer2[j++] = j; - } - children2.push(new TreeBuffer3(buffer2, nodes[2] - start, nodeSet)); - positions2.push(start - parentStart); + }), dbSchema.name, /* @__PURE__ */ import_react36.default.createElement(CollapseToggle, { + collapsed: false, + onToggle: null, + superstate: props.superstate + }))); +}; + +// src/core/react/components/SpaceView/Contexts/FilterBar/SearchBar.tsx +var import_react37 = __toESM(require_react()); +var SearchBar = (props) => { + const [searchActive, setSearchActive] = import_react37.default.useState(false); + const clearSearch = () => { + setSearchActive(false); + props.setSearchString(""); + }; + const ref2 = import_react37.default.useRef(null); + (0, import_react37.useEffect)(() => { + if (searchActive) { + ref2.current?.focus(); } - } - function makeBalanced(type) { - return (children2, positions2, length2) => { - let lookAhead2 = 0, lastI = children2.length - 1, last, lookAheadProp; - if (lastI >= 0 && (last = children2[lastI]) instanceof Tree3) { - if (!lastI && last.type == type && last.length == length2) - return last; - if (lookAheadProp = last.prop(NodeProp3.lookAhead)) - lookAhead2 = positions2[lastI] + last.length + lookAheadProp; - } - return makeTree(type, children2, positions2, length2, lookAhead2); - }; - } - function makeRepeatLeaf(children2, positions2, base2, i4, from, to2, type, lookAhead2) { - let localChildren = [], localPositions = []; - while (children2.length > i4) { - localChildren.push(children2.pop()); - localPositions.push(positions2.pop() + base2 - from); + }, [searchActive]); + return !searchActive ? /* @__PURE__ */ import_react37.default.createElement("button", { + className: "mk-toolbar-button", + onClick: (e5) => { + e5.stopPropagation(); + setSearchActive(true); + }, + dangerouslySetInnerHTML: { + __html: props.superstate.ui.getSticker("ui//search") } - children2.push(makeTree(nodeSet.types[type], localChildren, localPositions, to2 - from, lookAhead2 - to2)); - positions2.push(from - base2); - } - function makeTree(type, children2, positions2, length2, lookAhead2 = 0, props) { - if (contextHash) { - let pair2 = [NodeProp3.contextHash, contextHash]; - props = props ? [pair2].concat(props) : [pair2]; + }) : /* @__PURE__ */ import_react37.default.createElement("div", { + className: "mk-view-search" + }, /* @__PURE__ */ import_react37.default.createElement("button", { + className: "mk-toolbar-button", + dangerouslySetInnerHTML: { + __html: props.superstate.ui.getSticker("ui//search") } - if (lookAhead2 > 25) { - let pair2 = [NodeProp3.lookAhead, lookAhead2]; - props = props ? [pair2].concat(props) : [pair2]; + }), /* @__PURE__ */ import_react37.default.createElement(import_react37.default.Fragment, null, /* @__PURE__ */ import_react37.default.createElement("input", { + onChange: (e5) => props.setSearchString(e5.target.value), + placeholder: i18n_default.labels.searchPlaceholder, + className: "mk-search-bar", + ref: ref2 + }), /* @__PURE__ */ import_react37.default.createElement("button", { + className: "mk-toolbar-button", + dangerouslySetInnerHTML: { + __html: props.superstate.ui.getSticker("ui//clear") + }, + onClick: (e5) => { + e5.stopPropagation(); + clearSearch(); } - return new Tree3(type, children2, positions2, length2, props); - } - function findBufferSize(maxSize, inRepeat) { - let fork = cursor2.fork(); - let size2 = 0, start = 0, skip = 0, minStart = fork.end - maxBufferLength; - let result = { size: 0, start: 0, skip: 0 }; - scan: - for (let minPos = fork.pos - maxSize; fork.pos > minPos; ) { - let nodeSize4 = fork.size; - if (fork.id == inRepeat && nodeSize4 >= 0) { - result.size = size2; - result.start = start; - result.skip = skip; - skip += 4; - size2 += 4; - fork.next(); - continue; - } - let startPos = fork.pos - nodeSize4; - if (nodeSize4 < 0 || startPos < minPos || fork.start < minStart) - break; - let localSkipped = fork.id >= minRepeatType ? 4 : 0; - let nodeStart = fork.start; - fork.next(); - while (fork.pos > startPos) { - if (fork.size < 0) { - if (fork.size == -3) - localSkipped += 4; - else - break scan; - } else if (fork.id >= minRepeatType) { - localSkipped += 4; - } - fork.next(); - } - start = nodeStart; - size2 += nodeSize4; - skip += localSkipped; - } - if (inRepeat < 0 || size2 == maxSize) { - result.size = size2; - result.start = start; - result.skip = skip; + }))); +}; + +// src/core/react/components/SpaceView/Contexts/FilterBar/FilterBar.tsx +var FilterBar = (props) => { + const { spaceState: spaceCache } = (0, import_react38.useContext)(SpaceContext); + const { + source, + dbSchema, + cols, + setSearchString, + setEditMode, + predicate, + savePredicate, + hideColumn, + delColumn, + saveColumn + } = (0, import_react38.useContext)(ContextEditorContext); + const { frameSchema, saveSchema, setFrameSchema } = (0, import_react38.useContext)(FramesMDBContext); + const properties3 = spaceCache?.propertyTypes ?? []; + const propertiesForFrame = (path2) => { + if (!path2) + return []; + const uri = props.superstate.spaceManager.uriByString(path2); + if (uri.authority == "$kit") { + const node = props.superstate.kitFrames.get(uri.ref).node; + return Object.keys(node.types).map((f2) => ({ + type: node.types[f2], + name: f2, + attrs: JSON.stringify(node.propsAttrs?.[f2]), + schemaId: node.schemaId, + value: JSON.stringify(node.propsValue?.[f2]) + })).filter((f2) => !f2.name.startsWith("_")); + } else { + return props.superstate.framesIndex.get(uri.path)?.frames[uri.ref].cols.filter((f2) => !f2.name.startsWith("_")); } - return result.size > 4 ? result : void 0; - } - function copyToBuffer(bufferStart, buffer2, index2) { - let { id: id3, start, end, size: size2 } = cursor2; - cursor2.next(); - if (size2 >= 0 && id3 < minRepeatType) { - let startIndex = index2; - if (size2 > 4) { - let endPos = cursor2.pos - (size2 - 4); - while (cursor2.pos > endPos) - index2 = copyToBuffer(bufferStart, buffer2, index2); - } - buffer2[--index2] = startIndex; - buffer2[--index2] = end - bufferStart; - buffer2[--index2] = start - bufferStart; - buffer2[--index2] = id3; - } else if (size2 == -3) { - contextHash = id3; - } else if (size2 == -4) { - lookAhead = id3; + }; + const filteredCols = cols.filter((f2) => f2.hidden != "true"); + const [expanded, setExpanded] = (0, import_react38.useState)(false); + const saveViewType = (type) => { + if (type == "table") { + savePredicate({ + view: "table", + listView: "", + listGroup: "", + listItem: "" + }); } - return index2; - } - let children = [], positions = []; - while (cursor2.pos > 0) - takeNode(data2.start || 0, data2.bufferStart || 0, children, positions, -1, 0); - let length = (_a = data2.length) !== null && _a !== void 0 ? _a : children.length ? positions[0] + children[0].length : 0; - return new Tree3(types2[data2.topID], children.reverse(), positions.reverse(), length); -} -var nodeSizeCache3 = /* @__PURE__ */ new WeakMap(); -function nodeSize3(balanceType, node) { - if (!balanceType.isAnonymous || node instanceof TreeBuffer3 || node.type != balanceType) - return 1; - let size2 = nodeSizeCache3.get(node); - if (size2 == null) { - size2 = 1; - for (let child of node.children) { - if (child.type != balanceType || !(child instanceof Tree3)) { - size2 = 1; - break; - } - size2 += nodeSize3(balanceType, child); + if (type == "flow") { + savePredicate({ + view: "list", + listView: "spaces://$kit/#*listView", + listGroup: "spaces://$kit/#*listGroup", + listItem: "spaces://$kit/#*flowListItem" + }); } - nodeSizeCache3.set(node, size2); - } - return size2; -} -function balanceRange3(balanceType, children, positions, from, to2, start, length, mkTop, mkTree) { - let total = 0; - for (let i4 = from; i4 < to2; i4++) - total += nodeSize3(balanceType, children[i4]); - let maxChild = Math.ceil(total * 1.5 / 8); - let localChildren = [], localPositions = []; - function divide3(children2, positions2, from2, to3, offset2) { - for (let i4 = from2; i4 < to3; ) { - let groupFrom = i4, groupStart = positions2[i4], groupSize = nodeSize3(balanceType, children2[i4]); - i4++; - for (; i4 < to3; i4++) { - let nextSize = nodeSize3(balanceType, children2[i4]); - if (groupSize + nextSize >= maxChild) - break; - groupSize += nextSize; - } - if (i4 == groupFrom + 1) { - if (groupSize > maxChild) { - let only = children2[groupFrom]; - divide3(only.children, only.positions, 0, only.children.length, positions2[groupFrom] + offset2); - continue; - } - localChildren.push(children2[groupFrom]); - } else { - let length2 = positions2[i4 - 1] + children2[i4 - 1].length - groupStart; - localChildren.push(balanceRange3(balanceType, children2, positions2, groupFrom, i4, groupStart, length2, null, mkTree)); - } - localPositions.push(groupStart + offset2 - start); - } - } - divide3(children, positions, from, to2, 0); - return (mkTop || mkTree)(localChildren, localPositions, length); -} -var stoppedInner3 = new NodeProp3({ perNode: true }); - -// node_modules/@lezer/highlight/dist/index.js -var nextTagID2 = 0; -var Tag2 = class { - constructor(set, base2, modified) { - this.set = set; - this.base = base2; - this.modified = modified; - this.id = nextTagID2++; - } - static define(parent) { - if (parent === null || parent === void 0 ? void 0 : parent.base) - throw new Error("Can not derive from a modified tag"); - let tag2 = new Tag2([], null, []); - tag2.set.push(tag2); - if (parent) - for (let t5 of parent.set) - tag2.set.push(t5); - return tag2; - } - static defineModifier() { - let mod3 = new Modifier2(); - return (tag2) => { - if (tag2.modified.indexOf(mod3) > -1) - return tag2; - return Modifier2.get(tag2.base || tag2, tag2.modified.concat(mod3).sort((a4, b2) => a4.id - b2.id)); - }; - } -}; -var nextModifierID2 = 0; -var Modifier2 = class { - constructor() { - this.instances = []; - this.id = nextModifierID2++; - } - static get(base2, mods) { - if (!mods.length) - return base2; - let exists = mods[0].instances.find((t5) => t5.base == base2 && sameArray2(mods, t5.modified)); - if (exists) - return exists; - let set = [], tag2 = new Tag2(set, base2, mods); - for (let m4 of mods) - m4.instances.push(tag2); - let configs = powerSet(mods); - for (let parent of base2.set) - if (!parent.modified.length) - for (let config4 of configs) - set.push(Modifier2.get(parent, config4)); - return tag2; - } -}; -function sameArray2(a4, b2) { - return a4.length == b2.length && a4.every((x2, i4) => x2 == b2[i4]); -} -function powerSet(array) { - let sets = [[]]; - for (let i4 = 0; i4 < array.length; i4++) { - for (let j = 0, e5 = sets.length; j < e5; j++) { - sets.push(sets[j].concat(array[i4])); - } - } - return sets.sort((a4, b2) => b2.length - a4.length); -} -var ruleNodeProp2 = new NodeProp3(); -var Rule2 = class { - constructor(tags3, mode2, context, next) { - this.tags = tags3; - this.mode = mode2; - this.context = context; - this.next = next; - } - get opaque() { - return this.mode == 0; - } - get inherit() { - return this.mode == 1; - } - sort(other) { - if (!other || other.depth < this.depth) { - this.next = other; - return this; - } - other.next = this.sort(other.next); - return other; - } - get depth() { - return this.context ? this.context.length : 0; - } -}; -Rule2.empty = new Rule2([], 2, null); -function tagHighlighter2(tags3, options) { - let map4 = /* @__PURE__ */ Object.create(null); - for (let style of tags3) { - if (!Array.isArray(style.tag)) - map4[style.tag.id] = style.class; - else - for (let tag2 of style.tag) - map4[tag2.id] = style.class; - } - let { scope, all: all2 = null } = options || {}; - return { - style: (tags4) => { - let cls = all2; - for (let tag2 of tags4) { - for (let sub2 of tag2.set) { - let tagClass = map4[sub2.id]; - if (tagClass) { - cls = cls ? cls + " " + tagClass : tagClass; - break; - } - } - } - return cls; - }, - scope - }; -} -var t3 = Tag2.define; -var comment2 = t3(); -var name316 = t3(); -var typeName3 = t3(name316); -var propertyName2 = t3(name316); -var literal3 = t3(); -var string3 = t3(literal3); -var number3 = t3(literal3); -var content2 = t3(); -var heading2 = t3(content2); -var keyword2 = t3(); -var operator2 = t3(); -var punctuation2 = t3(); -var bracket2 = t3(punctuation2); -var meta2 = t3(); -var tags2 = { - comment: comment2, - lineComment: t3(comment2), - blockComment: t3(comment2), - docComment: t3(comment2), - name: name316, - variableName: t3(name316), - typeName: typeName3, - tagName: t3(typeName3), - propertyName: propertyName2, - attributeName: t3(propertyName2), - className: t3(name316), - labelName: t3(name316), - namespace: t3(name316), - macroName: t3(name316), - literal: literal3, - string: string3, - docString: t3(string3), - character: t3(string3), - attributeValue: t3(string3), - number: number3, - integer: t3(number3), - float: t3(number3), - bool: t3(literal3), - regexp: t3(literal3), - escape: t3(literal3), - color: t3(literal3), - url: t3(literal3), - keyword: keyword2, - self: t3(keyword2), - null: t3(keyword2), - atom: t3(keyword2), - unit: t3(keyword2), - modifier: t3(keyword2), - operatorKeyword: t3(keyword2), - controlKeyword: t3(keyword2), - definitionKeyword: t3(keyword2), - moduleKeyword: t3(keyword2), - operator: operator2, - derefOperator: t3(operator2), - arithmeticOperator: t3(operator2), - logicOperator: t3(operator2), - bitwiseOperator: t3(operator2), - compareOperator: t3(operator2), - updateOperator: t3(operator2), - definitionOperator: t3(operator2), - typeOperator: t3(operator2), - controlOperator: t3(operator2), - punctuation: punctuation2, - separator: t3(punctuation2), - bracket: bracket2, - angleBracket: t3(bracket2), - squareBracket: t3(bracket2), - paren: t3(bracket2), - brace: t3(bracket2), - content: content2, - heading: heading2, - heading1: t3(heading2), - heading2: t3(heading2), - heading3: t3(heading2), - heading4: t3(heading2), - heading5: t3(heading2), - heading6: t3(heading2), - contentSeparator: t3(content2), - list: t3(content2), - quote: t3(content2), - emphasis: t3(content2), - strong: t3(content2), - link: t3(content2), - monospace: t3(content2), - strikethrough: t3(content2), - inserted: t3(), - deleted: t3(), - changed: t3(), - invalid: t3(), - meta: meta2, - documentMeta: t3(meta2), - annotation: t3(meta2), - processingInstruction: t3(meta2), - definition: Tag2.defineModifier(), - constant: Tag2.defineModifier(), - function: Tag2.defineModifier(), - standard: Tag2.defineModifier(), - local: Tag2.defineModifier(), - special: Tag2.defineModifier() -}; -var classHighlighter2 = tagHighlighter2([ - { tag: tags2.link, class: "tok-link" }, - { tag: tags2.heading, class: "tok-heading" }, - { tag: tags2.emphasis, class: "tok-emphasis" }, - { tag: tags2.strong, class: "tok-strong" }, - { tag: tags2.keyword, class: "tok-keyword" }, - { tag: tags2.atom, class: "tok-atom" }, - { tag: tags2.bool, class: "tok-bool" }, - { tag: tags2.url, class: "tok-url" }, - { tag: tags2.labelName, class: "tok-labelName" }, - { tag: tags2.inserted, class: "tok-inserted" }, - { tag: tags2.deleted, class: "tok-deleted" }, - { tag: tags2.literal, class: "tok-literal" }, - { tag: tags2.string, class: "tok-string" }, - { tag: tags2.number, class: "tok-number" }, - { tag: [tags2.regexp, tags2.escape, tags2.special(tags2.string)], class: "tok-string2" }, - { tag: tags2.variableName, class: "tok-variableName" }, - { tag: tags2.local(tags2.variableName), class: "tok-variableName tok-local" }, - { tag: tags2.definition(tags2.variableName), class: "tok-variableName tok-definition" }, - { tag: tags2.special(tags2.variableName), class: "tok-variableName2" }, - { tag: tags2.definition(tags2.propertyName), class: "tok-propertyName tok-definition" }, - { tag: tags2.typeName, class: "tok-typeName" }, - { tag: tags2.namespace, class: "tok-namespace" }, - { tag: tags2.className, class: "tok-className" }, - { tag: tags2.macroName, class: "tok-macroName" }, - { tag: tags2.propertyName, class: "tok-propertyName" }, - { tag: tags2.operator, class: "tok-operator" }, - { tag: tags2.comment, class: "tok-comment" }, - { tag: tags2.meta, class: "tok-meta" }, - { tag: tags2.invalid, class: "tok-invalid" }, - { tag: tags2.punctuation, class: "tok-punctuation" } -]); - -// node_modules/@uiw/codemirror-themes/esm/index.js -var import_view3 = require("@codemirror/view"); -var import_language3 = require("@codemirror/language"); -var createTheme = (_ref) => { - var { - theme, - settings = {}, - styles: styles2 = [] - } = _ref; - var themeOptions = { - ".cm-gutters": {} - }; - var baseStyle = {}; - if (settings.background) { - baseStyle.backgroundColor = settings.background; - } - if (settings.backgroundImage) { - baseStyle.backgroundImage = settings.backgroundImage; - } - if (settings.foreground) { - baseStyle.color = settings.foreground; - } - if (settings.background || settings.foreground) { - themeOptions["&"] = baseStyle; - } - if (settings.fontFamily) { - themeOptions["&.cm-editor .cm-scroller"] = { - fontFamily: settings.fontFamily - }; - } - if (settings.gutterBackground) { - themeOptions[".cm-gutters"].backgroundColor = settings.gutterBackground; - } - if (settings.gutterForeground) { - themeOptions[".cm-gutters"].color = settings.gutterForeground; - } - if (settings.gutterBorder) { - themeOptions[".cm-gutters"].borderRightColor = settings.gutterBorder; - } - if (settings.caret) { - themeOptions[".cm-content"] = { - caretColor: settings.caret - }; - themeOptions[".cm-cursor, .cm-dropCursor"] = { - borderLeftColor: settings.caret - }; - } - var activeLineGutterStyle = {}; - if (settings.gutterActiveForeground) { - activeLineGutterStyle.color = settings.gutterActiveForeground; - } - if (settings.lineHighlight) { - themeOptions[".cm-activeLine"] = { - backgroundColor: settings.lineHighlight - }; - activeLineGutterStyle.backgroundColor = settings.lineHighlight; - } - themeOptions[".cm-activeLineGutter"] = activeLineGutterStyle; - if (settings.selection) { - themeOptions["&.cm-focused .cm-selectionBackground, & .cm-line::selection, & .cm-selectionLayer .cm-selectionBackground, .cm-content ::selection"] = { - background: settings.selection + " !important" - }; - } - if (settings.selectionMatch) { - themeOptions["& .cm-selectionMatch"] = { - backgroundColor: settings.selectionMatch - }; - } - var themeExtension = import_view3.EditorView.theme(themeOptions, { - dark: theme === "dark" - }); - var highlightStyle = import_language3.HighlightStyle.define(styles2); - var extension = [themeExtension, (0, import_language3.syntaxHighlighting)(highlightStyle)]; - return extension; -}; - -// node_modules/@uiw/codemirror-theme-abcdef/esm/index.js -var defaultSettingsAbcdef = { - background: "#0f0f0f", - foreground: "#defdef", - caret: "#00FF00", - selection: "#515151", - selectionMatch: "#515151", - gutterBackground: "#555", - gutterForeground: "#FFFFFF", - lineHighlight: "#0a6bcb3d" -}; -var abcdefInit = (options) => { - var { - theme = "dark", - settings = {}, - styles: styles2 = [] - } = options || {}; - return createTheme({ - theme, - settings: _extends({}, defaultSettingsAbcdef, settings), - styles: [ - { - tag: tags2.keyword, - color: "darkgoldenrod", - fontWeight: "bold" - }, - { - tag: tags2.atom, - color: "#77F" - }, - { - tag: tags2.comment, - color: "#7a7b7c", - fontStyle: "italic" - }, - { - tag: tags2.number, - color: "violet" - }, - { - tag: tags2.definition(tags2.variableName), - color: "#fffabc" - }, - { - tag: tags2.variableName, - color: "#abcdef" - }, - { - tag: tags2.function(tags2.variableName), - color: "#fffabc" - }, - { - tag: tags2.typeName, - color: "#FFDD44" - }, - { - tag: tags2.tagName, - color: "#def" - }, - { - tag: tags2.string, - color: "#2b4" - }, - { - tag: tags2.meta, - color: "#C9F" - }, - { - tag: tags2.bracket, - color: "#8a8a8a" - }, - { - tag: tags2.attributeName, - color: "#DDFF00" - }, - { - tag: tags2.heading, - color: "aquamarine", - fontWeight: "bold" - }, - { - tag: tags2.link, - color: "blueviolet", - fontWeight: "bold" - }, - ...styles2 - ] - }); -}; -var abcdef = abcdefInit(); - -// node_modules/@uiw/react-codemirror/esm/index.js -var esm_exports2 = {}; -__export(esm_exports2, { - basicSetup: () => basicSetup, - color: () => color, - default: () => esm_default, - defaultLightThemeOption: () => defaultLightThemeOption, - getDefaultExtensions: () => getDefaultExtensions, - getStatistics: () => getStatistics, - minimalSetup: () => minimalSetup, - oneDark: () => oneDark, - oneDarkHighlightStyle: () => oneDarkHighlightStyle, - oneDarkTheme: () => oneDarkTheme, - useCodeMirror: () => useCodeMirror -}); - -// node_modules/@babel/runtime/helpers/esm/objectWithoutPropertiesLoose.js -function _objectWithoutPropertiesLoose(source, excluded) { - if (source == null) - return {}; - var target = {}; - var sourceKeys = Object.keys(source); - var key2, i4; - for (i4 = 0; i4 < sourceKeys.length; i4++) { - key2 = sourceKeys[i4]; - if (excluded.indexOf(key2) >= 0) - continue; - target[key2] = source[key2]; - } - return target; -} - -// node_modules/@uiw/react-codemirror/esm/index.js -var import_react22 = __toESM(require_react()); - -// node_modules/@uiw/react-codemirror/esm/useCodeMirror.js -var import_react21 = __toESM(require_react()); -var import_state6 = require("@codemirror/state"); -var import_view8 = require("@codemirror/view"); - -// node_modules/@uiw/react-codemirror/esm/getDefaultExtensions.js -var import_commands3 = require("@codemirror/commands"); - -// node_modules/@uiw/codemirror-extensions-basic-setup/esm/index.js -var import_view4 = require("@codemirror/view"); -var import_state4 = require("@codemirror/state"); -var import_commands2 = require("@codemirror/commands"); -var import_search3 = require("@codemirror/search"); -var import_autocomplete2 = require("@codemirror/autocomplete"); -var import_language4 = require("@codemirror/language"); -var import_lint = require("@codemirror/lint"); -var basicSetup = function basicSetup2(options) { - if (options === void 0) { - options = {}; - } - var { - crosshairCursor: initCrosshairCursor = false - } = options; - var keymaps = []; - if (options.closeBracketsKeymap !== false) { - keymaps = keymaps.concat(import_autocomplete2.closeBracketsKeymap); - } - if (options.defaultKeymap !== false) { - keymaps = keymaps.concat(import_commands2.defaultKeymap); - } - if (options.searchKeymap !== false) { - keymaps = keymaps.concat(import_search3.searchKeymap); - } - if (options.historyKeymap !== false) { - keymaps = keymaps.concat(import_commands2.historyKeymap); - } - if (options.foldKeymap !== false) { - keymaps = keymaps.concat(import_language4.foldKeymap); - } - if (options.completionKeymap !== false) { - keymaps = keymaps.concat(import_autocomplete2.completionKeymap); - } - if (options.lintKeymap !== false) { - keymaps = keymaps.concat(import_lint.lintKeymap); - } - var extensions = []; - if (options.lineNumbers !== false) - extensions.push((0, import_view4.lineNumbers)()); - if (options.highlightActiveLineGutter !== false) - extensions.push((0, import_view4.highlightActiveLineGutter)()); - if (options.highlightSpecialChars !== false) - extensions.push((0, import_view4.highlightSpecialChars)()); - if (options.history !== false) - extensions.push((0, import_commands2.history)()); - if (options.foldGutter !== false) - extensions.push((0, import_language4.foldGutter)()); - if (options.drawSelection !== false) - extensions.push((0, import_view4.drawSelection)()); - if (options.dropCursor !== false) - extensions.push((0, import_view4.dropCursor)()); - if (options.allowMultipleSelections !== false) - extensions.push(import_state4.EditorState.allowMultipleSelections.of(true)); - if (options.indentOnInput !== false) - extensions.push((0, import_language4.indentOnInput)()); - if (options.syntaxHighlighting !== false) - extensions.push((0, import_language4.syntaxHighlighting)(import_language4.defaultHighlightStyle, { - fallback: true - })); - if (options.bracketMatching !== false) - extensions.push((0, import_language4.bracketMatching)()); - if (options.closeBrackets !== false) - extensions.push((0, import_autocomplete2.closeBrackets)()); - if (options.autocompletion !== false) - extensions.push((0, import_autocomplete2.autocompletion)()); - if (options.rectangularSelection !== false) - extensions.push((0, import_view4.rectangularSelection)()); - if (initCrosshairCursor !== false) - extensions.push((0, import_view4.crosshairCursor)()); - if (options.highlightActiveLine !== false) - extensions.push((0, import_view4.highlightActiveLine)()); - if (options.highlightSelectionMatches !== false) - extensions.push((0, import_search3.highlightSelectionMatches)()); - if (options.tabSize && typeof options.tabSize === "number") - extensions.push(import_language4.indentUnit.of(" ".repeat(options.tabSize))); - return extensions.concat([import_view4.keymap.of(keymaps.flat())]).filter(Boolean); -}; -var minimalSetup = function minimalSetup2(options) { - if (options === void 0) { - options = {}; - } - var keymaps = []; - if (options.defaultKeymap !== false) { - keymaps = keymaps.concat(import_commands2.defaultKeymap); - } - if (options.historyKeymap !== false) { - keymaps = keymaps.concat(import_commands2.historyKeymap); - } - var extensions = []; - if (options.highlightSpecialChars !== false) - extensions.push((0, import_view4.highlightSpecialChars)()); - if (options.history !== false) - extensions.push((0, import_commands2.history)()); - if (options.drawSelection !== false) - extensions.push((0, import_view4.drawSelection)()); - if (options.syntaxHighlighting !== false) - extensions.push((0, import_language4.syntaxHighlighting)(import_language4.defaultHighlightStyle, { - fallback: true - })); - return extensions.concat([import_view4.keymap.of(keymaps.flat())]).filter(Boolean); -}; - -// node_modules/@uiw/react-codemirror/esm/getDefaultExtensions.js -var import_view7 = require("@codemirror/view"); - -// node_modules/@codemirror/theme-one-dark/dist/index.js -var import_view5 = require("@codemirror/view"); -var import_language5 = require("@codemirror/language"); -var chalky = "#e5c07b"; -var coral = "#e06c75"; -var cyan = "#56b6c2"; -var invalid = "#ffffff"; -var ivory = "#abb2bf"; -var stone = "#7d8799"; -var malibu = "#61afef"; -var sage = "#98c379"; -var whiskey = "#d19a66"; -var violet = "#c678dd"; -var darkBackground = "#21252b"; -var highlightBackground = "#2c313a"; -var background = "#282c34"; -var tooltipBackground = "#353a42"; -var selection = "#3E4451"; -var cursor = "#528bff"; -var color = { - chalky, - coral, - cyan, - invalid, - ivory, - stone, - malibu, - sage, - whiskey, - violet, - darkBackground, - highlightBackground, - background, - tooltipBackground, - selection, - cursor -}; -var oneDarkTheme = /* @__PURE__ */ import_view5.EditorView.theme({ - "&": { - color: ivory, - backgroundColor: background - }, - ".cm-content": { - caretColor: cursor - }, - ".cm-cursor, .cm-dropCursor": { borderLeftColor: cursor }, - "&.cm-focused > .cm-scroller > .cm-selectionLayer .cm-selectionBackground, .cm-selectionBackground, .cm-content ::selection": { backgroundColor: selection }, - ".cm-panels": { backgroundColor: darkBackground, color: ivory }, - ".cm-panels.cm-panels-top": { borderBottom: "2px solid black" }, - ".cm-panels.cm-panels-bottom": { borderTop: "2px solid black" }, - ".cm-searchMatch": { - backgroundColor: "#72a1ff59", - outline: "1px solid #457dff" - }, - ".cm-searchMatch.cm-searchMatch-selected": { - backgroundColor: "#6199ff2f" - }, - ".cm-activeLine": { backgroundColor: "#6699ff0b" }, - ".cm-selectionMatch": { backgroundColor: "#aafe661a" }, - "&.cm-focused .cm-matchingBracket, &.cm-focused .cm-nonmatchingBracket": { - backgroundColor: "#bad0f847" - }, - ".cm-gutters": { - backgroundColor: background, - color: stone, - border: "none" - }, - ".cm-activeLineGutter": { - backgroundColor: highlightBackground - }, - ".cm-foldPlaceholder": { - backgroundColor: "transparent", - border: "none", - color: "#ddd" - }, - ".cm-tooltip": { - border: "none", - backgroundColor: tooltipBackground - }, - ".cm-tooltip .cm-tooltip-arrow:before": { - borderTopColor: "transparent", - borderBottomColor: "transparent" - }, - ".cm-tooltip .cm-tooltip-arrow:after": { - borderTopColor: tooltipBackground, - borderBottomColor: tooltipBackground - }, - ".cm-tooltip-autocomplete": { - "& > ul > li[aria-selected]": { - backgroundColor: highlightBackground, - color: ivory - } - } -}, { dark: true }); -var oneDarkHighlightStyle = /* @__PURE__ */ import_language5.HighlightStyle.define([ - { - tag: tags2.keyword, - color: violet - }, - { - tag: [tags2.name, tags2.deleted, tags2.character, tags2.propertyName, tags2.macroName], - color: coral - }, - { - tag: [/* @__PURE__ */ tags2.function(tags2.variableName), tags2.labelName], - color: malibu - }, - { - tag: [tags2.color, /* @__PURE__ */ tags2.constant(tags2.name), /* @__PURE__ */ tags2.standard(tags2.name)], - color: whiskey - }, - { - tag: [/* @__PURE__ */ tags2.definition(tags2.name), tags2.separator], - color: ivory - }, - { - tag: [tags2.typeName, tags2.className, tags2.number, tags2.changed, tags2.annotation, tags2.modifier, tags2.self, tags2.namespace], - color: chalky - }, - { - tag: [tags2.operator, tags2.operatorKeyword, tags2.url, tags2.escape, tags2.regexp, tags2.link, /* @__PURE__ */ tags2.special(tags2.string)], - color: cyan - }, - { - tag: [tags2.meta, tags2.comment], - color: stone - }, - { - tag: tags2.strong, - fontWeight: "bold" - }, - { - tag: tags2.emphasis, - fontStyle: "italic" - }, - { - tag: tags2.strikethrough, - textDecoration: "line-through" - }, - { - tag: tags2.link, - color: stone, - textDecoration: "underline" - }, - { - tag: tags2.heading, - fontWeight: "bold", - color: coral - }, - { - tag: [tags2.atom, tags2.bool, /* @__PURE__ */ tags2.special(tags2.variableName)], - color: whiskey - }, - { - tag: [tags2.processingInstruction, tags2.string, tags2.inserted], - color: sage - }, - { - tag: tags2.invalid, - color: invalid - } -]); -var oneDark = [oneDarkTheme, /* @__PURE__ */ (0, import_language5.syntaxHighlighting)(oneDarkHighlightStyle)]; - -// node_modules/@uiw/react-codemirror/esm/getDefaultExtensions.js -var import_state5 = require("@codemirror/state"); - -// node_modules/@uiw/react-codemirror/esm/theme/light.js -var import_view6 = require("@codemirror/view"); -var defaultLightThemeOption = import_view6.EditorView.theme({ - "&": { - backgroundColor: "#fff" - } -}, { - dark: false -}); - -// node_modules/@uiw/react-codemirror/esm/getDefaultExtensions.js -var getDefaultExtensions = function getDefaultExtensions2(optios) { - if (optios === void 0) { - optios = {}; - } - var { - indentWithTab: defaultIndentWithTab = true, - editable = true, - readOnly = false, - theme = "light", - placeholder: placeholderStr = "", - basicSetup: defaultBasicSetup = true - } = optios; - var getExtensions = []; - if (defaultIndentWithTab) { - getExtensions.unshift(import_view7.keymap.of([import_commands3.indentWithTab])); - } - if (defaultBasicSetup) { - if (typeof defaultBasicSetup === "boolean") { - getExtensions.unshift(basicSetup()); - } else { - getExtensions.unshift(basicSetup(defaultBasicSetup)); - } - } - if (placeholderStr) { - getExtensions.unshift((0, import_view7.placeholder)(placeholderStr)); - } - switch (theme) { - case "light": - getExtensions.push(defaultLightThemeOption); - break; - case "dark": - getExtensions.push(oneDark); - break; - case "none": - break; - default: - getExtensions.push(theme); - break; - } - if (editable === false) { - getExtensions.push(import_view7.EditorView.editable.of(false)); - } - if (readOnly) { - getExtensions.push(import_state5.EditorState.readOnly.of(true)); - } - return [...getExtensions]; -}; - -// node_modules/@uiw/react-codemirror/esm/utils.js -var getStatistics = (view) => { - return { - line: view.state.doc.lineAt(view.state.selection.main.from), - lineCount: view.state.doc.lines, - lineBreak: view.state.lineBreak, - length: view.state.doc.length, - readOnly: view.state.readOnly, - tabSize: view.state.tabSize, - selection: view.state.selection, - selectionAsSingle: view.state.selection.asSingle().main, - ranges: view.state.selection.ranges, - selectionCode: view.state.sliceDoc(view.state.selection.main.from, view.state.selection.main.to), - selections: view.state.selection.ranges.map((r2) => view.state.sliceDoc(r2.from, r2.to)), - selectedText: view.state.selection.ranges.some((r2) => !r2.empty) - }; -}; - -// node_modules/@uiw/react-codemirror/esm/useCodeMirror.js -var External = import_state6.Annotation.define(); -var emptyExtensions = []; -function useCodeMirror(props) { - var { - value, - selection: selection2, - onChange, - onStatistics, - onCreateEditor, - onUpdate, - extensions = emptyExtensions, - autoFocus, - theme = "light", - height = null, - minHeight = null, - maxHeight = null, - width = null, - minWidth = null, - maxWidth = null, - placeholder: placeholderStr = "", - editable = true, - readOnly = false, - indentWithTab: defaultIndentWithTab = true, - basicSetup: defaultBasicSetup = true, - root, - initialState: initialState2 - } = props; - var [container, setContainer] = (0, import_react21.useState)(); - var [view, setView] = (0, import_react21.useState)(); - var [state, setState] = (0, import_react21.useState)(); - var defaultThemeOption = import_view8.EditorView.theme({ - "&": { - height, - minHeight, - maxHeight, - width, - minWidth, - maxWidth - }, - "& .cm-scroller": { - height: "100% !important" - } - }); - var updateListener = import_view8.EditorView.updateListener.of((vu) => { - if (vu.docChanged && typeof onChange === "function" && !vu.transactions.some((tr) => tr.annotation(External))) { - var doc = vu.state.doc; - var _value = doc.toString(); - onChange(_value, vu); - } - onStatistics && onStatistics(getStatistics(vu)); - }); - var defaultExtensions = getDefaultExtensions({ - theme, - editable, - readOnly, - placeholder: placeholderStr, - indentWithTab: defaultIndentWithTab, - basicSetup: defaultBasicSetup - }); - var getExtensions = [updateListener, defaultThemeOption, ...defaultExtensions]; - if (onUpdate && typeof onUpdate === "function") { - getExtensions.push(import_view8.EditorView.updateListener.of(onUpdate)); - } - getExtensions = getExtensions.concat(extensions); - (0, import_react21.useEffect)(() => { - if (container && !state) { - var config4 = { - doc: value, - selection: selection2, - extensions: getExtensions - }; - var stateCurrent = initialState2 ? import_state6.EditorState.fromJSON(initialState2.json, config4, initialState2.fields) : import_state6.EditorState.create(config4); - setState(stateCurrent); - if (!view) { - var viewCurrent = new import_view8.EditorView({ - state: stateCurrent, - parent: container, - root - }); - setView(viewCurrent); - onCreateEditor && onCreateEditor(viewCurrent, stateCurrent); - } + if (type == "list") { + savePredicate({ + view: "list", + listView: "spaces://$kit/#*listView", + listGroup: "spaces://$kit/#*listGroup", + listItem: "spaces://$kit/#*rowItem" + }); } - return () => { - if (view) { - setState(void 0); - setView(void 0); - } - }; - }, [container, state]); - (0, import_react21.useEffect)(() => setContainer(props.container), [props.container]); - (0, import_react21.useEffect)(() => () => { - if (view) { - view.destroy(); - setView(void 0); + if (type == "details") { + savePredicate({ + view: "list", + listView: "spaces://$kit/#*listView", + listGroup: "spaces://$kit/#*listGroup", + listItem: "spaces://$kit/#*detailItem" + }); } - }, [view]); - (0, import_react21.useEffect)(() => { - if (autoFocus && view) { - view.focus(); + if (type == "board") { + savePredicate({ + view: "list", + listView: "spaces://$kit/#*columnView", + listGroup: "spaces://$kit/#*columnGroup", + listItem: "spaces://$kit/#*cardListItem" + }); } - }, [autoFocus, view]); - (0, import_react21.useEffect)(() => { - if (view) { - view.dispatch({ - effects: import_state6.StateEffect.reconfigure.of(getExtensions) + if (type == "cards") { + savePredicate({ + view: "list", + listView: "spaces://$kit/#*listView", + listGroup: "spaces://$kit/#*gridGroup", + listItem: "spaces://$kit/#*cardsListItem" }); } - }, [theme, extensions, height, minHeight, maxHeight, width, minWidth, maxWidth, placeholderStr, editable, readOnly, defaultIndentWithTab, defaultBasicSetup, onChange, onUpdate]); - (0, import_react21.useEffect)(() => { - if (value === void 0) { - return; + if (type == "catalog") { + savePredicate({ + view: "list", + listView: "spaces://$kit/#*listView", + listGroup: "spaces://$kit/#*rowGroup", + listItem: "spaces://$kit/#*coverListItem" + }); } - var currentValue = view ? view.state.doc.toString() : ""; - if (view && value !== currentValue) { - view.dispatch({ - changes: { - from: 0, - to: currentValue.length, - insert: value || "" - }, - annotations: [External.of(true)] + if (type == "gallery") { + savePredicate({ + view: "list", + listView: "spaces://$kit/#*listView", + listGroup: "spaces://$kit/#*masonryGroup", + listItem: "spaces://$kit/#*imageListItem" }); } - }, [value, view]); - return { - state, - setState, - view, - setView, - container, - setContainer - }; -} - -// node_modules/@uiw/react-codemirror/esm/index.js -var import_jsx_runtime = __toESM(require_jsx_runtime()); -__reExport(esm_exports2, require("@codemirror/view")); -__reExport(esm_exports2, require("@codemirror/state")); -var _excluded = ["className", "value", "selection", "extensions", "onChange", "onStatistics", "onCreateEditor", "onUpdate", "autoFocus", "theme", "height", "minHeight", "maxHeight", "width", "minWidth", "maxWidth", "basicSetup", "placeholder", "indentWithTab", "editable", "readOnly", "root", "initialState"]; -var ReactCodeMirror = /* @__PURE__ */ (0, import_react22.forwardRef)((props, ref2) => { - var { - className, - value = "", - selection: selection2, - extensions = [], - onChange, - onStatistics, - onCreateEditor, - onUpdate, - autoFocus, - theme = "light", - height, - minHeight, - maxHeight, - width, - minWidth, - maxWidth, - basicSetup: basicSetup3, - placeholder: placeholder2, - indentWithTab: indentWithTab2, - editable, - readOnly, - root, - initialState: initialState2 - } = props, other = _objectWithoutPropertiesLoose(props, _excluded); - var editor = (0, import_react22.useRef)(null); - var { - state, - view, - container - } = useCodeMirror({ - container: editor.current, - root, - value, - autoFocus, - theme, - height, - minHeight, - maxHeight, - width, - minWidth, - maxWidth, - basicSetup: basicSetup3, - placeholder: placeholder2, - indentWithTab: indentWithTab2, - editable, - readOnly, - selection: selection2, - onChange, - onStatistics, - onCreateEditor, - onUpdate, - extensions, - initialState: initialState2 - }); - (0, import_react22.useImperativeHandle)(ref2, () => ({ - editor: editor.current, - state, - view - }), [editor, container, state, view]); - if (typeof value !== "string") { - throw new Error("value must be typeof string but got " + typeof value); - } - var defaultClassNames2 = typeof theme === "string" ? "cm-theme-" + theme : "cm-theme"; - return /* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", _extends({ - ref: editor, - className: "" + defaultClassNames2 + (className ? " " + className : "") - }, other)); -}); -ReactCodeMirror.displayName = "CodeMirror"; -var esm_default = ReactCodeMirror; - -// src/core/react/components/SpaceEditor/Actions/FormulaEditor.tsx -var import_react24 = __toESM(require_react()); - -// src/core/react/components/SpaceEditor/Actions/ActionTester.tsx -var import_react23 = __toESM(require_react()); -var ActionTester = (props) => { - const path2 = props.superstate.pathsIndex.get(props.path); - const [fieldValues, setFieldValues] = (0, import_react23.useState)({}); - const [result, setResult] = (0, import_react23.useState)(); - const [error, setError] = (0, import_react23.useState)(); - const runCommand = async () => { - const values2 = Object.keys(fieldValues).reduce( - (f2, g) => { - const col = props.fields.find((c3) => c3.name == g); - const value = parsePropertyValue(col.type, fieldValues[g]); - if (value?.length > 0) - return { ...f2, [g]: parsePropertyValue(col.type, fieldValues[g]) }; - return f2; - }, - { - ...props.value, - $api: props.superstate.api, - $contexts: { - $space: { - path: path2 - }, - $context: {} - }, - $properties: props.fields - } - ); - let result2; - let error2; - try { - if (props.type == "actions") - result2 = await runActionString(props.superstate, props.code, { - props: {}, - instanceProps: values2, - iterations: 0 - }); - if (props.type == "script") - result2 = await executeCode(props.code, values2); - if (props.type == "formula") - result2 = await runFormulaWithContext( - props.superstate.formulaContext, - props.superstate.pathsIndex, - props.code, - props.fields.reduce((p, c3) => ({ ...p, [c3.name]: c3 }), {}), - values2, - path2, - true - ); - } catch (e5) { - error2 = e5; + if (type == "calendar") { + savePredicate({ + view: "list", + listView: "spaces://$kit/#*calendarView", + listGroup: "spaces://$kit/#*dateGroup", + listItem: "spaces://$kit/#*eventItem" + }); } - setResult(result2); - setError(error2); - }; - return /* @__PURE__ */ import_react23.default.createElement("div", { - className: "mk-editor-tester" - }, "= ", result && String(result), /* @__PURE__ */ import_react23.default.createElement("div", { - className: "mk-menu-separator" - }), /* @__PURE__ */ import_react23.default.createElement("span", null), /* @__PURE__ */ import_react23.default.createElement("button", { - onClick: () => runCommand() - }, i18n_default.buttons.run)); -}; - -// src/core/react/components/SpaceEditor/Actions/FormulaEditor.tsx -var FormulaEditor = (props) => { - const [formula, setFormula] = (0, import_react24.useState)(props.formula); - const saveFormula = (fml) => { - setFormula(fml); - }; - const save = () => { - props.saveFormula(formula); - props.hide(); }; - (0, import_react24.useEffect)(() => { - setFormula(props.formula); - }, [props.formula]); - return /* @__PURE__ */ import_react24.default.createElement("div", { - className: "mk-editor-formula" - }, /* @__PURE__ */ import_react24.default.createElement("div", { - className: "mk-space-editor-header" - }, /* @__PURE__ */ import_react24.default.createElement("div", { - className: "mk-space-editor-header-title" - }, /* @__PURE__ */ import_react24.default.createElement("div", { - className: "mk-space-editor-title" - }, "Formula"), /* @__PURE__ */ import_react24.default.createElement("div", { - className: "mk-space-editor-description" - }, props.description ?? "Use formula to filter and transform your data")), /* @__PURE__ */ import_react24.default.createElement("span", null), /* @__PURE__ */ import_react24.default.createElement("button", { - "aria-label": "Save Formula", - onClick: () => save() - }, "Done")), /* @__PURE__ */ import_react24.default.createElement(esm_default, { - value: formula, - height: "200px", - theme: abcdef, - basicSetup: { - syntaxHighlighting: true, - history: true, - closeBrackets: true, - autocompletion: true, - defaultKeymap: true, - lineNumbers: false - }, - extensions: [javascript()], - onChange: saveFormula - }), /* @__PURE__ */ import_react24.default.createElement(ActionTester, { - type: "formula", - code: formula, - fields: props.fields, - value: props.value, - superstate: props.superstate, - path: props.path - })); -}; - -// src/core/utils/contexts/predicate/sort.ts -var simpleSort = (a4, b2) => { - if (a4 < b2) - return -1; - if (a4 > b2) - return 1; - return 0; -}; -var linkSort = (value, filterValue) => { - const a4 = value.split("/").pop(); - const b2 = filterValue.split("/").pop(); - return simpleSort(a4.toLowerCase(), b2.toLowerCase()); -}; -var stringSort = (value, filterValue) => simpleSort(value.toLowerCase(), filterValue.toLowerCase()); -var numSort = (value, filterValue) => simpleSort(parseFloat(value), parseFloat(filterValue)); -var boolSort = (value, filterValue) => simpleSort(value == "true" ? 1 : 0, filterValue == "true" ? 1 : 0); -var countSort = (value, filterValue) => simpleSort(parseMultiString(value).length, parseMultiString(filterValue).length); -var normalizedSortForType = (type, desc) => { - return Object.keys(sortFnTypes).find( - (f2) => sortFnTypes[f2].type.some((g) => g == type) && sortFnTypes[f2].desc == desc - ); -}; -var sortFnTypes = { - alphabetical: { - type: ["text", "option"], - fn: stringSort, - label: i18n_default.sortTypes.alphaAsc, - desc: false - }, - reverseAlphabetical: { - type: ["text", "option"], - fn: (v2, f2) => stringSort(v2, f2) * -1, - label: i18n_default.sortTypes.alphaDesc, - desc: true - }, - linkAlphabetical: { - type: ["link", "context", "file", "image"], - fn: linkSort, - label: i18n_default.sortTypes.alphaAsc, - desc: false - }, - linkReverseAlphabetical: { - type: ["link", "context", "file", "image"], - fn: (v2, f2) => linkSort(v2, f2) * -1, - label: i18n_default.sortTypes.alphaDesc, - desc: true - }, - earliest: { - type: ["date"], - fn: stringSort, - label: i18n_default.sortTypes.earliest, - desc: false - }, - latest: { - type: ["date"], - fn: (v2, f2) => stringSort(v2, f2) * -1, - label: i18n_default.sortTypes.latest, - desc: true - }, - boolean: { - type: ["boolean"], - fn: boolSort, - label: i18n_default.sortTypes.checkAsc, - desc: false - }, - booleanReverse: { - type: ["boolean"], - fn: (v2, f2) => boolSort(v2, f2) * -1, - label: i18n_default.sortTypes.checkDesc, - desc: true - }, - number: { - type: ["number"], - fn: numSort, - label: "1 \u2192 9", - desc: false - }, - reverseNumber: { - type: ["number"], - fn: (v2, f2) => numSort(v2, f2) * -1, - label: "9 \u2192 1", - desc: true - }, - count: { - type: ["option-multi", "context-multi", "link-multi", "tags-multi"], - fn: countSort, - label: i18n_default.sortTypes.itemsDesc, - desc: true - }, - reverseCount: { - type: ["option-multi", "context-multi", "link-multi", "tags-multi"], - fn: (v2, f2) => countSort(v2, f2) * -1, - label: i18n_default.sortTypes.itemsAsc, - desc: false - } -}; -var sortReturnForCol = (col, sort2, row2, row22) => { - if (!col) - return 0; - const sortType = sortFnTypes[sort2.fn]; - if (sortType) { - return sortType.fn(row2[sort2.field], row22[sort2.field]); - } - return 0; -}; - -// src/core/react/components/UI/Menus/contexts/spacePropertyMenu.tsx -var import_react25 = __toESM(require_react()); -var selectPropertyTypeMenu = (e5, ui, selectedType) => { - ui.openMenu(e5.target.getBoundingClientRect(), { - ui, - multi: false, - editable: false, - searchable: false, - saveOptions: selectedType, - value: [], - showAll: true, - options: fieldTypes.filter((f2) => !f2.restricted).map((f2, i4) => ({ - id: i4 + 1, - name: f2.label, - value: f2.type, - icon: f2.icon - })) - }); -}; -var PropertyMenuComponent = (props) => { - const [field, setField] = (0, import_react25.useState)(props.field); - const selectedType = (_15, value) => { - const newField = { - ...field, - type: value[0], - value: JSON.stringify(getNewValueForType(field, value)) - }; - setField(newField); - props.saveField(newField); + const clearFilters = () => { + savePredicate({ + filters: [], + sort: [] + }); }; - const selectedValue = (value) => { - const newField = { ...field, value }; - setField(newField); - props.saveField(newField); + const clearHiddenCols = () => { + savePredicate({ + colsHidden: [] + }); }; - const toggleMulti = () => { - const newField = { - ...field, - type: field.type == fieldType.multiType ? fieldType.type : fieldType.multiType - }; - setField(newField); - props.saveField(newField); + const removeFilter = (filter4, index2) => { + const pred = predicate ?? defaultPredicateForSchema(dbSchema); + const newFilters = [...pred.filters.filter((f2, i4) => i4 != index2)]; + savePredicate({ + filters: newFilters + }); }; - const fieldType = fieldTypeForType(field.type, field.name) ?? fieldTypes[0]; - const getNewValueForType = (f2, value) => { - if (value[0].startsWith("option")) { - return JSON.stringify({ - options: props.options.map((f3) => ({ - name: f3, - value: f3 - })) + const showViewsMenu = (e5) => { + const menuOptions = []; + if (predicate?.listItem?.length > 0 && !predicate.listItem.startsWith("spaces://$kit")) { + menuOptions.push({ + name: i18n_default.menu.customView, + type: 5 /* Custom */, + fragment: (_props) => /* @__PURE__ */ import_react38.default.createElement(CustomViewOption, { + ui: props.superstate.ui, + icon: "ui//toy-brick", + type: i18n_default.menu.customView, + onSelect: () => null, + selected: true, + hide: _props.hide, + onCustomize: () => { + setEditMode(3 /* Group */); + } + }) }); } - return value[0] == fieldType.type || value[0] == fieldType.multiType ? f2.value : null; - }; - return /* @__PURE__ */ import_react25.default.createElement(import_react25.default.Fragment, null, /* @__PURE__ */ import_react25.default.createElement("li", null, /* @__PURE__ */ import_react25.default.createElement("div", { - className: "mk-menu-option", - onClick: (e5) => selectPropertyTypeMenu(e5, props.superstate.ui, selectedType) - }, /* @__PURE__ */ import_react25.default.createElement("span", null, i18n_default.labels.propertyType), /* @__PURE__ */ import_react25.default.createElement("span", null, fieldType.label))), fieldType.multi ? /* @__PURE__ */ import_react25.default.createElement("div", { - className: "mk-menu-option" - }, /* @__PURE__ */ import_react25.default.createElement("span", null, i18n_default.labels.multiple), /* @__PURE__ */ import_react25.default.createElement("input", { - type: "checkbox", - checked: field.type == fieldType.multiType, - onChange: () => toggleMulti() - })) : /* @__PURE__ */ import_react25.default.createElement(import_react25.default.Fragment, null), /* @__PURE__ */ import_react25.default.createElement("div", { - className: "mk-menu-separator" - }), /* @__PURE__ */ import_react25.default.createElement(PropertyValueComponent, { - superstate: props.superstate, - name: field.name, - table: field.table, - fields: props.fields, - fieldType: fieldType.type, - value: field.value, - contextPath: props.contextPath, - saveValue: selectedValue - })); -}; -var showPropertyMenu = (props) => { - const { - superstate, - rect, - editable, - options, - field, - fields, - contextPath, - saveField, - hide, - deleteColumn, - sortColumn, - editCode, - hidden - } = props; - const menuOptions = []; - if (editable) { - menuOptions.push( - menuInput( - field?.name ?? "", - (value) => saveField({ ...field, name: value }) - ) - ); - menuOptions.push(menuSeparator); menuOptions.push({ - name: "", + name: i18n_default.menu.listView, type: 5 /* Custom */, - fragment: () => /* @__PURE__ */ import_react25.default.createElement(PropertyMenuComponent, { - superstate, - field, - fields, - contextPath, - options, - saveField + fragment: (_props) => /* @__PURE__ */ import_react38.default.createElement(CustomViewOption, { + ui: props.superstate.ui, + icon: "ui//list", + type: i18n_default.menu.listView, + onSelect: () => saveViewType("list"), + selected: predicate?.listItem == "spaces://$kit/#*rowItem", + hide: _props.hide, + onCustomize: () => { + saveViewType("list"); + setEditMode(3 /* Group */); + } + }) + }); + menuOptions.push({ + name: i18n_default.menu.cardView, + type: 5 /* Custom */, + fragment: (_props) => /* @__PURE__ */ import_react38.default.createElement(CustomViewOption, { + ui: props.superstate.ui, + icon: "ui//layout-grid", + type: i18n_default.menu.cardView, + onSelect: () => saveViewType("cards"), + hide: _props.hide, + selected: predicate?.listItem == "spaces://$kit/#*cardsListItem", + onCustomize: () => { + saveViewType("card"); + setEditMode(3 /* Group */); + } + }) + }); + menuOptions.push({ + name: i18n_default.menu.detailsView, + type: 5 /* Custom */, + fragment: (_props) => /* @__PURE__ */ import_react38.default.createElement(CustomViewOption, { + ui: props.superstate.ui, + icon: "ui//layout-list", + type: i18n_default.menu.detailsView, + onSelect: () => saveViewType("details"), + hide: _props.hide, + selected: predicate?.listItem == "spaces://$kit/#*detailItem", + onCustomize: () => { + saveViewType("details"); + setEditMode(3 /* Group */); + } }) }); menuOptions.push(menuSeparator); menuOptions.push({ - name: i18n_default.menu.setIcon, - icon: "ui//gem", - onClick: () => { - superstate.ui.openPalette((_props) => /* @__PURE__ */ import_react25.default.createElement(StickerModal_default, { - ui: superstate.ui, - hide: _props.hide, - selectedSticker: (emoji) => saveField({ ...field, attrs: JSON.stringify({ icon: emoji }) }) - })); + name: i18n_default.menu.tableView, + icon: "ui//table-2", + onClick: (e6) => { + saveViewType("table"); } }); - menuOptions.push(menuSeparator); - const sortableString = normalizedSortForType(field.type, false); - if (sortableString && sortColumn) { - menuOptions.push({ - name: i18n_default.menu.sortAscending, - icon: "ui//sort-asc", - onClick: () => { - sortColumn({ - field: field.name + field.table, - fn: sortableString - }); - } - }); - menuOptions.push({ - name: i18n_default.menu.sortDescending, - icon: "ui//sort-desc", - onClick: () => { - sortColumn({ - field: field.name + field.table, - fn: normalizedSortForType(field.type, true) - }); + menuOptions.push({ + name: i18n_default.menu.boardView, + type: 5 /* Custom */, + fragment: (_props) => /* @__PURE__ */ import_react38.default.createElement(CustomViewOption, { + ui: props.superstate.ui, + icon: "ui//square-kanban", + type: i18n_default.menu.boardView, + onSelect: () => saveViewType("board"), + hide: _props.hide, + selected: predicate?.listItem == "spaces://$kit/#*cardListItem", + onCustomize: () => { + saveViewType("card"); + setEditMode(3 /* Group */); } - }); - } + }) + }); menuOptions.push(menuSeparator); - if (hide) { - if (!hidden) { - menuOptions.push({ - name: i18n_default.menu.hideProperty, - icon: "ui//eye-off", - onClick: () => { - hide(field, true); - } - }); - } else { - menuOptions.push({ - name: i18n_default.menu.unhideProperty, - icon: "ui//eye", - onClick: () => { - hide(field, false); - } - }); - } - } - if (editCode) { - menuOptions.push({ - name: i18n_default.menu.editCode, - icon: "ui//code", - onClick: () => { - editCode(); + menuOptions.push({ + name: i18n_default.menu.catalogView, + type: 5 /* Custom */, + fragment: (_props) => /* @__PURE__ */ import_react38.default.createElement(CustomViewOption, { + ui: props.superstate.ui, + icon: "ui//gallery-horizontal-end", + type: i18n_default.menu.catalogView, + hide: _props.hide, + onSelect: () => saveViewType("catalog"), + selected: predicate?.listItem == "spaces://$kit/#*coverListItem", + onCustomize: () => { + saveViewType("catalog"); + setEditMode(3 /* Group */); } - }); - } - if (deleteColumn) { - menuOptions.push({ - name: i18n_default.menu.deleteProperty, - icon: "ui//trash", - onClick: () => { - deleteColumn(field); + }) + }); + menuOptions.push({ + name: i18n_default.menu.galleryView, + type: 5 /* Custom */, + fragment: (_props) => /* @__PURE__ */ import_react38.default.createElement(CustomViewOption, { + ui: props.superstate.ui, + icon: "ui//layout-dashboard", + type: i18n_default.menu.galleryView, + hide: _props.hide, + onSelect: () => saveViewType("gallery"), + selected: predicate?.listItem == "spaces://$kit/#*imageListItem", + onCustomize: () => { + saveViewType("gallery"); + setEditMode(3 /* Group */); } + }) + }); + if (dbSchema?.primary) { + menuOptions.push({ + name: i18n_default.menu.flowView, + type: 5 /* Custom */, + fragment: (_props) => /* @__PURE__ */ import_react38.default.createElement(CustomViewOption, { + ui: props.superstate.ui, + icon: "ui//infinity", + type: i18n_default.menu.flowView, + onSelect: () => saveViewType("flow"), + hide: _props.hide, + selected: predicate?.listItem == "spaces://$kit/#*flowListItem", + onCustomize: () => { + saveViewType("flow"); + setEditMode(3 /* Group */); + } + }) }); } - } - const menu = superstate.ui.openMenu( - rect, - defaultMenu(superstate.ui, menuOptions) - ); - return menu; -}; - -// src/core/react/context/ContextEditorContext.tsx -var import_lodash10 = __toESM(require_lodash()); -var import_react28 = __toESM(require_react()); - -// src/core/utils/contexts/predicate/predicate.tsx -var defaultPredicateFnForType = (type, types2) => { - const fnType = Object.keys(types2).find( - (f2) => types2[f2].type.find((g) => g == type) - ); - return fnType; -}; -var allPredicateFns = (types2) => { - return Object.keys(types2); -}; -var predicateFnsForType = (type, types2) => { - const fnTypes = Object.keys(types2).filter( - (f2) => types2[f2].type.find((g) => g == type) - ); - return fnTypes; -}; -var cleanPredicateType = (type, definedTypes) => { - return type.filter((f2) => Object.keys(definedTypes).find((g) => g == f2.fn)); -}; -var validatePredicate = (prevPredicate, defaultPredicate2) => { - if (!prevPredicate) { - return defaultPredicate2; - } - return { - ...defaultPredicate2, - view: prevPredicate.view, - listItem: prevPredicate.listItem, - listGroup: prevPredicate.listGroup, - listView: prevPredicate.listView, - listViewProps: prevPredicate.listViewProps, - listItemProps: prevPredicate.listItemProps, - listGroupProps: prevPredicate.listGroupProps, - filters: Array.isArray(prevPredicate.filters) ? cleanPredicateType(prevPredicate.filters, filterFnTypes) : [], - sort: Array.isArray(prevPredicate.sort) ? cleanPredicateType(prevPredicate.sort, sortFnTypes) : [], - groupBy: Array.isArray(prevPredicate.groupBy) ? prevPredicate.groupBy : [], - colsOrder: Array.isArray(prevPredicate.colsOrder) ? prevPredicate.colsOrder : [], - colsHidden: Array.isArray(prevPredicate.colsHidden) ? prevPredicate.colsHidden : [], - colsSize: prevPredicate.colsSize ?? {} + const offset2 = e5.target.getBoundingClientRect(); + props.superstate.ui.openMenu( + offset2, + defaultMenu(props.superstate.ui, menuOptions) + ); }; -}; -var defaultPredicateForSchema = (schema) => { - return schema?.primary == "true" ? defaultPredicate : { - ...defaultPredicate, - view: "table" + const selectSource = (e5) => { + const offset2 = e5.target.getBoundingClientRect(); + showSpacesMenu(offset2, props.superstate, (link) => { + const newSchema = { + ...frameSchema, + name: frameSchema.name, + def: { + db: dbSchema.id, + context: link + }, + type: "view" + }; + saveSchema(newSchema).then((f2) => setFrameSchema(newSchema)); + }); }; -}; -var defaultPredicate = { - view: "list", - filters: [], - listView: "", - listItem: "", - listGroup: "", - listGroupProps: {}, - listViewProps: {}, - listItemProps: {}, - sort: [], - groupBy: [], - colsOrder: [], - colsHidden: [], - colsSize: {} -}; - -// src/core/react/context/FramesMDBContext.tsx -var import_react27 = __toESM(require_react()); - -// src/core/react/context/SpaceContext.tsx -var import_react26 = __toESM(require_react()); -var SpaceContext = (0, import_react26.createContext)({ - spaceInfo: null, - readMode: false, - spaceState: null -}); -var SpaceProvider = (props) => { - const { pathState } = (0, import_react26.useContext)(PathContext); - const spaceInfo = (0, import_react26.useMemo)(() => { - return props.superstate.spacesIndex.get(pathState.path)?.space; - }, [pathState]); - const readMode = spaceInfo?.readOnly; - const [spaceState, setSpaceState] = (0, import_react26.useState)(null); - (0, import_react26.useEffect)(() => { - const reloadSpace = () => { - setSpaceState(props.superstate.spacesIndex.get(pathState.path)); - }; - const refreshSpace = (payload) => { - if (payload.path == pathState.path) { - reloadSpace(); + const showFilterMenu = (e5) => { + const menuOptions = []; + menuOptions.push({ + name: i18n_default.menu.editProperties, + icon: "ui//list", + type: 6 /* Submenu */, + onSubmenu: (offset3) => { + return showPropertyEditMenu(offset3); } - }; - reloadSpace(); - props.superstate.eventsDispatcher.addListener( - "spaceStateUpdated", - refreshSpace - ); - return () => { - props.superstate.eventsDispatcher.removeListener( - "spaceStateUpdated", - refreshSpace - ); - }; - }, [pathState]); - return /* @__PURE__ */ import_react26.default.createElement(SpaceContext.Provider, { - value: { - spaceState, - readMode, - spaceInfo - } - }, spaceInfo && props.children); -}; - -// src/core/react/context/FramesMDBContext.tsx -var FramesMDBContext = (0, import_react27.createContext)({ - frameSchemas: [], - frames: [], - tableData: null, - saveFrame: () => null, - frameSchema: null, - setFrameSchema: () => null, - saveSchema: () => null, - deleteSchema: () => null, - saveProperty: () => false, - newProperty: () => false, - delProperty: () => null, - getMDBData: () => null, - undoLastAction: () => null, - redoAction: () => null -}); -var FramesMDBProvider = (props) => { - const [history2, setHistory] = (0, import_react27.useState)([]); - const [future, setFuture] = (0, import_react27.useState)([]); - const [schemaTable, setSchemaTable] = (0, import_react27.useState)(null); - const schemas = (0, import_react27.useMemo)( - () => (schemaTable?.rows ?? []).map( - (f2) => mdbSchemaToFrameSchema(f2) - ) ?? [], - [schemaTable] - ); - const frames = schemas.filter((f2) => f2.type == "frame"); - const [frameData, setFrameData] = (0, import_react27.useState)(null); - const [frameSchema, setFrameSchema] = (0, import_react27.useState)(null); - const tableData = (0, import_react27.useMemo)(() => { - return frameData?.[frameSchema?.id]; - }, [frameData, frameSchema]); - const { spaceInfo, readMode } = (0, import_react27.useContext)(SpaceContext); - const deleteSchema = async (table) => { - if (table.primary) - return; - await props.superstate.spaceManager.deleteFrame(spaceInfo.path, table.id); - const newSchemaTable = { - ...schemaTable, - rows: schemaTable.rows.filter((f2) => f2.id != table.id) - }; - setSchemaTable(newSchemaTable); - }; - const saveSchema = async (table) => { - const newSchema = schemaTable.rows.find((f2) => f2.id == table.id) ? true : false; - const newSchemaTable = newSchema ? { - ...schemaTable, - rows: schemaTable.rows.map( - (f2) => f2.id == table.id ? frameSchemaToTableSchema(table) : f2 - ) - } : { - ...schemaTable, - rows: [...schemaTable.rows, frameSchemaToTableSchema(table)] - }; - if (!spaceInfo.readOnly) { - await props.superstate.spaceManager.saveFrameSchema( - spaceInfo.path, - table.id, - () => frameSchemaToTableSchema(table) - ); - } - if (table.id == frameSchema?.id) { - setFrameSchema(table); - setFrameData((f2) => ({ - ...f2, - [table.id]: { - ...f2[table.id], - schema: frameSchemaToTableSchema(table) + }); + menuOptions.push({ + name: i18n_default.menu.unhideFields, + icon: "ui//eye", + onClick: (e6) => { + clearHiddenCols(); + } + }); + menuOptions.push(menuSeparator); + menuOptions.push({ + name: i18n_default.menu.groupBy, + icon: "ui//columns", + type: 6 /* Submenu */, + onSubmenu: (offset3) => { + return showGroupByMenu(offset3); + } + }); + menuOptions.push({ + name: i18n_default.menu.sortBy, + icon: "ui//sort-desc", + type: 6 /* Submenu */, + onSubmenu: (offset3) => { + return showSortMenu(offset3); + } + }); + menuOptions.push(menuSeparator); + menuOptions.push({ + name: i18n_default.menu.newFilter, + icon: "ui//filter", + onClick: (e6) => { + showAddFilterMenu(e6); + } + }); + menuOptions.push({ + name: i18n_default.menu.clearFilters, + icon: "ui//x-square", + onClick: (e6) => { + clearFilters(); + } + }); + menuOptions.push(menuSeparator); + const listViewOptions = propertiesForFrame(predicate?.listView); + const listGroupOptions = propertiesForFrame(predicate?.listGroup); + const listItemOptions = propertiesForFrame(predicate?.listItem); + const savePropValue = (type, prop2, value) => { + savePredicate({ + [type]: { + ...predicate[type], + [prop2]: value } - })); - } - setSchemaTable(newSchemaTable); - }; - (0, import_react27.useEffect)(() => { - if (schemaTable) - getMDBData().then((f2) => { - if (f2 && Object.keys(f2).length > 0) { - setFrameData(f2); + }); + }; + listViewOptions.forEach((f2) => { + menuOptions.push({ + name: nameForField(f2, props.superstate), + icon: stickerForField(f2), + type: 1 /* Disclosure */, + onClick: (e6) => { + showSetValueMenu( + e6.target.getBoundingClientRect(), + props.superstate, + f2, + (value) => savePropValue( + "listViewProps", + f2.name, + parseMDBValue(f2.type, value) + ), + spaceCache.path + ); } }); - }, [schemaTable]); - (0, import_react27.useEffect)(() => { - if (schemaTable) { - setFrameSchema((p) => { - if (props.schema) { - const preselectSchema = mdbSchemaToFrameSchema( - schemaTable.rows.find( - (g) => g.id == props.schema - ) + }); + listGroupOptions.forEach((f2) => { + menuOptions.push({ + name: nameForField(f2, props.superstate), + icon: stickerForField(f2), + type: 1 /* Disclosure */, + onClick: (e6) => { + showSetValueMenu( + e6.target.getBoundingClientRect(), + props.superstate, + f2, + (value) => savePropValue( + "listGroupProps", + f2.name, + parseMDBValue(f2.type, value) + ), + spaceCache.path ); - if (preselectSchema) { - return preselectSchema; - } else { - if (props.schema == defaultFrameListViewSchema.id) { - return mdbSchemaToFrameSchema(defaultFrameListViewSchema); - } - const newSchema = { - id: uniqueNameFromString( - sanitizeTableName(props.schema), - schemaTable.rows.map((g) => g.id) - ), - name: props.schema, - type: "frame" - }; - return newSchema; - } - } else { - if (p) { - return mdbSchemaToFrameSchema( - schemaTable.rows?.find((g) => g.id == p.id) - ); - } else { - if (props.contextSchema) { - return mdbSchemaToFrameSchema({ - id: uniqueNameFromString( - props.contextSchema, - schemaTable?.rows.map((f2) => f2.id) ?? [] - ), - name: "Table", - type: "view", - predicate: JSON.stringify({ - ...defaultPredicate, - view: "table" - }), - def: JSON.stringify({ - db: props.contextSchema, - icon: "ui//table" - }) - }); - } else { - return mdbSchemaToFrameSchema(defaultFrameListViewSchema); - } - } } - return p; }); - } - }, [schemaTable, props.contextSchema, props.schema]); - const loadTables = (0, import_react27.useCallback)(async () => { - if (!spaceInfo) - return; - props.superstate.spaceManager.framesForSpace(spaceInfo.path).then((f2) => { - if (f2) - setSchemaTable((prev) => ({ - uniques: [], - cols: ["id", "name", "type", "def", "predicate", "primary"], - rows: f2 - })); }); - }, [props.schema, spaceInfo]); - const refreshSpace = (0, import_react27.useCallback)( - async (payload) => { - if (payload.path == spaceInfo.path) { - loadTables(); - return; - } - }, - [spaceInfo, loadTables] - ); - (0, import_react27.useEffect)(() => { - props.superstate.eventsDispatcher.addListener( - "frameStateUpdated", - refreshSpace - ); - return () => { - props.superstate.eventsDispatcher.removeListener( - "frameStateUpdated", - refreshSpace - ); - }; - }, [refreshSpace]); - const getMDBData = async () => { - const tables = await props.superstate.spaceManager.readAllFrames( - spaceInfo.path + listItemOptions.forEach((f2) => { + menuOptions.push({ + name: nameForField(f2, props.superstate), + icon: stickerForField(f2), + type: 1 /* Disclosure */, + onClick: (e6) => { + showSetValueMenu( + e6.target.getBoundingClientRect(), + props.superstate, + f2, + (value) => savePropValue( + "listItemProps", + f2.name, + parseMDBValue(f2.type, value) + ), + spaceCache.path + ); + } + }); + }); + menuOptions.push(menuSeparator); + if (dbSchema?.primary == "true") { + menuOptions.push({ + name: "Source", + icon: "ui//table", + type: 1 /* Disclosure */, + value: source, + onClick: (e6) => { + selectSource(e6); + } + }); + menuOptions.push(menuSeparator); + } + const offset2 = e5.target.getBoundingClientRect(); + props.superstate.ui.openMenu( + offset2, + defaultMenu(props.superstate.ui, menuOptions) ); - return tables; }; - (0, import_react27.useEffect)(() => { - loadTables(); - }, [spaceInfo, props.schema]); - const saveFrame = async (newTable, track = true) => { - if (spaceInfo.readOnly) - return; - if (track) { - setHistory((prevHistory) => [...prevHistory, newTable]); - setFuture([]); + const addSort = (_15, sort2) => { + const field = sort2[0]; + const fieldObject = filteredCols.find((f2) => f2.name + f2.table == field); + const fieldType = fieldTypeForField(fieldObject); + if (fieldType) { + const type = defaultPredicateFnForType(fieldType, sortFnTypes); + const newSort = { + field, + fn: type + }; + savePredicate({ + sort: [ + ...predicate?.sort.filter((s4) => s4.field != newSort.field) ?? [], + newSort + ] + }); } - await props.superstate.spaceManager.saveFrame(spaceInfo.path, newTable).then((f2) => { - setFrameData((p) => ({ - ...p, - [newTable.schema.id]: newTable - })); + }; + const saveGroupBy = (_15, groupBy2) => { + savePredicate({ + groupBy: groupBy2 }); }; - const undoLastAction = () => { - if (history2.length === 0) - return; - const newHistory = history2.slice(0, -1); - const undoneState = history2[history2.length - 1]; - setHistory(newHistory); - setFuture((prevFuture) => [undoneState, ...prevFuture]); - if (newHistory.length > 0) { - const lastState = newHistory[newHistory.length - 1]; - saveFrame(lastState, false); - } + const removeSort = (sort2) => { + const newSort = [ + ...(predicate?.sort ?? []).filter((f2) => f2.field != sort2.field) + ]; + savePredicate({ + sort: newSort + }); }; - const redoAction = () => { - if (future.length === 0) - return; - const newFuture = future.slice(1); - const redoneState = future[0]; - setFuture(newFuture); - setHistory((prevHistory) => [...prevHistory, redoneState]); - saveFrame(redoneState, false); + const addFilter = (_15, filter4) => { + const field = filter4[0]; + const fieldObject = filteredCols.find((f2) => f2.name + f2.table == field); + const fieldType = fieldTypeForField(fieldObject); + if (fieldType) { + const type = defaultPredicateFnForType(fieldType, filterFnTypes); + if (!type) + return; + const newFilter = fieldType == "boolean" ? { + field, + fn: type, + fType: filterFnTypes[type].valueType, + value: "true" + } : { + field, + fn: type, + fType: filterFnTypes[type].valueType, + value: "" + }; + savePredicate({ + filters: [...predicate?.filters ?? [], newFilter] + }); + } }; - const delProperty = (column2) => { - const mdbtable = tableData; - const newFields = mdbtable.cols.filter( - (f2, i4) => f2.name != column2.name - ); - const newTable = { - ...mdbtable, - cols: newFields ?? [] + const changeSortMenu = (e5, sort2) => { + const offset2 = e5.target.getBoundingClientRect(); + const saveSort = (_15, newType) => { + const type = newType[0]; + const newSort = { + ...sort2, + fn: type + }; + savePredicate({ + sort: [ + ...(predicate?.sort ?? []).filter((s4) => s4.field != newSort.field), + newSort + ] + }); }; - saveFrame(newTable); - }; - const newProperty = (col) => { - return saveProperty(col); + const fieldObject = filteredCols.find( + (f2) => f2.name + f2.table == sort2.field + ); + const fieldType = fieldTypeForField(fieldObject); + const sortsForType = predicateFnsForType(fieldType, sortFnTypes); + props.superstate.ui.openMenu(offset2, { + ui: props.superstate.ui, + multi: false, + editable: false, + value: [], + options: sortsForType.map((f2) => ({ + name: sortFnTypes[f2].label, + value: f2 + })), + saveOptions: saveSort, + placeholder: i18n_default.labels.sortItemSelectPlaceholder, + searchable: false, + showAll: true + }); }; - const saveProperty = (newColumn, oldColumn) => { - const column2 = { - ...newColumn, - name: sanitizeColumnName(newColumn.name) - }; - const mdbtable = tableData; - if (column2.name == "") { - props.superstate.ui.notify(i18n_default.notice.noPropertyName); - return false; - } - if (!oldColumn && mdbtable.cols.find( - (f2) => f2.name.toLowerCase() == column2.name.toLowerCase() - ) || oldColumn && oldColumn.name != column2.name && mdbtable.cols.find( - (f2) => f2.name.toLowerCase() == column2.name.toLowerCase() - )) { - props.superstate.ui.notify(i18n_default.notice.duplicatePropertyName); - return false; + const showColsMenu = (e5) => { + const sourceCache = props.superstate.spacesIndex.get(source); + if (sourceCache) { + openSpaceEditorModal(props.superstate, sourceCache, 1); } - const oldFieldIndex = oldColumn ? mdbtable.cols.findIndex((f2) => f2.name == oldColumn.name) : -1; - const newFields = oldFieldIndex == -1 ? [...mdbtable.cols, column2] : mdbtable.cols.map((f2, i4) => i4 == oldFieldIndex ? column2 : f2); - const newTable = { - ...mdbtable, - cols: newFields ?? [] - }; - saveFrame(newTable); - return true; }; - return /* @__PURE__ */ import_react27.default.createElement(FramesMDBContext.Provider, { - value: { - frames, - tableData, - saveFrame, - frameSchemas: schemas, - saveSchema, - deleteSchema, - saveProperty, - newProperty, - delProperty, - frameSchema, - setFrameSchema, - getMDBData, - undoLastAction, - redoAction - } - }, props.children); -}; - -// src/core/react/context/ContextEditorContext.tsx -var ContextEditorContext = (0, import_react28.createContext)({ - dbSchema: null, - views: [], - source: "", - sortedColumns: [], - filteredData: [], - contextTable: {}, - editMode: 0, - setEditMode: () => null, - selectedRows: [], - selectRows: () => null, - setContextTable: () => null, - predicate: null, - savePredicate: () => null, - saveDB: () => null, - hideColumn: () => null, - saveColumn: () => false, - newColumn: () => false, - sortColumn: () => null, - delColumn: () => null, - searchString: "", - setSearchString: () => null, - updateValue: () => null, - updateFieldValue: () => null, - tableData: null, - cols: [] -}); -var ContextEditorProvider = (props) => { - const { frameSchemas, saveSchema, frameSchema } = (0, import_react28.useContext)(FramesMDBContext); - const { - spaceInfo, - readMode, - spaceState: spaceCache - } = (0, import_react28.useContext)(SpaceContext); - const [schemaTable, setSchemaTable] = (0, import_react28.useState)(null); - const [contextTable, setContextTable] = (0, import_react28.useState)({}); - const [tableData, setTableData] = (0, import_react28.useState)(null); - const [searchString, setSearchString] = (0, import_react28.useState)(null); - const [predicate, setPredicate] = (0, import_react28.useState)(null); - const [selectedRows, setSelectedRows] = (0, import_react28.useState)([]); - const [editMode, setEditMode] = (0, import_react28.useState)(0); - const contextPath = frameSchema?.def?.context ?? spaceInfo?.path; - const dbSchema = (0, import_react28.useMemo)(() => { - if (frameSchema) { - if (schemaTable) - return schemaTable?.rows.find( - (f2) => f2.id == frameSchema.def.db - ); - return { - id: frameSchema.def.db, - ...defaultContextDBSchema + const changeFilterMenu = (e5, filter4, index2) => { + const offset2 = e5.target.getBoundingClientRect(); + const saveFilter = (_15, newType) => { + const type = newType[0]; + const newFilter = { + ...filter4, + fn: type, + fType: filterFnTypes[type].valueType }; - } - return null; - }, [frameSchema, schemaTable]); - const views = (0, import_react28.useMemo)(() => { - const _views = frameSchemas.filter( - (f2) => f2.type == "view" && f2.def.db == dbSchema?.id - ); - return _views.length > 0 ? _views : frameSchema ? [frameSchema] : []; - }, [frameSchemas, frameSchema, dbSchema]); - const defaultSchema = defaultContextTable; - const contexts = spaceCache?.contexts ?? []; - const loadTables = async () => { - const schemas = await props.superstate.spaceManager.tablesForSpace( - contextPath - ); - if (schemas) - setSchemaTable(() => ({ - ...defaultSchema, - rows: schemas - })); + savePredicate({ + filters: (predicate?.filters ?? []).map( + (s4, i4) => i4 == index2 ? newFilter : s4 + ) + }); + }; + const field = filteredCols.find((f2) => f2.name + f2.table == filter4.field); + const fieldType = fieldTypeForField(field); + const filtersForType = predicateFnsForType(fieldType, filterFnTypes); + props.superstate.ui.openMenu(offset2, { + ui: props.superstate.ui, + multi: false, + editable: false, + value: [], + options: filtersForType.map((f2) => ({ + name: filterFnLabels[f2], + value: f2 + })), + saveOptions: saveFilter, + placeholder: i18n_default.labels.filterItemSelectPlaceholder, + searchable: false, + showAll: true + }); }; - (0, import_react28.useEffect)(() => { - if (dbSchema) - retrieveCachedTable(dbSchema); - }, [dbSchema]); - const loadContextFields = (0, import_react28.useCallback)(async (tag2) => { - props.superstate.spaceManager.contextForSpace(tagSpacePathFromTag(tag2)).then((f2) => { - setContextTable((t5) => ({ - ...t5, - [tag2]: f2 - })); + const showAddFilterMenu = (e5) => { + const offset2 = e5.target.getBoundingClientRect(); + props.superstate.ui.openMenu(offset2, { + ui: props.superstate.ui, + multi: false, + editable: false, + value: [], + options: filteredCols.filter( + (f2) => f2.type == "fileprop" || predicateFnsForType(f2.type, filterFnTypes).length > 0 + ).map((f2) => ({ + name: f2.name + f2.table, + value: f2.name + f2.table, + icon: stickerForField(f2) + })), + saveOptions: addFilter, + placeholder: i18n_default.labels.propertyItemSelectPlaceholder, + searchable: true, + showAll: true }); - }, []); - const retrieveCachedTable = (newSchema) => { - const f2 = props.superstate.contextsIndex?.get(contextPath)?.tables[newSchema.id]; - if (f2) { - if (newSchema.primary) { - for (const c3 of contexts) { - loadContextFields(c3); - } + }; + const showSortMenu = (offset2) => { + return props.superstate.ui.openMenu(offset2, { + ui: props.superstate.ui, + multi: false, + editable: false, + value: [], + options: filteredCols.map((f2) => ({ + name: f2.name + f2.table, + icon: stickerForField(f2), + value: f2.name + f2.table + })), + saveOptions: addSort, + placeholder: i18n_default.labels.sortItemSelectPlaceholder, + searchable: true, + showAll: true + }); + }; + const saveField = (field, oldField) => { + if (field.name.length > 0) { + if (field.name != oldField.name || field.type != oldField.type || field.value != oldField.value || field.attrs != oldField.attrs) { + const saveResult = saveColumn(field, oldField); } - updateTable(f2); - return; } - props.superstate.spaceManager.readTable(contextPath, newSchema.id).then((f3) => { - if (f3) { - if (newSchema.primary) { - for (const c3 of contexts) { - loadContextFields(c3); - } - } - updateTable(f3); - } - }); }; - const updateTable = (newTable) => { - setTableData(newTable); + const saveNewField = (source2, field) => { + saveColumn({ ...field, table: "" }); }; - (0, import_react28.useEffect)(() => { - const refreshMDB = (payload) => { - if (dbSchema?.primary != "true") { - return; - } - if (payload.path == contextPath) { - if (dbSchema) { - retrieveCachedTable(dbSchema); - } - } else { - const tag2 = Object.keys(contextTable).find( - (t5) => props.superstate.spaceManager.spaceInfoForPath(t5)?.path == payload.path + const showPropertyEditMenu = (offset2) => { + const options = []; + options.push({ + name: i18n_default.labels.newProperty, + icon: "ui//plus", + onClick: (e5) => { + showNewPropertyMenu( + props.superstate, + offset2, + [], + [], + saveNewField, + dbSchema.id, + spaceCache.path, + false ); - if (tag2) - loadContextFields(tag2); - } - }; - const refreshPath = (payload) => { - if (payload.path == contextPath && dbSchema) { - retrieveCachedTable(dbSchema); - } else if (dbSchema?.primary == "true" && tableData?.rows.some((f2) => f2[PathPropertyName] == payload.path)) { - retrieveCachedTable(dbSchema); } - }; - props.superstate.eventsDispatcher.addListener( - "contextStateUpdated", - refreshMDB + }); + options.push(menuSeparator); + options.push( + ...filteredCols.map((f2) => ({ + name: f2.name + f2.table, + icon: stickerForField(f2), + value: f2.name + f2.table, + type: 6 /* Submenu */, + onSubmenu: (offset3) => { + return showPropertyMenu({ + superstate: props.superstate, + rect: offset3, + editable: true, + options: [], + field: f2, + fields: filteredCols, + contextPath: spaceCache.path, + saveField: (newField) => saveField(newField, f2), + hide: hideColumn, + deleteColumn: delColumn, + hidden: predicate?.colsHidden.includes(f2.name + f2.table) + }); + } + })) ); - props.superstate.eventsDispatcher.addListener( - "pathStateUpdated", - refreshPath + return props.superstate.ui.openMenu( + offset2, + { + ui: props.superstate.ui, + multi: false, + editable: false, + value: [], + options, + placeholder: i18n_default.labels.propertyItemSelectPlaceholder, + searchable: false, + showAll: true + }, + "right" ); - return () => { - props.superstate.eventsDispatcher.removeListener( - "contextStateUpdated", - refreshMDB - ); - props.superstate.eventsDispatcher.removeListener( - "pathStateUpdated", - refreshPath - ); - }; - }, [contextTable, dbSchema, retrieveCachedTable, spaceInfo, tableData]); - (0, import_react28.useEffect)(() => { - loadTables(); - }, [spaceInfo, frameSchema]); - const saveDB = async (newTable) => { - if (spaceInfo.readOnly) - return; - await props.superstate.spaceManager.saveTable(contextPath, newTable, true).then((f2) => { - updateTable(newTable); - }); }; - const cols = (0, import_react28.useMemo)( - () => tableData ? [ - ...tableData.cols.map((f2) => ({ ...f2, table: "" })) ?? [], - ...dbSchema?.primary == "true" ? contexts.reduce( - (p, c3) => [ - ...p, - ...contextTable[c3]?.cols.filter((f2) => f2.primary != "true").map((f2) => ({ ...f2, table: c3 })) ?? [] - ], - [] - ) : [] - ] : [], - [tableData, contextTable, contexts, dbSchema] - ); - const data2 = (0, import_react28.useMemo)( - () => tableData?.rows.map((r2, index2) => ({ - _index: index2.toString(), - ...r2, - ...r2[PathPropertyName] ? { - [PathPropertyName]: props.superstate.spaceManager.resolvePath( - r2[PathPropertyName], - spaceCache?.path - ) - } : {}, - ...contexts.reduce((p, c3) => { - const contextRowIndexByPath = contextTable[c3]?.rows.findIndex( - (f2) => f2[PathPropertyName] == r2[PathPropertyName] - ) ?? -1; - const contextRowsByPath = contextTable[c3]?.rows[contextRowIndexByPath] ?? {}; - const contextRowsWithKeysAppended = Object.keys( - contextRowsByPath - ).reduce((pa, ca) => ({ ...pa, [ca + c3]: contextRowsByPath[ca] }), { - ["_index" + c3]: contextRowIndexByPath.toString() - }); - return { ...p, ...contextRowsWithKeysAppended }; - }, {}) - })) ?? [], - [tableData, contextTable, cols, dbSchema, spaceCache] - ); - (0, import_react28.useEffect)(() => { - if (tableData) { - for (const c3 of contexts) { - loadContextFields(c3); + const showGroupByMenu = (offset2) => { + return props.superstate.ui.openMenu( + offset2, + { + ui: props.superstate.ui, + multi: false, + editable: false, + value: [], + options: filteredCols.map((f2) => ({ + name: f2.name + f2.table, + icon: stickerForField(f2), + value: f2.name + f2.table + })), + saveOptions: saveGroupBy, + placeholder: i18n_default.labels.propertyItemSelectPlaceholder, + searchable: false, + showAll: true + }, + "right" + ); + }; + const selectFilterValue = (e5, filter4, index2) => { + switch (filter4.fType ?? filterFnTypes[filter4.fn].valueType) { + case "property": + { + savePredicate({ + filters: (predicate?.filters ?? []).map( + (s4, i4) => i4 == index2 ? filter4 : s4 + ) + }); + } + break; + case "text": + case "number": + { + savePredicate({ + filters: (predicate?.filters ?? []).map( + (s4, i4) => i4 == index2 ? filter4 : s4 + ) + }); + } + break; + case "date": { + const saveValue = (date2) => { + const newFilter = { + ...filter4, + value: date2 ? format(date2, "yyyy-MM-dd") : "" + }; + savePredicate({ + filters: (predicate?.filters ?? []).map( + (s4, i4) => i4 == index2 ? newFilter : s4 + ) + }); + }; + const offset2 = e5.target.getBoundingClientRect(); + const date = new Date(filter4.value); + showDatePickerMenu( + props.superstate.ui, + offset2, + date.getTime() ? date : null, + saveValue, + 0 /* None */ + ); + break; } + case "link": + { + const col = cols.find((f2) => f2.name + f2.table == filter4.field); + if (col?.type.startsWith("context")) { + const space2 = parseFieldValue(col.value, col.type)?.space; + if (!space2) + return; + const contextData = props.superstate.contextsIndex.get(space2)?.paths ?? []; + const offset3 = e5.target.getBoundingClientRect(); + props.superstate.ui.openMenu(offset3, { + ui: props.superstate.ui, + multi: false, + editable: false, + value: parseMultiString(filter4.value), + options: contextData.map((f2) => ({ + name: pathToString(f2), + value: f2 + })) ?? [], + saveOptions: (options, values2) => { + const newFilter = { + ...filter4, + value: values2[0] + }; + savePredicate({ + filters: (predicate?.filters ?? []).map( + (s4, i4) => i4 == index2 ? newFilter : s4 + ) + }); + }, + placeholder: i18n_default.labels.optionItemSelectPlaceholder, + searchable: true, + showAll: true + }); + return; + } + const saveValue = (link) => { + const newFilter = { + ...filter4, + value: link + }; + savePredicate({ + filters: (predicate?.filters ?? []).map( + (s4, i4) => i4 == index2 ? newFilter : s4 + ) + }); + }; + const offset2 = e5.target.getBoundingClientRect(); + showLinkMenu( + offset2, + props.superstate, + (link) => { + saveValue(link); + }, + { multi: true } + ); + e5.stopPropagation(); + } + break; + case "list": + { + const col = cols.find((f2) => f2.name + f2.table == filter4.field); + const saveOptions = (options, values2) => { + const newFilter = { + ...filter4, + value: serializeMultiString(values2) + }; + savePredicate({ + filters: (predicate?.filters ?? []).map( + (s4, i4) => i4 == index2 ? newFilter : s4 + ) + }); + }; + if (col.type.startsWith("option")) { + const offset2 = e5.target.getBoundingClientRect(); + const options = parseFieldValue(col.value, col.type).options; + props.superstate.ui.openMenu(offset2, { + ui: props.superstate.ui, + multi: true, + editable: false, + value: parseMultiString(filter4.value), + options: options ?? [], + saveOptions, + placeholder: i18n_default.labels.optionItemSelectPlaceholder, + searchable: true, + showAll: true + }); + } else if (col.type.startsWith("context")) { + const space2 = parseFieldValue(col.value, col.type)?.space; + if (!space2) + return; + const contextData = props.superstate.contextsIndex.get(space2)?.paths ?? []; + const offset2 = e5.target.getBoundingClientRect(); + props.superstate.ui.openMenu(offset2, { + ui: props.superstate.ui, + multi: true, + editable: false, + value: parseMultiString(filter4.value), + options: contextData.map((f2) => ({ + name: pathToString(f2), + value: f2 + })) ?? [], + saveOptions, + placeholder: i18n_default.labels.optionItemSelectPlaceholder, + searchable: true, + showAll: true + }); + } else if (col.type.startsWith("link")) { + const offset2 = e5.target.getBoundingClientRect(); + showLinkMenu( + offset2, + props.superstate, + (link) => { + saveOptions([link], [link]); + }, + { multi: true } + ); + e5.stopPropagation(); + } else if (col.type.startsWith("tags")) { + const contextData = props.superstate.spaceManager.readTags(); + const offset2 = e5.target.getBoundingClientRect(); + props.superstate.ui.openMenu(offset2, { + ui: props.superstate.ui, + multi: true, + editable: false, + value: parseMultiString(filter4.value), + options: contextData.map((f2) => ({ + name: f2, + value: f2 + })) ?? [], + saveOptions, + placeholder: i18n_default.labels.tagItemSelectPlaceholder, + searchable: true, + showAll: true + }); + } + } + break; } - }, [tableData]); - const saveContextDB = async (newTable, tag2) => { - await props.superstate.spaceManager.saveTable(tagSpacePathFromTag(tag2), newTable, true).then((f2) => { - setContextTable((t5) => ({ - ...t5, - [tag2]: newTable - })); - }); }; - const sortedColumns = (0, import_react28.useMemo)(() => { - return cols.filter( - (f2) => f2.hidden != "true" && !(predicate?.colsHidden ?? []).some((c3) => c3 == f2.name + f2.table) - ).sort( - (a4, b2) => (predicate?.colsOrder ?? []).findIndex((x2) => x2 == a4.name + a4.table) - (predicate?.colsOrder ?? []).findIndex((x2) => x2 == b2.name + b2.table) - ); - }, [cols, predicate]); - const filteredData = (0, import_react28.useMemo)( - () => data2.filter((f2) => { - return (predicate?.filters ?? []).reduce((p, c3) => { - return p ? filterReturnForCol( - cols.find((col) => col.name + col.table == c3.field), - c3, - f2, - spaceCache.properties - ) : p; - }, true); - }).filter( - (f2) => searchString?.length > 0 ? matchAny(searchString).test( - Object.keys(f2).filter((g) => g.charAt(0) != "_").map((g) => f2[g]).join("|") - ) : true - ).sort((a4, b2) => { - return (predicate?.sort ?? []).reduce((p, c3) => { - return p == 0 ? sortReturnForCol( - cols.find((col) => col.name + col.table == c3.field), - c3, - a4, - b2 - ) : p; - }, 0); - }), - [predicate, data2, cols, searchString] - ); - const updateValue2 = (column2, value, table, index2, path2) => { - const col = (table == "" ? tableData : contextTable[table])?.cols.find( - (f2) => f2.name == column2 - ); - if (col) - saveProperties( - props.superstate, - path2 ?? tableData.rows[index2]?.[PathPropertyName], - { [column2]: parseMDBValue(col.type, value) } - ); - if (table == "") { - saveDB({ - ...tableData, - rows: tableData.rows.map( - (r2, i4) => i4 == index2 ? { - ...r2, - [column2]: value - } : r2 - ) - }); - } else if (contextTable[table]) { - const path3 = tableData.rows[index2][PathPropertyName]; - saveContextDB( + return /* @__PURE__ */ import_react38.default.createElement(import_react38.default.Fragment, null, /* @__PURE__ */ import_react38.default.createElement("div", { + className: "mk-view-config" + }, !expanded && /* @__PURE__ */ import_react38.default.createElement(ListSelector, { + superstate: props.superstate, + expanded: false, + setView: props.setView + }), /* @__PURE__ */ import_react38.default.createElement("div", { + className: "mk-view-options" + }, /* @__PURE__ */ import_react38.default.createElement("span", null), /* @__PURE__ */ import_react38.default.createElement(SearchBar, { + superstate: props.superstate, + setSearchString + }), /* @__PURE__ */ import_react38.default.createElement("button", { + className: "mk-toolbar-button", + onClick: (e5) => showViewsMenu(e5), + dangerouslySetInnerHTML: { + __html: props.superstate.ui.getSticker("ui//layout-panel-left") + } + }), /* @__PURE__ */ import_react38.default.createElement("button", { + className: "mk-toolbar-button", + onClick: (e5) => showFilterMenu(e5), + dangerouslySetInnerHTML: { + __html: props.superstate.ui.getSticker("ui//view-options") + } + }), dbSchema?.id == defaultContextSchemaID && /* @__PURE__ */ import_react38.default.createElement(import_react38.default.Fragment, null, /* @__PURE__ */ import_react38.default.createElement("button", { + className: "mk-button-new", + onClick: (e5) => showSpaceAddMenu( + props.superstate, + e5.target.getBoundingClientRect(), + spaceCache, + true + ), + dangerouslySetInnerHTML: { + __html: props.superstate.ui.getSticker("ui//plus") + } + })))), (predicate?.filters.length > 0 || predicate?.sort.length > 0 || predicate?.groupBy.length > 0) && /* @__PURE__ */ import_react38.default.createElement("div", { + className: "mk-filter-bar" + }, predicate.groupBy.length > 0 && /* @__PURE__ */ import_react38.default.createElement("div", { + className: "mk-filter" + }, /* @__PURE__ */ import_react38.default.createElement("span", null, i18n_default.menu.groupBy), /* @__PURE__ */ import_react38.default.createElement("span", { + onClick: (e5) => showGroupByMenu( + e5.target.getBoundingClientRect() + ) + }, predicate.groupBy[0]), /* @__PURE__ */ import_react38.default.createElement("div", { + onClick: () => saveGroupBy(null, []), + dangerouslySetInnerHTML: { + __html: props.superstate.ui.getSticker("ui//close") + } + })), (predicate?.sort ?? []).map((f2, i4) => /* @__PURE__ */ import_react38.default.createElement("div", { + key: i4, + className: "mk-filter" + }, /* @__PURE__ */ import_react38.default.createElement("span", null, f2.field), /* @__PURE__ */ import_react38.default.createElement("span", { + onClick: (e5) => changeSortMenu(e5, f2) + }, sortFnTypes[f2.fn].label), /* @__PURE__ */ import_react38.default.createElement("div", { + onClick: () => removeSort(f2), + dangerouslySetInnerHTML: { + __html: props.superstate.ui.getSticker("ui//close") + } + }))), (predicate?.filters ?? [] ?? []).map((f2, i4) => /* @__PURE__ */ import_react38.default.createElement("div", { + key: i4, + className: "mk-filter" + }, /* @__PURE__ */ import_react38.default.createElement("span", null, f2.field), /* @__PURE__ */ import_react38.default.createElement("span", { + onClick: (e5) => changeFilterMenu(e5, f2, i4) + }, filterFnLabels[f2.fn]), /* @__PURE__ */ import_react38.default.createElement(FilterValueSpan, { + superstate: props.superstate, + fieldType: cols.find((c3) => c3.name + c3.table == f2.field)?.type, + filter: f2, + selectFilterValue: (e5, f3) => selectFilterValue(e5, f3, i4) + }), properties3.length > 0 && /* @__PURE__ */ import_react38.default.createElement("span", { + onClick: (e5) => { + e5.stopPropagation(); + props.superstate.ui.openMenu( + e5.currentTarget.getBoundingClientRect(), { - ...contextTable[table], - rows: contextTable[table].rows.map( - (r2, i4) => r2[PathPropertyName] == path3 ? { - ...r2, - [column2]: value - } : r2 - ) - }, - table + ui: props.superstate.ui, + multi: false, + editable: false, + value: [], + options: properties3.map((f3) => ({ + name: f3.name, + value: f3.name, + section: f3.type + })), + saveOptions: (_15, value) => selectFilterValue( + e5, + { + ...f2, + fType: "property", + value: value[0] + }, + i4 + ), + placeholder: i18n_default.labels.contextItemSelectPlaceholder, + searchable: true, + showAll: true, + sections: [], + showSections: false + } ); } - }; - const sortColumn = (sort2) => { - savePredicate({ - sort: [sort2] - }); - }; - const hideColumn = (col, hidden) => { - savePredicate({ - colsHidden: hidden ? [ - ...predicate.colsHidden.filter((s4) => s4 != col.name + col.table), - col.name + col.table - ] : predicate.colsHidden.filter((s4) => s4 != col.name + col.table) + }, /* @__PURE__ */ import_react38.default.createElement("div", { + className: "mk-icon-xsmall", + dangerouslySetInnerHTML: { + __html: props.superstate.ui.getSticker("ui//plug") + } + })), /* @__PURE__ */ import_react38.default.createElement("div", { + onClick: () => removeFilter(f2, i4), + dangerouslySetInnerHTML: { + __html: props.superstate.ui.getSticker("ui//close") + } + }))), (predicate?.filters ?? []).length > 0 && /* @__PURE__ */ import_react38.default.createElement("div", { + className: "mk-filter-add", + onClick: (e5) => showAddFilterMenu(e5) + }, /* @__PURE__ */ import_react38.default.createElement("span", null, /* @__PURE__ */ import_react38.default.createElement("span", { + className: "mk-icon-xsmall", + dangerouslySetInnerHTML: { + __html: props.superstate.ui.getSticker("ui//plus") + } + }), i18n_default.buttons.addFilter)), /* @__PURE__ */ import_react38.default.createElement("span", null))); +}; +var FilterValueSpan = (props) => { + const { filter: filter4, selectFilterValue, fieldType } = props; + const fnType = filterFnTypes[filter4.fn]; + const [value, setValue] = (0, import_react38.useState)(filter4.value); + (0, import_react38.useEffect)(() => setValue(filter4.value), [filter4.value]); + if (filter4.fType == "property") { + return /* @__PURE__ */ import_react38.default.createElement("span", null, filter4.value); + } + if (!fieldType || !fnType || fnType.valueType == "none") { + return /* @__PURE__ */ import_react38.default.createElement(import_react38.default.Fragment, null); + } else if (fnType.valueType == "text" || fnType.valueType == "number") { + return /* @__PURE__ */ import_react38.default.createElement("input", { + type: "text", + onChange: (e5) => setValue(e5.currentTarget.value), + onBlur: (e5) => { + selectFilterValue(null, { ...filter4, value }); + }, + onKeyDown: (e5) => { + if (e5.key == "Escape") { + setValue(filter4.value); + e5.currentTarget.blur(); + } + if (e5.key == "Enter") { + e5.currentTarget.blur(); + } + }, + value }); - }; - const updateFieldValue = (column2, fieldValue, value, table, index2, path2) => { - const col = tableData.cols.find((f2) => f2.name == column2); - saveProperties( - props.superstate, - path2 ?? tableData.rows[index2]?.[PathPropertyName], - { [column2]: parseMDBValue(col.type, value) } - ); - if (table == "") { - const newTable = { - ...tableData, - cols: tableData.cols.map( - (m4) => m4.name == column2 ? { - ...m4, - value: fieldValue - } : m4 - ), - rows: tableData.rows.map( - (r2, i4) => i4 == index2 ? { - ...r2, - [column2]: value - } : r2 + } else if (fieldType.startsWith("option") || fieldType.startsWith("context") || fieldType.startsWith("link") || fieldType.startsWith("tag")) { + const options = parseMultiString(filter4.value); + return /* @__PURE__ */ import_react38.default.createElement("span", { + onClick: (e5) => selectFilterValue(e5, filter4) + }, options.length == 0 ? i18n_default.labels.select : options.map( + (f2, i4) => fieldType.startsWith("option") ? /* @__PURE__ */ import_react38.default.createElement("span", { + key: i4 + }, f2) : /* @__PURE__ */ import_react38.default.createElement(PathCrumb, { + superstate: props.superstate, + key: i4, + path: f2 + }) + )); + } else if (!filter4.value || filter4.value.length == 0) { + return /* @__PURE__ */ import_react38.default.createElement("span", { + onClick: (e5) => selectFilterValue(e5, filter4) + }, i18n_default.labels.select); + } + return /* @__PURE__ */ import_react38.default.createElement("span", { + onClick: (e5) => selectFilterValue(e5, filter4) + }, filter4.value); +}; + +// src/core/react/components/SpaceEditor/SpaceQuery.tsx +var SpaceQuery = (props) => { + (0, import_react39.useEffect)(() => { + props.superstate.refreshMetadata(); + }, []); + const { filters, setFilters } = props; + const selectFilterValue = (e5, filter4, i4, k2) => { + const saveFilterValue = (value) => { + setDefFilterValue(value, i4, k2); + }; + if (filter4.fType == "property") { + setFilters( + filters.map( + (f2, groupIndex) => i4 == groupIndex ? { + ...f2, + filters: f2.filters.map( + (g, filterIndex) => k2 == filterIndex ? { + ...g, + fType: "property", + value: filter4.value + } : g + ) + } : f2 ) - }; - saveDB(newTable); - } else if (contextTable[table]) { - const path3 = tableData.rows[index2][PathPropertyName]; - saveContextDB( - { - ...contextTable[table], - cols: contextTable[table].cols.map( - (m4) => m4.name == column2 ? { - ...m4, - value: fieldValue - } : m4 - ), - rows: contextTable[table].rows.map( - (r2, i4) => path3 == r2[PathPropertyName] ? { - ...r2, - [column2]: value - } : r2 - ) - }, - table ); + return; } - }; - const syncAllProperties = async (f2) => { - const paths = f2.rows.map((f3) => f3[PathPropertyName]); - const getPathProperties2 = async (paths2, fmKeys) => { - let rows = { uniques: [], cols: fmKeys, rows: [] }; - for (const c3 of paths2) { - const properties3 = props.superstate.pathsIndex.get(c3)?.metadata.property; - rows = { - uniques: [], - cols: fmKeys, - rows: [ - ...rows.rows, - { - [PathPropertyName]: c3, - ...properties3 ? fmKeys.reduce((p, c4) => { - const value = parseProperty(c4, properties3[c4]); - if (value?.length > 0) - return { ...p, [c4]: value }; - return p; - }, {}) : {} - } - ] + switch (filterFnTypes[filter4.fn]?.valueType) { + case "text": + case "number": + { + saveFilterValue(filter4.value); + } + break; + case "date": { + const saveValue = (date2) => { + saveFilterValue(format(date2, "yyyy-MM-dd")); + }; + const offset2 = e5.target.getBoundingClientRect(); + const date = new Date(filter4.value); + showDatePickerMenu( + props.superstate.ui, + offset2, + date.getTime() ? date : null, + saveValue, + 0 /* None */ + ); + break; + } + case "link": { + const saveValue = (value) => { + saveFilterValue(value); }; + const offset2 = e5.target.getBoundingClientRect(); + showLinkMenu(offset2, props.superstate, saveValue); + e5.stopPropagation(); + break; } - return rows; - }; - const pathPropertiesTable = await getPathProperties2( - paths, - f2.cols.filter((f3) => !f3.type.includes("file")).map((f3) => f3.name) - ); - const newRows = f2.rows.map((r2) => { - const fmRow = pathPropertiesTable.rows.find( - (f3) => f3[PathPropertyName] == r2[PathPropertyName] - ); - if (fmRow) { - return { - ...r2, - ...fmRow + case "space": { + const saveValue = (value) => { + saveFilterValue(value); }; + const offset2 = e5.target.getBoundingClientRect(); + showSpacesMenu(offset2, props.superstate, saveValue); + break; } - return r2; - }); - const rowsChanged = !import_lodash10.default.isEqual(newRows, tableData?.rows); - const colsChanged = !import_lodash10.default.isEqual(tableData?.cols, f2.cols); - if (rowsChanged || colsChanged) { - saveDB({ - ...f2, - rows: newRows - }); + case "list": + { + const fieldType = filter4.fType; + const saveOptions = (options2, values2) => { + saveFilterValue(serializeMultiString(values2)); + }; + let options = []; + if (fieldType.startsWith("option")) { + options = parseMultiString(filter4.value).map((f2) => ({ + name: f2, + value: f2 + })); + } else if (fieldType.startsWith("tags")) { + options = props.superstate.spaceManager.readTags().map((f2) => ({ + value: f2, + name: f2 + })); + } else if (fieldType.startsWith("links")) { + options = props.superstate.spaceManager.allPaths().map((f2) => ({ + name: pathNameToString(f2), + value: f2, + description: f2 + })); + } + const offset2 = e5.target.getBoundingClientRect(); + props.superstate.ui.openMenu(offset2, { + ui: props.superstate.ui, + multi: true, + editable: true, + value: parseMultiString(filter4.value), + options, + saveOptions, + placeholder: i18n_default.labels.optionItemSelectPlaceholder, + searchable: false, + showAll: true + }); + } + break; } }; - (0, import_react28.useEffect)(() => { - if (frameSchema) { - parsePredicate(frameSchema.predicate); - } - }, [frameSchema]); - const selectRows = (lastSelected, rows) => { - setSelectedRows(rows); - if (!(dbSchema?.primary == "true")) + const addDefGroup = () => { + setFilters((p) => [ + ...p, + { + type: "any", + trueFalse: true, + filters: [] + } + ]); + }; + const removeDefGroup = (groupIndex) => { + setFilters(filters.filter((f2, i4) => i4 == groupIndex ? false : true)); + }; + const setDefFilter = (filter4, groupIndex, filterIndex) => { + if (!filter4) + return; + if (filters.length == 0) { + setFilters([ + { + type: "all", + trueFalse: true, + filters: [ + { + type: filter4.type, + field: filter4.field, + fType: filter4.vType, + fn: filter4.defaultFilter, + value: "" + } + ] + } + ]); return; - if (lastSelected) { - const path2 = tableData.rows[parseInt(lastSelected)]?.[PathPropertyName]; - if (path2) - props.superstate.ui.setActivePath(path2); - } else { - props.superstate.ui.setActivePath(contextPath); } - }; - const savePredicate = (newPredicate) => { - const defPredicate = defaultPredicateForSchema(dbSchema); - const pred = { - ...predicate ?? defPredicate, - ...newPredicate - }; - const cleanedPredicate = validatePredicate(pred, defPredicate); - if (frameSchema) { - saveSchema({ - ...frameSchema, - predicate: JSON.stringify(cleanedPredicate) - }); - } else { - saveSchema({ - id: uniqueNameFromString( - dbSchema.id + "View", - frameSchemas.map((f2) => f2.id) - ), - name: dbSchema.name + " View", - type: "view", - def: { db: dbSchema.id }, - predicate: JSON.stringify(cleanedPredicate) - }); + if (filters[groupIndex]?.filters.length == 0) { + setFilters( + filters.map( + (f2, i4) => i4 == groupIndex ? { + ...f2, + filters: [ + { + type: filter4.type, + field: filter4.field, + fType: filter4.vType, + fn: filter4.defaultFilter, + value: "" + } + ] + } : f2 + ) + ); + return; } - setPredicate(cleanedPredicate); - }; - (0, import_react28.useEffect)(() => { - if (predicate) - setPredicate((p) => ({ - ...p, - colsOrder: uniq([ - ...p.colsOrder, - ...cols.filter((f2) => f2.hidden != "true").map((c3) => c3.name + c3.table) - ]) - })); - }, [cols]); - const parsePredicate = (predicateStr) => { - const defPredicate = defaultPredicateForSchema(dbSchema); - const newPredicate = validatePredicate( - safelyParseJSON(predicateStr), - defPredicate + setFilters( + filters.map( + (f2, i4) => i4 == groupIndex ? { + ...f2, + filters: !f2.filters || filterIndex == f2.filters.length ? [ + ...f2.filters ?? [], + { + type: filter4.type, + field: filter4.field, + fType: filter4.vType, + fn: filter4.defaultFilter, + value: "" + } + ] : f2.filters.map( + (g, k2) => k2 == filterIndex ? { + ...g, + type: filter4.type, + field: filter4.field, + fType: filter4.vType, + fn: filter4.defaultFilter + } : g + ) + } : f2 + ) ); - setPredicate({ - ...newPredicate, - colsOrder: uniq([ - ...newPredicate.colsOrder, - ...cols.filter((f2) => f2.hidden != "true").map((c3) => c3.name + c3.table) - ]) - }); }; - const delColumn = (column2) => { - let mdbtable; - const table = column2.table; - if (table == "") { - mdbtable = tableData; - } else if (contextTable[table]) { - mdbtable = contextTable[table]; - } - const newFields = mdbtable.cols.filter( - (f2, i4) => f2.name != column2.name + const setDefFilterFn = (fn, groupIndex, filterIndex) => { + setFilters( + filters.map( + (f2, i4) => i4 == groupIndex ? { + ...f2, + filters: f2.filters.map( + (g, k2) => k2 == filterIndex ? { + ...g, + fn + } : g + ) + } : f2 + ) ); - const newTable = { - ...mdbtable, - cols: newFields, - rows: mdbtable.rows.map((r2) => { - const { [column2.name]: val, ...rest } = r2; - return rest; - }) - }; - if (table == "") { - saveDB(newTable); - } else if (contextTable[table]) { - saveContextDB(newTable, table); - } }; - const newColumn = (col) => { - return saveColumn(col); + const setDefFilterValue = (value, groupIndex, filterIndex) => { + setFilters( + filters.map( + (f2, i4) => i4 == groupIndex ? { + ...f2, + filters: f2.filters.map( + (g, k2) => k2 == filterIndex ? { + ...g, + value + } : g + ) + } : f2 + ) + ); }; - const saveColumn = (newColumn2, oldColumn) => { - let mdbtable; - const column2 = { - ...newColumn2, - name: sanitizeColumnName(newColumn2.name) - }; - const table = column2.table; - if (table == "" || table == contextPath) { - mdbtable = tableData; - } else if (contextTable[table]) { - mdbtable = contextTable[table]; - } - if (column2.name == "") { - props.superstate.ui.notify(i18n_default.notice.noPropertyName); - return false; - } - if (!oldColumn && mdbtable.cols.find( - (f2) => f2.name.toLowerCase() == column2.name.toLowerCase() - ) || oldColumn && oldColumn.name != column2.name && mdbtable.cols.find( - (f2) => f2.name.toLowerCase() == column2.name.toLowerCase() - )) { - props.superstate.ui.notify(i18n_default.notice.duplicatePropertyName); - return false; - } - const oldFieldIndex = oldColumn ? mdbtable.cols.findIndex((f2) => f2.name == oldColumn.name) : -1; - const newFields = oldFieldIndex == -1 ? [...mdbtable.cols, column2] : mdbtable.cols.map((f2, i4) => i4 == oldFieldIndex ? column2 : f2); - const newTable = { - ...mdbtable, - cols: newFields, - rows: mdbtable.rows.map( - (f2) => oldColumn ? { + const removeDefFilter = (filterIndex, groupIndex) => { + setFilters( + filters.map( + (f2, i4) => i4 == groupIndex ? { ...f2, - [column2.name]: f2[oldColumn.name], - oldColumn: void 0 + filters: f2.filters.filter( + (g, k2) => k2 == filterIndex ? false : true + ) } : f2 ) - }; - if (oldColumn) - savePredicate({ - filters: (predicate?.filters ?? []).map( - (f2) => f2.field == oldColumn.name + oldColumn.table ? { ...f2, field: column2.name + column2.table } : f2 - ), - sort: (predicate?.sort ?? []).map( - (f2) => f2.field == oldColumn.name + oldColumn.table ? { ...f2, field: column2.name + column2.table } : f2 - ), - groupBy: (predicate?.groupBy ?? []).map( - (f2) => f2 == oldColumn.name + oldColumn.table ? column2.name + column2.table : f2 - ), - colsHidden: (predicate?.colsHidden ?? []).map( - (f2) => f2 == oldColumn.name + oldColumn.table ? column2.name + column2.table : f2 - ), - colsOrder: (predicate?.colsOrder ?? []).map( - (f2) => f2 == oldColumn.name + oldColumn.table ? column2.name + column2.table : f2 - ), - colsSize: { - ...predicate?.colsSize ?? {}, - [column2.name + column2.table]: predicate?.colsSize?.[oldColumn.name + oldColumn.table], - [oldColumn.name + oldColumn.table]: void 0 + ); + }; + const setGroupType = (groupIndex, type) => { + if (groupIndex == 0 && filters.length == 0) { + setFilters([ + { + type, + trueFalse: true, + filters: [] } - }); - if (table == "") { - if (dbSchema.id == defaultContextSchemaID) { - syncAllProperties(newTable); - } else { - saveDB(newTable); - } - } else if (contextTable[table]) { - saveContextDB(newTable, table); + ]); + } else { + setFilters( + filters.map( + (f2, i4) => i4 == groupIndex ? { + ...f2, + type + } : f2 + ) + ); } - return true; }; - return /* @__PURE__ */ import_react28.default.createElement(ContextEditorContext.Provider, { - value: { - source: contextPath, - views, - cols, - saveDB, - filteredData, - dbSchema, - tableData, - selectedRows, - selectRows, - sortedColumns, - contextTable, - setContextTable, - predicate, - savePredicate, - saveColumn, - hideColumn, - sortColumn, - delColumn, - newColumn, - searchString, - setSearchString, - updateValue: updateValue2, - updateFieldValue, - editMode, - setEditMode - } - }, props.children); + const selectGroupType = (e5, i4) => { + const offset2 = e5.target.getBoundingClientRect(); + const filters2 = ["any", "all"]; + props.superstate.ui.openMenu(offset2, { + ui: props.superstate.ui, + multi: false, + editable: false, + value: [], + options: filters2.map((f2) => ({ + name: f2 == "any" ? "or" : "and", + value: f2 + })), + saveOptions: (_15, value) => setGroupType(i4, value[0]), + searchable: false, + showAll: true + }); + }; + const selectFilter = (e5, i4, k2) => { + const offset2 = e5.target.getBoundingClientRect(); + const { type, field, fType } = filters[i4].filters[k2]; + const _filters = fType == "any" ? allPredicateFns(filterFnTypes) : predicateFnsForType(fType, filterFnTypes); + props.superstate.ui.openMenu(offset2, { + ui: props.superstate.ui, + multi: false, + editable: true, + value: [], + options: _filters.map((f2) => ({ name: filterFnLabels[f2], value: f2 })), + saveOptions: (_15, value) => setDefFilterFn(value[0], i4, k2), + placeholder: i18n_default.labels.contextItemSelectPlaceholder, + searchable: true, + showAll: true + }); + }; + const selectField = async (e5, i4, k2) => { + const offset2 = e5.target.getBoundingClientRect(); + props.superstate.ui.openMenu(offset2, { + ui: props.superstate.ui, + multi: false, + editable: false, + value: [], + options: props.fields.map((f2) => ({ + name: f2.label, + value: f2, + section: f2.type, + description: f2.description + })), + saveOptions: (_15, value) => setDefFilter(value[0], i4, k2), + placeholder: i18n_default.labels.contextItemSelectPlaceholder, + searchable: true, + showAll: true, + sections: props.sections, + showSections: true + }); + }; + return /* @__PURE__ */ import_react39.default.createElement("div", { + className: "mk-query" + }, filters.length == 0 ? /* @__PURE__ */ import_react39.default.createElement(DefFilterGroup, { + superstate: props.superstate, + selectGroupType, + group: null, + addDefGroup, + selectField, + i: 0, + removeable: props.removeable, + removeDefGroup + }) : filters.map((f2, i4) => /* @__PURE__ */ import_react39.default.createElement(DefFilterGroup, { + superstate: props.superstate, + key: i4, + group: f2, + selectGroupType, + addDefGroup, + selectField, + removeable: props.removeable, + i: i4, + removeDefGroup + }, f2.filters.map((filter4, k2, arr) => /* @__PURE__ */ import_react39.default.createElement(import_react39.default.Fragment, { + key: k2 + }, /* @__PURE__ */ import_react39.default.createElement(DefFilter, { + superstate: props.superstate, + key: k2, + filter: filter4, + i: i4, + k: k2, + selectField, + selectFilter, + selectFilterValue, + removeDefFilter, + linkProps: props.linkProps + }), k2 != arr.length - 1 && /* @__PURE__ */ import_react39.default.createElement("div", { + className: "mk-filter", + onClick: (e5) => selectGroupType(e5, i4) + }, /* @__PURE__ */ import_react39.default.createElement("span", null, f2.type == "any" ? "or" : "and"))))))); }; - -// src/core/react/hooks/useCombinedRef.tsx -var import_react29 = __toESM(require_react()); -function useCombinedRefs2(...refs) { - return (0, import_react29.useMemo)( - () => (node) => { - refs.forEach((ref2) => ref2(node)); - }, - refs - ); -} - -// src/core/react/components/SpaceView/Contexts/TableView/ColumnHeader.tsx -var import_react30 = __toESM(require_react()); -var filePropTypes = [ - { - name: i18n_default.properties.fileProperty.name, - value: "name" - }, - { - name: i18n_default.properties.fileProperty.createdTime, - value: "ctime" - }, - { - name: i18n_default.properties.fileProperty.modifiedTime, - value: "mtime" - }, - { - name: i18n_default.properties.fileProperty.sticker, - value: "sticker" - }, - { - name: i18n_default.properties.fileProperty.extension, - value: "extension" - }, - { - name: i18n_default.properties.fileProperty.size, - value: "size" - }, - { - name: i18n_default.properties.fileProperty.parentFolder, - value: "folder" - }, - { - name: i18n_default.properties.fileProperty.links, - value: "inlinks" - }, - { - name: i18n_default.properties.fileProperty.tags, - value: "tags" - }, - { - name: i18n_default.properties.fileProperty.spaces, - value: "spaces" - } -]; -var ColumnHeader = (props) => { - const [field, setField] = (0, import_react30.useState)(props.column); - const menuRef = (0, import_react30.useRef)(null); - const { spaceInfo, spaceState: spaceCache } = (0, import_react30.useContext)(SpaceContext); - const { - predicate, - tableData, - contextTable, - cols, - newColumn, - saveColumn, - hideColumn, - sortColumn, - delColumn - } = (0, import_react30.useContext)(ContextEditorContext); - (0, import_react30.useEffect)(() => { - setField(props.column); - }, [props.column]); +var DefFilter = (props) => { const { - attributes, - listeners, - setNodeRef: setDraggableNodeRef, - transform - } = useDraggable({ - id: field.name + field.table, - data: { name: field.name } - }); - const { setNodeRef: setDroppableNodeRef } = useDroppable({ - id: field.name + field.table, - data: { name: field.name } - }); - const saveField = (field2) => { - if (field2.name.length > 0) { - if (field2.name != props.column.name || field2.type != props.column.type || field2.value != props.column.value || field2.attrs != props.column.attrs) { - const saveResult = saveColumn(field2, props.column); - if (saveResult) { - if (props.isNew) { - setField(props.column); - } + filter: filter4, + selectField, + selectFilter, + selectFilterValue, + removeDefFilter, + i: i4, + k: k2 + } = props; + const filterFieldName = props.superstate.allMetadata[filter4.type]?.properties.find( + (f2) => f2.field == filter4.field + )?.label ?? filter4.field; + return /* @__PURE__ */ import_react39.default.createElement("div", { + className: "mk-filter" + }, /* @__PURE__ */ import_react39.default.createElement("span", { + onClick: (e5) => selectField(e5, i4, k2) + }, filter4.field.length == 0 ? i18n_default.labels.select : filterFieldName), filter4.field.length > 0 && /* @__PURE__ */ import_react39.default.createElement("span", { + onClick: (e5) => selectFilter(e5, i4, k2) + }, !filterFnLabels[filter4.fn] ? i18n_default.labels.select : filterFnLabels[filter4.fn]), filter4.field.length > 0 && filterFnLabels[filter4.fn] && filterFnTypes[filter4.fn]?.valueType != "none" && /* @__PURE__ */ import_react39.default.createElement(import_react39.default.Fragment, null, /* @__PURE__ */ import_react39.default.createElement("span", null, /* @__PURE__ */ import_react39.default.createElement(FilterValueSpan, { + superstate: props.superstate, + fieldType: filter4.fType, + filter: filter4, + selectFilterValue: (e5, h3) => selectFilterValue(e5, h3, i4, k2) + })), props.linkProps && props.linkProps.length > 0 && /* @__PURE__ */ import_react39.default.createElement("span", { + onClick: (e5) => { + e5.stopPropagation(); + props.superstate.ui.openMenu( + e5.currentTarget.getBoundingClientRect(), + { + ui: props.superstate.ui, + multi: false, + editable: false, + value: [], + options: props.linkProps.map((f2) => ({ + name: f2.name, + value: f2.name, + section: f2.type + })), + saveOptions: (_15, value) => selectFilterValue( + e5, + { + ...filter4, + fType: "property", + value: value[0] + }, + i4, + k2 + ), + placeholder: i18n_default.labels.contextItemSelectPlaceholder, + searchable: true, + showAll: true, + sections: [], + showSections: false } - } - } - }; - const showNewMenu = (e5) => { - const offset2 = ref2.current.getBoundingClientRect(); - showNewPropertyMenu( - props.superstate, - offset2, - spaceCache?.contexts ?? [], - cols, - (source, field2) => newColumn({ ...field2, table: source }), - tableData.schema.id, - spaceInfo.path, - false - ); - }; - const toggleMenu = (e5) => { - if (props.isNew) { - showNewMenu(e5); - } else { - const offset2 = e5.target.getBoundingClientRect(); - const options = optionValuesForColumn( - field.name, - field.table == "" ? tableData : contextTable[field.table] ); - showPropertyMenu({ - superstate: props.superstate, - rect: offset2, - editable: props.editable, - options, - field, - fields: cols, - contextPath: spaceInfo.path, - saveField, - hide: hideColumn, - deleteColumn: delColumn, - sortColumn, - hidden: predicate?.colsHidden.includes(field.name + field.table) - }); } - }; - const ref2 = (0, import_react30.useRef)(null); - const setNodeRef = useCombinedRefs2(setDroppableNodeRef, setDraggableNodeRef); - return /* @__PURE__ */ import_react30.default.createElement("div", { - ref: setNodeRef, - ...listeners, - ...attributes, - className: "mk-col-header", + }, /* @__PURE__ */ import_react39.default.createElement("div", { + className: "mk-icon-xsmall", + dangerouslySetInnerHTML: { + __html: props.superstate.ui.getSticker("ui//plug") + } + }))), /* @__PURE__ */ import_react39.default.createElement("span", { onClick: (e5) => { - toggleMenu(e5); + removeDefFilter(k2, i4); + e5.stopPropagation(); } - }, /* @__PURE__ */ import_react30.default.createElement("div", { - ref: ref2 - }, props.column.name.length > 0 ? /* @__PURE__ */ import_react30.default.createElement(import_react30.default.Fragment, null, /* @__PURE__ */ import_react30.default.createElement("div", { - className: "mk-path-context-field-icon", + }, /* @__PURE__ */ import_react39.default.createElement("div", { + className: "mk-icon-xsmall", dangerouslySetInnerHTML: { - __html: props.superstate.ui.getSticker( - stickerForField(props.column) - ) + __html: props.superstate.ui.getSticker("ui//close") } - }), /* @__PURE__ */ import_react30.default.createElement("div", { - className: "mk-path-context-field-key" - }, field.name)) : "+", /* @__PURE__ */ import_react30.default.createElement("span", { - className: "mk-col-header-context", - "aria-label": props.column.table.length > 0 ? props.column.table : "" - }, props.column.table.length > 0 ? "#" : ""))); + }))); }; - -// src/core/utils/properties/allProperties.ts -var allCacheTypesForPaths = (superstate, paths) => { - if (!superstate.settings.experimental) - return []; - ; - const properties3 = {}; - for (const path2 of paths) { - const f2 = superstate.pathsIndex.get(path2)?.metadata; - if (f2) { - Object.keys(f2).forEach((k2) => { - const type = detectPropertyType(f2[k2], k2); - if (type != "unknown" && type != "object") - properties3[k2] = [...properties3[k2] ?? [], type]; - }); +var DefFilterGroup = (props) => { + const { + group, + selectGroupType, + addDefGroup, + selectField, + i: i4, + removeDefGroup + } = props; + return /* @__PURE__ */ import_react39.default.createElement("div", { + className: "mk-query-group" + }, /* @__PURE__ */ import_react39.default.createElement("div", { + className: "mk-filter-bar mk-query-filters" + }, props.children, /* @__PURE__ */ import_react39.default.createElement("div", { + className: "mk-filter-add", + onClick: (e5) => selectField(e5, i4, group?.filters.length ?? 0) + }, /* @__PURE__ */ import_react39.default.createElement("span", null, /* @__PURE__ */ import_react39.default.createElement("span", { + className: "mk-icon-xsmall", + dangerouslySetInnerHTML: { + __html: props.superstate.ui.getSticker("ui//plus") } - } - return Object.keys(properties3).reduce((p, c3) => { - return [...p, { name: c3, type: properties3[c3][0] }]; - }, []); + }), i18n_default.buttons.addCondition))), props.removeable && /* @__PURE__ */ import_react39.default.createElement("div", { + className: "mk-filter-add", + onClick: (e5) => { + removeDefGroup(i4); + e5.stopPropagation(); + } + }, /* @__PURE__ */ import_react39.default.createElement("span", null, /* @__PURE__ */ import_react39.default.createElement("span", { + className: "mk-icon-small", + dangerouslySetInnerHTML: { + __html: props.superstate.ui.getSticker("ui//close") + } + })))); }; -// src/core/react/components/UI/Menus/contexts/PropertyValue.tsx -var import_react31 = __toESM(require_react()); -var PropertyValueComponent = (props) => { - const showOptions = (e5, value, options, field, saveProperty) => { - props.superstate.ui.openMenu( - e5.target.getBoundingClientRect(), - { - ui: props.superstate.ui, - multi: false, - editable: true, - searchable: true, - saveOptions: (_15, v2) => { - if (saveProperty) { - saveProperty(v2[0]); - } else { - saveParsedValue(field, v2[0]); - } - }, - placeholder: i18n_default.labels.propertyValueSpace, - value: [value ?? ""], - options - } - ); +// src/core/react/components/SpaceEditor/SpaceItems.tsx +var SpaceItems = (props) => { + const [metadata, setMetadata] = (0, import_react40.useState)( + props.space.metadata ?? {} + ); + const [smartSearch, setSmartSearch] = (0, import_react40.useState)(metadata?.filters?.length > 0); + const saveMetadata = (metadata2) => { + setMetadata(metadata2); + saveSpaceCache(props.superstate, props.space.space, metadata2); }; - const selectType = (e5) => { - props.superstate.ui.openMenu( - e5.target.getBoundingClientRect(), - { - ui: props.superstate.ui, - multi: false, - editable: false, - searchable: false, - saveOptions: (_15, v2) => saveParsedValue("type", v2[0]), - value: [], - showAll: true, - options: fieldTypes.filter((f2) => f2.primative).map((f2, i4) => ({ - id: i4 + 1, - name: f2.label, - value: f2.type, - icon: f2.icon - })) - } - ); + const saveQuery = (q2) => { + saveMetadata({ + ...metadata, + filters: q2 + }); }; - const parsedValue = (0, import_react31.useMemo)( - () => parseFieldValue(props.value, props.fieldType, props.superstate), - [props.value, props.fieldType] + const linkCaches = (0, import_react40.useMemo)( + () => (metadata?.links ?? []).map((f2) => props.superstate.pathsIndex.get(f2)).filter((f2) => f2), + [metadata] ); - const saveParsedValue = (field, value) => { - props.saveValue(JSON.stringify({ ...parsedValue, [field]: value })); - }; - const saveSpaceProperty = (field) => { - const colExists = props.superstate.contextsIndex.get(parsedValue.space)?.cols?.some((f2) => f2.name == field); - if (!colExists) { - props.superstate.spaceManager.addSpaceProperty(parsedValue.space, { - name: field, - schemaId: defaultContextSchemaID, - type: "context", - value: props.name - }); + const directChildren = (0, import_react40.useMemo)(() => { + return [...props.superstate.spacesMap.getInverse(props.space.path)].map((f2) => props.superstate.pathsIndex.get(f2)).filter((f2) => f2.parent == props.space.path); + }, [props.space]); + const metadataProperties = props.superstate.allMetadata; + const allOptions = []; + Object.keys(metadataProperties).forEach((type) => { + metadataProperties[type].properties.forEach((field) => { + allOptions.push(field); + }); + }); + const sections = Object.keys(metadataProperties).map((f2) => { + return { + name: metadataProperties[f2].name, + value: f2 + }; + }); + return /* @__PURE__ */ import_react40.default.createElement(import_react40.default.Fragment, null, /* @__PURE__ */ import_react40.default.createElement("div", { + className: "mk-space-editor" + }, /* @__PURE__ */ import_react40.default.createElement("div", { + className: "mk-space-editor-header" + }, /* @__PURE__ */ import_react40.default.createElement("div", { + className: "mk-space-editor-header-title" + }, /* @__PURE__ */ import_react40.default.createElement("div", { + className: "mk-space-editor-title" + }, i18n_default.subViews.spaceItems), /* @__PURE__ */ import_react40.default.createElement("div", { + className: "mk-space-editor-description" + }, i18n_default.descriptions.spaceItems)), /* @__PURE__ */ import_react40.default.createElement("span", null), /* @__PURE__ */ import_react40.default.createElement("button", { + className: "mk-toolbar-button", + dangerouslySetInnerHTML: { + __html: props.superstate.ui.getSticker("ui//live") + }, + onClick: () => setSmartSearch((p) => !p) + }), /* @__PURE__ */ import_react40.default.createElement("button", { + className: "mk-button-new", + "aria-label": i18n_default.buttons.addItem, + onClick: (e5) => { + const offset2 = e5.target.getBoundingClientRect(); + showLinkMenu( + offset2, + props.superstate, + (link) => saveMetadata({ + ...metadata, + links: [...metadata.links ?? [], link] + }) + ); + e5.stopPropagation(); + }, + dangerouslySetInnerHTML: { + __html: props.superstate.ui.getSticker("ui//plus") } - saveParsedValue("field", field); - }; - const selectContext = (e5) => { - showOptions( - e5, - parsedValue.space, - props.superstate.allSpaces().filter((f2) => f2.type != "default").map((m4) => ({ name: m4.name, value: m4.path, description: m4.path })), - "space" - ); - }; - const selectSpaceProperty = (e5) => { - showOptions( - e5, - parsedValue.property, - props.superstate.contextsIndex.get(parsedValue.space)?.cols.filter((f2) => { - return f2.type?.startsWith("context") && parseFieldValue(f2.value, f2.type, props.superstate)["space"] == props.contextPath ? true : false; - }).map((m4) => ({ name: m4.name, value: m4.name })) ?? [], - "field", - saveSpaceProperty - ); - }; - const selectProperty = (e5) => { - const properties3 = props.fields.filter( - (f2) => f2.type == "file" || f2.type == "link" || f2.type == "context" - ).map((f2) => ({ - name: f2.name, - value: f2.name - })) ?? []; - showOptions(e5, null, properties3, "field"); + })), /* @__PURE__ */ import_react40.default.createElement("div", { + className: "mk-space-editor-contents" + }, smartSearch && /* @__PURE__ */ import_react40.default.createElement("div", { + className: "mk-space-editor-smart" + }, /* @__PURE__ */ import_react40.default.createElement("span", null, i18n_default.subViews.smartSearch), metadata?.filters?.length > 0 && /* @__PURE__ */ import_react40.default.createElement(SpaceQuery, { + superstate: props.superstate, + filters: metadata.filters ?? [], + setFilters: saveQuery, + removeable: true, + fields: allOptions, + sections, + linkProps: props.space.propertyTypes + }), /* @__PURE__ */ import_react40.default.createElement("button", { + className: "mk-filter-add", + "aria-label": i18n_default.buttons.addSmartSearch, + onClick: (e5) => saveMetadata({ + ...metadata, + filters: [ + ...metadata.filters ?? [], + { + type: "any", + trueFalse: true, + filters: [] + } + ] + }) + }, /* @__PURE__ */ import_react40.default.createElement("div", { + className: "mk-icon-xsmall", + dangerouslySetInnerHTML: { + __html: props.superstate.ui.getSticker("ui//plus") + } + }), i18n_default.buttons.addSmartSearch)), linkCaches.map((f2, i4) => /* @__PURE__ */ import_react40.default.createElement(PathCrumb, { + key: i4, + superstate: props.superstate, + path: f2.path + })), directChildren.map((f2, i4) => /* @__PURE__ */ import_react40.default.createElement(PathCrumb, { + key: i4, + superstate: props.superstate, + path: f2.path + }))))); +}; + +// src/core/react/components/SpaceEditor/SpaceTemplates.tsx +var import_react41 = __toESM(require_react()); +var TemplatesList = (props) => { + const { pathState } = (0, import_react41.useContext)(PathContext); + const { spaceState } = (0, import_react41.useContext)(SpaceContext); + const [templates, setTemplates] = import_react41.default.useState([]); + (0, import_react41.useEffect)(() => { + refreshData({ path: pathState.path }); + }, []); + const refreshData = (payload) => { + if (payload.path == pathState?.path) + setTemplates( + props.superstate.spacesIndex.get(spaceState.path)?.templates + ); }; - const selectPathProp = (e5) => { - const property = props.fields.find((f2) => f2.name == parsedValue.field); - const allPaths = props.superstate.spaceManager.allPaths(); - const fileProps = property ? property.type == "file" || property.type == "link" ? filePropTypes.map((f2) => ({ - name: f2.name, - value: f2.value - })) : props.superstate.contextsIndex.get( - parseFieldValue(property.value, "context", props.superstate).space - )?.cols.filter((f2) => f2.hidden != "true").map((f2) => ({ - name: f2.name, - value: f2.name - })) ?? [] : []; - const cacheTypes = allCacheTypesForPaths(props.superstate, allPaths).map( - (f2) => ({ name: f2.name, value: f2.name }) + (0, import_react41.useEffect)(() => { + props.superstate.eventsDispatcher.addListener( + "spaceStateUpdated", + refreshData + ); + return () => { + props.superstate.eventsDispatcher.removeListener( + "spaceStateUpdated", + refreshData + ); + }; + }, [pathState]); + const newAction = (e5) => { + const offset2 = e5.target.getBoundingClientRect(); + showLinkMenu(offset2, props.superstate, (space2) => { + saveSpaceTemplate(props.superstate, pathState.path, space2); + }); + e5.stopPropagation(); + }; + const showMenu2 = (e5, f2) => { + const offset2 = e5.target.getBoundingClientRect(); + const menuOptions = []; + menuOptions.push({ + name: "Set as Default", + icon: "ui//clipboard-pen", + onClick: () => setTemplateInSpace(props.superstate, pathState.path, f2) + }); + props.superstate.ui.openMenu( + offset2, + defaultMenu(props.superstate.ui, menuOptions), + "bottom" ); - showOptions(e5, null, [...fileProps, ...cacheTypes], "value"); }; const editFormula = (e5) => { const _props = { superstate: props.superstate, - saveFormula: (value) => saveParsedValue("value", value), - formula: parsedValue.value, + saveFormula: (value) => setTemplateNameInSpace(props.superstate, pathState.path, value), + formula: spaceState.metadata.templateName, value: {}, - fields: props.fields, - path: "" + fields: [], + description: "Automatically set a template name using a formula", + path: pathState.path }; props.superstate.ui.openCustomMenu( e5.target.getBoundingClientRect(), - /* @__PURE__ */ import_react31.default.createElement(FormulaEditor, { + /* @__PURE__ */ import_react41.default.createElement(FormulaEditor, { ..._props }), { ..._props }, "bottom" ); }; - const selectDateFormat = (e5) => { - const formats = [ - { - name: "2020-04-21", - value: "yyyy-MM-dd" - }, - { - name: "Apr 21, 2020", - value: "MMM d, yyyy" - }, - { - name: "Tue Apr 21, 2020", - value: "EEE MMM d, yyyy" - } - ]; - showOptions(e5, null, formats, "format"); - }; - return props.fieldType?.startsWith("date") ? /* @__PURE__ */ import_react31.default.createElement("div", { - className: "mk-menu-option", - onClick: (e5) => selectDateFormat(e5) - }, /* @__PURE__ */ import_react31.default.createElement("span", null, i18n_default.labels.dateFormat), /* @__PURE__ */ import_react31.default.createElement("span", null, parsedValue.format)) : props.fieldType?.startsWith("context") ? /* @__PURE__ */ import_react31.default.createElement(import_react31.default.Fragment, null, /* @__PURE__ */ import_react31.default.createElement("div", { - className: "mk-menu-option", - onClick: (e5) => selectContext(e5) - }, /* @__PURE__ */ import_react31.default.createElement("span", null, i18n_default.labels.propertyValueSpace), /* @__PURE__ */ import_react31.default.createElement("span", null, spaceNameFromSpacePath(parsedValue.space, props.superstate))), parsedValue.space?.length > 0 && props.contextPath && /* @__PURE__ */ import_react31.default.createElement("div", { - className: "mk-menu-option", - onClick: (e5) => selectSpaceProperty(e5) - }, /* @__PURE__ */ import_react31.default.createElement("span", null, i18n_default.labels.propertyValueProperty), /* @__PURE__ */ import_react31.default.createElement("span", null, parsedValue.field))) : props.fieldType == "number" ? /* @__PURE__ */ import_react31.default.createElement(import_react31.default.Fragment, null) : props.fieldType == "fileprop" ? /* @__PURE__ */ import_react31.default.createElement(import_react31.default.Fragment, null, /* @__PURE__ */ import_react31.default.createElement("div", { - className: "mk-menu-option", - onClick: (e5) => editFormula(e5) - }, /* @__PURE__ */ import_react31.default.createElement("span", null, i18n_default.labels.propertyLookup)), /* @__PURE__ */ import_react31.default.createElement("div", { - className: "mk-menu-option", - onClick: (e5) => selectType(e5) - }, /* @__PURE__ */ import_react31.default.createElement("span", null, i18n_default.labels.propertyType), /* @__PURE__ */ import_react31.default.createElement("span", null, fieldTypeForType(parsedValue.type)?.label))) : props.fieldType == "object" ? /* @__PURE__ */ import_react31.default.createElement("div", { - className: "mk-menu-option", - onClick: (e5) => { - props.superstate.ui.openModal( - "Object Name", - (_props) => /* @__PURE__ */ import_react31.default.createElement(InputModal, { - value: parsedValue.typeName, - saveLabel: "Rename Object", - saveValue: (value) => { - saveParsedValue("typeName", value); - }, - hide: _props.hide - }) - ); + return /* @__PURE__ */ import_react41.default.createElement("div", { + className: "mk-actions-list" + }, /* @__PURE__ */ import_react41.default.createElement("div", { + className: "mk-space-editor-header" + }, /* @__PURE__ */ import_react41.default.createElement("div", null, /* @__PURE__ */ import_react41.default.createElement("div", { + className: "mk-space-editor-title" + }, i18n_default.subViews.spaceTemplates), /* @__PURE__ */ import_react41.default.createElement("div", { + className: "mk-space-editor-description" + }, i18n_default.descriptions.spaceTemplates)), /* @__PURE__ */ import_react41.default.createElement("span", null), /* @__PURE__ */ import_react41.default.createElement("button", { + className: "mk-toolbar-button", + "aria-label": i18n_default.labels.editFormula, + onClick: (e5) => editFormula(e5), + dangerouslySetInnerHTML: { + __html: props.superstate.ui.getSticker("ui//formula") } - }, /* @__PURE__ */ import_react31.default.createElement("span", null, "Name"), /* @__PURE__ */ import_react31.default.createElement("span", null, parsedValue.typeName)) : props.fieldType == "super" ? /* @__PURE__ */ import_react31.default.createElement(import_react31.default.Fragment, null, /* @__PURE__ */ import_react31.default.createElement("div", { - className: "mk-menu-option" - }, /* @__PURE__ */ import_react31.default.createElement("span", null, i18n_default.labels.propertyDynamic), /* @__PURE__ */ import_react31.default.createElement("input", { - type: "checkbox", - checked: parsedValue.dynamic == true, - onChange: () => saveParsedValue("dynamic", !parsedValue.dynamic) - })), /* @__PURE__ */ import_react31.default.createElement("div", { - className: "mk-menu-option", - onClick: (e5) => selectProperty(e5) - }, /* @__PURE__ */ import_react31.default.createElement("span", null, i18n_default.labels.propertyFileProp), /* @__PURE__ */ import_react31.default.createElement("span", null, parsedValue.field))) : /* @__PURE__ */ import_react31.default.createElement(import_react31.default.Fragment, null); + }), /* @__PURE__ */ import_react41.default.createElement("button", { + className: "mk-button-new", + "aria-label": i18n_default.labels.newAction, + onClick: (e5) => newAction(e5), + dangerouslySetInnerHTML: { + __html: props.superstate.ui.getSticker("ui//plus") + } + })), /* @__PURE__ */ import_react41.default.createElement("div", { + className: "mk-space-editor-contents" + }, templates.map((f2, i4) => /* @__PURE__ */ import_react41.default.createElement("div", { + key: i4, + className: "mk-action", + onContextMenu: (e5) => showMenu2(e5, f2) + }, /* @__PURE__ */ import_react41.default.createElement("div", { + className: "mk-path" + }, /* @__PURE__ */ import_react41.default.createElement("div", { + className: "mk-path-icon", + dangerouslySetInnerHTML: { + __html: props.superstate.ui.getSticker("ui//clipboard-pen") + } + }), /* @__PURE__ */ import_react41.default.createElement("div", null, f2)), /* @__PURE__ */ import_react41.default.createElement("span", null), spaceState.metadata.template == f2 && /* @__PURE__ */ import_react41.default.createElement("div", { + className: "mk-path-icon", + "aria-label": "Default", + dangerouslySetInnerHTML: { + __html: props.superstate.ui.getSticker("ui//check") + } + }), /* @__PURE__ */ import_react41.default.createElement("button", { + className: "mk-toolbar-button", + onClick: () => props.superstate.spaceManager.deleteTemplate(f2, spaceState.path), + dangerouslySetInnerHTML: { + __html: props.superstate.ui.getSticker("ui//trash") + } + }))))); }; -// src/core/react/components/UI/Menus/contexts/newSpacePropertyMenu.tsx -var NewPropertyMenuComponent = (props) => { - const [fieldName, setFieldName] = (0, import_react32.useState)(""); - const [fieldSource, setFieldSource] = (0, import_react32.useState)( - props.fileMetadata ? "$fm" : "" - ); - const spaceCaches = (0, import_react32.useMemo)( - () => props.spaces.map((f2) => props.superstate.spacesIndex.get(f2)).filter((f2) => f2), - [props.spaces] - ); - const [fieldValue, setFieldValue] = (0, import_react32.useState)(""); - const [fieldType, setFieldType] = (0, import_react32.useState)("text"); - const options = (0, import_react32.useMemo)(() => { - const options2 = []; - if (props.fileMetadata) { - options2.push({ - name: i18n_default.menu.setNone, - value: "$fm" - }); +// src/core/react/context/WindowContext.tsx +var import_react42 = __toESM(require_react()); +var import_react_dom3 = __toESM(require_react_dom()); +var WindowContext = import_react42.default.createContext({ + dragNode: null, + setDragNode: () => null, + dragActive: false +}); +var WindowProvider = (props) => { + const [dragNode, setDragNode] = import_react42.default.useState(null); + useDndMonitor({ + onDragCancel: () => { + setDragNode(null); + }, + onDragEnd: () => { + setDragNode(null); } - if (props.contextPath) { - options2.push({ - name: folderPathToString(props.contextPath), - value: "" - }); + }); + return /* @__PURE__ */ import_react42.default.createElement(WindowContext.Provider, { + value: { + dragNode, + setDragNode, + dragActive: props.dragActive } - options2.push( - ...(spaceCaches ?? []).map((f2) => ({ - name: f2.name, - value: f2.path - })) - ); - return options2; - }, [spaceCaches]); - const selectedType = (_15, value) => { - setFieldType(value[0]); - }; - const selectedValue = (value) => { - setFieldValue(value); - }; - const selectedSource = (_15, value) => { - setFieldSource(value[0]); + }, props.children, dragNode && (0, import_react_dom3.createPortal)( + /* @__PURE__ */ import_react42.default.createElement(DragOverlay, { + dropAnimation: null, + zIndex: 1600 + }, dragNode), + document.body + )); +}; + +// src/core/react/components/UI/Crumbs/ContextTableCrumb.tsx +var import_react43 = __toESM(require_react()); +var ContextTableCrumb = (props) => { + const { setDragNode } = (0, import_react43.useContext)(WindowContext); + const { spaceInfo } = (0, import_react43.useContext)(SpaceContext); + const dragId = spaceInfo.path + props.schema.id; + const { + attributes, + listeners, + setNodeRef: setDraggableNodeRef, + transform + } = useDraggable({ + id: dragId, + data: { + id: dragId, + type: "context", + space: spaceInfo?.path, + schema: props.schema.id + } + }); + const ref2 = (0, import_react43.useRef)(null); + useDndMonitor({ + onDragStart: (e5) => { + if (e5.active.data.current.id == dragId) { + setDragNode( + /* @__PURE__ */ import_react43.default.createElement("div", { + dangerouslySetInnerHTML: { __html: ref2.current.innerHTML } + }) + ); + } + } + }); + return /* @__PURE__ */ import_react43.default.createElement("div", { + className: "mk-path", + onClick: (e5) => props.onClick(e5), + ref: (el) => { + setDraggableNodeRef(el); + ref2.current = el; + }, + onContextMenu: (e5) => props.onContextMenu(e5), + ...attributes, + ...listeners + }, /* @__PURE__ */ import_react43.default.createElement("div", { + className: "mk-path-icon", + dangerouslySetInnerHTML: { + __html: props.superstate.ui.getSticker( + props.schema.primary == "true" ? "ui//layout-list" : "ui//table" + ) + } + }), props.schema.name); +}; + +// src/core/react/components/SpaceEditor/TableList.tsx +var import_react44 = __toESM(require_react()); +var TableList = (props) => { + const { pathState } = (0, import_react44.useContext)(PathContext); + const { spaceState } = (0, import_react44.useContext)(SpaceContext); + const [tables, setTables] = (0, import_react44.useState)([]); + (0, import_react44.useEffect)(() => { + refreshData({ path: pathState.path }); + }, []); + const refreshData = (payload) => { + if (payload.path == pathState?.path) + setTables( + (props.superstate.contextsIndex.get(pathState?.path)?.schemas ?? []).filter((f2) => f2.primary != "true") + ); }; - const toggleMulti = () => { - const field = fieldTypes.find( - (f2) => f2.type == fieldType || f2.multiType == fieldType + (0, import_react44.useEffect)(() => { + props.superstate.eventsDispatcher.addListener( + "contextStateUpdated", + refreshData ); - setFieldType(field.type == fieldType ? field.multiType : field.type); - }; - const selectType = (e5) => { - props.superstate.ui.openMenu( - e5.target.getBoundingClientRect(), - { - ui: props.superstate.ui, - multi: false, - editable: false, - searchable: true, - saveOptions: selectedType, - value: [], - showAll: true, - options: fieldTypes.filter( - (f2) => fieldSource == "$fm" && !props.isSpace ? f2.metadata : !f2.restricted - ).map((f2, i4) => ({ - id: i4 + 1, - name: f2.label, - value: f2.type, - icon: f2.icon, - description: f2.description - })) - } + return () => { + props.superstate.eventsDispatcher.removeListener( + "contextStateUpdated", + refreshData + ); + }; + }, [pathState]); + const newTable = (e5) => { + props.superstate.ui.openModal( + i18n_default.labels.newTable, + (_props) => /* @__PURE__ */ import_react44.default.createElement(InputModal, { + value: "", + saveLabel: i18n_default.buttons.save, + hide: _props.hide, + saveValue: (value) => { + props.superstate.spaceManager.tablesForSpace(spaceState.path).then((schemas) => { + if (schemas) { + const newSchema = { + id: uniqueNameFromString( + sanitizeTableName(value), + schemas.map((g) => g.id) + ), + name: value, + type: "db" + }; + return props.superstate.spaceManager.createTable(spaceState.path, newSchema).then((f2) => { + return props.superstate.spaceManager.addSpaceProperty( + spaceState.path, + { ...defaultTableFields[0], schemaId: newSchema.id } + ); + }); + } + }); + } + }) ); }; - const selectedContext = (value) => { - setFieldValue(value); - }; - const type = (0, import_react32.useMemo)( - () => fieldTypeForType(fieldType, fieldName) ?? fieldTypes[0], - [fieldType, fieldName] - ); - const selectSource = (e5) => { - e5.stopPropagation(); + const viewContextMenu = (e5, _schema) => { + const menuOptions = []; + menuOptions.push({ + name: i18n_default.menu.copyEmbedLink, + icon: "ui//link", + onClick: (e6) => { + navigator.clipboard.writeText( + contextEmbedStringFromContext(spaceState, _schema.id) + ); + } + }); + menuOptions.push({ + name: i18n_default.menu.moveFile, + icon: "ui//move", + onClick: (e6) => { + const offset2 = e6.target.getBoundingClientRect(); + showSpacesMenu(offset2, props.superstate, (space2) => { + const table = props.superstate.contextsIndex.get(spaceState.path).tables?.[_schema.id]; + table.schema.id = uniqueNameFromString( + sanitizeTableName(table.schema.id), + Object.keys(props.superstate.contextsIndex.get(space2).tables) + ); + table.cols = table.cols.map((f2) => ({ + ...f2, + schemaId: table.schema.id + })); + props.superstate.spaceManager.createTable(space2, table.schema).then((f2) => props.superstate.spaceManager.saveTable(space2, table)); + }); + } + }); + menuOptions.push({ + name: i18n_default.menu.duplicate, + icon: "ui//copy", + onClick: (e6) => { + props.superstate.ui.openModal( + "Duplicate Table", + (_props) => /* @__PURE__ */ import_react44.default.createElement(InputModal, { + value: "", + hide: _props.hide, + saveLabel: "Save", + saveValue: (value) => { + const table = props.superstate.contextsIndex.get( + spaceState.path + ).tables?.[_schema.id]; + table.schema.id = uniqueNameFromString( + sanitizeTableName(value), + Object.keys( + props.superstate.contextsIndex.get(spaceState.path).tables + ) + ); + table.cols = table.cols.map((f2) => ({ + ...f2, + schemaId: table.schema.id + })); + props.superstate.spaceManager.createTable(spaceState.path, table.schema).then( + (f2) => props.superstate.spaceManager.saveTable( + spaceState.path, + table + ) + ); + } + }) + ); + } + }); + menuOptions.push({ + name: i18n_default.buttons.renameView, + icon: "ui//edit", + onClick: (e6) => { + props.superstate.ui.openModal( + i18n_default.labels.renameView, + (_props) => /* @__PURE__ */ import_react44.default.createElement(InputModal, { + value: _schema.name, + saveLabel: i18n_default.labels.renameView, + hide: _props.hide, + saveValue: (value) => { + props.superstate.spaceManager.saveTableSchema( + pathState.path, + _schema.id, + () => ({ + ..._schema, + name: value + }) + ); + } + }) + ); + } + }); + menuOptions.push({ + name: i18n_default.buttons.delete, + icon: "ui//trash", + onClick: (e6) => { + props.superstate.spaceManager.deleteTable(pathState.path, _schema.id); + } + }); props.superstate.ui.openMenu( e5.target.getBoundingClientRect(), - { - ui: props.superstate.ui, - multi: false, - editable: false, - searchable: false, - saveOptions: selectedSource, - value: [], - showAll: true, - options - } + defaultMenu(props.superstate.ui, menuOptions) ); }; - const saveField = () => { - if (fieldName.length == 0) { - props.superstate.ui.notify(i18n_default.notice.noPropertyName); - return; + return /* @__PURE__ */ import_react44.default.createElement("div", { + className: "mk-space-editor" + }, /* @__PURE__ */ import_react44.default.createElement("div", { + className: "mk-space-editor-header" + }, /* @__PURE__ */ import_react44.default.createElement("div", { + className: "mk-space-editor-header-title" + }, /* @__PURE__ */ import_react44.default.createElement("div", { + className: "mk-space-editor-title" + }, i18n_default.subViews.spaceLists), /* @__PURE__ */ import_react44.default.createElement("div", { + className: "mk-space-editor-description" + }, i18n_default.descriptions.spaceLists)), /* @__PURE__ */ import_react44.default.createElement("span", null), /* @__PURE__ */ import_react44.default.createElement("button", { + className: "mk-button-new", + "aria-label": i18n_default.labels.newTable, + onClick: (e5) => newTable(e5), + dangerouslySetInnerHTML: { + __html: props.superstate.ui.getSticker("ui//plus") } - props.saveField(fieldSource, { - name: fieldName, - type: fieldType, - value: fieldValue, - schemaId: props.schemaId - }); - props.hide(); - }; - const onKeyDown = (e5) => { - if (e5.key == "Enter") { - saveField(); + })), /* @__PURE__ */ import_react44.default.createElement("div", { + className: "mk-space-editor-contents" + }, tables.map((f2, i4) => /* @__PURE__ */ import_react44.default.createElement(ContextTableCrumb, { + key: i4, + superstate: props.superstate, + schema: f2, + onClick: (e5) => { + props.hide(); + props.superstate.ui.openPath( + contextPathForSpace(spaceState, f2.id), + e5.metaKey + ); + }, + onContextMenu: (e5) => { + viewContextMenu(e5, f2); } - }; - (0, import_react32.useEffect)(() => { - setTimeout(() => { - input.current?.focus(); - }, 50); - }, []); - const input = (0, import_react32.useRef)(null); - return /* @__PURE__ */ import_react32.default.createElement("div", { - className: "mk-menu-container" - }, /* @__PURE__ */ import_react32.default.createElement("div", { - className: "mk-menu-suggestions" - }, /* @__PURE__ */ import_react32.default.createElement("div", { - className: "mk-menu-input" - }, /* @__PURE__ */ import_react32.default.createElement("input", { - type: "text", - ref: input, - placeholder: "Name", - onKeyDown, - onChange: (e5) => setFieldName(e5.target.value), - onMouseDown: (e5) => e5.stopPropagation(), - value: fieldName - })), /* @__PURE__ */ import_react32.default.createElement("div", { - className: "mk-menu-separator" - }), options.length > 1 && /* @__PURE__ */ import_react32.default.createElement("div", { - className: "mk-menu-option", - onClick: (e5) => selectSource(e5) - }, /* @__PURE__ */ import_react32.default.createElement("div", { - className: "mk-menu-options-inner" - }, i18n_default.labels.propertyValueSpace), /* @__PURE__ */ import_react32.default.createElement("span", null, fieldSource == "$fm" ? "None" : fieldSource == "" ? props.contextPath : fieldSource)), /* @__PURE__ */ import_react32.default.createElement("div", { - className: "mk-menu-option", - onClick: (e5) => selectType(e5) - }, /* @__PURE__ */ import_react32.default.createElement("div", { - className: "mk-menu-options-inner" - }, i18n_default.labels.propertyValueProperty), /* @__PURE__ */ import_react32.default.createElement("span", null, type.label)), type.multi ? /* @__PURE__ */ import_react32.default.createElement("div", { - className: "mk-menu-option" - }, /* @__PURE__ */ import_react32.default.createElement("span", null, i18n_default.labels.multiple), /* @__PURE__ */ import_react32.default.createElement("input", { - type: "checkbox", - checked: fieldType == type.multiType, - onChange: () => toggleMulti() - })) : /* @__PURE__ */ import_react32.default.createElement(import_react32.default.Fragment, null), /* @__PURE__ */ import_react32.default.createElement("div", { - className: "mk-menu-separator" - }), fieldSource != "$fm" || props.isSpace ? /* @__PURE__ */ import_react32.default.createElement(PropertyValueComponent, { + })))); +}; + +// src/core/react/components/SpaceEditor/SpaceEditor.tsx +var SpaceEditor = (props) => { + const [tab, setTab] = (0, import_react45.useState)( + props.space?.type == "tag" ? Math.max(1, props.tab) : props.tab + ); + return /* @__PURE__ */ import_react45.default.createElement("div", { + className: "mk-space-editor-container" + }, /* @__PURE__ */ import_react45.default.createElement("div", { + className: "mk-tab-group" + }, props.space?.type != "tag" && /* @__PURE__ */ import_react45.default.createElement("div", { + "aria-label": i18n_default.subViews.spaceItems, + onClick: () => setTab(0), + className: `mk-tab ${tab == 0 ? "mk-active" : ""}`, + dangerouslySetInnerHTML: { + __html: props.superstate.ui.getSticker("ui//file-stack") + } + }), /* @__PURE__ */ import_react45.default.createElement("div", { + "aria-label": i18n_default.subViews.spaceContext, + onClick: () => setTab(1), + className: `mk-tab ${tab == 1 ? "mk-active" : ""}`, + dangerouslySetInnerHTML: { + __html: props.superstate.ui.getSticker("ui//list") + } + }), /* @__PURE__ */ import_react45.default.createElement("div", { + "aria-label": i18n_default.subViews.spaceLists, + onClick: () => setTab(2), + className: `mk-tab ${tab == 2 ? "mk-active" : ""}`, + dangerouslySetInnerHTML: { + __html: props.superstate.ui.getSticker("ui//layout-list") + } + }), /* @__PURE__ */ import_react45.default.createElement("div", { + "aria-label": i18n_default.subViews.spaceActions, + onClick: () => setTab(3), + className: `mk-tab ${tab == 3 ? "mk-active" : ""}`, + dangerouslySetInnerHTML: { + __html: props.superstate.ui.getSticker("ui//mouse-pointer-click") + } + }), /* @__PURE__ */ import_react45.default.createElement("div", { + "aria-label": i18n_default.subViews.spaceTemplates, + onClick: () => setTab(4), + className: `mk-tab ${tab == 4 ? "mk-active" : ""}`, + dangerouslySetInnerHTML: { + __html: props.superstate.ui.getSticker("ui//clipboard-pen") + } + })), /* @__PURE__ */ import_react45.default.createElement(PathProvider, { superstate: props.superstate, - table: fieldSource, - fields: props.fields, - fieldType, - value: fieldValue, - contextPath: props.contextPath, - saveValue: selectedValue - }) : /* @__PURE__ */ import_react32.default.createElement(import_react32.default.Fragment, null), /* @__PURE__ */ import_react32.default.createElement("div", { - className: "mk-menu-separator" - }), /* @__PURE__ */ import_react32.default.createElement("div", { - className: "mk-menu-option", - onClick: (e5) => saveField() - }, /* @__PURE__ */ import_react32.default.createElement("span", null, i18n_default.buttons.saveProperty)), /* @__PURE__ */ import_react32.default.createElement("div", { - className: "mk-menu-option", - onClick: (e5) => props.hide() - }, /* @__PURE__ */ import_react32.default.createElement("span", null, i18n_default.buttons.cancel)))); + path: props.space.path, + readMode: false + }, /* @__PURE__ */ import_react45.default.createElement(SpaceProvider, { + superstate: props.superstate + }, tab == 0 ? /* @__PURE__ */ import_react45.default.createElement(SpaceItems, { + superstate: props.superstate, + space: props.space + }) : tab == 1 ? /* @__PURE__ */ import_react45.default.createElement(FramesMDBProvider, { + superstate: props.superstate + }, /* @__PURE__ */ import_react45.default.createElement(ContextEditorProvider, { + superstate: props.superstate + }, /* @__PURE__ */ import_react45.default.createElement(SpacePropertyEditorContext, { + superstate: props.superstate + }))) : tab == 2 ? /* @__PURE__ */ import_react45.default.createElement(TableList, { + superstate: props.superstate, + hide: props.close + }) : tab == 3 ? /* @__PURE__ */ import_react45.default.createElement(ActionsList, { + superstate: props.superstate, + close: props.close + }) : tab == 4 ? /* @__PURE__ */ import_react45.default.createElement(TemplatesList, { + superstate: props.superstate, + close: props.close + }) : /* @__PURE__ */ import_react45.default.createElement(import_react45.default.Fragment, null)))); }; -var showNewPropertyMenu = (superstate, rect, spaces2, fields, saveField, schemaId, contextPath, fileMetadata, isSpace) => { - return superstate.ui.openCustomMenu( - rect, - /* @__PURE__ */ import_react32.default.createElement(NewPropertyMenuComponent, { +var SpaceEditor_default = SpaceEditor; + +// src/core/react/components/UI/Modals/ContextEditor.tsx +var openSpaceEditorModal = (superstate, space2, tab) => { + superstate.ui.openModal( + space2.name, + (props) => /* @__PURE__ */ import_react46.default.createElement(SpaceEditor_default, { superstate, - spaces: spaces2, - schemaId, - contextPath, - fields, - saveField, - fileMetadata, - isSpace + space: space2, + tab, + close: () => { + props.hide(); + } }), - {}, - "bottom" + "mk-space-editor-modal" + ); +}; +var SpacePropertyEditorContext = (props) => { + const { spaceState: spaceCache } = (0, import_react46.useContext)(SpaceContext); + const { + predicate, + savePredicate, + tableData, + sortedColumns, + hideColumn, + delColumn, + saveColumn + } = (0, import_react46.useContext)(ContextEditorContext); + const columns = (0, import_react46.useMemo)(() => { + return (tableData?.cols ?? []).sort( + (a4, b2) => (predicate?.colsOrder ?? []).findIndex((x2) => x2 == a4.name) - (predicate?.colsOrder ?? []).findIndex((x2) => x2 == b2.name) + ); + }, [tableData, predicate]); + const saveContexts = (contexts) => { + saveSpaceMetadataValue( + props.superstate, + spaceCache.path, + "contexts", + contexts + ); + }; + return /* @__PURE__ */ import_react46.default.createElement(SpacePropertyEditor, { + superstate: props.superstate, + colsOrder: predicate?.colsOrder ?? [], + setColumnOrder: (cols) => savePredicate({ colsOrder: cols }), + colsHidden: predicate?.colsHidden ?? [], + columns, + contexts: spaceCache?.contexts ?? [], + saveContexts, + hideColumn, + delColumn, + saveColumn + }); +}; + +// src/core/react/components/UI/Menus/navigator/spaceContextMenu.tsx +var showSpaceContextMenu = (superstate, path2, e5, activePath, parentSpace, onClose) => { + const space2 = superstate.spacesIndex.get(path2.path); + if (!space2) + return; + const menuOptions = []; + menuOptions.push({ + name: "New", + type: 6 /* Submenu */, + onSubmenu: (offset2) => { + return showSpaceAddMenu(superstate, offset2, space2); + }, + icon: "ui//plus" + }); + if (space2.type == "folder") { + menuOptions.push({ + name: i18n_default.buttons.addIntoSpace, + icon: "ui//pin", + onClick: (e6) => { + const offset2 = e6.target.getBoundingClientRect(); + showLinkMenu(offset2, superstate, (link) => { + pinPathToSpaceAtIndex(superstate, space2, link); + }); + e6.stopPropagation(); + } + }); + } + menuOptions.push(menuSeparator); + if (space2.type != "default") { + menuOptions.push({ + name: i18n_default.labels.renameSection, + icon: "ui//edit", + onClick: (e6) => { + openSpaceEditorModal(superstate, space2, 0); + } + }); + } + if (onClose) { + menuOptions.push({ + name: i18n_default.menu.closeSpace, + icon: "ui//close", + onClick: (e6) => { + onClose(); + } + }); + } + menuOptions.push(menuSeparator); + if (space2.type == "folder") { + menuOptions.push({ + name: i18n_default.buttons.addToSpace, + icon: "ui//pin", + onClick: (e6) => { + const offset2 = e6.target.getBoundingClientRect(); + showSpacesMenu( + offset2, + superstate, + (link) => { + const spaceCache = superstate.spacesIndex.get(link); + if (spaceCache) + addPathToSpaceAtIndex(superstate, spaceCache, space2.path, -1); + }, + true + ); + } + }); + menuOptions.push(menuSeparator); + } + const parentSpaceCache = superstate.spacesIndex.get(parentSpace); + if (parentSpaceCache && (parentSpaceCache.type == "folder" || parentSpaceCache.type == "vault")) { + menuOptions.push({ + name: "Save as Template", + icon: "ui//clipboard-add", + onClick: (e6) => { + saveSpaceTemplate(superstate, space2.path, parentSpace); + } + }); + if (parentSpace != path2.parent) { + const spaceCache = superstate.spacesIndex.get(parentSpace); + if (spaceCache) { + menuOptions.push({ + name: i18n_default.menu.removeFromSpace, + icon: "ui//pin-off", + onClick: (e6) => { + removePathsFromSpace(superstate, spaceCache.path, [space2.path]); + } + }); + } + } + } + menuOptions.push(menuSeparator); + if (superstate.settings.spacesStickers) { + menuOptions.push({ + name: i18n_default.menu.changeColor, + icon: "ui//palette", + type: 6 /* Submenu */, + onSubmenu: (offset2) => { + return showColorPickerMenu( + superstate, + offset2, + "", + (value) => savePathColor(superstate, space2.path, value) + ); + } + }); + menuOptions.push({ + name: i18n_default.buttons.changeIcon, + icon: "ui//sticker", + onClick: (e6) => { + superstate.ui.openPalette((_props) => /* @__PURE__ */ import_react47.default.createElement(StickerModal_default, { + ui: superstate.ui, + hide: _props.hide, + selectedSticker: (emoji) => savePathSticker(superstate, space2.path, emoji) + })); + } + }); + menuOptions.push({ + name: i18n_default.buttons.removeIcon, + icon: "ui//file-minus", + onClick: (e6) => { + removePathIcon(superstate, space2.path); + } + }); + } + if (space2.metadata?.sort) { + menuOptions.push(menuSeparator); + menuOptions.push({ + name: i18n_default.menu.sortBy, + icon: "ui//sort-desc", + type: 6 /* Submenu */, + onSubmenu: (offset2) => { + const sortOptions = []; + sortOptions.push({ + name: i18n_default.menu.groupSpaces, + icon: "ui//arrow-up-down", + value: space2.metadata.sort.group == true, + type: 3 /* Radio */, + onClick: (e6) => { + updateSpaceSort(superstate, space2.path, { + field: space2.metadata.sort.field, + asc: space2.metadata.sort.asc, + group: !space2.metadata.sort.group + }); + } + }); + sortOptions.push(menuSeparator); + const rankSortOption = { + field: "rank", + asc: true, + group: space2.metadata.sort.group + }; + sortOptions.push({ + name: i18n_default.menu.customSort, + icon: "ui//arrow-up-down", + value: space2.metadata.sort.field == rankSortOption.field && space2.metadata.sort.asc == rankSortOption.asc, + type: 3 /* Radio */, + onClick: (e6) => { + updateSpaceSort(superstate, space2.path, rankSortOption); + } + }); + sortOptions.push(menuSeparator); + const nameSortOption = { + field: "name", + asc: true, + group: space2.metadata.sort.group + }; + sortOptions.push({ + name: i18n_default.menu.fileNameSortAlphaAsc, + icon: "ui//arrow-up-down", + value: space2.metadata.sort.field == nameSortOption.field && space2.metadata.sort.asc == nameSortOption.asc, + type: 3 /* Radio */, + onClick: (e6) => { + updateSpaceSort(superstate, space2.path, nameSortOption); + } + }); + const nameSortOptionDesc = { + field: "name", + asc: false, + group: space2.metadata.sort.group + }; + sortOptions.push({ + name: i18n_default.menu.fileNameSortAlphaDesc, + icon: "ui//arrow-up-down", + value: space2.metadata.sort.field == nameSortOptionDesc.field && space2.metadata.sort.asc == nameSortOptionDesc.asc, + type: 3 /* Radio */, + onClick: (e6) => { + updateSpaceSort(superstate, space2.path, nameSortOptionDesc); + } + }); + sortOptions.push(menuSeparator); + const numberSortOption = { + field: "number", + asc: true, + group: space2.metadata.sort.group + }; + sortOptions.push({ + name: i18n_default.menu.fileNameSortNumericalAsc, + icon: "ui//arrow-up-down", + value: space2.metadata.sort.field == numberSortOption.field && space2.metadata.sort.asc == numberSortOption.asc, + type: 3 /* Radio */, + onClick: (e6) => { + updateSpaceSort(superstate, space2.path, numberSortOption); + } + }); + const numberSortOptionDesc = { + field: "number", + asc: false, + group: space2.metadata.sort.group + }; + sortOptions.push({ + name: i18n_default.menu.fileNameSortNumericalDesc, + icon: "ui//arrow-up-down", + value: space2.metadata.sort.field == numberSortOptionDesc.field && space2.metadata.sort.asc == numberSortOptionDesc.asc, + type: 3 /* Radio */, + onClick: (e6) => { + updateSpaceSort(superstate, space2.path, numberSortOptionDesc); + } + }); + sortOptions.push(menuSeparator); + const createdTimeSortOption = { + field: "ctime", + asc: false, + group: space2.metadata.sort.group + }; + sortOptions.push({ + name: i18n_default.menu.createdTimeSortAsc, + icon: "ui//arrow-up-down", + value: space2.metadata.sort.field == createdTimeSortOption.field && space2.metadata.sort.asc == createdTimeSortOption.asc, + type: 3 /* Radio */, + onClick: (e6) => { + updateSpaceSort(superstate, space2.path, createdTimeSortOption); + } + }); + const createdTimeSortOptionDesc = { + field: "ctime", + asc: true, + group: space2.metadata.sort.group + }; + sortOptions.push({ + name: i18n_default.menu.createdTimeSortDesc, + icon: "ui//arrow-up-down", + value: space2.metadata.sort.field == createdTimeSortOptionDesc.field && space2.metadata.sort.asc == createdTimeSortOptionDesc.asc, + type: 3 /* Radio */, + onClick: (e6) => { + updateSpaceSort(superstate, space2.path, createdTimeSortOptionDesc); + } + }); + sortOptions.push(menuSeparator); + const sizeSortOption = { + field: "size", + asc: false, + group: space2.metadata.sort.group + }; + sortOptions.push({ + name: i18n_default.menu.sizeSortAsc, + icon: "ui//arrow-up-down", + value: space2.metadata.sort.field == sizeSortOption.field && space2.metadata.sort.asc == sizeSortOption.asc, + type: 3 /* Radio */, + onClick: (e6) => { + updateSpaceSort(superstate, space2.path, sizeSortOption); + } + }); + const sizeSortOptionDesc = { + field: "size", + asc: true, + group: space2.metadata.sort.group + }; + sortOptions.push({ + name: i18n_default.menu.sizeSortDesc, + icon: "ui//arrow-up-down", + value: space2.metadata.sort.field == sizeSortOptionDesc.field && space2.metadata.sort.asc == sizeSortOptionDesc.asc, + type: 3 /* Radio */, + onClick: (e6) => { + updateSpaceSort(superstate, space2.path, sizeSortOptionDesc); + } + }); + return superstate.ui.openMenu( + offset2, + defaultMenu(superstate.ui, sortOptions) + ); + } + }); + } + if (space2.type != "default") { + menuOptions.push(menuSeparator); + menuOptions.push({ + name: i18n_default.menu.rename, + icon: "ui//edit", + onClick: (e6) => { + superstate.ui.openModal( + i18n_default.labels.rename, + (_props) => /* @__PURE__ */ import_react47.default.createElement(InputModal, { + saveLabel: i18n_default.buttons.rename, + value: space2.type == "tag" ? stringFromTag(space2.name) : space2.name, + hide: _props.hide, + saveValue: (v2) => renamePathByName(superstate, space2.path, v2) + }) + ); + } + }); + } + menuOptions.push({ + name: i18n_default.menu.duplicate, + icon: "ui//documents", + onClick: (e6) => { + superstate.spaceManager.copyPath(path2.path, `${path2.parent}`); + } + }); + if (space2.type == "folder") { + menuOptions.push({ + name: i18n_default.menu.moveFile, + icon: "ui//paper-plane", + onClick: (e6) => { + const offset2 = e6.target.getBoundingClientRect(); + showSpacesMenu(offset2, superstate, (link) => { + superstate.spaceManager.renameSpace( + space2.path, + movePath(space2.path, link) + ); + }); + } + }); + } + menuOptions.push(menuSeparator); + if (!isTouchScreen(superstate.ui)) { + menuOptions.push({ + name: i18n_default.menu.revealInDefault, + icon: "ui//arrow-up-right", + onClick: (e6) => { + superstate.ui.openPath( + space2.type == "folder" ? space2.path : `${superstate.settings.spacesFolder}/${space2.name}`, + "system" + ); + } + }); + } + menuOptions.push(menuSeparator); + if (space2.type == "folder") { + menuOptions.push({ + name: i18n_default.menu.hide, + icon: "ui//eye-off", + onClick: (e6) => { + hidePath(superstate, space2.path); + } + }); + } + if (space2.type == "folder" || space2.type == "tag") + menuOptions.push({ + name: i18n_default.menu.delete, + icon: "ui//trash", + onClick: (e6) => { + superstate.ui.openModal( + i18n_default.labels.deleteSpace, + (_props) => /* @__PURE__ */ import_react47.default.createElement(ConfirmationModal, { + hide: _props.hide, + confirmAction: () => removeSpace(superstate, space2.path), + confirmLabel: i18n_default.buttons.delete, + message: i18n_default.descriptions.deleteSpace + }) + ); + } + }); + superstate.ui.openMenu( + e5.target.getBoundingClientRect(), + defaultMenu(superstate.ui, menuOptions) ); + return false; }; // src/core/react/components/SpaceView/Contexts/DataTypeView/DataPropertyView.tsx -var import_react78 = __toESM(require_react()); +var import_react72 = __toESM(require_react()); // src/core/react/components/UI/Toggles/CollapseToggleSmall.tsx -var import_react33 = __toESM(require_react()); +var import_react48 = __toESM(require_react()); var CollapseToggleSmall = (props) => { - return /* @__PURE__ */ import_react33.default.createElement("button", { + return /* @__PURE__ */ import_react48.default.createElement("button", { className: `mk-collapse mk-inline-button mk-icon-xsmall ${props.collapsed ? "mk-collapsed" : ""}`, onClick: (e5) => { props.onToggle(!props.collapsed, e5); @@ -104311,46 +102402,13 @@ var CollapseToggleSmall = (props) => { }); }; -// src/core/react/context/WindowContext.tsx -var import_react34 = __toESM(require_react()); -var import_react_dom2 = __toESM(require_react_dom()); -var WindowContext = import_react34.default.createContext({ - dragNode: null, - setDragNode: () => null, - dragActive: false -}); -var WindowProvider = (props) => { - const [dragNode, setDragNode] = import_react34.default.useState(null); - useDndMonitor({ - onDragCancel: () => { - setDragNode(null); - }, - onDragEnd: () => { - setDragNode(null); - } - }); - return /* @__PURE__ */ import_react34.default.createElement(WindowContext.Provider, { - value: { - dragNode, - setDragNode, - dragActive: props.dragActive - } - }, props.children, dragNode && (0, import_react_dom2.createPortal)( - /* @__PURE__ */ import_react34.default.createElement(DragOverlay, { - dropAnimation: null, - zIndex: 1600 - }, dragNode), - document.body - )); -}; - // src/core/react/components/SpaceView/Contexts/ContextBuilder/ContextListEditSelector.tsx -var import_react36 = __toESM(require_react()); +var import_react50 = __toESM(require_react()); // src/core/react/components/SpaceView/Frames/Setters/ToggleSetter.tsx -var import_react35 = __toESM(require_react()); +var import_react49 = __toESM(require_react()); var ToggleSetter = (props) => { - return /* @__PURE__ */ import_react35.default.createElement("div", { + return /* @__PURE__ */ import_react49.default.createElement("div", { "aria-label": props.name, className: `mk-editor-frame-node-button ${props.value == props.onValue ? "mk-active" : ""}`, onClick: (e5) => props.value == props.onValue ? props.setValue(props.defaultValue) : props.setValue(props.onValue), @@ -104362,17 +102420,17 @@ var ToggleSetter = (props) => { // src/core/react/components/SpaceView/Contexts/ContextBuilder/ContextListEditSelector.tsx var ContextListEditSelector = (props) => { - const { pathState } = (0, import_react36.useContext)(PathContext); - const { spaceInfo } = (0, import_react36.useContext)(SpaceContext); - const { predicate, savePredicate, sortedColumns } = (0, import_react36.useContext)(ContextEditorContext); + const { pathState } = (0, import_react50.useContext)(PathContext); + const { spaceInfo } = (0, import_react50.useContext)(SpaceContext); + const { predicate, savePredicate, sortedColumns } = (0, import_react50.useContext)(ContextEditorContext); const selectFrame = (frameRef, type) => { savePredicate({ view: "frame", [type]: frameRef }); }; - const { frameSchemas, saveSchema } = (0, import_react36.useContext)(FramesMDBContext); - const listItems = (0, import_react36.useMemo)(() => { + const { frameSchemas, saveSchema } = (0, import_react50.useContext)(FramesMDBContext); + const listItems = (0, import_react50.useMemo)(() => { const items = []; if (frameSchemas) { items.push( @@ -104451,20 +102509,20 @@ var ContextListEditSelector = (props) => { } props.setEditSection(type); }; - const [loaded, setLoaded] = (0, import_react36.useState)(false); - const [isPending, startTransition] = (0, import_react36.useTransition)(); - (0, import_react36.useEffect)(() => { + const [loaded, setLoaded] = (0, import_react50.useState)(false); + const [isPending, startTransition] = (0, import_react50.useTransition)(); + (0, import_react50.useEffect)(() => { startTransition(() => { setLoaded(true); }); }, []); - return predicate ? /* @__PURE__ */ import_react36.default.createElement("div", { + return predicate ? /* @__PURE__ */ import_react50.default.createElement("div", { className: "mk-editor-context-selector" - }, /* @__PURE__ */ import_react36.default.createElement("div", { + }, /* @__PURE__ */ import_react50.default.createElement("div", { className: "mk-editor-context-groups" - }, /* @__PURE__ */ import_react36.default.createElement("div", { + }, /* @__PURE__ */ import_react50.default.createElement("div", { className: "mk-editor-context-group" - }, /* @__PURE__ */ import_react36.default.createElement(ToggleSetter, { + }, /* @__PURE__ */ import_react50.default.createElement(ToggleSetter, { superstate: props.superstate, name: i18n_default.editor.rows, icon: "ui//rows", @@ -104478,7 +102536,7 @@ var ContextListEditSelector = (props) => { listGroup: "spaces://$kit/#*listGroup" }); } - }), /* @__PURE__ */ import_react36.default.createElement(ToggleSetter, { + }), /* @__PURE__ */ import_react50.default.createElement(ToggleSetter, { superstate: props.superstate, name: i18n_default.editor.columns, icon: "ui//columns", @@ -104492,7 +102550,7 @@ var ContextListEditSelector = (props) => { listGroup: "spaces://$kit/#*columnGroup" }); } - }), /* @__PURE__ */ import_react36.default.createElement(ToggleSetter, { + }), /* @__PURE__ */ import_react50.default.createElement(ToggleSetter, { superstate: props.superstate, name: i18n_default.editor.catalog, icon: "ui//gallery-horizontal-end", @@ -104506,7 +102564,7 @@ var ContextListEditSelector = (props) => { listGroup: "spaces://$kit/#*rowGroup" }); } - }), /* @__PURE__ */ import_react36.default.createElement(ToggleSetter, { + }), /* @__PURE__ */ import_react50.default.createElement(ToggleSetter, { superstate: props.superstate, name: i18n_default.editor.grid, icon: "ui//layout-grid", @@ -104520,7 +102578,7 @@ var ContextListEditSelector = (props) => { listGroup: "spaces://$kit/#*gridGroup" }); } - }), /* @__PURE__ */ import_react36.default.createElement("button", { + }), /* @__PURE__ */ import_react50.default.createElement("button", { onClick: (e5) => { editItem("listGroup"); }, @@ -104530,22 +102588,22 @@ var ContextListEditSelector = (props) => { __html: props.superstate.ui.getSticker("ui//brush") }, style: { height: "20px", padding: "8px" } - })), /* @__PURE__ */ import_react36.default.createElement("div", { + })), /* @__PURE__ */ import_react50.default.createElement("div", { className: "mk-editor-context-group" - }, /* @__PURE__ */ import_react36.default.createElement("div", { + }, /* @__PURE__ */ import_react50.default.createElement("div", { className: "mk-editor-context-group-select", onClick: (e5) => { selectFrameMenu(e5, "listItem"); e5.stopPropagation(); } - }, listItems.find((f2) => f2.value == predicate.listItem)?.name ?? i18n_default.labels.select, /* @__PURE__ */ import_react36.default.createElement(CollapseToggleSmall, { + }, listItems.find((f2) => f2.value == predicate.listItem)?.name ?? i18n_default.labels.select, /* @__PURE__ */ import_react50.default.createElement(CollapseToggleSmall, { superstate: props.superstate, collapsed: false, onToggle: (c3, e5) => { selectFrameMenu(e5, "listItem"); e5.stopPropagation(); } - })), /* @__PURE__ */ import_react36.default.createElement("button", { + })), /* @__PURE__ */ import_react50.default.createElement("button", { onClick: (e5) => { editItem("listItem"); }, @@ -104555,7 +102613,7 @@ var ContextListEditSelector = (props) => { dangerouslySetInnerHTML: { __html: props.superstate.ui.getSticker("ui//brush") } - }), /* @__PURE__ */ import_react36.default.createElement("button", { + }), /* @__PURE__ */ import_react50.default.createElement("button", { onClick: (e5) => { addListItemToKit(); }, @@ -104564,23 +102622,23 @@ var ContextListEditSelector = (props) => { __html: props.superstate.ui.getSticker("ui//package-plus") }, style: { height: "20px", padding: "8px" } - })), /* @__PURE__ */ import_react36.default.createElement("span", null), /* @__PURE__ */ import_react36.default.createElement("div", { + })), /* @__PURE__ */ import_react50.default.createElement("span", null), /* @__PURE__ */ import_react50.default.createElement("div", { className: "mk-editor-frame-node-button-primary", onClick: (e5) => { props.setEditMode(0 /* Read */); e5.stopPropagation(); } - }, i18n_default.labels.done)), props.editSection == "listItem" && /* @__PURE__ */ import_react36.default.createElement("div", { + }, i18n_default.labels.done)), props.editSection == "listItem" && /* @__PURE__ */ import_react50.default.createElement("div", { className: "mk-editor-context-properties" - }, /* @__PURE__ */ import_react36.default.createElement("div", { + }, /* @__PURE__ */ import_react50.default.createElement("div", { style: { display: "flex" } - }, i18n_default.labels.properties, /* @__PURE__ */ import_react36.default.createElement("div", { + }, i18n_default.labels.properties, /* @__PURE__ */ import_react50.default.createElement("div", { "aria-label": i18n_default.hintText.dragDropProperties, className: `mk-icon-xsmall`, dangerouslySetInnerHTML: { __html: props.superstate.ui.getSticker("ui//help-circle") } - })), /* @__PURE__ */ import_react36.default.createElement("div", null, sortedColumns.map((f2, i4) => /* @__PURE__ */ import_react36.default.createElement(PropertyField, { + })), /* @__PURE__ */ import_react50.default.createElement("div", null, sortedColumns.map((f2, i4) => /* @__PURE__ */ import_react50.default.createElement(PropertyField, { contexts: [pathState.path], path: pathState.path, key: i4, @@ -104590,7 +102648,7 @@ var ContextListEditSelector = (props) => { }))))) : null; }; var PropertyField = (props) => { - const { uid } = (0, import_react36.useContext)(PathContext); + const { uid } = (0, import_react50.useContext)(PathContext); const primaryContext = props.contexts?.[0]; const id3 = `${uid}_props_${primaryContext ?? ""}${props.property.name}`; const { @@ -104609,54 +102667,54 @@ var PropertyField = (props) => { type: "property" } }); - const { setDragNode } = (0, import_react36.useContext)(WindowContext); + const { setDragNode } = (0, import_react50.useContext)(WindowContext); useDndMonitor({ onDragStart: (e5) => { if (e5.active.data.current.id == id3) setDragNode( - /* @__PURE__ */ import_react36.default.createElement("div", { + /* @__PURE__ */ import_react50.default.createElement("div", { className: "mk-path-context-field", onClick: (e6) => props.onClick ? props.onClick(e6) : null - }, /* @__PURE__ */ import_react36.default.createElement("div", { + }, /* @__PURE__ */ import_react50.default.createElement("div", { className: "mk-path-context-field-icon", dangerouslySetInnerHTML: { __html: props.superstate.ui.getSticker( stickerForField(props.property) ) } - }), /* @__PURE__ */ import_react36.default.createElement("div", { + }), /* @__PURE__ */ import_react50.default.createElement("div", { className: "mk-path-context-field-key" }, nameForField(props.property, props.superstate))) ); } }); - return /* @__PURE__ */ import_react36.default.createElement("div", { + return /* @__PURE__ */ import_react50.default.createElement("div", { ref: setDraggableNodeRef, className: "mk-path-context-field", onClick: (e5) => props.onClick ? props.onClick(e5) : null, ...attributes, ...listeners - }, /* @__PURE__ */ import_react36.default.createElement("div", { + }, /* @__PURE__ */ import_react50.default.createElement("div", { className: "mk-path-context-field-icon", dangerouslySetInnerHTML: { __html: props.superstate.ui.getSticker( stickerForField(props.property) ) } - }), props.contexts?.length > 0 && /* @__PURE__ */ import_react36.default.createElement("div", { + }), props.contexts?.length > 0 && /* @__PURE__ */ import_react50.default.createElement("div", { className: "mk-path-context-field-space", dangerouslySetInnerHTML: { __html: props.contexts.length == 1 ? props.superstate.ui.getSticker( props.superstate.pathsIndex.get(props.contexts[0])?.label?.sticker ) : props.contexts.length } - }), /* @__PURE__ */ import_react36.default.createElement("div", { + }), /* @__PURE__ */ import_react50.default.createElement("div", { className: "mk-path-context-field-key" }, nameForField(props.property, props.superstate))); }; // node_modules/@tanstack/react-table/build/lib/index.mjs -var React34 = __toESM(require_react(), 1); +var React47 = __toESM(require_react(), 1); // node_modules/@tanstack/table-core/build/lib/index.mjs function functionalUpdate(updater, input) { @@ -106804,16 +104862,16 @@ function isSubRowSelected(row2, selection2, table) { } var reSplitAlphaNumeric = /([0-9]+)/gm; var alphanumeric = (rowA, rowB, columnId) => { - return compareAlphanumeric(toString3(rowA.getValue(columnId)).toLowerCase(), toString3(rowB.getValue(columnId)).toLowerCase()); + return compareAlphanumeric(toString2(rowA.getValue(columnId)).toLowerCase(), toString2(rowB.getValue(columnId)).toLowerCase()); }; var alphanumericCaseSensitive = (rowA, rowB, columnId) => { - return compareAlphanumeric(toString3(rowA.getValue(columnId)), toString3(rowB.getValue(columnId))); + return compareAlphanumeric(toString2(rowA.getValue(columnId)), toString2(rowB.getValue(columnId))); }; var text = (rowA, rowB, columnId) => { - return compareBasic(toString3(rowA.getValue(columnId)).toLowerCase(), toString3(rowB.getValue(columnId)).toLowerCase()); + return compareBasic(toString2(rowA.getValue(columnId)).toLowerCase(), toString2(rowB.getValue(columnId)).toLowerCase()); }; var textCaseSensitive = (rowA, rowB, columnId) => { - return compareBasic(toString3(rowA.getValue(columnId)), toString3(rowB.getValue(columnId))); + return compareBasic(toString2(rowA.getValue(columnId)), toString2(rowB.getValue(columnId))); }; var datetime = (rowA, rowB, columnId) => { const a4 = rowA.getValue(columnId); @@ -106826,7 +104884,7 @@ var basic = (rowA, rowB, columnId) => { function compareBasic(a4, b2) { return a4 === b2 ? 0 : a4 > b2 ? 1 : -1; } -function toString3(a4) { +function toString2(a4) { if (typeof a4 === "number") { if (isNaN(a4) || a4 === Infinity || a4 === -Infinity) { return ""; @@ -107270,7954 +105328,10154 @@ function getExpandedRowModel() { if (!rowModel.rows.length || expanded !== true && !Object.keys(expanded != null ? expanded : {}).length) { return rowModel; } - if (!paginateExpandedRows) { - return rowModel; + if (!paginateExpandedRows) { + return rowModel; + } + return expandRows(rowModel); + }, getMemoOptions(table.options, "debugTable", "getExpandedRowModel")); +} +function expandRows(rowModel) { + const expandedRows = []; + const handleRow = (row2) => { + var _row$subRows; + expandedRows.push(row2); + if ((_row$subRows = row2.subRows) != null && _row$subRows.length && row2.getIsExpanded()) { + row2.subRows.forEach(handleRow); + } + }; + rowModel.rows.forEach(handleRow); + return { + rows: expandedRows, + flatRows: rowModel.flatRows, + rowsById: rowModel.rowsById + }; +} +function getGroupedRowModel() { + return (table) => memo2(() => [table.getState().grouping, table.getPreGroupedRowModel()], (grouping, rowModel) => { + if (!rowModel.rows.length || !grouping.length) { + return rowModel; + } + const existingGrouping = grouping.filter((columnId) => table.getColumn(columnId)); + const groupedFlatRows = []; + const groupedRowsById = {}; + const groupUpRecursively = function(rows, depth, parentId) { + if (depth === void 0) { + depth = 0; + } + if (depth >= existingGrouping.length) { + return rows.map((row2) => { + row2.depth = depth; + groupedFlatRows.push(row2); + groupedRowsById[row2.id] = row2; + if (row2.subRows) { + row2.subRows = groupUpRecursively(row2.subRows, depth + 1, row2.id); + } + return row2; + }); + } + const columnId = existingGrouping[depth]; + const rowGroupsMap = groupBy(rows, columnId); + const aggregatedGroupedRows = Array.from(rowGroupsMap.entries()).map((_ref, index2) => { + let [groupingValue, groupedRows2] = _ref; + let id3 = `${columnId}:${groupingValue}`; + id3 = parentId ? `${parentId}>${id3}` : id3; + const subRows = groupUpRecursively(groupedRows2, depth + 1, id3); + const leafRows = depth ? flattenBy(groupedRows2, (row3) => row3.subRows) : groupedRows2; + const row2 = createRow2(table, id3, leafRows[0].original, index2, depth, void 0, parentId); + Object.assign(row2, { + groupingColumnId: columnId, + groupingValue, + subRows, + leafRows, + getValue: (columnId2) => { + if (existingGrouping.includes(columnId2)) { + if (row2._valuesCache.hasOwnProperty(columnId2)) { + return row2._valuesCache[columnId2]; + } + if (groupedRows2[0]) { + var _groupedRows$0$getVal; + row2._valuesCache[columnId2] = (_groupedRows$0$getVal = groupedRows2[0].getValue(columnId2)) != null ? _groupedRows$0$getVal : void 0; + } + return row2._valuesCache[columnId2]; + } + if (row2._groupingValuesCache.hasOwnProperty(columnId2)) { + return row2._groupingValuesCache[columnId2]; + } + const column2 = table.getColumn(columnId2); + const aggregateFn = column2 == null ? void 0 : column2.getAggregationFn(); + if (aggregateFn) { + row2._groupingValuesCache[columnId2] = aggregateFn(columnId2, leafRows, groupedRows2); + return row2._groupingValuesCache[columnId2]; + } + } + }); + subRows.forEach((subRow) => { + groupedFlatRows.push(subRow); + groupedRowsById[subRow.id] = subRow; + }); + return row2; + }); + return aggregatedGroupedRows; + }; + const groupedRows = groupUpRecursively(rowModel.rows, 0); + groupedRows.forEach((subRow) => { + groupedFlatRows.push(subRow); + groupedRowsById[subRow.id] = subRow; + }); + return { + rows: groupedRows, + flatRows: groupedFlatRows, + rowsById: groupedRowsById + }; + }, getMemoOptions(table.options, "debugTable", "getGroupedRowModel", () => { + table._queue(() => { + table._autoResetExpanded(); + table._autoResetPageIndex(); + }); + })); +} +function groupBy(rows, columnId) { + const groupMap = /* @__PURE__ */ new Map(); + return rows.reduce((map4, row2) => { + const resKey = `${row2.getGroupingValue(columnId)}`; + const previous = map4.get(resKey); + if (!previous) { + map4.set(resKey, [row2]); + } else { + previous.push(row2); + } + return map4; + }, groupMap); +} +function getPaginationRowModel(opts) { + return (table) => memo2(() => [table.getState().pagination, table.getPrePaginationRowModel(), table.options.paginateExpandedRows ? void 0 : table.getState().expanded], (pagination, rowModel) => { + if (!rowModel.rows.length) { + return rowModel; + } + const { + pageSize, + pageIndex + } = pagination; + let { + rows, + flatRows, + rowsById + } = rowModel; + const pageStart = pageSize * pageIndex; + const pageEnd = pageStart + pageSize; + rows = rows.slice(pageStart, pageEnd); + let paginatedRowModel; + if (!table.options.paginateExpandedRows) { + paginatedRowModel = expandRows({ + rows, + flatRows, + rowsById + }); + } else { + paginatedRowModel = { + rows, + flatRows, + rowsById + }; + } + paginatedRowModel.flatRows = []; + const handleRow = (row2) => { + paginatedRowModel.flatRows.push(row2); + if (row2.subRows.length) { + row2.subRows.forEach(handleRow); + } + }; + paginatedRowModel.rows.forEach(handleRow); + return paginatedRowModel; + }, getMemoOptions(table.options, "debugTable", "getPaginationRowModel")); +} + +// node_modules/@tanstack/react-table/build/lib/index.mjs +function flexRender(Comp, props) { + return !Comp ? null : isReactComponent(Comp) ? /* @__PURE__ */ React47.createElement(Comp, props) : Comp; +} +function isReactComponent(component) { + return isClassComponent(component) || typeof component === "function" || isExoticComponent(component); +} +function isClassComponent(component) { + return typeof component === "function" && (() => { + const proto = Object.getPrototypeOf(component); + return proto.prototype && proto.prototype.isReactComponent; + })(); +} +function isExoticComponent(component) { + return typeof component === "object" && typeof component.$$typeof === "symbol" && ["react.memo", "react.forward_ref"].includes(component.$$typeof.description); +} +function useReactTable(options) { + const resolvedOptions = { + state: {}, + onStateChange: () => { + }, + renderFallbackValue: null, + ...options + }; + const [tableRef] = React47.useState(() => ({ + current: createTable(resolvedOptions) + })); + const [state, setState] = React47.useState(() => tableRef.current.initialState); + tableRef.current.setOptions((prev) => ({ + ...prev, + ...options, + state: { + ...state, + ...options.state + }, + onStateChange: (updater) => { + setState(updater); + options.onStateChange == null || options.onStateChange(updater); + } + })); + return tableRef.current; +} + +// src/core/react/components/SpaceView/Contexts/TableView/TableView.tsx +var import_react71 = __toESM(require_react()); +var import_react_dom5 = __toESM(require_react_dom()); + +// src/core/utils/ui/selection.ts +var selectNextIndex = (currIndex, array) => { + if (!currIndex && array.length > 0) + return array[0]; + const pos = array.indexOf(currIndex); + if (pos < array.length - 1) + return array[pos + 1]; + return currIndex; +}; +var selectPrevIndex = (currIndex, array) => { + const pos = array.indexOf(currIndex); + if (pos > 0) + return array[pos - 1]; + return array[0]; +}; +var selectRange = (currSel, newSel, array) => { + const lastIndex = array.findIndex((f2) => f2 == currSel); + const newIndex = array.findIndex((f2) => f2 == newSel); + if (lastIndex < newIndex) { + return array.filter((f2, i4) => i4 > lastIndex && i4 <= newIndex); + } + return array.filter((f2, i4) => i4 < lastIndex && i4 >= newIndex); +}; + +// src/core/react/components/SpaceView/Contexts/TableView/TableView.tsx +var import_lodash11 = __toESM(require_lodash()); + +// src/core/react/components/SpaceView/Contexts/DataTypeView/DataTypeView.tsx +var import_react70 = __toESM(require_react()); + +// src/core/react/components/SpaceView/Contexts/DataTypeView/BooleanCell.tsx +var import_react51 = __toESM(require_react()); +var BooleanCell = (props) => { + const { initialValue, saveValue } = props; + const [value, setValue] = import_react51.default.useState(initialValue == "true"); + const onChange = () => { + if (props.editMode == 0 /* EditModeReadOnly */) { + return; + } + setValue(!value); + saveValue(!value ? "true" : "false"); + }; + (0, import_react51.useEffect)(() => { + if (props.editMode == 4 /* EditModeActive */) { + setValue(!value); + saveValue(!value ? "true" : "false"); + props.setEditMode(null); + } + }, [props.editMode]); + import_react51.default.useEffect(() => { + setValue(initialValue == "true"); + }, [initialValue]); + if (props.editMode < 2 /* EditModeView */) { + return /* @__PURE__ */ import_react51.default.createElement("div", { + className: "mk-cell-boolean" + }, /* @__PURE__ */ import_react51.default.createElement("input", { + type: "checkbox", + checked: value, + onChange + })); + } + return /* @__PURE__ */ import_react51.default.createElement("div", { + className: "mk-cell-boolean" + }, /* @__PURE__ */ import_react51.default.createElement("input", { + type: "checkbox", + checked: value, + onChange + })); +}; + +// src/core/react/components/SpaceView/Contexts/DataTypeView/ColorCell.tsx +var import_react52 = __toESM(require_react()); +var ColorCell = (props) => { + const showMenu2 = (e5) => { + const handleChangeComplete = (color2) => { + props.saveValue(color2); + }; + const offset2 = e5.target.getBoundingClientRect(); + showColorPickerMenu( + props.superstate, + offset2, + props.initialValue, + handleChangeComplete + ); + }; + return /* @__PURE__ */ import_react52.default.createElement("div", null, /* @__PURE__ */ import_react52.default.createElement("div", { + className: "mk-setter-color", + onClick: (e5) => showMenu2(e5), + style: { + backgroundColor: props.initialValue, + width: 30, + height: 30 + } + })); +}; + +// src/core/react/components/SpaceView/Contexts/DataTypeView/ContextCell.tsx +var import_react54 = __toESM(require_react()); + +// src/core/react/components/SpaceView/Contexts/DataTypeView/OptionCell.tsx +var import_lodash10 = __toESM(require_lodash()); +var import_react53 = __toESM(require_react()); +var OptionCell = (props) => { + const parsedValue = (0, import_react53.useMemo)( + () => parseFieldValue( + props.propertyValue, + "option", + props.superstate, + props.source + ), + [props.propertyValue, props.source] + ); + const serializeValue = (newOptions, value2) => { + return JSON.stringify({ + ...value2, + options: newOptions.map((f2) => ({ + name: f2.name, + value: f2.value, + color: f2.color + })) + }); + }; + const parseOptions = (_options, values2, editMode, editable) => { + return [ + ...(_options ?? []).filter((f2) => f2.value).map((t5) => ({ + ...t5, + color: editable ? t5.color?.length > 0 ? t5.color : "var(--mk-color-none)" : void 0, + removeable: editable ? editMode >= 2 /* EditModeView */ : false + })) ?? [], + ...values2.map((f2) => { + return { + name: f2, + value: f2, + color: editable ? "var(--mk-color-none)" : void 0, + removeable: editable ? editMode >= 2 /* EditModeView */ : false + }; + }) + ].filter(onlyUniqueProp("value")).filter((f2) => f2.value.length > 0); + }; + const parseValues = (value2, multi) => { + return (multi ? parseMultiString(value2) ?? [] : [value2]).filter( + (f2) => f2 && f2.length > 0 + ); + }; + const [options, setOptions] = (0, import_react53.useState)( + parseOptions( + parsedValue.options ?? [], + parseValues(props.initialValue, props.multi), + props.editMode, + parsedValue.source ? false : true + ) + ); + const [value, setValue] = (0, import_react53.useState)( + parseValues(props.initialValue, props.multi) + ); + (0, import_react53.useEffect)(() => { + setValue(parseValues(props.initialValue, props.multi)); + }, [props.initialValue, props.multi]); + (0, import_react53.useEffect)(() => { + setOptions( + parseOptions( + parsedValue.options ?? [], + value, + props.editMode, + parsedValue.source ? false : true + ) + ); + }, [parsedValue, value, props.editMode]); + const removeValue = (v2) => { + if (props.multi) { + const newValues = value.filter((f2) => f2 != v2); + setValue(newValues); + props.saveValue(serializeMultiString(newValues)); + } else { + setValue([]); + props.saveValue(""); + } + }; + const removeOption = (option) => { + const newOptions = options.filter((f2) => f2.value != option); + const newValues = value.filter((f2) => f2 != option); + setOptions(newOptions); + setValue(newValues); + if (props.multi) { + props.saveOptions( + serializeValue(newOptions, parsedValue), + serializeMultiString(newValues) + ); + } else { + props.saveOptions( + serializeValue(newOptions, parsedValue), + serializeMultiDisplayString(newValues) + ); + } + }; + const savePropValue = (options2, value2) => { + if (props.multi) { + props.saveOptions( + serializeValue(options2, parsedValue), + serializeMultiString(value2) + ); + } else { + props.saveOptions( + serializeValue(options2, parsedValue), + serializeMultiDisplayString(value2) + ); + } + }; + const saveOptions = (_options, _value) => { + const newOptions = (0, import_lodash10.uniq)([..._options, ..._value]).filter((f2) => f2.length > 0).map( + (t5) => options.find((f2) => f2.value == t5) ?? { + name: t5, + value: t5 + } + ); + if (!props.multi) { + if (props.editMode >= 2 /* EditModeView */) { + setOptions(newOptions); + } + setValue(_value); + savePropValue(newOptions, _value); + } else { + const newValues = (0, import_lodash10.uniq)([...value, _value[0]]); + if (props.editMode >= 2 /* EditModeView */) + setOptions(newOptions); + setValue(newValues); + savePropValue(newOptions, newValues); + } + }; + const saveOption = (option, newValue) => { + const newOptions = options.map((t5) => t5.value == option ? newValue : t5); + const newValues = value; + setOptions(newOptions); + setValue(newValues); + savePropValue(newOptions, newValues); + }; + const showOptionMenu = (e5, optionValue) => { + const option = options.find((f2) => f2.value == optionValue); + const menuOptions = []; + menuOptions.push( + menuInput( + option.value, + (value2) => saveOption(option.value, { ...option, value: value2 }) + ) + ); + menuOptions.push(menuSeparator); + menuOptions.push({ + name: "None", + color: "var(--mk-color-none)", + onClick: () => { + saveOption(option.value, { ...option, color: "" }); + } + }); + colors.forEach((f2) => { + menuOptions.push({ + name: f2[0], + value: f2[1], + color: `${f2[1]}`, + onClick: () => { + saveOption(option.value, { ...option, color: f2[1] }); + } + }); + }); + props.superstate.ui.openMenu( + e5.target.getBoundingClientRect(), + defaultMenu(props.superstate.ui, menuOptions) + ); + }; + const menuProps = () => ({ + multi: false, + editable: props.editMode >= 2 /* EditModeView */, + ui: props.superstate.ui, + value, + options: !props.multi ? [{ name: i18n_default.menu.none, value: "" }, ...options] : options, + saveOptions, + removeOption: props.editMode >= 2 /* EditModeView */ && removeOption, + onMoreOption: props.editMode >= 2 /* EditModeView */ && showOptionMenu, + placeholder: i18n_default.labels.optionItemSelectPlaceholder, + searchable: true, + showAll: true, + onHide: () => props.setEditMode(null) + }); + return /* @__PURE__ */ import_react53.default.createElement(OptionCellBase, { + superstate: props.superstate, + baseClass: "mk-cell-option", + value, + menuProps, + multi: props.multi, + removeValue, + selectLabel: props.compactMode ? props.property.name : i18n_default.labels.select, + editMode: props.editMode, + labelElement: (_props) => { + const color2 = options.find((f2) => f2.value == _props.value)?.color ?? "var(--mk-color-none)"; + return /* @__PURE__ */ import_react53.default.createElement("div", { + className: "mk-cell-option-item", + style: { + background: `${color2}`, + color: color2 == "var(--mk-color-none)" ? "inherit" : "var(--mk-color-white)" + } + }, _props.value, _props.children); + } + }); +}; +var OptionCellBase = (props) => { + const { value, menuProps } = props; + const menuRef = (0, import_react53.useRef)(null); + (0, import_react53.useEffect)(() => { + if (props.editMode == 4 /* EditModeActive */) { + if (!menuRef.current) + showMenu2(); + } + }, [props.editMode]); + const ref2 = (0, import_react53.useRef)(null); + const showMenu2 = () => { + if (menuRef.current) { + menuRef.current.hide(); + menuRef.current = null; + return; + } + const offset2 = ref2.current.getBoundingClientRect(); + menuRef.current = props.superstate.ui.openMenu( + offset2, + menuProps(), + "bottom", + () => menuRef.current = null + ); + }; + const editable = props.editMode > 1 /* EditModeNone */; + return /* @__PURE__ */ import_react53.default.createElement("div", { + className: props.baseClass, + ref: ref2 + }, value.length > 0 ? value.map((o2, i4) => /* @__PURE__ */ import_react53.default.createElement(import_react53.default.Fragment, { + key: i4 + }, props.labelElement && /* @__PURE__ */ import_react53.default.createElement(props.labelElement, { + value: o2 + }, editable ? !props.multi && value.length > 0 ? /* @__PURE__ */ import_react53.default.createElement(import_react53.default.Fragment, null, /* @__PURE__ */ import_react53.default.createElement("span", null), /* @__PURE__ */ import_react53.default.createElement("div", { + onClick: (e5) => { + e5.stopPropagation(); + showMenu2(); + }, + className: "mk-cell-option-select mk-icon-xxsmall mk-icon-rotated", + dangerouslySetInnerHTML: { + __html: props.superstate.ui.getSticker( + "ui//collapse-solid" + ) + } + })) : props.multi ? /* @__PURE__ */ import_react53.default.createElement("div", { + className: "mk-cell-option-remove mk-icon-xxsmall", + onClick: (e5) => { + e5.stopPropagation(); + props.removeValue(o2); + }, + dangerouslySetInnerHTML: { + __html: props.superstate.ui.getSticker("ui//close") + } + }) : null : null))) : editable && !props.multi ? /* @__PURE__ */ import_react53.default.createElement("div", { + className: "mk-cell-option-item", + onClick: (e5) => { + showMenu2(); + } + }, /* @__PURE__ */ import_react53.default.createElement("div", { + className: "mk-cell-empty" + }, props.selectLabel), /* @__PURE__ */ import_react53.default.createElement("div", { + className: "mk-cell-option-select mk-icon-xxsmall mk-icon-rotated", + dangerouslySetInnerHTML: { + __html: props.superstate.ui.getSticker("ui//collapse-solid") + } + })) : props.editMode == 0 /* EditModeReadOnly */ ? /* @__PURE__ */ import_react53.default.createElement("div", { + className: "mk-cell-option-item mk-cell-empty" + }, /* @__PURE__ */ import_react53.default.createElement("div", null, i18n_default.menu.none)) : /* @__PURE__ */ import_react53.default.createElement(import_react53.default.Fragment, null), editable && props.multi ? /* @__PURE__ */ import_react53.default.createElement("div", { + onClick: (e5) => editable && showMenu2(), + className: "mk-cell-option-new mk-icon-small", + dangerouslySetInnerHTML: { + __html: props.superstate.ui.getSticker("ui//plus") + } + }) : /* @__PURE__ */ import_react53.default.createElement(import_react53.default.Fragment, null)); +}; + +// src/core/react/components/SpaceView/Contexts/DataTypeView/ContextCell.tsx +var ContextCell = (props) => { + const { spaceState } = (0, import_react54.useContext)(SpaceContext); + const fieldValue = (0, import_react54.useMemo)( + () => parseFieldValue(props.propertyValue, "context", props.superstate), + [props.propertyValue] + ); + const spacePath = (0, import_react54.useMemo)( + () => fieldValue ? props.superstate.spaceManager.resolvePath( + fieldValue.space, + spaceState?.path + ) : null, + [fieldValue.space, spaceState] + ); + const parseValue = (v2, multi) => (multi ? parseMultiString(v2) ?? [] : [v2]).filter((f2) => f2); + const [propValues, setPropValues] = (0, import_react54.useState)( + props.superstate.contextsIndex.get(spacePath)?.spaceMap[fieldValue.spaceField]?.[props.path] ?? [] + ); + (0, import_react54.useEffect)(() => { + setPropValues( + props.superstate.contextsIndex.get(spacePath)?.spaceMap[fieldValue.spaceField]?.[props.path] ?? [] + ); + }, [spacePath, fieldValue]); + const options = [...props.superstate.spacesMap.getInverse(spacePath)].map((f2) => props.superstate.pathsIndex.get(f2)).filter((f2) => f2).map((f2) => ({ + name: f2.name, + icon: f2.label.sticker, + description: f2.path, + value: f2.path + })); + const [value, setValue] = (0, import_react54.useState)( + parseValue(props.initialValue, props.multi) + ); + const allValues = (0, import_react54.useMemo)( + () => uniq([...value, ...propValues]), + [value, propValues] + ); + const saveValue = (_values) => { + if (props.multi) { + props.saveValue(serializeMultiString(_values)); + } else { + props.saveValue(serializeMultiDisplayString(_values)); + } + }; + const removeValue = (v2) => { + if (propValues.includes(v2)) { + const newPropValues = propValues.filter((f2) => f2 != v2); + setPropValues(newPropValues); + updateContextValue( + props.superstate.spaceManager, + props.superstate.spacesIndex.get(spacePath).space, + v2, + fieldValue.spaceField, + props.path, + deletePropertyMultiValue + ); + } else { + const newValues = value.filter((f2) => f2 != v2); + setValue(newValues); + saveValue(newValues.map((f2) => f2)); + } + }; + (0, import_react54.useEffect)(() => { + setValue(parseValue(props.initialValue, props.multi)); + }, [props.initialValue, props.multi]); + const saveOptions = (_options, _value) => { + insertContextItems(props.superstate.spaceManager, _value, spacePath); + if (!props.multi) { + setValue(_value); + saveValue(_value); + } else { + const newValue = _value[0]; + if (newValue) { + const newValues = [...value, newValue]; + setValue(newValues); + saveValue(newValues); + } + } + }; + const menuProps = () => { + const _options = !props.multi ? [{ name: i18n_default.menu.none, value: "" }, ...options] : options; + return { + ui: props.superstate.ui, + multi: false, + editable: true, + value: allValues.map((f2) => f2.path), + options: _options, + saveOptions, + placeholder: i18n_default.labels.contextItemSelectPlaceholder, + searchable: true, + showAll: true, + onHide: () => props.setEditMode(null) + }; + }; + return /* @__PURE__ */ import_react54.default.createElement(OptionCellBase, { + baseClass: "mk-cell-context", + superstate: props.superstate, + menuProps, + removeValue, + selectLabel: props.compactMode ? props.property.name : i18n_default.labels.select, + labelElement: (_props) => /* @__PURE__ */ import_react54.default.createElement(PathCrumb, { + superstate: props.superstate, + path: _props.value, + source: spaceState?.path + }, _props.children), + value: allValues, + multi: props.multi, + editMode: props.editMode + }); +}; + +// src/core/react/components/SpaceView/Contexts/DataTypeView/DateCell.tsx +var import_classnames = __toESM(require_classnames()); +var import_react55 = __toESM(require_react()); +var DateCell = (props) => { + const [value, setValue] = (0, import_react55.useState)(props.initialValue); + (0, import_react55.useEffect)(() => { + setValue(props.initialValue); + }, [props.initialValue]); + const date = (0, import_react55.useMemo)(() => { + const dateTime = parseDate2(value); + if (!isValidDate(dateTime)) { + return null; + } + return dateTime; + }, [value]); + const saveValue = (date2) => { + const newValue = formatDate(props.superstate, date2, "yyyy-MM-dd"); + props.saveValue(newValue); + setValue(newValue); + props.setEditMode(null); + }; + const menuRef = (0, import_react55.useRef)(null); + const ref2 = (0, import_react55.useRef)(null); + (0, import_react55.useEffect)(() => { + if (props.editMode == 4 /* EditModeActive */) { + if (ref2.current) { + showPicker(); + ref2.current.focus(); + } + } + }, [props.editMode]); + const showPicker = (0, import_react55.useCallback)( + (e5) => { + if (props.editMode <= 1 /* EditModeNone */) { + return; + } + const offset2 = e5 ? e5.target.getBoundingClientRect() : ref2.current.getBoundingClientRect(); + menuRef.current = showDatePickerMenu( + props.superstate.ui, + offset2, + date, + saveValue, + 0 /* None */, + null, + "bottom" + ); + }, + [date] + ); + const onKeyDown = (e5) => { + e5.stopPropagation(); + if (e5.key == "Enter" || e5.key == "Escape") { + e5.target.blur(); + saveValue(date); + menuRef.current.hide(); + } + }; + const format8 = (0, import_react55.useMemo)( + () => safelyParseJSON(props.propertyValue)?.format, + [props.propertyValue] + ); + const isEmpty = !(value?.length > 0); + return /* @__PURE__ */ import_react55.default.createElement("div", { + className: "mk-cell-date", + onClick: (e5) => !value && showPicker(e5) + }, /* @__PURE__ */ import_react55.default.createElement("div", { + className: (0, import_classnames.default)( + "mk-cell-date-item", + isEmpty && "mk-cell-date-new" + ) + }, /* @__PURE__ */ import_react55.default.createElement("div", { + className: "mk-icon-xsmall", + dangerouslySetInnerHTML: { + __html: props.superstate.ui.getSticker("ui//calendar") + } + }), isEmpty && "Select", props.editMode == 4 /* EditModeActive */ ? /* @__PURE__ */ import_react55.default.createElement("input", { + onClick: (e5) => e5.stopPropagation(), + className: "mk-cell-text", + ref: ref2, + type: "text", + value, + onChange: (e5) => setValue(e5.target.value), + onMouseDown: () => showPicker(), + onKeyDown + }) : /* @__PURE__ */ import_react55.default.createElement("div", { + className: "mk-cell-date-value", + onClick: (e5) => showPicker(e5) + }, date ? formatDate( + props.superstate, + date, + format8?.length > 0 ? format8 : null + ) : value))); +}; + +// src/core/react/components/SpaceView/Contexts/DataTypeView/IconCell.tsx +var import_react56 = __toESM(require_react()); +var IconCell = (props) => { + const value = (0, import_react56.useMemo)( + () => props.multi ? parseMultiString(props.initialValue) ?? [] : [props.initialValue], + [props.initialValue] + ); + const ref2 = (0, import_react56.useRef)(null); + (0, import_react56.useEffect)(() => { + if (props.editMode == 4 /* EditModeActive */) { + ref2?.current?.focus(); + } + }, [props.editMode]); + const triggerStickerMenu = (e5) => { + props.superstate.ui.openPalette((_props) => /* @__PURE__ */ import_react56.default.createElement(StickerModal_default, { + ui: props.superstate.ui, + hide: _props.hide, + selectedSticker: (emoji) => props.saveValue(emoji) + })); + }; + return /* @__PURE__ */ import_react56.default.createElement("div", { + className: "mk-cell-icon" + }, value.map( + (v2, i4) => v2?.length > 0 ? /* @__PURE__ */ import_react56.default.createElement("div", { + className: "mk-cell-clickable", + key: i4, + "aria-label": i18n_default.buttons.changeIcon, + dangerouslySetInnerHTML: { + __html: props.superstate.ui.getSticker(v2) + }, + onClick: (e5) => triggerStickerMenu(e5) + }) : /* @__PURE__ */ import_react56.default.createElement("div", { + key: i4, + className: "mk-cell-placeholder", + onClick: (e5) => triggerStickerMenu(e5) + }, i18n_default.labels.selectIcon) + )); +}; + +// src/core/react/components/UI/Modals/ImageModal.tsx +var import_react57 = __toESM(require_react()); + +// src/utils/regex.ts +var urlRegex = /https?:\/\/(www\.)?[-a-zA-Z0-9@:%._\+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b([-a-zA-Z0-9()@:%_\+.~#?&//=]*)/gi; + +// src/core/react/components/UI/Modals/ImageModal.tsx +var ImageModal = (props) => { + const [query, setQuery] = (0, import_react57.useState)(""); + const [allImages, setAllImages] = (0, import_react57.useState)([]); + const [images, setImages] = (0, import_react57.useState)([]); + const [selectedImage, setSelectedImage] = (0, import_react57.useState)(null); + (0, import_react57.useEffect)(() => { + const _allImages = []; + _allImages.push( + ...[...props.superstate.pathsIndex.values()].filter((f2) => f2.subtype == "image").map((f2) => ({ path: f2.path, thumnail: f2.label.thumbnail })) + ); + setAllImages(_allImages); + setImages(_allImages); + }, []); + (0, import_react57.useEffect)(() => { + query.match(urlRegex) ? setImages([{ path: query, thumnail: query }]) : setImages(allImages.filter((f2) => f2.path.includes(query))); + }, [query, allImages]); + const handleInputChange = (event) => { + setQuery(event.target.value); + }; + const handleKeyDown = (event) => { + const currentIndex = images.findIndex((f2) => f2.path == selectedImage); + if (event.key === "ArrowUp" && currentIndex > 0) { + setSelectedImage(images[currentIndex - 1].path); + } else if (event.key === "ArrowDown" && currentIndex < images.length - 1) { + setSelectedImage(images[currentIndex + 1].path); + } else if (event.key === "Enter") { + props.selectedPath(selectedImage); + props.hide(); + } + }; + const ref2 = (0, import_react57.useRef)(null); + (0, import_react57.useEffect)(() => { + if (ref2.current) { + ref2.current.focus(); + } + }, [ref2.current]); + return /* @__PURE__ */ import_react57.default.createElement(import_react57.default.Fragment, null, /* @__PURE__ */ import_react57.default.createElement("input", { + onKeyDown: handleKeyDown, + value: query, + ref: ref2, + onChange: handleInputChange, + className: "mk-input mk-input-large mk-border-bottom" + }), /* @__PURE__ */ import_react57.default.createElement("div", { + className: "mk-layout-masonry mk-padding-12 mk-layout-scroll" + }, images.map((image) => /* @__PURE__ */ import_react57.default.createElement("img", { + key: image.path, + src: props.superstate.ui.getUIPath(image.thumnail), + className: selectedImage === image.path ? "mk-selected" : "", + onClick: () => { + props.selectedPath(image.path); + props.hide(); + } + })))); +}; +var ImageModal_default = ImageModal; + +// src/core/react/components/SpaceView/Contexts/DataTypeView/ImageCell.tsx +var import_react58 = __toESM(require_react()); +var ImageCell = (props) => { + const { initialValue, multi } = props; + const [value, setValue] = import_react58.default.useState( + parseMultiString(initialValue) + ); + const menuRef = (0, import_react58.useRef)(null); + const sourcePaths = (0, import_react58.useMemo)(() => { + if (value?.length > 0) { + return value.map((f2) => props.superstate.ui.getUIPath(f2)); + } + return []; + }, [value]); + import_react58.default.useEffect(() => { + setValue(parseMultiString(initialValue)); + }, [initialValue]); + const deleteValue = (index2) => { + if (multi) { + const newValue = [...value]; + newValue.splice(index2, 1); + setValue(newValue); + props.saveValue(serializeMultiString(newValue)); + } else { + props.saveValue(""); + } + }; + const saveValue = (index2, image) => { + if (props.multi) { + if (index2 == -1) { + props.saveValue(serializeMultiString([...value, image])); + } else { + props.saveValue( + serializeMultiString(value.map((f2, i4) => i4 == index2 ? image : f2)) + ); + } + } else { + props.saveValue(image); + } + }; + const showModal2 = (index2) => { + props.superstate.ui.openPalette((_props) => /* @__PURE__ */ import_react58.default.createElement(ImageModal_default, { + superstate: props.superstate, + hide: _props.hide, + selectedPath: (image) => saveValue(index2, image) + })); + props.setEditMode(null); + }; + return /* @__PURE__ */ import_react58.default.createElement("div", { + className: "mk-cell-image" + }, sourcePaths.map((f2, i4) => /* @__PURE__ */ import_react58.default.createElement("div", { + key: i4, + className: "mk-cell-image-item" + }, /* @__PURE__ */ import_react58.default.createElement("img", { + onClick: (e5) => props.superstate.ui.openPath( + initialValue, + e5.metaKey ? "tab" : false + ), + src: f2 + }), props.editMode > 1 /* EditModeNone */ ? /* @__PURE__ */ import_react58.default.createElement("div", { + className: "mk-image-selector" + }, /* @__PURE__ */ import_react58.default.createElement("div", { + onClick: () => showModal2(i4), + className: "mk-hover-button mk-icon-xsmall", + dangerouslySetInnerHTML: { + __html: props.superstate.ui.getSticker("ui//edit") + } + }), /* @__PURE__ */ import_react58.default.createElement("div", { + onClick: () => deleteValue(i4), + className: "mk-hover-button mk-icon-xsmall", + dangerouslySetInnerHTML: { + __html: props.superstate.ui.getSticker("ui//close") } - return expandRows(rowModel); - }, getMemoOptions(table.options, "debugTable", "getExpandedRowModel")); -} -function expandRows(rowModel) { - const expandedRows = []; - const handleRow = (row2) => { - var _row$subRows; - expandedRows.push(row2); - if ((_row$subRows = row2.subRows) != null && _row$subRows.length && row2.getIsExpanded()) { - row2.subRows.forEach(handleRow); + })) : /* @__PURE__ */ import_react58.default.createElement(import_react58.default.Fragment, null))), props.editMode > 1 /* EditModeNone */ ? props.multi ? /* @__PURE__ */ import_react58.default.createElement("div", { + onClick: (e5) => showModal2(-1), + className: "mk-cell-option-new mk-icon-small", + dangerouslySetInnerHTML: { + __html: props.superstate.ui.getSticker("ui//plus") } + }) : value.length == 0 ? /* @__PURE__ */ import_react58.default.createElement("div", { + onClick: () => showModal2(-1), + className: "mk-cell-clickable" + }, "Select") : null : /* @__PURE__ */ import_react58.default.createElement(import_react58.default.Fragment, null)); +}; + +// src/core/react/components/SpaceView/Contexts/DataTypeView/LinkCell.tsx +var import_react59 = __toESM(require_react()); +var LinkCell = (props) => { + const parseValue = (v2) => props.multi ? parseMultiString(v2) ?? [] : [v2].filter((f2) => f2); + (0, import_react59.useEffect)(() => { + setValue(parseValue(props.initialValue)); + }, [props.initialValue]); + const [value, setValue] = (0, import_react59.useState)(parseValue(props.initialValue)); + const removeValue = (v2) => { + const newValues = value.filter((f2) => f2 != v2); + setValue(newValues); + saveValue(newValues); }; - rowModel.rows.forEach(handleRow); - return { - rows: expandedRows, - flatRows: rowModel.flatRows, - rowsById: rowModel.rowsById - }; -} -function getGroupedRowModel() { - return (table) => memo2(() => [table.getState().grouping, table.getPreGroupedRowModel()], (grouping, rowModel) => { - if (!rowModel.rows.length || !grouping.length) { - return rowModel; + const saveValue = (_values) => { + if (props.multi) { + props.saveValue(serializeMultiString(_values)); + } else { + props.saveValue(serializeMultiDisplayString(_values)); } - const existingGrouping = grouping.filter((columnId) => table.getColumn(columnId)); - const groupedFlatRows = []; - const groupedRowsById = {}; - const groupUpRecursively = function(rows, depth, parentId) { - if (depth === void 0) { - depth = 0; - } - if (depth >= existingGrouping.length) { - return rows.map((row2) => { - row2.depth = depth; - groupedFlatRows.push(row2); - groupedRowsById[row2.id] = row2; - if (row2.subRows) { - row2.subRows = groupUpRecursively(row2.subRows, depth + 1, row2.id); - } - return row2; - }); + }; + const saveOptions = (_15, _value) => { + if (!props.multi) { + setValue(_value); + saveValue(_value); + } else { + const newValue = _value[0]; + if (newValue) { + const newValues = uniq([...value, newValue]); + setValue(newValues); + saveValue(newValues); } - const columnId = existingGrouping[depth]; - const rowGroupsMap = groupBy(rows, columnId); - const aggregatedGroupedRows = Array.from(rowGroupsMap.entries()).map((_ref, index2) => { - let [groupingValue, groupedRows2] = _ref; - let id3 = `${columnId}:${groupingValue}`; - id3 = parentId ? `${parentId}>${id3}` : id3; - const subRows = groupUpRecursively(groupedRows2, depth + 1, id3); - const leafRows = depth ? flattenBy(groupedRows2, (row3) => row3.subRows) : groupedRows2; - const row2 = createRow2(table, id3, leafRows[0].original, index2, depth, void 0, parentId); - Object.assign(row2, { - groupingColumnId: columnId, - groupingValue, - subRows, - leafRows, - getValue: (columnId2) => { - if (existingGrouping.includes(columnId2)) { - if (row2._valuesCache.hasOwnProperty(columnId2)) { - return row2._valuesCache[columnId2]; - } - if (groupedRows2[0]) { - var _groupedRows$0$getVal; - row2._valuesCache[columnId2] = (_groupedRows$0$getVal = groupedRows2[0].getValue(columnId2)) != null ? _groupedRows$0$getVal : void 0; - } - return row2._valuesCache[columnId2]; - } - if (row2._groupingValuesCache.hasOwnProperty(columnId2)) { - return row2._groupingValuesCache[columnId2]; - } - const column2 = table.getColumn(columnId2); - const aggregateFn = column2 == null ? void 0 : column2.getAggregationFn(); - if (aggregateFn) { - row2._groupingValuesCache[columnId2] = aggregateFn(columnId2, leafRows, groupedRows2); - return row2._groupingValuesCache[columnId2]; - } - } - }); - subRows.forEach((subRow) => { - groupedFlatRows.push(subRow); - groupedRowsById[subRow.id] = subRow; - }); - return row2; - }); - return aggregatedGroupedRows; - }; - const groupedRows = groupUpRecursively(rowModel.rows, 0); - groupedRows.forEach((subRow) => { - groupedFlatRows.push(subRow); - groupedRowsById[subRow.id] = subRow; - }); + } + }; + const menuProps = () => { + const options = [...props.superstate.pathsIndex.values()].filter((f2) => !f2.hidden).map((f2) => ({ + name: f2.name, + value: f2.path, + description: f2.path + })); + const _options = !props.multi ? [{ name: i18n_default.menu.none, value: "" }, ...options] : options; return { - rows: groupedRows, - flatRows: groupedFlatRows, - rowsById: groupedRowsById + ui: props.superstate.ui, + multi: false, + editable: true, + value: value.map((f2) => f2), + options: _options, + saveOptions, + placeholder: i18n_default.labels.linkItemSelectPlaceholder, + detail: true, + searchable: true }; - }, getMemoOptions(table.options, "debugTable", "getGroupedRowModel", () => { - table._queue(() => { - table._autoResetExpanded(); - table._autoResetPageIndex(); - }); - })); -} -function groupBy(rows, columnId) { - const groupMap = /* @__PURE__ */ new Map(); - return rows.reduce((map4, row2) => { - const resKey = `${row2.getGroupingValue(columnId)}`; - const previous = map4.get(resKey); - if (!previous) { - map4.set(resKey, [row2]); - } else { - previous.push(row2); - } - return map4; - }, groupMap); -} -function getPaginationRowModel(opts) { - return (table) => memo2(() => [table.getState().pagination, table.getPrePaginationRowModel(), table.options.paginateExpandedRows ? void 0 : table.getState().expanded], (pagination, rowModel) => { - if (!rowModel.rows.length) { - return rowModel; - } - const { - pageSize, - pageIndex - } = pagination; - let { - rows, - flatRows, - rowsById - } = rowModel; - const pageStart = pageSize * pageIndex; - const pageEnd = pageStart + pageSize; - rows = rows.slice(pageStart, pageEnd); - let paginatedRowModel; - if (!table.options.paginateExpandedRows) { - paginatedRowModel = expandRows({ - rows, - flatRows, - rowsById - }); + }; + const openLink = async (o2) => { + const pathExists = await props.superstate.spaceManager.pathExists(o2); + if (pathExists) { + props.superstate.ui.openPath(o2, false); } else { - paginatedRowModel = { - rows, - flatRows, - rowsById - }; + await props.superstate.spaceManager.createItemAtPath("/", "md", o2); + props.superstate.ui.openPath(o2, false); } - paginatedRowModel.flatRows = []; - const handleRow = (row2) => { - paginatedRowModel.flatRows.push(row2); - if (row2.subRows.length) { - row2.subRows.forEach(handleRow); - } + }; + return /* @__PURE__ */ import_react59.default.createElement(OptionCellBase, { + superstate: props.superstate, + baseClass: "mk-cell-link", + removeValue, + selectLabel: props.compactMode ? props.property.name : i18n_default.labels.select, + menuProps, + labelElement: (_props) => /* @__PURE__ */ import_react59.default.createElement(PathCrumb, { + superstate: props.superstate, + path: _props.value + }, _props.children), + value, + multi: props.multi, + editMode: props.editMode + }); +}; + +// src/core/react/components/SpaceView/Contexts/DataTypeView/LookUpCell.tsx +var import_react60 = __toESM(require_react()); +var LookUpCell = (props) => { + const initialValue = ensureString(props.initialValue); + const parsedValue = (0, import_react60.useMemo)( + () => parseFieldValue(props.propertyValue, "fileprop", props.superstate), + [props.propertyValue] + ); + const saveParsedValue = (field, value) => { + props.saveOptions(JSON.stringify({ ...parsedValue, [field]: value }), ""); + }; + const editFormula = (e5) => { + const _props = { + superstate: props.superstate, + saveFormula: (value) => saveParsedValue("value", value), + formula: parsedValue.value, + value: props.row, + fields: props.columns, + path: props.path }; - paginatedRowModel.rows.forEach(handleRow); - return paginatedRowModel; - }, getMemoOptions(table.options, "debugTable", "getPaginationRowModel")); -} + props.superstate.ui.openCustomMenu( + e5.target.getBoundingClientRect(), + /* @__PURE__ */ import_react60.default.createElement(FormulaEditor, { + ..._props + }), + { ..._props }, + "bottom" + ); + }; + return parsedValue.type == "image" ? /* @__PURE__ */ import_react60.default.createElement(ImageCell, { + ...props, + editMode: 0 /* EditModeReadOnly */, + multi: false + }) : parsedValue.type == "icon" ? /* @__PURE__ */ import_react60.default.createElement(IconCell, { + ...props, + multi: false, + editMode: 0 /* EditModeReadOnly */ + }) : parsedValue.type == "link" ? /* @__PURE__ */ import_react60.default.createElement(LinkCell, { + ...props, + multi: false, + editMode: 0 /* EditModeReadOnly */ + }) : /* @__PURE__ */ import_react60.default.createElement("div", { + className: "mk-cell-fileprop", + onClick: (e5) => editFormula(e5) + }, initialValue); +}; -// node_modules/@tanstack/react-table/build/lib/index.mjs -function flexRender(Comp, props) { - return !Comp ? null : isReactComponent(Comp) ? /* @__PURE__ */ React34.createElement(Comp, props) : Comp; -} -function isReactComponent(component) { - return isClassComponent(component) || typeof component === "function" || isExoticComponent(component); -} -function isClassComponent(component) { - return typeof component === "function" && (() => { - const proto = Object.getPrototypeOf(component); - return proto.prototype && proto.prototype.isReactComponent; - })(); -} -function isExoticComponent(component) { - return typeof component === "object" && typeof component.$$typeof === "symbol" && ["react.memo", "react.forward_ref"].includes(component.$$typeof.description); -} -function useReactTable(options) { - const resolvedOptions = { - state: {}, - onStateChange: () => { - }, - renderFallbackValue: null, - ...options +// src/core/react/components/SpaceView/Contexts/DataTypeView/NumberCell.tsx +var import_react61 = __toESM(require_react()); +var NumberCell = (props) => { + const { initialValue, saveValue } = props; + const [value, setValue] = import_react61.default.useState(initialValue); + const ref2 = (0, import_react61.useRef)(null); + const onBlur = () => { + if (initialValue != value) + saveValue(value); }; - const [tableRef] = React34.useState(() => ({ - current: createTable(resolvedOptions) - })); - const [state, setState] = React34.useState(() => tableRef.current.initialState); - tableRef.current.setOptions((prev) => ({ - ...prev, - ...options, - state: { - ...state, - ...options.state - }, - onStateChange: (updater) => { - setState(updater); - options.onStateChange == null || options.onStateChange(updater); + const onKeyDown = (e5) => { + e5.stopPropagation(); + if (e5.key == "Enter") { + e5.target.blur(); + props.setEditMode(null); } - })); - return tableRef.current; -} - -// src/core/react/components/SpaceView/Contexts/TableView/TableView.tsx -var import_react77 = __toESM(require_react()); -var import_react_dom5 = __toESM(require_react_dom()); - -// src/core/react/components/UI/Menus/navigator/spaceContextMenu.tsx -var import_react56 = __toESM(require_react()); + if (e5.key == "Escape") { + setValue(initialValue); + e5.target.blur(); + props.setEditMode(null); + } + }; + import_react61.default.useEffect(() => { + setValue(initialValue); + }, [initialValue]); + (0, import_react61.useEffect)(() => { + if (props.editMode == 4 /* EditModeActive */) { + ref2?.current?.focus(); + } + }, [props.editMode]); + return props.editMode > 2 /* EditModeView */ ? /* @__PURE__ */ import_react61.default.createElement("input", { + className: "mk-cell-text", + type: "number", + ref: ref2, + value: value ?? "", + onChange: (e5) => setValue(e5.target.value), + onKeyDown, + onBlur + }) : /* @__PURE__ */ import_react61.default.createElement("div", { + className: "mk-cell-number" + }, value); +}; -// src/core/react/components/SpaceEditor/SpacePropertyEditor.tsx -var import_react37 = __toESM(require_react()); -var import_react_dom3 = __toESM(require_react_dom()); -var SpacePropertyEditor = (props) => { - const [activeId, setActiveId] = (0, import_react37.useState)(""); - const items = props.columns.map((f2) => ({ ...f2, table: "", id: f2.name })); - const [openNodes, setOpenNodes] = (0, import_react37.useState)([]); - const [overId, setOverId] = (0, import_react37.useState)(""); - const contextProperties = (0, import_react37.useMemo)(() => { - return props.contexts.reduce((p, c3) => { +// src/core/react/components/SpaceView/Contexts/DataTypeView/ObjectCell.tsx +var import_react62 = __toESM(require_react()); +var import_react_dom4 = __toESM(require_react_dom()); +var ObjectEditor = (props) => { + const { value, saveValue, saveType } = props; + const allProperties = [ + ...Object.keys(props.type ?? {}).map((f2) => { return { - ...p, - [c3]: { - path: props.superstate.pathsIndex.get(tagSpacePathFromTag(c3)), - space: props.superstate.spacesIndex.get(tagSpacePathFromTag(c3)), - cols: props.superstate.contextsIndex.get(tagSpacePathFromTag(c3))?.cols ?? [].map((f2) => ({ ...f2, table: c3 })) - } + name: f2, + type: props.type[f2].type, + value: JSON.stringify(props.type[f2].value) }; - }, {}); - }, [props.contexts]); - const sensors = useSensors( - useSensor(MouseSensor, { - activationConstraint: { - distance: 10 - } - }), - useSensor(TouchSensor, { - activationConstraint: { - delay: 250, - tolerance: 5 - } }), - useSensor(KeyboardSensor, { - coordinateGetter: sortableKeyboardCoordinates + ...Object.keys(value).filter((f2) => !Object.keys(props.type ?? {}).includes(f2)).map((f2) => { + return { + name: f2, + type: "text" + }; }) - ); - const resetState = () => { - setActiveId(null); - setOverId(null); + ]; + const saveKey = (key2, newKey) => { + if (key2 != newKey) + saveValue({ + ...value, + [newKey]: value[key2], + [key2]: void 0 + }); }; - const saveNewField = (source, field) => { - props.saveColumn({ ...field, table: "" }); + const saveVal = (key2, val) => { + saveValue({ + ...value, + [key2]: val + }); }; - const newProperty = (e5) => { + const showPropertyMenu2 = (e5, field) => { + if (props.editMode <= 3 /* EditModeValueOnly */) { + return; + } const offset2 = e5.target.getBoundingClientRect(); - showNewPropertyMenu( - props.superstate, + const menuOptions = []; + menuOptions.push({ + name: i18n_default.menu.rename, + icon: "ui//edit", + onClick: (e6) => { + props.superstate.ui.openModal( + i18n_default.labels.rename, + (props2) => /* @__PURE__ */ import_react62.default.createElement(InputModal, { + value: field, + saveLabel: i18n_default.labels.rename, + hide: props2.hide, + saveValue: (value2) => { + saveKey(field, value2); + props2.hide(); + } + }) + ); + } + }); + menuOptions.push({ + name: i18n_default.buttons.delete, + icon: "ui//trash", + onClick: (e6) => { + props.saveType( + Object.keys(props.type ?? {}).reduce((p, c3) => { + if (c3 != field) + return { ...p, [c3]: props.type[c3] }; + return p; + }, {}), + Object.keys(value).reduce((p, c3) => { + if (c3 != field) + return { ...p, [c3]: value[c3] }; + return p; + }, {}) + ); + } + }); + props.superstate.ui.openMenu( offset2, - props.contexts ?? [], - [], - saveNewField, - defaultContextSchemaID, - null, - false + defaultMenu(props.superstate.ui, menuOptions) ); }; - const newContexts = (e5) => { + const saveFieldValue = (field, fieldValue, value2) => { + const val = parseObject(value2, field.type == "object-multi"); + if (propertyIsObjectType(field)) { + const parsedValue = parseFieldValue(fieldValue, field.type); + const newType = { + ...props.type, + [field.name]: { + type: field.type, + label: field.name, + value: parsedValue + } + }; + saveType(newType, val); + } + }; + return /* @__PURE__ */ import_react62.default.createElement("div", { + className: "mk-cell-object-group" + }, props.draggable && /* @__PURE__ */ import_react62.default.createElement("div", { + className: "mk-cell-object-group-header", + onClick: (e5) => { + props.showDragMenu(e5); + } + }, props.typeName ?? "Object"), /* @__PURE__ */ import_react62.default.createElement("div", { + className: "mk-cell-object" + }, allProperties.map((f2, i4) => /* @__PURE__ */ import_react62.default.createElement(DataPropertyView, { + key: i4, + initialValue: value[f2.name] ?? "", + superstate: props.superstate, + updateValue: (v2) => saveVal(f2.name, v2), + updateFieldValue: (fv, v2) => saveFieldValue(f2, fv, v2), + propertyMenu: (e5) => showPropertyMenu2(e5, f2.name), + row: value, + columns: allProperties, + source: null, + compactMode: props.compactMode, + column: f2, + editMode: 5 /* EditModeAlways */ + })))); +}; +var ObjectCell = (props) => { + const parsedValue = parseFieldValue( + props.propertyValue, + "object", + props.superstate + ); + const type = parsedValue.type; + const { initialValue, superstate } = props; + const value = (0, import_react62.useMemo)( + () => parseObject(initialValue, props.multi), + [initialValue, props.multi] + ); + const saveType = (newType, _value) => { + if (props.multi) { + const newValues = value.map((f2) => ({ + ...Object.keys(newType).reduce((p, c3) => { + if (f2[c3]) + return { ...p, [c3]: f2[c3] }; + return p; + }, {}) + })); + props.savePropValue( + JSON.stringify({ ...parsedValue, type: newType }), + JSON.stringify(newValues) + ); + } else { + props.savePropValue( + JSON.stringify({ ...parsedValue, type: newType }), + JSON.stringify(_value) + ); + } + }; + const saveValue = (newValue) => { + props.saveValue(JSON.stringify(newValue)); + }; + const insertMultiValue = (index2) => { + const item = Object.keys(type).reduce((p, c3) => ({ ...p, [c3]: "" }), {}); + props.saveValue( + JSON.stringify([...value.slice(0, index2), item, ...value.slice(index2)]) + ); + }; + const saveMultiValue = (newValue, index2) => { + if (index2 >= value.length) { + props.saveValue(JSON.stringify([...value, newValue])); + return; + } + props.saveValue( + JSON.stringify( + value.map( + (f2, i4) => i4 == index2 ? newValue : f2 + ) + ) + ); + }; + const deleteMultiValue = (index2) => { + props.saveValue( + JSON.stringify( + value.filter((f2, i4) => i4 != index2) + ) + ); + }; + const newKey = (key2) => { + if (key2) + saveValue({ + ...value, + [key2]: "" + }); + }; + const showPropertyMultiMenu = (e5, index2) => { const offset2 = e5.target.getBoundingClientRect(); - const f2 = props.superstate.spaceManager.readTags(); - const addTag2 = async (tag2) => { - const newTag = ensureTag(tag2); - props.saveContexts([ - ...props.contexts.filter((f3) => f3 != newTag), - newTag - ]); - }; - props.superstate.ui.openMenu(offset2, { - ui: props.superstate.ui, - multi: false, - editable: true, - value: [], - options: f2.map((m4) => ({ name: m4, value: m4 })), - saveOptions: (_15, value) => addTag2(value[0]), - placeholder: i18n_default.labels.contextItemSelectPlaceholder, - searchable: true, - showAll: true + const menuOptions = []; + menuOptions.push({ + name: i18n_default.menu.insertAbove, + onClick: (e6) => { + insertMultiValue(index2); + } }); - }; - return /* @__PURE__ */ import_react37.default.createElement(DndContext, { - sensors, - collisionDetection: closestCenter, - measuring: { - droppable: { - strategy: MeasuringStrategy.Always + menuOptions.push({ + name: i18n_default.menu.insertBelow, + onClick: (e6) => { + insertMultiValue(index2 + 1); + } + }); + menuOptions.push(menuSeparator); + if (index2 > 0) + menuOptions.push({ + name: i18n_default.menu.moveUp, + onClick: (e6) => { + props.saveValue( + JSON.stringify( + arrayMove(value, index2, index2 - 1) + ) + ); + } + }); + if (index2 < value.length - 1) + menuOptions.push({ + name: i18n_default.menu.moveDown, + onClick: (e6) => { + props.saveValue( + JSON.stringify( + arrayMove(value, index2, index2 + 1) + ) + ); + } + }); + menuOptions.push(menuSeparator); + menuOptions.push({ + name: i18n_default.buttons.delete, + icon: "ui//trash", + onClick: (e6) => { + deleteMultiValue(index2); } + }); + props.superstate.ui.openMenu( + offset2, + defaultMenu(props.superstate.ui, menuOptions) + ); + }; + const [dragProperty, setDragProperty] = (0, import_react62.useState)(-1); + const [hoverNode, setHoverNode] = (0, import_react62.useState)(-1); + const resetState = () => { + setHoverNode(-1); + setDragProperty(-1); + }; + useDndMonitor({ + onDragStart({ active }) { + if (active.data.current.type == "object") + setDragProperty(active.data.current.id); }, - onDragStart: ({ active }) => { - setActiveId(active.data.current.id); + onDragOver({ active, over }) { + const overId = over?.data.current.id; + if (active.data.current.type == "object") { + if (overId) + setHoverNode(overId); + } }, - onDragOver: ({ active, over }) => { - const overId2 = over?.data.current?.id; - if (overId2) - setOverId(overId2); + onDragCancel() { + resetState(); }, - onDragEnd: ({ active, over }) => { - const overId2 = over?.data.current?.id; - if (!overId2) { + onDragEnd({ active, over }) { + if (!active || hoverNode != -1) { resetState(); return; } - props.setColumnOrder( - arrayMove( - props.colsOrder, - props.colsOrder.findIndex((f2) => f2 == activeId), - props.colsOrder.findIndex((f2) => f2 == overId2) + props.saveValue( + JSON.stringify( + arrayMove(value, dragProperty, hoverNode) ) ); resetState(); - }, - onDragCancel: resetState - }, /* @__PURE__ */ import_react37.default.createElement("div", { - className: "mk-space-editor" - }, /* @__PURE__ */ import_react37.default.createElement("div", { - className: "mk-space-editor-header" - }, /* @__PURE__ */ import_react37.default.createElement("div", { - className: "mk-space-editor-header-title" - }, /* @__PURE__ */ import_react37.default.createElement("div", { - className: "mk-space-editor-title" - }, i18n_default.labels.properties), /* @__PURE__ */ import_react37.default.createElement("div", { - className: "mk-space-editor-description" - }, i18n_default.descriptions.spaceProperties)), /* @__PURE__ */ import_react37.default.createElement("span", null), /* @__PURE__ */ import_react37.default.createElement("button", { - className: "mk-toolbar-button", - dangerouslySetInnerHTML: { - __html: props.superstate.ui.getSticker("ui//combine") - }, - onClick: (e5) => { - newContexts(e5); } - }), /* @__PURE__ */ import_react37.default.createElement("button", { - className: "mk-button-new", - "aria-label": i18n_default.buttons.addItem, - onClick: (e5) => newProperty(e5), - dangerouslySetInnerHTML: { - __html: props.superstate.ui.getSticker("ui//plus") + }); + const menuRef = (0, import_react62.useRef)(); + (0, import_react62.useEffect)(() => { + if (menuRef.current) { + menuRef.current.update(props); } - })), /* @__PURE__ */ import_react37.default.createElement("div", { - className: "mk-space-editor-contents" - }, /* @__PURE__ */ import_react37.default.createElement("div", { - className: "mk-space-editor-context-list" - }, props.contexts.map((f2, i4) => /* @__PURE__ */ import_react37.default.createElement("div", { + }, [props]); + return !props.compactMode ? props.multi ? /* @__PURE__ */ import_react62.default.createElement("div", { + className: "mk-cell-object-multi" + }, value.map((f2, i4) => /* @__PURE__ */ import_react62.default.createElement(ObjectEditor, { key: i4, - className: "mk-props-contexts-space-name", - style: contextProperties[f2].path?.label?.color?.length > 0 ? { - "--tag-background": contextProperties[f2].path?.label?.color, - "--tag-color": "var(--color-white)" - } : {} - }, /* @__PURE__ */ import_react37.default.createElement("div", { - className: `mk-icon-xsmall`, - dangerouslySetInnerHTML: { - __html: props.superstate.ui.getSticker( - contextProperties[f2].path?.label?.sticker - ) + superstate, + value: f2, + compactMode: props.compactMode, + row: props.row, + typeName: parsedValue.typeName, + columns: props.columns, + type, + saveValue: (newValue) => saveMultiValue(newValue, i4), + saveType, + editMode: props.editMode, + draggable: true, + index: i4, + showDragMenu: (e5) => showPropertyMultiMenu(e5, i4) + })), dragProperty != -1 && (0, import_react_dom4.createPortal)( + /* @__PURE__ */ import_react62.default.createElement(DragOverlay, { + dropAnimation: null, + zIndex: 1600 + }, /* @__PURE__ */ import_react62.default.createElement(ObjectEditor, { + superstate, + value: value[dragProperty], + typeName: parsedValue.typeName, + compactMode: props.compactMode, + row: props.row, + columns: props.columns, + type, + saveValue: null, + saveType: null, + editMode: props.editMode, + draggable: false + })), + document.body + )) : /* @__PURE__ */ import_react62.default.createElement(ObjectEditor, { + superstate, + value, + typeName: parsedValue.typeName, + compactMode: props.compactMode, + row: props.row, + columns: props.columns, + type, + saveValue, + saveType, + editMode: props.editMode, + draggable: false + }) : /* @__PURE__ */ import_react62.default.createElement("div", { + className: "mk-cell-object" + }, /* @__PURE__ */ import_react62.default.createElement("div", { + className: "mk-cell-clickable", + onClick: (e5) => { + menuRef.current = superstate.ui.openCustomMenu( + e5.currentTarget.getBoundingClientRect(), + /* @__PURE__ */ import_react62.default.createElement(ObjectEditorModal, { + ...props + }), + props + ); } - }), f2, /* @__PURE__ */ import_react37.default.createElement("div", { - className: "mk-icon-small", + }, /* @__PURE__ */ import_react62.default.createElement("div", { + className: "mk-icon-xsmall", dangerouslySetInnerHTML: { - __html: props.superstate.ui.getSticker("ui//close") - }, - onClick: (e5) => { - props.saveContexts(props.contexts.filter((g) => g != f2)); + __html: props.superstate.ui.getSticker("ui//edit") } - })))), /* @__PURE__ */ import_react37.default.createElement("div", { - className: "mk-space-editor-contents" - }, /* @__PURE__ */ import_react37.default.createElement(SortableContext, { - items, - strategy: verticalListSortingStrategy - }, items.map((value, index2) => { - return /* @__PURE__ */ import_react37.default.createElement(SortableItem, { - key: index2, - id: value.id, - field: value, - superstate: props.superstate, - saveColumn: (field) => props.saveColumn(field, value), - cols: items, - colsHidden: props.colsHidden, - hideColumn: props.hideColumn, - delColumn: props.delColumn - }); - }))), props.contexts.map((f2, i4) => /* @__PURE__ */ import_react37.default.createElement("div", { - key: i4, - className: "mk-property-editor-context" - }, /* @__PURE__ */ import_react37.default.createElement("div", { - className: "mk-property-editor-list" - }, contextProperties[f2]?.cols.filter((f3) => f3.primary != "true").map((g, h3) => /* @__PURE__ */ import_react37.default.createElement(SortableItem, { - key: h3, - id: g.name + "#" + f2, - field: g, - superstate: props.superstate, - saveColumn: (field) => props.saveColumn(field, g), - cols: contextProperties[f2].cols, - colsHidden: props.colsHidden, - hideColumn: props.hideColumn, - delColumn: props.delColumn - }))))))), (0, import_react_dom3.createPortal)( - /* @__PURE__ */ import_react37.default.createElement(DragOverlay, { - adjustScale: false - }, activeId ? /* @__PURE__ */ import_react37.default.createElement(SortableItem, { - id: items.find((f2) => f2.id == activeId).id, - field: items.find((f2) => f2.id == activeId), - superstate: props.superstate, - cols: items, - colsHidden: props.colsHidden - }) : null), - document.body - )); + }), `${i18n_default.menu.edit} ${props.property.name}`)); }; -function SortableItem(props) { - const { spaceInfo } = (0, import_react37.useContext)(SpaceContext); - const { field } = props; - const saveField = (field2, oldField) => { - if (field2.name.length > 0) { - if (field2.name != oldField.name || field2.type != oldField.type || field2.value != oldField.value || field2.attrs != oldField.attrs) { - const saveResult = props.saveColumn(field2, oldField); - } +var ObjectEditorModal = (props) => { + const [value, setValue] = (0, import_react62.useState)(props.initialValue); + const [fieldValue, setFieldValue] = (0, import_react62.useState)(props.property.value); + const saveValue = (value2) => { + setValue(value2); + props.saveValue(value2); + }; + const savePropValue = (propValue, value2) => { + setValue(value2); + setFieldValue(propValue); + props.savePropValue(propValue, value2); + }; + const saveType = (newType, _value) => { + const parsedValue = parseFieldValue(fieldValue, props.property.type); + const newValue = parseObject(value, props.property.type == "object-multi"); + if (props.property.type == "object-multi") { + savePropValue( + JSON.stringify({ ...parsedValue, type: newType }), + JSON.stringify(newValue) + ); + } else { + savePropValue( + JSON.stringify({ ...parsedValue, type: newType }), + JSON.stringify(_value) + ); } }; - const { attributes, listeners, setNodeRef, transform, transition } = useSortable({ id: props.id }); - const style = { - transform: CSS.Transform.toString(transform), - transition + const newProperty = (e5) => { + const offset2 = e5.target.getBoundingClientRect(); + const type = parseFieldValue(fieldValue, props.property.type)?.type; + const _value = parseObject(value, props.property.type == "object-multi"); + showNewPropertyMenu( + props.superstate, + offset2, + [], + [], + (source, field) => { + saveType( + { + ...type ?? {}, + [field.name]: { type: field.type, label: field.name } + }, + { + ..._value, + [field.name]: "" + } + ); + }, + null, + null, + true, + false + ); }; - const icon = stickerForField(props.field); - const selectedType = (_15, value) => { - const newField = { - ...props.field, - type: value[0] - }; - props.saveColumn(newField); + const insertMultiValue = (index2) => { + const val = parseObject(value, props.property.type == "object-multi"); + const type = parseFieldValue(fieldValue, props.property.type)?.type; + const item = Object.keys(type).reduce((p, c3) => ({ ...p, [c3]: "" }), {}); + saveValue( + JSON.stringify([...val.slice(0, index2), item, ...val.slice(index2)]) + ); }; - return /* @__PURE__ */ import_react37.default.createElement("div", { - className: "mk-property-editor-property", - ref: setNodeRef, - style, - ...attributes, - ...listeners - }, /* @__PURE__ */ import_react37.default.createElement("div", { - className: "mk-path-context-field-icon", + return /* @__PURE__ */ import_react62.default.createElement("div", { + className: "mk-editor-frame-properties" + }, /* @__PURE__ */ import_react62.default.createElement("div", { + className: "mk-editor-actions-name" + }, /* @__PURE__ */ import_react62.default.createElement("div", { + className: "mk-editor-actions-name-icon" + }, /* @__PURE__ */ import_react62.default.createElement("div", { + className: "mk-icon-small", dangerouslySetInnerHTML: { - __html: props.superstate.ui.getSticker(icon) - }, - onClick: (e5) => { - selectPropertyTypeMenu(e5, props.superstate.ui, selectedType); + __html: props.superstate.ui.getSticker("ui//list") } - }), props.field.name, /* @__PURE__ */ import_react37.default.createElement("span", null), /* @__PURE__ */ import_react37.default.createElement("div", { - className: "mk-icon-small", + })), /* @__PURE__ */ import_react62.default.createElement("div", { + className: "mk-editor-actions-name-text" + }, i18n_default.labels.editObject), /* @__PURE__ */ import_react62.default.createElement("span", null), /* @__PURE__ */ import_react62.default.createElement("div", { + className: "mk-icon-small mk-inline-button", dangerouslySetInnerHTML: { - __html: props.superstate.ui.getSticker("ui//options") + __html: props.superstate.ui.getSticker("ui//close") }, - onClick: (e5) => { - const offset2 = e5.target.getBoundingClientRect(); - showPropertyMenu({ - superstate: props.superstate, - rect: offset2, - editable: true, - options: [], - field, - fields: props.cols, - contextPath: spaceInfo?.path, - saveField: (newField) => saveField(newField, field), - hide: props.hideColumn, - deleteColumn: props.delColumn, - hidden: props.colsHidden.includes(field.name + field.table) - }); + onClick: () => props.hide() + })), /* @__PURE__ */ import_react62.default.createElement(ObjectCell, { + ...props, + initialValue: value, + compactMode: false, + propertyValue: fieldValue, + saveValue: (v2) => { + saveValue(v2); + }, + savePropValue: (v2, p) => { + savePropValue(v2, p); + }, + editMode: 5 /* EditModeAlways */ + }), /* @__PURE__ */ import_react62.default.createElement("div", { + className: "mk-cell-object-options" + }, /* @__PURE__ */ import_react62.default.createElement("button", { + onClick: (e5) => newProperty(e5), + className: "mk-inline-button" + }, /* @__PURE__ */ import_react62.default.createElement("div", { + className: "mk-icon-xsmall", + dangerouslySetInnerHTML: { + __html: props.superstate.ui.getSticker("ui//plus") } - })); -} - -// src/core/react/components/UI/Modals/ContextEditor.tsx -var import_react55 = __toESM(require_react()); - -// src/core/react/components/SpaceEditor/SpaceEditor.tsx -var import_react54 = __toESM(require_react()); - -// src/core/utils/contexts/embed.ts -var framePathForSpace = (space2, schema) => { - if (space2.type == "folder") { - return `${space2.path}/#*${schema}`; - } - if (space2.type == "vault") { - return `/#*${schema}`; - } - return `${space2.path}/#*${schema}`; -}; -var actionPathForSpace = (space2, schema) => { - if (space2.type == "folder") { - return `${space2.path}/#;${schema}`; - } - if (space2.type == "vault") { - return `/#;${schema}`; - } - return `${space2.path}/#;${schema}`; -}; -var contextPathForSpace = (space2, schema) => { - if (space2.type == "folder") { - return `${space2.path}/#^${schema}`; - } - if (space2.type == "vault") { - return `/#^${schema}`; - } - return `${space2.path}/#^${schema}`; + }), i18n_default.labels.propertyFileProp), props.property.type == "object-multi" && /* @__PURE__ */ import_react62.default.createElement("button", { + onClick: (e5) => insertMultiValue(0), + className: "mk-inline-button" + }, /* @__PURE__ */ import_react62.default.createElement("div", { + className: "mk-icon-xsmall", + dangerouslySetInnerHTML: { + __html: props.superstate.ui.getSticker("ui//insert") + } + }), "Object"))); }; -var contextViewEmbedStringFromContext = (space2, schema) => `![![${framePathForSpace(space2, schema)}]]`; -var contextEmbedStringFromContext = (space2, schema) => `![![${contextPathForSpace(space2, schema)}]]`; -// src/core/react/components/SpaceEditor/ActionsList.tsx -var import_react38 = __toESM(require_react()); -var ActionsList = (props) => { - const { pathState } = (0, import_react38.useContext)(PathContext); - const { spaceState } = (0, import_react38.useContext)(SpaceContext); - const [actions, setActions] = import_react38.default.useState([]); - (0, import_react38.useEffect)(() => { - refreshData({ path: pathState.path }); - }, []); - const refreshData = (payload) => { - if (payload.path == pathState?.path) - props.superstate.spaceManager.commandsForSpace(pathState.path).then((f2) => setActions(f2)); - }; - (0, import_react38.useEffect)(() => { - props.superstate.eventsDispatcher.addListener( - "actionStateUpdated", - refreshData - ); - return () => { - props.superstate.eventsDispatcher.removeListener( - "actionStateUpdated", - refreshData - ); - }; - }, [pathState]); - const newAction = (e5) => { - props.superstate.ui.openModal( - i18n_default.labels.newAction, - (_props) => /* @__PURE__ */ import_react38.default.createElement(InputModal, { - value: "", - saveLabel: i18n_default.buttons.save, - hide: _props.hide, - saveValue: (value) => { - props.superstate.spaceManager.createCommand(spaceState.path, { - id: value, - name: value, - type: "actions" - }); - } - }) +// src/core/react/components/SpaceView/Contexts/DataTypeView/PathCell.tsx +var import_react63 = __toESM(require_react()); +var PathCell = (props) => { + const fileOrCleanPath = (f2) => { + if (!f2) + return { + path: "" + }; + const resolvedPath = props.superstate.spaceManager.resolvePath( + f2, + props.folder ); + const pathState = props.superstate.pathsIndex.get(resolvedPath); + return pathState ? { path: f2, pathState } : { path: f2 }; }; - return /* @__PURE__ */ import_react38.default.createElement("div", { - className: "mk-space-editor" - }, /* @__PURE__ */ import_react38.default.createElement("div", { - className: "mk-space-editor-header" - }, /* @__PURE__ */ import_react38.default.createElement("div", { - className: "mk-space-editor-header-title" - }, /* @__PURE__ */ import_react38.default.createElement("div", { - className: "mk-space-editor-title" - }, i18n_default.subViews.spaceActions), /* @__PURE__ */ import_react38.default.createElement("div", { - className: "mk-space-editor-description" - }, i18n_default.descriptions.spaceActions)), /* @__PURE__ */ import_react38.default.createElement("span", null), /* @__PURE__ */ import_react38.default.createElement("button", { - className: "mk-button-new", - "aria-label": i18n_default.labels.newAction, - onClick: (e5) => newAction(e5), - dangerouslySetInnerHTML: { - __html: props.superstate.ui.getSticker("ui//plus") + const value = (0, import_react63.useMemo)( + () => (props.multi ? parseMultiString(props.initialValue) ?? [] : [props.initialValue]).map((f2) => fileOrCleanPath(f2)), + [props.initialValue] + ); + const ref2 = (0, import_react63.useRef)(null); + const onKeyDown = (e5) => { + e5.stopPropagation(); + e5.key == "Enter" && e5.target.blur(); + }; + const pathExists = async (name317) => { + if (!name317) + return false; + return await props.superstate.spaceManager.pathExists(name317) ? true : false; + }; + const onBlur = async () => { + if (!ref2.current) + return; + if (await pathExists(ref2.current?.value)) { + props.superstate.ui.notify(i18n_default.notice.fileExists); + } else { + props.saveValue(ref2.current.value); + props.setEditMode(null); } - })), /* @__PURE__ */ import_react38.default.createElement("div", { - className: "mk-space-editor-contents" - }, actions.map((f2, i4) => /* @__PURE__ */ import_react38.default.createElement("div", { - key: i4, - className: "mk-action" - }, /* @__PURE__ */ import_react38.default.createElement("div", { - className: "mk-path" - }, /* @__PURE__ */ import_react38.default.createElement("div", { - className: "mk-path-icon", - dangerouslySetInnerHTML: { - __html: props.superstate.ui.getSticker( - stickerForSchema(f2.schema) - ) + }; + const newPath = async (file) => { + const pathName = file.path.replace(/\//g, "").replace(/\./g, ""); + const path2 = `${props.folder}/${pathName}.md`; + if (pathName.length == 0) { + return; } - }), /* @__PURE__ */ import_react38.default.createElement("div", { - onClick: (e5) => { - props.superstate.ui.openPath( - actionPathForSpace(spaceState, f2.schema.id), - e5.metaKey + if (await pathExists(path2)) { + props.superstate.ui.notify(i18n_default.notice.fileExists); + } else { + await props.superstate.spaceManager.createItemAtPath( + props.folder, + "md", + pathName ); - props.close(); } - }, f2.schema.name)), /* @__PURE__ */ import_react38.default.createElement("span", null), /* @__PURE__ */ import_react38.default.createElement("button", { - className: "mk-toolbar-button", - onClick: () => props.superstate.cli.runCommand( - actionPathForSpace(spaceState, f2.schema.id), - { iterations: 0, instanceProps: {}, props: {} } - ), - dangerouslySetInnerHTML: { - __html: props.superstate.ui.getSticker("lucide//play") + }; + const deleteRow = () => { + props.deleteRow(); + }; + (0, import_react63.useEffect)(() => { + if (props.editMode == 4 /* EditModeActive */) { + ref2?.current?.focus(); } - }), /* @__PURE__ */ import_react38.default.createElement("button", { - className: "mk-toolbar-button", - onClick: () => props.superstate.spaceManager.deleteCommand( - spaceState.path, - f2.schema.id - ), - dangerouslySetInnerHTML: { - __html: props.superstate.ui.getSticker("ui//trash") + }, [props.editMode]); + return /* @__PURE__ */ import_react63.default.createElement("div", { + className: "mk-cell-file" + }, value.map((v2, i4) => { + if (props.editMode == 0 /* EditModeReadOnly */) { + if (v2.pathState) { + return /* @__PURE__ */ import_react63.default.createElement("div", { + key: i4, + className: "mk-cell-file-title" + }, v2 && v2.pathState ? v2.pathState.name : "", v2.pathState.type == "file" && v2.pathState.subtype != "md" && /* @__PURE__ */ import_react63.default.createElement("span", { + className: "nav-file-tag" + }, v2.pathState.metadata.file.extension), /* @__PURE__ */ import_react63.default.createElement("button", { + "aria-label": i18n_default.buttons.toggleFlow, + className: "mk-cell-file-flow mk-inline-button", + dangerouslySetInnerHTML: { + __html: props.superstate.ui.getSticker("ui//flow-hover") + }, + onClick: (e5) => { + if (props.openFlow) { + props.openFlow(e5); + e5.stopPropagation(); + } + } + })); + } else { + return /* @__PURE__ */ import_react63.default.createElement("div", { + key: i4, + className: "mk-cell-file-title" + }, v2.path); + } } - }))))); + if (v2.pathState) { + return /* @__PURE__ */ import_react63.default.createElement("div", { + className: "mk-cell-file-item", + key: i4 + }, /* @__PURE__ */ import_react63.default.createElement(PathCrumb, { + superstate: props.superstate, + path: v2.pathState.path + })); + } + return /* @__PURE__ */ import_react63.default.createElement("div", { + className: "mk-cell-file-item", + key: i4 + }, /* @__PURE__ */ import_react63.default.createElement("div", { + className: "mk-path-icon" + }, /* @__PURE__ */ import_react63.default.createElement("button", { + onClick: (e5) => newPath(v2), + dangerouslySetInnerHTML: { + __html: props.superstate.ui.getSticker("ui//new-file") + } + })), props.editMode > 2 /* EditModeView */ ? /* @__PURE__ */ import_react63.default.createElement("input", { + className: "mk-cell-file-name", + type: "text", + placeholder: i18n_default.buttons.newNote, + ref: ref2, + defaultValue: v2.path, + onKeyDown, + onBlur + }) : /* @__PURE__ */ import_react63.default.createElement("div", { + className: "mk-cell-file-name" + }, v2.path)); + })); }; -// src/core/react/components/UI/Menus/properties/linkMenu.tsx -var showLinkMenu = (e5, superstate, saveLink, options) => { - const offset2 = e5.target.getBoundingClientRect(); - const suggestions = [...superstate.pathsIndex.values()].filter((f2) => !f2.hidden).map((f2) => ({ - name: f2.displayName, - value: f2.path, - description: f2.path, - icon: f2.label?.sticker - })); - e5.stopPropagation(); - return superstate.ui.openMenu(offset2, { - ui: superstate.ui, +// src/core/react/components/SpaceView/Contexts/DataTypeView/PropertySelectCell.tsx +var import_react64 = __toESM(require_react()); +var PropertySelectCell = (props) => { + const [value, setValue] = (0, import_react64.useState)( + parseLinkedPropertyToValue(props.initialValue) + ); + const saveOptions = (_15, _value) => { + setValue(parseLinkedPropertyToValue(_value[0])); + props.saveValue(_value[0]); + }; + const menuProps = () => { + const options = (props.columns ?? []).map((f2) => ({ + name: f2.name, + description: f2.table, + value: f2.table == "" ? `$root['props']['${f2.name}']` : `$contexts['${f2.table}']['${f2.name}']` + })); + return { + ui: props.superstate.ui, + multi: false, + editable: true, + value: value ? [value] : [], + options, + saveOptions, + placeholder: i18n_default.labels.linkItemSelectPlaceholder, + detail: true, + searchable: true + }; + }; + return /* @__PURE__ */ import_react64.default.createElement(OptionCellBase, { + superstate: props.superstate, + removeValue: null, + baseClass: "mk-cell-link", + selectLabel: props.compactMode ? props.property.name : i18n_default.labels.select, + menuProps, + labelElement: (_props) => /* @__PURE__ */ import_react64.default.createElement("div", null, _props.value), + value: value ? [value] : [], + multi: false, + editMode: props.editMode + }); +}; + +// src/core/react/components/SpaceView/Contexts/DataTypeView/SpaceCell.tsx +var import_react65 = __toESM(require_react()); +var SpaceCell = (props) => { + const openLink = async () => { + props.superstate.ui.openPath(props.initialValue, false); + }; + const menuRef = (0, import_react65.useRef)(null); + const spaceObject = contextPathFromPath(props.superstate, props.initialValue); + const ref2 = (0, import_react65.useRef)(null); + const menuProps = () => ({ multi: false, + ui: props.superstate.ui, editable: true, - value: [], - options: suggestions, - saveOptions: (_15, value) => { - saveLink(value[0]); + value: [props.initialValue], + options: props.superstate.allSpaces().map((f2) => ({ + name: f2.name, + value: f2.path, + description: f2.name + })), + saveOptions: (_15, value) => props.saveValue(value[0]), + removeOption: () => { }, - placeholder: i18n_default.labels.linkItemSelectPlaceholder, - detail: true, + placeholder: i18n_default.labels.optionItemSelectPlaceholder, searchable: true, showAll: true, - ...options ?? {} + onHide: () => props.setEditMode(null) + }); + const menuSchemaProps = () => ({ + multi: false, + ui: props.superstate.ui, + editable: true, + value: [spaceObject.schema], + options: props.superstate.contextsIndex.get(spaceObject.space).schemas.map((f2) => ({ + name: f2.name, + value: f2.id, + description: f2.name + })), + saveOptions: (_15, value) => props.saveValue(`${spaceObject?.space}/#^${value[0]}`), + removeOption: () => { + }, + placeholder: i18n_default.labels.optionItemSelectPlaceholder, + searchable: true, + showAll: true, + onHide: () => props.setEditMode(null) }); + const showMenu2 = () => { + const offset2 = ref2.current.getBoundingClientRect(); + menuRef.current = props.superstate.ui.openMenu(offset2, menuProps()); + }; + const showSchemaMenu = () => { + const offset2 = ref2.current.getBoundingClientRect(); + menuRef.current = props.superstate.ui.openMenu(offset2, menuSchemaProps()); + }; + return /* @__PURE__ */ import_react65.default.createElement("div", { + ref: ref2, + className: "mk-cell-space" + }, /* @__PURE__ */ import_react65.default.createElement("div", { + className: "mk-cell-option-item" + }, /* @__PURE__ */ import_react65.default.createElement("div", { + onClick: () => openLink() + }, spaceObject?.space), props.editMode > 2 /* EditModeView */ && /* @__PURE__ */ import_react65.default.createElement(import_react65.default.Fragment, null, /* @__PURE__ */ import_react65.default.createElement("span", null), /* @__PURE__ */ import_react65.default.createElement("div", { + onClick: (e5) => showMenu2(), + className: "mk-cell-option-select mk-icon-xxsmall mk-icon-rotated", + dangerouslySetInnerHTML: { + __html: props.superstate.ui.getSticker("ui//collapse-solid") + } + }))), props.isTable && /* @__PURE__ */ import_react65.default.createElement("div", { + className: "mk-cell-option-item" + }, /* @__PURE__ */ import_react65.default.createElement("div", { + onClick: () => openLink() + }, spaceObject?.schemaName), spaceObject?.space && /* @__PURE__ */ import_react65.default.createElement("div", { + onClick: (e5) => showSchemaMenu(), + className: "mk-cell-option-select mk-icon-xxsmall mk-icon-rotated", + dangerouslySetInnerHTML: { + __html: props.superstate.ui.getSticker("ui//collapse-solid") + } + }))); }; -// src/core/react/components/SpaceEditor/SpaceItems.tsx -var import_react50 = __toESM(require_react()); - -// src/core/react/components/UI/Crumbs/PathCrumb.tsx -var import_react40 = __toESM(require_react()); +// src/core/react/components/SpaceView/Contexts/DataTypeView/SuperCell.tsx +var import_react67 = __toESM(require_react()); -// src/core/react/components/UI/Stickers/PathSticker/PathSticker.tsx -var import_react39 = __toESM(require_react()); -var PathStickerView = (props) => { - const { pathState } = props; - const sticker = pathState?.label?.sticker; - const color2 = pathState?.label?.color; - const extension = pathState?.type; - const triggerStickerContextMenu = (e5) => { - if (!pathState) - return; - e5.preventDefault(); - const menuOptions = []; - menuOptions.push({ - name: i18n_default.buttons.changeIcon, - icon: "ui//sticker", - onClick: () => { - props.superstate.ui.openPalette((_props) => /* @__PURE__ */ import_react39.default.createElement(StickerModal_default, { - ui: props.superstate.ui, - hide: _props.hide, - selectedSticker: (emoji) => savePathSticker(props.superstate, pathState?.path, emoji) - })); - } - }); - menuOptions.push({ - name: i18n_default.buttons.removeIcon, - icon: "ui//file-minus", - onClick: () => { - removeIconsForPaths(props.superstate, [pathState.path]); - } - }); - props.superstate.ui.openMenu( - e5.target.getBoundingClientRect(), - defaultMenu(props.superstate.ui, menuOptions) - ); - return false; +// src/core/react/components/SpaceView/Contexts/DataTypeView/SuperCell/ParameterSetter.tsx +var import_react66 = __toESM(require_react()); +var ParameterSetter = (props) => { + const [value, setValue] = (0, import_react66.useState)(props.value); + const saveValue = (key2, val) => { + setValue({ ...value, [key2]: val }); + props.saveValue(key2, val); }; - const triggerStickerMenu = (e5) => { - if (pathState?.type == "space") { - props.superstate.ui.openPalette((_props) => /* @__PURE__ */ import_react39.default.createElement(StickerModal_default, { - ui: props.superstate.ui, - hide: _props.hide, - selectedSticker: (emoji) => savePathSticker(props.superstate, pathState.path, emoji) - })); - return; - } - props.superstate.ui.openPalette((_props) => /* @__PURE__ */ import_react39.default.createElement(StickerModal_default, { - ui: props.superstate.ui, - hide: _props.hide, - selectedSticker: (emoji) => savePathSticker(props.superstate, pathState.path, emoji) - })); + const stackedProperty = (field) => { + return field.type.startsWith("object") || field.type == "super"; }; - const [stickerType, stickerPath] = parseStickerString(sticker); - return /* @__PURE__ */ import_react39.default.createElement("div", { - className: `mk-path-icon ${sticker ? "" : "mk-path-icon-placeholder"}` - }, stickerType == "image" ? /* @__PURE__ */ import_react39.default.createElement("img", { - src: props.superstate.ui.getUIPath( - props.superstate.imagesCache.get(stickerPath) - ) - }) : /* @__PURE__ */ import_react39.default.createElement("button", { - "aria-label": i18n_default.buttons.changeIcon, - onContextMenu: triggerStickerContextMenu, - style: color2?.length > 0 ? { - "--label-color": `${color2}`, - "--icon-color": `#ffffff` - } : { - "--icon-color": `var(--mk-ui-text-secondary)` - }, - dangerouslySetInnerHTML: { - __html: props.superstate.ui.getSticker(sticker) - }, - onClick: (e5) => props.editable && triggerStickerMenu(e5) + return /* @__PURE__ */ import_react66.default.createElement("div", { + className: "mk-cell-object" + }, props.command.fields.map((field, i4) => { + const isStacked = stackedProperty(field); + return /* @__PURE__ */ import_react66.default.createElement(DataPropertyView, { + key: i4, + superstate: props.superstate, + initialValue: !field.type.startsWith("object") ? removeQuotes(value?.[field.name]) : value?.[field.name], + compactMode: false, + updateFieldValue: (fv, f2) => { + saveValue( + field.name, + !field.type.startsWith("object") ? wrapQuotes(f2) : f2 + ); + }, + updateValue: (value2) => { + saveValue( + field.name, + !field.type.startsWith("object") ? wrapQuotes(value2) : value2 + ); + }, + column: { ...field, table: "" }, + editMode: 5 /* EditModeAlways */, + columns: props.command.fields + }); })); }; -var PathStickerContainer = (props) => { - const [cache2, setCache] = (0, import_react39.useState)(null); - const reloadCache = () => { - setCache(props.superstate.pathsIndex.get(props.path)); - }; - const reloadIcon = (payload) => { - if (payload.path == props.path) { - reloadCache(); + +// src/core/react/components/SpaceView/Contexts/DataTypeView/SuperCell.tsx +var SuperCell = (props) => { + const command = (0, import_react67.useMemo)(() => { + const parsedValue = parseFieldValue( + props.propertyValue, + "super", + props.superstate + ); + const superPropertyName = parsedValue.dynamic ? props.row?.[parsedValue.field] : parsedValue.field; + return props.superstate.cli.commandForAction(superPropertyName); + }, [props.propertyValue, props.row]); + const parseValue = (value2) => { + if (!value2) + return null; + let parsedValue; + try { + parsedValue = JSON.parse(value2); + parsedValue = Object.keys(parsedValue).reduce((p, c3) => { + if (typeof parsedValue[c3] === "object") { + return { ...p, [c3]: JSON.stringify(parsedValue[c3]) }; + } + if (typeof parsedValue[c3] === "string") { + return { ...p, [c3]: wrapQuotes(parsedValue[c3]) }; + } + return { ...p, [c3]: parsedValue[c3] }; + }, {}); + } catch (e5) { + console.log(e5); + return null; } + return parsedValue; }; - (0, import_react39.useEffect)(() => { - reloadCache(); - props.superstate.eventsDispatcher.addListener( - "pathStateUpdated", - reloadIcon + const [value, setValue] = (0, import_react67.useState)( + parseValue(unwrapParanthesis(props.initialValue)) + ); + (0, import_react67.useEffect)(() => { + setValue(parseValue(unwrapParanthesis(props.initialValue))); + }, [props.initialValue]); + const specialStringify = (obj) => { + return `{${Object.keys(obj ?? {}).map((key2) => `"${key2}": ${obj[key2]}`).join(",")}}`; + }; + const saveValue = (key2, val) => { + setValue({ ...value, [key2]: val }); + const newValue = wrapParanthesis( + specialStringify({ ...value, [key2]: val }) ); - return () => { - props.superstate.eventsDispatcher.removeListener( - "pathStateUpdated", - reloadIcon - ); + props.saveValue(newValue); + }; + const editParameters = (e5) => { + const rect = e5.currentTarget.getBoundingClientRect(); + const _props = { + superstate: props.superstate, + command, + value, + saveValue }; - }, [props.path]); - return cache2 ? /* @__PURE__ */ import_react39.default.createElement(PathStickerView, { + props.superstate.ui.openCustomMenu( + rect, + /* @__PURE__ */ import_react67.default.createElement(ParameterSetter, { + ..._props + }), + _props, + "bottom" + ); + }; + return /* @__PURE__ */ import_react67.default.createElement(import_react67.default.Fragment, null, command && (props.compactMode ? /* @__PURE__ */ import_react67.default.createElement("div", { + className: "mk-cell-super", + onClick: (e5) => editParameters(e5) + }, "Edit Parameters") : /* @__PURE__ */ import_react67.default.createElement(ParameterSetter, { superstate: props.superstate, - pathState: cache2, - editable: true - }) : /* @__PURE__ */ import_react39.default.createElement(import_react39.default.Fragment, null); + command, + value, + saveValue + }))); }; -// src/core/react/components/UI/Crumbs/PathCrumb.tsx -var PathCrumb = (props) => { - const path2 = (0, import_react40.useMemo)( - () => props.source && props.path ? props.superstate.spaceManager.resolvePath(props.path, props.source) : props.path, - [props.source, props.path] - ); - const [cache2, setCache] = (0, import_react40.useState)( - props.superstate.pathsIndex.get(path2) - ); - const reloadCache = () => { - setCache(props.superstate.pathsIndex.get(path2)); - }; - const reloadIcon = (payload) => { - if (payload.path == path2) { - reloadCache(); - } - }; - (0, import_react40.useEffect)(() => { +// src/core/react/components/SpaceView/Contexts/DataTypeView/TagCell.tsx +var import_react68 = __toESM(require_react()); +var TagCell = (props) => { + const [value, setValue] = (0, import_react68.useState)([]); + (0, import_react68.useEffect)(() => { + setValue([...props.superstate.tagsMap.get(props.path) ?? []]); + }, []); + (0, import_react68.useEffect)(() => { + const updateValue2 = (payload) => { + if (payload.path == props.path) + setValue([...props.superstate.tagsMap.get(props.path) ?? []]); + }; props.superstate.eventsDispatcher.addListener( "pathStateUpdated", - reloadIcon + updateValue2 ); - reloadCache(); return () => { props.superstate.eventsDispatcher.removeListener( "pathStateUpdated", - reloadIcon + updateValue2 ); }; - }, [path2]); - return /* @__PURE__ */ import_react40.default.createElement("div", { - className: "mk-path", - "aria-label": path2, - onClick: () => props.superstate.ui.openPath(cache2?.path ?? path2, false), - onContextMenu: (e5) => cache2 && showPathContextMenu(props.superstate, cache2.path, null, { - x: e5.clientX, - y: e5.clientY, - width: 0, - height: 0 - }) - }, cache2 && /* @__PURE__ */ import_react40.default.createElement(PathStickerView, { + }, [props.path]); + const removeValue = (v2) => { + deleteTagFromPath(props.superstate, props.path, v2); + }; + const saveOptions = (_options, _value) => { + const newValue = _value[0]; + addTagToPath(props.superstate, props.path, newValue); + }; + const menuProps = () => { + const options = props.superstate.spaceManager.readTags().map((f2) => ({ + name: f2, + value: f2 + })); + return { + ui: props.superstate.ui, + multi: false, + editable: true, + value, + options, + saveOptions, + placeholder: i18n_default.labels.tagItemSelectPlaceholder, + searchable: true, + showAll: true, + onHide: () => props.setEditMode(null) + }; + }; + return /* @__PURE__ */ import_react68.default.createElement(OptionCellBase, { superstate: props.superstate, - pathState: cache2 - }), /* @__PURE__ */ import_react40.default.createElement("span", null, (!props.hideName && cache2?.displayName) ?? path2), props.children); + baseClass: "mk-cell-tags", + removeValue, + menuProps, + selectLabel: props.compactMode ? props.property.name : i18n_default.labels.select, + value, + multi: true, + editMode: props.editMode, + labelElement: (_props) => /* @__PURE__ */ import_react68.default.createElement("div", { + className: "mk-cell-tags-label" + }, _props.value, _props.children) + }); }; -// src/core/react/components/UI/Menus/properties/datePickerMenu.tsx -var import_react42 = __toESM(require_react()); - -// node_modules/react-day-picker/dist/index.esm.js -var import_react41 = __toESM(require_react()); -var __assign = function() { - __assign = Object.assign || function __assign4(t5) { - for (var s4, i4 = 1, n3 = arguments.length; i4 < n3; i4++) { - s4 = arguments[i4]; - for (var p in s4) - if (Object.prototype.hasOwnProperty.call(s4, p)) - t5[p] = s4[p]; - } - return t5; +// src/core/react/components/SpaceView/Contexts/DataTypeView/TextCell.tsx +var import_react69 = __toESM(require_react()); +var TextCell = (props) => { + const { initialValue, saveValue } = props; + const ref2 = (0, import_react69.useRef)(null); + const onBlur = (e5) => { + const value = e5.currentTarget.innerText; + if (initialValue != value) + saveValue(value); }; - return __assign.apply(this, arguments); -}; -function __rest(s4, e5) { - var t5 = {}; - for (var p in s4) - if (Object.prototype.hasOwnProperty.call(s4, p) && e5.indexOf(p) < 0) - t5[p] = s4[p]; - if (s4 != null && typeof Object.getOwnPropertySymbols === "function") - for (var i4 = 0, p = Object.getOwnPropertySymbols(s4); i4 < p.length; i4++) { - if (e5.indexOf(p[i4]) < 0 && Object.prototype.propertyIsEnumerable.call(s4, p[i4])) - t5[p[i4]] = s4[p[i4]]; + const onKeyDown = (e5) => { + e5.stopPropagation(); + if (e5.key == "Enter") { + if (!e5.shiftKey) { + e5.target.blur(); + props.setEditMode(null); + } } - return t5; -} -function __spreadArray(to2, from, pack) { - if (pack || arguments.length === 2) - for (var i4 = 0, l2 = from.length, ar; i4 < l2; i4++) { - if (ar || !(i4 in from)) { - if (!ar) - ar = Array.prototype.slice.call(from, 0, i4); - ar[i4] = from[i4]; + if (e5.key == "Escape") { + ref2.current.innerText = initialValue; + e5.target.blur(); + props.setEditMode(null); + } + }; + (0, import_react69.useEffect)(() => { + if (props.editMode == 4 /* EditModeActive */) { + if (ref2?.current) { + const sel = window.getSelection(); + sel.selectAllChildren(ref2.current); + sel.collapseToEnd(); } } - return to2.concat(ar || Array.prototype.slice.call(from)); -} -var jsxRuntime = { exports: {} }; -var reactJsxRuntime_production_min = {}; -var hasRequiredReactJsxRuntime_production_min; -function requireReactJsxRuntime_production_min() { - if (hasRequiredReactJsxRuntime_production_min) - return reactJsxRuntime_production_min; - hasRequiredReactJsxRuntime_production_min = 1; - var f2 = import_react41.default, k2 = Symbol.for("react.element"), l2 = Symbol.for("react.fragment"), m4 = Object.prototype.hasOwnProperty, n3 = f2.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.ReactCurrentOwner, p = { key: true, ref: true, __self: true, __source: true }; - function q2(c3, a4, g) { - var b2, d4 = {}, e5 = null, h3 = null; - void 0 !== g && (e5 = "" + g); - void 0 !== a4.key && (e5 = "" + a4.key); - void 0 !== a4.ref && (h3 = a4.ref); - for (b2 in a4) - m4.call(a4, b2) && !p.hasOwnProperty(b2) && (d4[b2] = a4[b2]); - if (c3 && c3.defaultProps) - for (b2 in a4 = c3.defaultProps, a4) - void 0 === d4[b2] && (d4[b2] = a4[b2]); - return { $$typeof: k2, type: c3, key: e5, ref: h3, props: d4, _owner: n3.current }; - } - reactJsxRuntime_production_min.Fragment = l2; - reactJsxRuntime_production_min.jsx = q2; - reactJsxRuntime_production_min.jsxs = q2; - return reactJsxRuntime_production_min; -} -if (true) { - jsxRuntime.exports = requireReactJsxRuntime_production_min(); -} else { - jsxRuntime.exports = requireReactJsxRuntime_development(); -} -var jsxRuntimeExports = jsxRuntime.exports; -function isDayPickerMultiple(props) { - return props.mode === "multiple"; -} -function isDayPickerRange(props) { - return props.mode === "range"; -} -function isDayPickerSingle(props) { - return props.mode === "single"; -} -var defaultClassNames = { - root: "rdp", - multiple_months: "rdp-multiple_months", - with_weeknumber: "rdp-with_weeknumber", - vhidden: "rdp-vhidden", - button_reset: "rdp-button_reset", - button: "rdp-button", - caption: "rdp-caption", - caption_start: "rdp-caption_start", - caption_end: "rdp-caption_end", - caption_between: "rdp-caption_between", - caption_label: "rdp-caption_label", - caption_dropdowns: "rdp-caption_dropdowns", - dropdown: "rdp-dropdown", - dropdown_month: "rdp-dropdown_month", - dropdown_year: "rdp-dropdown_year", - dropdown_icon: "rdp-dropdown_icon", - months: "rdp-months", - month: "rdp-month", - table: "rdp-table", - tbody: "rdp-tbody", - tfoot: "rdp-tfoot", - head: "rdp-head", - head_row: "rdp-head_row", - head_cell: "rdp-head_cell", - nav: "rdp-nav", - nav_button: "rdp-nav_button", - nav_button_previous: "rdp-nav_button_previous", - nav_button_next: "rdp-nav_button_next", - nav_icon: "rdp-nav_icon", - row: "rdp-row", - weeknumber: "rdp-weeknumber", - cell: "rdp-cell", - day: "rdp-day", - day_today: "rdp-day_today", - day_outside: "rdp-day_outside", - day_selected: "rdp-day_selected", - day_disabled: "rdp-day_disabled", - day_hidden: "rdp-day_hidden", - day_range_start: "rdp-day_range_start", - day_range_end: "rdp-day_range_end", - day_range_middle: "rdp-day_range_middle" -}; -function formatCaption(month, options) { - return format(month, "LLLL y", options); -} -function formatDay(day, options) { - return format(day, "d", options); -} -function formatMonthCaption(month, options) { - return format(month, "LLLL", options); -} -function formatWeekNumber(weekNumber) { - return "".concat(weekNumber); -} -function formatWeekdayName(weekday, options) { - return format(weekday, "cccccc", options); -} -function formatYearCaption(year, options) { - return format(year, "yyyy", options); -} -var formatters3 = /* @__PURE__ */ Object.freeze({ - __proto__: null, - formatCaption, - formatDay, - formatMonthCaption, - formatWeekNumber, - formatWeekdayName, - formatYearCaption -}); -var labelDay = function(day, activeModifiers, options) { - return format(day, "do MMMM (EEEE)", options); -}; -var labelMonthDropdown = function() { - return "Month: "; -}; -var labelNext = function() { - return "Go to next month"; -}; -var labelPrevious = function() { - return "Go to previous month"; -}; -var labelWeekday = function(day, options) { - return format(day, "cccc", options); -}; -var labelWeekNumber = function(n3) { - return "Week n. ".concat(n3); -}; -var labelYearDropdown = function() { - return "Year: "; + }, [props.editMode]); + return props.editMode > 2 /* EditModeView */ ? /* @__PURE__ */ import_react69.default.createElement("div", { + onClick: (e5) => e5.stopPropagation(), + className: "mk-cell-text", + ref: ref2, + "data-ph": props.compactMode ? props.property.name : "Empty", + onKeyDown, + onBlur, + contentEditable: true, + dangerouslySetInnerHTML: { __html: initialValue } + }) : /* @__PURE__ */ import_react69.default.createElement("div", { + className: "mk-cell-text" + }, initialValue); }; -var labels = /* @__PURE__ */ Object.freeze({ - __proto__: null, - labelDay, - labelMonthDropdown, - labelNext, - labelPrevious, - labelWeekNumber, - labelWeekday, - labelYearDropdown -}); -function getDefaultContextValues() { - var captionLayout = "buttons"; - var classNames13 = defaultClassNames; - var locale2 = en_US_default; - var modifiersClassNames = {}; - var modifiers = {}; - var numberOfMonths = 1; - var styles2 = {}; - var today = new Date(); - return { - captionLayout, - classNames: classNames13, - formatters: formatters3, - labels, - locale: locale2, - modifiersClassNames, - modifiers, - numberOfMonths, - styles: styles2, - today, - mode: "default" - }; -} -function parseFromToProps(props) { - var fromYear = props.fromYear, toYear = props.toYear, fromMonth = props.fromMonth, toMonth = props.toMonth; - var fromDate = props.fromDate, toDate2 = props.toDate; - if (fromMonth) { - fromDate = startOfMonth(fromMonth); - } else if (fromYear) { - fromDate = new Date(fromYear, 0, 1); - } - if (toMonth) { - toDate2 = endOfMonth(toMonth); - } else if (toYear) { - toDate2 = new Date(toYear, 11, 31); - } - return { - fromDate: fromDate ? startOfDay(fromDate) : void 0, - toDate: toDate2 ? startOfDay(toDate2) : void 0 + +// src/core/react/components/SpaceView/Contexts/DataTypeView/DataTypeView.tsx +var DataTypeView = (props) => { + const { initialValue, column: column2, row: row2 } = props; + const saveValue = (value) => { + props.updateValue(value); }; -} -var DayPickerContext = (0, import_react41.createContext)(void 0); -function DayPickerProvider(props) { - var _a; - var initialProps = props.initialProps; - var defaultContextValues = getDefaultContextValues(); - var _b = parseFromToProps(initialProps), fromDate = _b.fromDate, toDate2 = _b.toDate; - var captionLayout = (_a = initialProps.captionLayout) !== null && _a !== void 0 ? _a : defaultContextValues.captionLayout; - if (captionLayout !== "buttons" && (!fromDate || !toDate2)) { - captionLayout = "buttons"; - } - var onSelect; - if (isDayPickerSingle(initialProps) || isDayPickerMultiple(initialProps) || isDayPickerRange(initialProps)) { - onSelect = initialProps.onSelect; - } - var value = __assign(__assign(__assign({}, defaultContextValues), initialProps), { captionLayout, classNames: __assign(__assign({}, defaultContextValues.classNames), initialProps.classNames), components: __assign({}, initialProps.components), formatters: __assign(__assign({}, defaultContextValues.formatters), initialProps.formatters), fromDate, labels: __assign(__assign({}, defaultContextValues.labels), initialProps.labels), mode: initialProps.mode || defaultContextValues.mode, modifiers: __assign(__assign({}, defaultContextValues.modifiers), initialProps.modifiers), modifiersClassNames: __assign(__assign({}, defaultContextValues.modifiersClassNames), initialProps.modifiersClassNames), onSelect, styles: __assign(__assign({}, defaultContextValues.styles), initialProps.styles), toDate: toDate2 }); - return jsxRuntimeExports.jsx(DayPickerContext.Provider, { value, children: props.children }); -} -function useDayPicker() { - var context = (0, import_react41.useContext)(DayPickerContext); - if (!context) { - throw new Error("useDayPicker must be used within a DayPickerProvider."); - } - return context; -} -function CaptionLabel(props) { - var _a = useDayPicker(), locale2 = _a.locale, classNames13 = _a.classNames, styles2 = _a.styles, formatCaption2 = _a.formatters.formatCaption; - return jsxRuntimeExports.jsx("div", { className: classNames13.caption_label, style: styles2.caption_label, "aria-live": "polite", role: "presentation", id: props.id, children: formatCaption2(props.displayMonth, { locale: locale2 }) }); -} -function IconDropdown(props) { - return jsxRuntimeExports.jsx("svg", __assign({ width: "8px", height: "8px", viewBox: "0 0 120 120", "data-testid": "iconDropdown" }, props, { children: jsxRuntimeExports.jsx("path", { d: "M4.22182541,48.2218254 C8.44222828,44.0014225 15.2388494,43.9273804 19.5496459,47.9996989 L19.7781746,48.2218254 L60,88.443 L100.221825,48.2218254 C104.442228,44.0014225 111.238849,43.9273804 115.549646,47.9996989 L115.778175,48.2218254 C119.998577,52.4422283 120.07262,59.2388494 116.000301,63.5496459 L115.778175,63.7781746 L67.7781746,111.778175 C63.5577717,115.998577 56.7611506,116.07262 52.4503541,112.000301 L52.2218254,111.778175 L4.22182541,63.7781746 C-0.0739418023,59.4824074 -0.0739418023,52.5175926 4.22182541,48.2218254 Z", fill: "currentColor", fillRule: "nonzero" }) })); -} -function Dropdown(props) { - var _a, _b; - var onChange = props.onChange, value = props.value, children = props.children, caption = props.caption, className = props.className, style = props.style; - var dayPicker = useDayPicker(); - var IconDropdownComponent = (_b = (_a = dayPicker.components) === null || _a === void 0 ? void 0 : _a.IconDropdown) !== null && _b !== void 0 ? _b : IconDropdown; - return jsxRuntimeExports.jsxs("div", { className, style, children: [jsxRuntimeExports.jsx("span", { className: dayPicker.classNames.vhidden, children: props["aria-label"] }), jsxRuntimeExports.jsx("select", { name: props.name, "aria-label": props["aria-label"], className: dayPicker.classNames.dropdown, style: dayPicker.styles.dropdown, value, onChange, children }), jsxRuntimeExports.jsxs("div", { className: dayPicker.classNames.caption_label, style: dayPicker.styles.caption_label, "aria-hidden": "true", children: [caption, jsxRuntimeExports.jsx(IconDropdownComponent, { className: dayPicker.classNames.dropdown_icon, style: dayPicker.styles.dropdown_icon })] })] }); -} -function MonthsDropdown(props) { - var _a; - var _b = useDayPicker(), fromDate = _b.fromDate, toDate2 = _b.toDate, styles2 = _b.styles, locale2 = _b.locale, formatMonthCaption2 = _b.formatters.formatMonthCaption, classNames13 = _b.classNames, components = _b.components, labelMonthDropdown2 = _b.labels.labelMonthDropdown; - if (!fromDate) - return jsxRuntimeExports.jsx(jsxRuntimeExports.Fragment, {}); - if (!toDate2) - return jsxRuntimeExports.jsx(jsxRuntimeExports.Fragment, {}); - var dropdownMonths = []; - if (isSameYear(fromDate, toDate2)) { - var date = startOfMonth(fromDate); - for (var month = fromDate.getMonth(); month <= toDate2.getMonth(); month++) { - dropdownMonths.push(setMonth(date, month)); - } - } else { - var date = startOfMonth(new Date()); - for (var month = 0; month <= 11; month++) { - dropdownMonths.push(setMonth(date, month)); + const saveFieldValue = (fieldValue, value) => { + if (props.editMode > 0 /* EditModeReadOnly */ && props.updateFieldValue) { + props.updateFieldValue(fieldValue, value); + } else { + props.updateValue(value); } - } - var handleChange = function(e5) { - var selectedMonth = Number(e5.target.value); - var newMonth = setMonth(startOfMonth(props.displayMonth), selectedMonth); - props.onChange(newMonth); - }; - var DropdownComponent2 = (_a = components === null || components === void 0 ? void 0 : components.Dropdown) !== null && _a !== void 0 ? _a : Dropdown; - return jsxRuntimeExports.jsx(DropdownComponent2, { name: "months", "aria-label": labelMonthDropdown2(), className: classNames13.dropdown_month, style: styles2.dropdown_month, onChange: handleChange, value: props.displayMonth.getMonth(), caption: formatMonthCaption2(props.displayMonth, { locale: locale2 }), children: dropdownMonths.map(function(m4) { - return jsxRuntimeExports.jsx("option", { value: m4.getMonth(), children: formatMonthCaption2(m4, { locale: locale2 }) }, m4.getMonth()); - }) }); -} -function YearsDropdown(props) { - var _a; - var displayMonth = props.displayMonth; - var _b = useDayPicker(), fromDate = _b.fromDate, toDate2 = _b.toDate, locale2 = _b.locale, styles2 = _b.styles, classNames13 = _b.classNames, components = _b.components, formatYearCaption2 = _b.formatters.formatYearCaption, labelYearDropdown2 = _b.labels.labelYearDropdown; - var years = []; - if (!fromDate) - return jsxRuntimeExports.jsx(jsxRuntimeExports.Fragment, {}); - if (!toDate2) - return jsxRuntimeExports.jsx(jsxRuntimeExports.Fragment, {}); - var fromYear = fromDate.getFullYear(); - var toYear = toDate2.getFullYear(); - for (var year = fromYear; year <= toYear; year++) { - years.push(setYear(startOfYear(new Date()), year)); - } - var handleChange = function(e5) { - var newMonth = setYear(startOfMonth(displayMonth), Number(e5.target.value)); - props.onChange(newMonth); }; - var DropdownComponent2 = (_a = components === null || components === void 0 ? void 0 : components.Dropdown) !== null && _a !== void 0 ? _a : Dropdown; - return jsxRuntimeExports.jsx(DropdownComponent2, { name: "years", "aria-label": labelYearDropdown2(), className: classNames13.dropdown_year, style: styles2.dropdown_year, onChange: handleChange, value: displayMonth.getFullYear(), caption: formatYearCaption2(displayMonth, { locale: locale2 }), children: years.map(function(year2) { - return jsxRuntimeExports.jsx("option", { value: year2.getFullYear(), children: formatYearCaption2(year2, { locale: locale2 }) }, year2.getFullYear()); - }) }); -} -function useControlledValue(defaultValue2, controlledValue) { - var _a = (0, import_react41.useState)(defaultValue2), uncontrolledValue = _a[0], setValue = _a[1]; - var value = controlledValue === void 0 ? uncontrolledValue : controlledValue; - return [value, setValue]; -} -function getInitialMonth(context) { - var month = context.month, defaultMonth = context.defaultMonth, today = context.today; - var initialMonth = month || defaultMonth || today || new Date(); - var toDate2 = context.toDate, fromDate = context.fromDate, _a = context.numberOfMonths, numberOfMonths = _a === void 0 ? 1 : _a; - if (toDate2 && differenceInCalendarMonths(toDate2, initialMonth) < 0) { - var offset2 = -1 * (numberOfMonths - 1); - initialMonth = addMonths(toDate2, offset2); - } - if (fromDate && differenceInCalendarMonths(initialMonth, fromDate) < 0) { - initialMonth = fromDate; - } - return startOfMonth(initialMonth); -} -function useNavigationState() { - var context = useDayPicker(); - var initialMonth = getInitialMonth(context); - var _a = useControlledValue(initialMonth, context.month), month = _a[0], setMonth2 = _a[1]; - var goToMonth = function(date) { - var _a2; - if (context.disableNavigation) - return; - var month2 = startOfMonth(date); - setMonth2(month2); - (_a2 = context.onMonthChange) === null || _a2 === void 0 ? void 0 : _a2.call(context, month2); + const viewProps = { + initialValue, + saveValue, + editMode: props.editMode, + setEditMode: props.setEditMode ?? (() => { + }), + superstate: props.superstate, + propertyValue: column2.value, + path: props.source ?? row2?.[PathPropertyName], + property: column2, + compactMode: props.compactMode }; - return [month, goToMonth]; -} -function getDisplayMonths(month, _a) { - var reverseMonths = _a.reverseMonths, numberOfMonths = _a.numberOfMonths; - var start = startOfMonth(month); - var end = startOfMonth(addMonths(start, numberOfMonths)); - var monthsDiff = differenceInCalendarMonths(end, start); - var months = []; - for (var i4 = 0; i4 < monthsDiff; i4++) { - var nextMonth = addMonths(start, i4); - months.push(nextMonth); - } - if (reverseMonths) - months = months.reverse(); - return months; -} -function getNextMonth(startingMonth, options) { - if (options.disableNavigation) { - return void 0; - } - var toDate2 = options.toDate, pagedNavigation = options.pagedNavigation, _a = options.numberOfMonths, numberOfMonths = _a === void 0 ? 1 : _a; - var offset2 = pagedNavigation ? numberOfMonths : 1; - var month = startOfMonth(startingMonth); - if (!toDate2) { - return addMonths(month, offset2); - } - var monthsDiff = differenceInCalendarMonths(toDate2, startingMonth); - if (monthsDiff < numberOfMonths) { - return void 0; - } - return addMonths(month, offset2); -} -function getPreviousMonth(startingMonth, options) { - if (options.disableNavigation) { - return void 0; - } - var fromDate = options.fromDate, pagedNavigation = options.pagedNavigation, _a = options.numberOfMonths, numberOfMonths = _a === void 0 ? 1 : _a; - var offset2 = pagedNavigation ? numberOfMonths : 1; - var month = startOfMonth(startingMonth); - if (!fromDate) { - return addMonths(month, -offset2); - } - var monthsDiff = differenceInCalendarMonths(month, fromDate); - if (monthsDiff <= 0) { - return void 0; + const fieldType = fieldTypeForType(column2.type, column2.name); + if (!fieldType) { + return /* @__PURE__ */ import_react70.default.createElement(import_react70.default.Fragment, null); } - return addMonths(month, -offset2); -} -var NavigationContext = (0, import_react41.createContext)(void 0); -function NavigationProvider(props) { - var dayPicker = useDayPicker(); - var _a = useNavigationState(), currentMonth = _a[0], goToMonth = _a[1]; - var displayMonths = getDisplayMonths(currentMonth, dayPicker); - var nextMonth = getNextMonth(currentMonth, dayPicker); - var previousMonth = getPreviousMonth(currentMonth, dayPicker); - var isDateDisplayed = function(date) { - return displayMonths.some(function(displayMonth) { - return isSameMonth(date, displayMonth); + if (fieldType.type == "file") { + if (props.compactMode) { + return /* @__PURE__ */ import_react70.default.createElement(LinkCell, { + ...viewProps, + multi: false, + source: props.source + }); + } + return /* @__PURE__ */ import_react70.default.createElement(PathCell, { + ...viewProps, + multi: fieldType.multiType == column2.type + }); + } else if (fieldType.type == "icon") { + return /* @__PURE__ */ import_react70.default.createElement(IconCell, { + ...viewProps, + multi: fieldType.multiType == column2.type + }); + } else if (fieldType.type == "boolean") { + return /* @__PURE__ */ import_react70.default.createElement(BooleanCell, { + ...viewProps, + column: column2 + }); + } else if (fieldType.type == "option") { + return /* @__PURE__ */ import_react70.default.createElement(OptionCell, { + ...viewProps, + multi: fieldType.multiType == column2.type, + saveOptions: saveFieldValue, + source: props.source + }); + } else if (fieldType.type == "date") { + return /* @__PURE__ */ import_react70.default.createElement(DateCell, { + ...viewProps + }); + } else if (fieldType.type == "context") { + return /* @__PURE__ */ import_react70.default.createElement(ContextCell, { + ...viewProps, + multi: fieldType.multiType == column2.type, + source: props.source + }); + } else if (fieldType.type == "fileprop") { + return /* @__PURE__ */ import_react70.default.createElement(LookUpCell, { + ...viewProps, + row: props.row, + columns: props.columns, + saveOptions: saveFieldValue + }); + } else if (fieldType.type == "number") { + return /* @__PURE__ */ import_react70.default.createElement(NumberCell, { + ...viewProps + }); + } else if (fieldType.type == "link") { + return /* @__PURE__ */ import_react70.default.createElement(LinkCell, { + ...viewProps, + multi: fieldType.multiType == column2.type, + source: props.source + }); + } else if (fieldType.type == "tags-multi") { + return /* @__PURE__ */ import_react70.default.createElement(TagCell, { + ...viewProps + }); + } else if (fieldType.type == "image") { + return /* @__PURE__ */ import_react70.default.createElement(ImageCell, { + ...viewProps, + multi: fieldType.multiType == column2.type + }); + } else if (fieldType.type == "object") { + return /* @__PURE__ */ import_react70.default.createElement(ObjectCell, { + ...viewProps, + multi: fieldType.multiType == column2.type, + savePropValue: saveFieldValue, + columns: props.columns, + row: props.row, + compactMode: props.compactMode + }); + } else if (fieldType.type == "color") { + return /* @__PURE__ */ import_react70.default.createElement(ColorCell, { + ...viewProps + }); + } else if (fieldType.type == "space") { + return /* @__PURE__ */ import_react70.default.createElement(SpaceCell, { + ...viewProps, + isTable: false + }); + } else if (fieldType.type == "table") { + return /* @__PURE__ */ import_react70.default.createElement(SpaceCell, { + ...viewProps, + isTable: true }); + } else if (fieldType.type == "super") { + return /* @__PURE__ */ import_react70.default.createElement(SuperCell, { + ...viewProps, + row: row2, + columns: props.columns, + compactMode: props.compactMode, + source: props.source + }); + } else if (fieldType.type == "input") { + return /* @__PURE__ */ import_react70.default.createElement(PropertySelectCell, { + ...viewProps, + columns: props.columns + }); + } + return /* @__PURE__ */ import_react70.default.createElement(TextCell, { + ...viewProps + }); +}; + +// src/core/react/components/SpaceView/Contexts/TableView/TableView.tsx +var TableView = (props) => { + const { + spaceInfo, + readMode, + spaceState: spaceCache + } = (0, import_react71.useContext)(SpaceContext); + const { + tableData, + dbSchema, + contextTable, + saveDB, + selectedRows, + selectRows, + sortedColumns: cols, + filteredData: data2, + predicate, + savePredicate, + updateFieldValue, + updateValue: updateValue2 + } = (0, import_react71.useContext)(ContextEditorContext); + const [pagination, setPagination] = import_react71.default.useState({ + pageIndex: 0, + pageSize: 10 + }); + const [activeId, setActiveId] = (0, import_react71.useState)(null); + const [lastSelectedIndex, setLastSelectedIndex] = (0, import_react71.useState)(null); + const [selectedColumn, setSelectedColumn] = (0, import_react71.useState)(null); + const [currentEdit, setCurrentEdit] = (0, import_react71.useState)(null); + const [overId, setOverId] = (0, import_react71.useState)(null); + const [openFlows, setOpenFlows] = (0, import_react71.useState)([]); + const [colsSize, setColsSize] = (0, import_react71.useState)({}); + const ref2 = (0, import_react71.useRef)(null); + const primaryCol = cols.find((f2) => f2.primary == "true"); + (0, import_react71.useEffect)(() => { + setColsSize({ ...predicate?.colsSize ?? {}, "+": 30 }); + }, [predicate]); + (0, import_react71.useEffect)(() => { + setCurrentEdit(null); + }, [selectedColumn, lastSelectedIndex]); + const saveColsSize = (colSize) => { + const newColSize = colSize(colsSize); + setColsSize(newColSize); + debouncedSavePredicate(newColSize); }; - var goToDate = function(date, refDate) { - if (isDateDisplayed(date)) { + const debouncedSavePredicate = (0, import_react71.useCallback)( + (0, import_lodash11.debounce)( + (nextValue) => savePredicate({ + colsSize: nextValue + }), + 1e3 + ), + [predicate] + ); + const newRow = (name317, index2, data3) => { + if (dbSchema?.id == defaultContextSchemaID) { + newPathInSpace(props.superstate, spaceCache, "md", name317, true); + } else { + saveDB( + createNewRow( + tableData, + primaryCol ? { [primaryCol.name]: name317 ?? "", ...data3 ?? {} } : data3 ?? {}, + index2 + ) + ); + } + }; + const toggleFlow = (path2) => { + setOpenFlows( + (f2) => f2.find((p) => p == path2) ? f2.filter((p) => p != path2) : uniq([...f2, path2]) + ); + }; + const selectItem = (modifier, index2) => { + if (modifier.metaKey) { + props.superstate.ui.openPath( + tableData.rows[parseInt(index2)][PathPropertyName], + false + ); return; } - if (refDate && isBefore(date, refDate)) { - goToMonth(addMonths(date, 1 + dayPicker.numberOfMonths * -1)); + if (modifier.ctrlKey) { + selectedRows.some((f2) => f2 == index2) ? selectRows( + null, + selectedRows.filter((f2) => f2 != index2) + ) : selectRows(index2, uniq([...selectedRows, index2])); + } else if (modifier.shiftKey) { + selectRows( + index2, + uniq([ + ...selectedRows, + ...selectRange( + lastSelectedIndex, + index2, + data2.map((f2) => f2._index) + ) + ]) + ); } else { - goToMonth(date); + selectRows(index2, [index2]); } + setLastSelectedIndex(index2); }; - var value = { - currentMonth, - displayMonths, - goToMonth, - goToDate, - previousMonth, - nextMonth, - isDateDisplayed + const onKeyDown = (e5) => { + const setCellValue = (value) => { + if (selectedColumn) { + const columnTuple = selectedColumn.split("#"); + updateValue2( + columnTuple[0], + value, + columnTuple[1] ?? "", + parseInt(lastSelectedIndex), + "" + ); + } + }; + const clearCell = () => { + setCellValue(""); + }; + const copyCell = () => { + navigator.clipboard.writeText( + tableData.rows[parseInt(lastSelectedIndex)][selectedColumn] + ); + }; + const nextRow = () => { + const newIndex = selectNextIndex( + lastSelectedIndex, + data2.map((f2) => f2._index) + ); + selectRows(newIndex, [newIndex]); + setLastSelectedIndex(newIndex); + }; + const lastRow = () => { + const newIndex = selectPrevIndex( + lastSelectedIndex, + data2.map((f2) => f2._index) + ); + selectRows(newIndex, [newIndex]); + setLastSelectedIndex(newIndex); + }; + if (e5.key == "c" && e5.metaKey) { + copyCell(); + } + if (e5.key == "x" && e5.metaKey) { + copyCell(); + clearCell(); + } + if (e5.key == "v" && e5.metaKey) { + navigator.clipboard.readText().then((f2) => setCellValue(f2)); + } + if (e5.key == "Escape") { + selectRows(null, []); + setLastSelectedIndex(null); + setSelectedColumn(null); + } + if (e5.key == "Backspace" || e5.key == "Delete") { + clearCell(); + } + if (e5.key == "Enter") { + if (selectedColumn && lastSelectedIndex) { + if (e5.shiftKey) { + newRow("", parseInt(lastSelectedIndex) + 1); + nextRow(); + } else { + setCurrentEdit([selectedColumn, lastSelectedIndex]); + e5.preventDefault(); + e5.stopPropagation(); + } + } + return; + } + if (e5.key == "ArrowDown") { + nextRow(); + e5.preventDefault(); + } + if (e5.key == "ArrowUp") { + lastRow(); + e5.preventDefault(); + } + if (e5.key == "ArrowLeft") { + const newIndex = selectPrevIndex( + selectedColumn, + columns.map((f2) => f2.accessorKey).filter((f2) => f2 != "+") + ); + setSelectedColumn(newIndex); + } + if (e5.key == "ArrowRight") { + const newIndex = selectNextIndex( + selectedColumn, + columns.map((f2) => f2.accessorKey).filter((f2) => f2 != "+") + ); + setSelectedColumn(newIndex); + } }; - return jsxRuntimeExports.jsx(NavigationContext.Provider, { value, children: props.children }); -} -function useNavigation() { - var context = (0, import_react41.useContext)(NavigationContext); - if (!context) { - throw new Error("useNavigation must be used within a NavigationProvider"); - } - return context; -} -function CaptionDropdowns(props) { - var _a; - var _b = useDayPicker(), classNames13 = _b.classNames, styles2 = _b.styles, components = _b.components; - var goToMonth = useNavigation().goToMonth; - var handleMonthChange = function(newMonth) { - goToMonth(addMonths(newMonth, props.displayIndex ? -props.displayIndex : 0)); + const columns = (0, import_react71.useMemo)( + () => [ + ...cols.map((f2) => { + return { + header: f2.name, + accessorKey: f2.name + f2.table, + meta: { + table: f2.table, + editable: f2.name != PathPropertyName, + schemaId: dbSchema?.id + }, + cell: ({ + getValue, + row: { index: index2 }, + column: { colId }, + cell, + table: table2 + }) => { + const initialValue = getValue(); + const rowIndex = parseInt(data2[index2]["_index"]); + const tableIndex = parseInt(data2[index2]["_index"]); + const saveValue = (value) => { + setCurrentEdit(null); + setSelectedColumn(null); + if (initialValue != value) + table2.options.meta?.updateData( + f2.name, + value, + f2.table, + rowIndex + ); + }; + const saveFieldValue = (fieldValue, value) => { + table2.options.meta?.updateFieldValue( + f2.name, + fieldValue, + value, + f2.table, + rowIndex + ); + }; + const editMode = readMode ? 0 /* EditModeReadOnly */ : !cell.getIsGrouped() ? isTouchScreen(props.superstate.ui) ? 5 /* EditModeAlways */ : currentEdit && currentEdit[0] == f2.name + f2.table && currentEdit[1] == tableIndex.toString() ? 4 /* EditModeActive */ : 2 /* EditModeView */ : 0 /* EditModeReadOnly */; + const cellProps = { + compactMode: true, + initialValue, + updateValue: saveValue, + updateFieldValue: saveFieldValue, + superstate: props.superstate, + setEditMode: setCurrentEdit, + column: f2, + editMode, + row: data2[index2], + contextTable, + source: data2[index2][PathPropertyName] + }; + const fieldType = fieldTypeForType(f2.type, f2.name); + if (!fieldType) { + return /* @__PURE__ */ import_react71.default.createElement(import_react71.default.Fragment, null, initialValue); + } + return /* @__PURE__ */ import_react71.default.createElement(DataTypeView, { + ...cellProps + }); + } + }; + }) ?? [], + ...readMode ? [] : [ + { + header: "+", + meta: { schemaId: dbSchema?.id }, + accessorKey: "+", + size: 20, + cell: () => /* @__PURE__ */ import_react71.default.createElement(import_react71.default.Fragment, null) + } + ] + ], + [cols, data2, currentEdit, predicate, dbSchema, contextTable] + ); + const groupBy2 = (0, import_react71.useMemo)( + () => predicate?.groupBy?.length > 0 && cols.find((f2) => f2.name + f2.table == predicate.groupBy[0]) ? predicate.groupBy : [], + [predicate, cols] + ); + const table = useReactTable({ + data: data2, + columns, + columnResizeMode: "onChange", + state: { + columnVisibility: predicate?.colsHidden.reduce( + (p, c3) => ({ ...p, [c3]: false }), + {} + ), + columnOrder: predicate?.colsOrder, + columnSizing: { + ...columns.reduce((p, c3) => ({ ...p, [c3.accessorKey]: 150 }), {}), + ...colsSize + }, + grouping: groupBy2, + expanded: true, + pagination + }, + onColumnSizingChange: saveColsSize, + getCoreRowModel: getCoreRowModel(), + getExpandedRowModel: getExpandedRowModel(), + getGroupedRowModel: getGroupedRowModel(), + getPaginationRowModel: getPaginationRowModel(), + onPaginationChange: setPagination, + meta: { + updateData: updateValue2, + updateFieldValue + } + }); + const sensors = useSensors( + useSensor(MouseSensor, { + activationConstraint: { + distance: 10 + } + }), + useSensor(TouchSensor, { + activationConstraint: { + delay: 250, + tolerance: 5 + } + }) + ); + const measuring = { + droppable: { + strategy: MeasuringStrategy.Always + } }; - var CaptionLabelComponent = (_a = components === null || components === void 0 ? void 0 : components.CaptionLabel) !== null && _a !== void 0 ? _a : CaptionLabel; - var captionLabel = jsxRuntimeExports.jsx(CaptionLabelComponent, { id: props.id, displayMonth: props.displayMonth }); - return jsxRuntimeExports.jsxs("div", { className: classNames13.caption_dropdowns, style: styles2.caption_dropdowns, children: [jsxRuntimeExports.jsx("div", { className: classNames13.vhidden, children: captionLabel }), jsxRuntimeExports.jsx(MonthsDropdown, { onChange: handleMonthChange, displayMonth: props.displayMonth }), jsxRuntimeExports.jsx(YearsDropdown, { onChange: handleMonthChange, displayMonth: props.displayMonth })] }); -} -function IconLeft(props) { - return jsxRuntimeExports.jsx("svg", __assign({ width: "16px", height: "16px", viewBox: "0 0 120 120" }, props, { children: jsxRuntimeExports.jsx("path", { d: "M69.490332,3.34314575 C72.6145263,0.218951416 77.6798462,0.218951416 80.8040405,3.34314575 C83.8617626,6.40086786 83.9268205,11.3179931 80.9992143,14.4548388 L80.8040405,14.6568542 L35.461,60 L80.8040405,105.343146 C83.8617626,108.400868 83.9268205,113.317993 80.9992143,116.454839 L80.8040405,116.656854 C77.7463184,119.714576 72.8291931,119.779634 69.6923475,116.852028 L69.490332,116.656854 L18.490332,65.6568542 C15.4326099,62.5991321 15.367552,57.6820069 18.2951583,54.5451612 L18.490332,54.3431458 L69.490332,3.34314575 Z", fill: "currentColor", fillRule: "nonzero" }) })); -} -function IconRight(props) { - return jsxRuntimeExports.jsx("svg", __assign({ width: "16px", height: "16px", viewBox: "0 0 120 120" }, props, { children: jsxRuntimeExports.jsx("path", { d: "M49.8040405,3.34314575 C46.6798462,0.218951416 41.6145263,0.218951416 38.490332,3.34314575 C35.4326099,6.40086786 35.367552,11.3179931 38.2951583,14.4548388 L38.490332,14.6568542 L83.8333725,60 L38.490332,105.343146 C35.4326099,108.400868 35.367552,113.317993 38.2951583,116.454839 L38.490332,116.656854 C41.5480541,119.714576 46.4651794,119.779634 49.602025,116.852028 L49.8040405,116.656854 L100.804041,65.6568542 C103.861763,62.5991321 103.926821,57.6820069 100.999214,54.5451612 L100.804041,54.3431458 L49.8040405,3.34314575 Z", fill: "currentColor" }) })); -} -var Button = (0, import_react41.forwardRef)(function(props, ref2) { - var _a = useDayPicker(), classNames13 = _a.classNames, styles2 = _a.styles; - var classNamesArr = [classNames13.button_reset, classNames13.button]; - if (props.className) { - classNamesArr.push(props.className); - } - var className = classNamesArr.join(" "); - var style = __assign(__assign({}, styles2.button_reset), styles2.button); - if (props.style) { - Object.assign(style, props.style); + function handleDragStart(event) { + const { + active: { id: activeId2 } + } = event; + setActiveId(activeId2); + setOverId(overId); + document.body.style.setProperty("cursor", "grabbing"); } - return jsxRuntimeExports.jsx("button", __assign({}, props, { ref: ref2, type: "button", className, style })); -}); -function Navigation(props) { - var _a, _b; - var _c = useDayPicker(), dir = _c.dir, locale2 = _c.locale, classNames13 = _c.classNames, styles2 = _c.styles, _d = _c.labels, labelPrevious2 = _d.labelPrevious, labelNext2 = _d.labelNext, components = _c.components; - if (!props.nextMonth && !props.previousMonth) { - return jsxRuntimeExports.jsx(jsxRuntimeExports.Fragment, {}); + function handleDragOver({ over }) { + const overId2 = over?.id; + if (overId2) { + setOverId(over?.id ?? null); + } } - var previousLabel = labelPrevious2(props.previousMonth, { locale: locale2 }); - var previousClassName = [ - classNames13.nav_button, - classNames13.nav_button_previous - ].join(" "); - var nextLabel = labelNext2(props.nextMonth, { locale: locale2 }); - var nextClassName = [ - classNames13.nav_button, - classNames13.nav_button_next - ].join(" "); - var IconRightComponent = (_a = components === null || components === void 0 ? void 0 : components.IconRight) !== null && _a !== void 0 ? _a : IconRight; - var IconLeftComponent = (_b = components === null || components === void 0 ? void 0 : components.IconLeft) !== null && _b !== void 0 ? _b : IconLeft; - return jsxRuntimeExports.jsxs("div", { className: classNames13.nav, style: styles2.nav, children: [!props.hidePrevious && jsxRuntimeExports.jsx(Button, { name: "previous-month", "aria-label": previousLabel, className: previousClassName, style: styles2.nav_button_previous, disabled: !props.previousMonth, onClick: props.onPreviousClick, children: dir === "rtl" ? jsxRuntimeExports.jsx(IconRightComponent, { className: classNames13.nav_icon, style: styles2.nav_icon }) : jsxRuntimeExports.jsx(IconLeftComponent, { className: classNames13.nav_icon, style: styles2.nav_icon }) }), !props.hideNext && jsxRuntimeExports.jsx(Button, { name: "next-month", "aria-label": nextLabel, className: nextClassName, style: styles2.nav_button_next, disabled: !props.nextMonth, onClick: props.onNextClick, children: dir === "rtl" ? jsxRuntimeExports.jsx(IconLeftComponent, { className: classNames13.nav_icon, style: styles2.nav_icon }) : jsxRuntimeExports.jsx(IconRightComponent, { className: classNames13.nav_icon, style: styles2.nav_icon }) })] }); -} -function CaptionNavigation(props) { - var numberOfMonths = useDayPicker().numberOfMonths; - var _a = useNavigation(), previousMonth = _a.previousMonth, nextMonth = _a.nextMonth, goToMonth = _a.goToMonth, displayMonths = _a.displayMonths; - var displayIndex = displayMonths.findIndex(function(month) { - return isSameMonth(props.displayMonth, month); - }); - var isFirst = displayIndex === 0; - var isLast = displayIndex === displayMonths.length - 1; - var hideNext = numberOfMonths > 1 && (isFirst || !isLast); - var hidePrevious = numberOfMonths > 1 && (isLast || !isFirst); - var handlePreviousClick = function() { - if (!previousMonth) - return; - goToMonth(previousMonth); + const saveFilter = (filter4) => { + savePredicate({ + filters: [ + ...(predicate?.filters ?? []).filter((s4) => s4.field != filter4.field), + filter4 + ] + }); }; - var handleNextClick = function() { - if (!nextMonth) + const selectCell = (e5, index2, column2) => { + if (isTouchScreen(props.superstate.ui) || column2 == "+") return; - goToMonth(nextMonth); + selectItem( + { + ctrlKey: e5.ctrlKey, + metaKey: e5.metaKey, + altKey: e5.altKey, + shiftKey: e5.shiftKey + }, + data2[index2]["_index"] + ); + setSelectedColumn(column2); + if (e5.detail === 1) { + } else if (e5.detail === 2) { + setCurrentEdit([column2, data2[index2]["_index"]]); + } }; - return jsxRuntimeExports.jsx(Navigation, { displayMonth: props.displayMonth, hideNext, hidePrevious, nextMonth, previousMonth, onPreviousClick: handlePreviousClick, onNextClick: handleNextClick }); -} -function Caption(props) { - var _a; - var _b = useDayPicker(), classNames13 = _b.classNames, disableNavigation = _b.disableNavigation, styles2 = _b.styles, captionLayout = _b.captionLayout, components = _b.components; - var CaptionLabelComponent = (_a = components === null || components === void 0 ? void 0 : components.CaptionLabel) !== null && _a !== void 0 ? _a : CaptionLabel; - var caption; - if (disableNavigation) { - caption = jsxRuntimeExports.jsx(CaptionLabelComponent, { id: props.id, displayMonth: props.displayMonth }); - } else if (captionLayout === "dropdown") { - caption = jsxRuntimeExports.jsx(CaptionDropdowns, { displayMonth: props.displayMonth, id: props.id }); - } else if (captionLayout === "dropdown-buttons") { - caption = jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment, { children: [jsxRuntimeExports.jsx(CaptionDropdowns, { displayMonth: props.displayMonth, displayIndex: props.displayIndex, id: props.id }), jsxRuntimeExports.jsx(CaptionNavigation, { displayMonth: props.displayMonth, displayIndex: props.displayIndex, id: props.id })] }); - } else { - caption = jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment, { children: [jsxRuntimeExports.jsx(CaptionLabelComponent, { id: props.id, displayMonth: props.displayMonth, displayIndex: props.displayIndex }), jsxRuntimeExports.jsx(CaptionNavigation, { displayMonth: props.displayMonth, id: props.id })] }); + function handleDragEnd({ active, over }) { + resetState(); + const currentCols = predicate?.colsOrder ?? []; + savePredicate({ + colsOrder: arrayMove( + currentCols, + currentCols.findIndex((f2) => f2 == activeId), + currentCols.findIndex((f2) => f2 == overId) + ) + }); } - return jsxRuntimeExports.jsx("div", { className: classNames13.caption, style: styles2.caption, children: caption }); -} -function Footer(props) { - var _a = useDayPicker(), footer = _a.footer, styles2 = _a.styles, tfoot = _a.classNames.tfoot; - if (!footer) - return jsxRuntimeExports.jsx(jsxRuntimeExports.Fragment, {}); - return jsxRuntimeExports.jsx("tfoot", { className: tfoot, style: styles2.tfoot, children: jsxRuntimeExports.jsx("tr", { children: jsxRuntimeExports.jsx("td", { colSpan: 8, children: footer }) }) }); -} -function getWeekdays(locale2, weekStartsOn, ISOWeek) { - var start = ISOWeek ? startOfISOWeek(new Date()) : startOfWeek(new Date(), { locale: locale2, weekStartsOn }); - var days = []; - for (var i4 = 0; i4 < 7; i4++) { - var day = addDays(start, i4); - days.push(day); + function handleDragCancel() { + resetState(); } - return days; -} -function HeadRow() { - var _a = useDayPicker(), classNames13 = _a.classNames, styles2 = _a.styles, showWeekNumber = _a.showWeekNumber, locale2 = _a.locale, weekStartsOn = _a.weekStartsOn, ISOWeek = _a.ISOWeek, formatWeekdayName2 = _a.formatters.formatWeekdayName, labelWeekday2 = _a.labels.labelWeekday; - var weekdays = getWeekdays(locale2, weekStartsOn, ISOWeek); - return jsxRuntimeExports.jsxs("tr", { style: styles2.head_row, className: classNames13.head_row, children: [showWeekNumber && jsxRuntimeExports.jsx("td", { style: styles2.head_cell, className: classNames13.head_cell }), weekdays.map(function(weekday, i4) { - return jsxRuntimeExports.jsx("th", { scope: "col", className: classNames13.head_cell, style: styles2.head_cell, "aria-label": labelWeekday2(weekday, { locale: locale2 }), children: formatWeekdayName2(weekday, { locale: locale2 }) }, i4); - })] }); -} -function Head() { - var _a; - var _b = useDayPicker(), classNames13 = _b.classNames, styles2 = _b.styles, components = _b.components; - var HeadRowComponent = (_a = components === null || components === void 0 ? void 0 : components.HeadRow) !== null && _a !== void 0 ? _a : HeadRow; - return jsxRuntimeExports.jsx("thead", { style: styles2.head, className: classNames13.head, children: jsxRuntimeExports.jsx(HeadRowComponent, {}) }); -} -function DayContent(props) { - var _a = useDayPicker(), locale2 = _a.locale, formatDay2 = _a.formatters.formatDay; - return jsxRuntimeExports.jsx(jsxRuntimeExports.Fragment, { children: formatDay2(props.date, { locale: locale2 }) }); -} -var SelectMultipleContext = (0, import_react41.createContext)(void 0); -function SelectMultipleProvider(props) { - if (!isDayPickerMultiple(props.initialProps)) { - var emptyContextValue = { - selected: void 0, - modifiers: { - disabled: [] - } - }; - return jsxRuntimeExports.jsx(SelectMultipleContext.Provider, { value: emptyContextValue, children: props.children }); + function resetState() { + setOverId(null); + setActiveId(null); + document.body.style.setProperty("cursor", ""); } - return jsxRuntimeExports.jsx(SelectMultipleProviderInternal, { initialProps: props.initialProps, children: props.children }); -} -function SelectMultipleProviderInternal(_a) { - var initialProps = _a.initialProps, children = _a.children; - var selected = initialProps.selected, min5 = initialProps.min, max5 = initialProps.max; - var onDayClick = function(day, activeModifiers, e5) { - var _a2, _b; - (_a2 = initialProps.onDayClick) === null || _a2 === void 0 ? void 0 : _a2.call(initialProps, day, activeModifiers, e5); - var isMinSelected = Boolean(activeModifiers.selected && min5 && (selected === null || selected === void 0 ? void 0 : selected.length) === min5); - if (isMinSelected) { - return; + return /* @__PURE__ */ import_react71.default.createElement(DndContext, { + sensors, + collisionDetection: closestCenter, + measuring, + onDragStart: handleDragStart, + onDragOver: handleDragOver, + onDragEnd: handleDragEnd, + onDragCancel: handleDragCancel + }, /* @__PURE__ */ import_react71.default.createElement("div", { + className: "mk-table", + ref: ref2, + tabIndex: 1, + onKeyDown + }, /* @__PURE__ */ import_react71.default.createElement("table", { + ...{} + }, /* @__PURE__ */ import_react71.default.createElement("thead", null, table.getHeaderGroups().map((headerGroup) => /* @__PURE__ */ import_react71.default.createElement("tr", { + key: headerGroup.id + }, /* @__PURE__ */ import_react71.default.createElement("th", null), headerGroup.headers.map((header) => /* @__PURE__ */ import_react71.default.createElement("th", { + className: "mk-th", + key: header.id, + style: { + minWidth: header.column.getIsGrouped() ? "0px" : colsSize[header.column.columnDef.accessorKey] ?? "150px", + maxWidth: header.column.getIsGrouped() ? "0px" : colsSize[header.column.columnDef.accessorKey] ?? "150px" } - var isMaxSelected = Boolean(!activeModifiers.selected && max5 && (selected === null || selected === void 0 ? void 0 : selected.length) === max5); - if (isMaxSelected) { - return; + }, header.isPlaceholder ? null : header.column.columnDef.header != "+" ? header.column.getIsGrouped() ? /* @__PURE__ */ import_react71.default.createElement(import_react71.default.Fragment, null) : /* @__PURE__ */ import_react71.default.createElement(ColumnHeader, { + superstate: props.superstate, + editable: header.column.columnDef.meta.editable, + column: cols.find( + (f2) => f2.name == header.column.columnDef.header && f2.table == header.column.columnDef.meta.table + ) + }) : /* @__PURE__ */ import_react71.default.createElement(ColumnHeader, { + superstate: props.superstate, + isNew: true, + editable: true, + column: { + name: "", + schemaId: header.column.columnDef.meta.schemaId, + type: "text", + table: "" } - var selectedDays = selected ? __spreadArray([], selected, true) : []; - if (activeModifiers.selected) { - var index2 = selectedDays.findIndex(function(selectedDay) { - return isSameDay(day, selectedDay); - }); - selectedDays.splice(index2, 1); + }), /* @__PURE__ */ import_react71.default.createElement("div", { + ...{ + onMouseDown: header.getResizeHandler(), + onTouchStart: header.getResizeHandler(), + className: `mk-resizer ${header.column.getIsResizing() ? "isResizing" : ""}` + } + })))))), /* @__PURE__ */ import_react71.default.createElement("tbody", null, table.getRowModel().rows.map((row2) => /* @__PURE__ */ import_react71.default.createElement("tr", { + className: selectedRows?.some( + (f2) => f2 == data2[row2.index]["_index"] + ) ? "mk-active" : void 0, + onContextMenu: (e5) => { + const rowIndex = parseInt( + data2[row2.index]["_index"] + ); + showRowContextMenu( + e5, + props.superstate, + spaceCache.path, + dbSchema.id, + rowIndex + ); + }, + key: row2.id + }, /* @__PURE__ */ import_react71.default.createElement("td", null), row2.getVisibleCells().map( + (cell, i4) => cell.getIsGrouped() ? /* @__PURE__ */ import_react71.default.createElement("td", { + key: i4, + className: "mk-td-group", + colSpan: cols.length + (readMode ? 0 : 1) + }, /* @__PURE__ */ import_react71.default.createElement("div", { + ...{ + onClick: row2.getToggleExpandedHandler(), + style: { + display: "flex", + alignItems: "center", + cursor: "normal" + } + } + }, flexRender( + cell.column.columnDef.cell, + cell.getContext() + ), " ", "(", row2.subRows.length, ")")) : cell.getIsAggregated() ? /* @__PURE__ */ import_react71.default.createElement(import_react71.default.Fragment, { + key: i4 + }, flexRender( + cell.column.columnDef.aggregatedCell ?? cell.column.columnDef.cell, + cell.getContext() + )) : /* @__PURE__ */ import_react71.default.createElement("td", { + onClick: (e5) => selectCell( + e5, + cell.row.index, + cell.column.columnDef.accessorKey + ), + className: `${cell.column.columnDef.accessorKey == selectedColumn ? "mk-selected-cell " : ""} mk-td ${cell.getIsPlaceholder() ? "mk-td-empty" : ""}`, + key: cell.id, + style: { + minWidth: cell.getIsPlaceholder() ? "0px" : colsSize[cell.column.columnDef.accessorKey] ?? "50px" + } + }, cell.getIsPlaceholder() ? null : flexRender( + cell.column.columnDef.cell, + cell.getContext() + )) + )))), /* @__PURE__ */ import_react71.default.createElement("tfoot", null, table.getCanNextPage() && /* @__PURE__ */ import_react71.default.createElement("tr", null, /* @__PURE__ */ import_react71.default.createElement("th", { + className: "mk-row-new", + colSpan: cols.length + (readMode ? 1 : 2), + onClick: () => table.setPageSize(pagination.pageSize + 25) + }, "Load More")), !readMode ? /* @__PURE__ */ import_react71.default.createElement("tr", null, /* @__PURE__ */ import_react71.default.createElement("th", { + className: "mk-row-new", + colSpan: cols.length + (readMode ? 1 : 2), + "data-placeholder": i18n_default.hintText.newItem, + onKeyPress: (e5) => { + if (e5.key == "Enter") { + newRow(e5.currentTarget.innerText); + e5.currentTarget.innerText = ""; + e5.currentTarget.blur(); + } + }, + contentEditable: true + })) : /* @__PURE__ */ import_react71.default.createElement(import_react71.default.Fragment, null))), (0, import_react_dom5.createPortal)( + /* @__PURE__ */ import_react71.default.createElement(DragOverlay, { + dropAnimation: null, + zIndex: 1600 + }, activeId ? /* @__PURE__ */ import_react71.default.createElement(ColumnHeader, { + superstate: props.superstate, + editable: false, + column: { + name: activeId, + schemaId: tableData.schema.id, + type: "text", + table: "" + } + }) : null), + document.body + ))); +}; + +// src/core/react/components/SpaceView/Contexts/DataTypeView/DataPropertyView.tsx +var DataPropertyView = (props) => { + const isObjectType = (0, import_react72.useMemo)( + () => propertyIsObjectType(props.column), + [props.column] + ); + const parsedValue = parseFieldValue( + props.column.value, + props.column.type, + props.superstate + ); + const saveType = (newType, _value) => { + const value = parseObject( + props.initialValue ?? "", + props.column.type == "object-multi" + ); + if (props.column.type == "object-multi") { + props.updateFieldValue( + JSON.stringify({ ...parsedValue, type: newType }), + JSON.stringify(value) + ); } else { - selectedDays.push(day); + props.updateFieldValue( + JSON.stringify({ ...parsedValue, type: newType }), + JSON.stringify(_value) + ); } - (_b = initialProps.onSelect) === null || _b === void 0 ? void 0 : _b.call(initialProps, selectedDays, day, activeModifiers, e5); }; - var modifiers = { - disabled: [] + const newProperty = (e5) => { + const offset2 = e5.target.getBoundingClientRect(); + const type = parseFieldValue(props.column.value, props.column.type)?.type; + const value = parseObject( + props.initialValue ?? "", + props.column.type == "object-multi" + ); + showNewPropertyMenu( + props.superstate, + offset2, + [], + [], + (source, field) => { + saveType( + { + ...type ?? {}, + [field.name]: { type: field.type, label: field.name } + }, + { + ...value, + [field.name]: "" + } + ); + }, + null, + null, + true, + false + ); }; - if (selected) { - modifiers.disabled.push(function(day) { - var isMaxSelected = max5 && selected.length > max5 - 1; - var isSelected = selected.some(function(selectedDay) { - return isSameDay(selectedDay, day); - }); - return Boolean(isMaxSelected && !isSelected); - }); - } - var contextValue = { - selected, - onDayClick, - modifiers + const insertMultiValue = (index2) => { + const type = parseFieldValue(props.column.value, props.column.type)?.type; + const value = parseObject( + props.initialValue ?? "", + props.column.type == "object-multi" + ); + const item = Object.keys(type).reduce((p, c3) => ({ ...p, [c3]: "" }), {}); + props.updateValue( + JSON.stringify([...value.slice(0, index2), item, ...value.slice(index2)]) + ); }; - return jsxRuntimeExports.jsx(SelectMultipleContext.Provider, { value: contextValue, children }); -} -function useSelectMultiple() { - var context = (0, import_react41.useContext)(SelectMultipleContext); - if (!context) { - throw new Error("useSelectMultiple must be used within a SelectMultipleProvider"); - } - return context; -} -function addToRange(day, range2) { - var _a = range2 || {}, from = _a.from, to2 = _a.to; - if (from && to2) { - if (isSameDay(to2, day) && isSameDay(from, day)) { - return void 0; + return /* @__PURE__ */ import_react72.default.createElement(import_react72.default.Fragment, null, /* @__PURE__ */ import_react72.default.createElement("div", { + className: "mk-path-context-row" + }, /* @__PURE__ */ import_react72.default.createElement(PropertyField, { + superstate: props.superstate, + path: props.path, + property: props.column, + onClick: (e5) => props.propertyMenu && props.propertyMenu(e5), + contexts: props.contexts, + draggable: props.draggable + }), /* @__PURE__ */ import_react72.default.createElement("div", { + className: "mk-path-context-value" + }, isObjectType ? !props.compactMode && /* @__PURE__ */ import_react72.default.createElement("div", { + className: "mk-cell-object-options" + }, props.editMode > 3 /* EditModeValueOnly */ && /* @__PURE__ */ import_react72.default.createElement("button", { + onClick: (e5) => newProperty(e5), + className: "mk-inline-button" + }, /* @__PURE__ */ import_react72.default.createElement("div", { + className: "mk-icon-xsmall", + dangerouslySetInnerHTML: { + __html: props.superstate.ui.getSticker("ui//plus") } - if (isSameDay(to2, day)) { - return { from: to2, to: void 0 }; + }), i18n_default.labels.propertyFileProp), props.column.type == "object-multi" && /* @__PURE__ */ import_react72.default.createElement("button", { + onClick: (e5) => insertMultiValue(0), + className: "mk-inline-button" + }, /* @__PURE__ */ import_react72.default.createElement("div", { + className: "mk-icon-xsmall", + dangerouslySetInnerHTML: { + __html: props.superstate.ui.getSticker("ui//insert") } - if (isSameDay(from, day)) { - return void 0; + }), parsedValue?.typeName ?? "Object")) : /* @__PURE__ */ import_react72.default.createElement(DataTypeView, { + ...props + })), props.linkProp && /* @__PURE__ */ import_react72.default.createElement(import_react72.default.Fragment, null, /* @__PURE__ */ import_react72.default.createElement("span", null), /* @__PURE__ */ import_react72.default.createElement("div", { + className: "mk-icon-small", + style: { height: "24px" }, + onClick: (e5) => props.linkProp(e5), + dangerouslySetInnerHTML: { + __html: props.superstate.ui.getSticker("ui//plug") } - if (isAfter(from, day)) { - return { from: day, to: to2 }; + }))), isObjectType && !props.compactMode && /* @__PURE__ */ import_react72.default.createElement("div", { + className: "mk-path-context-row", + style: { marginLeft: "30px" } + }, /* @__PURE__ */ import_react72.default.createElement(DataTypeView, { + ...props + }))); +}; + +// src/core/react/components/UI/Menus/contexts/EditPropertyMenu.tsx +var import_react73 = __toESM(require_react()); +var EditPropertiesSubmenu = (props) => { + const context = props.superstate.contextsIndex.get(props.path); + const fields = context?.tables?.[props.schema]?.cols ?? []; + const values2 = context?.tables?.[props.schema].rows[props.index]; + const savePropValue = (name317, value) => { + const row2 = props.superstate.contextsIndex.get(props.path)?.tables?.[props.schema].rows[props.index]; + if (row2) { + updateTableRow( + props.superstate.spaceManager, + context.space, + props.schema, + props.index, + { + ...row2, + [name317]: value + } + ); } - return { from, to: day }; + }; + return /* @__PURE__ */ import_react73.default.createElement("div", { + className: "mk-editor-frame-properties" + }, /* @__PURE__ */ import_react73.default.createElement("div", { + className: "mk-editor-actions-name" + }, /* @__PURE__ */ import_react73.default.createElement("div", { + className: "mk-editor-actions-name-icon" + }, /* @__PURE__ */ import_react73.default.createElement("div", { + className: "mk-icon-small", + dangerouslySetInnerHTML: { + __html: props.superstate.ui.getSticker("ui//list") + } + })), /* @__PURE__ */ import_react73.default.createElement("div", { + className: "mk-editor-actions-name-text" + }, i18n_default.buttons.editProperty), /* @__PURE__ */ import_react73.default.createElement("span", null), /* @__PURE__ */ import_react73.default.createElement("div", { + className: "mk-icon-small mk-inline-button", + dangerouslySetInnerHTML: { + __html: props.superstate.ui.getSticker("ui//close") + }, + onClick: () => props.hide() + })), /* @__PURE__ */ import_react73.default.createElement("div", { + className: "mk-props-contexts" + }, fields.map((f2, i4) => { + return /* @__PURE__ */ import_react73.default.createElement(import_react73.default.Fragment, { + key: i4 + }, /* @__PURE__ */ import_react73.default.createElement(DataPropertyView, { + initialValue: values2[f2.name], + column: f2, + compactMode: false, + superstate: props.superstate, + editMode: 3 /* EditModeValueOnly */, + row: values2, + updateValue: (value) => { + savePropValue(f2.name, value); + }, + source: props.pathState.path, + columns: fields + })); + }))); +}; + +// src/core/react/components/UI/Menus/contexts/rowContextMenu.tsx +var showRowContextMenu = (e5, superstate, contextPath, schema, index2) => { + e5.preventDefault(); + const context = superstate.contextsIndex.get(contextPath); + const dbSchema = context?.tables[schema]?.schema; + const rows = context?.tables[schema]?.rows; + if (!context) + return; + if (dbSchema.primary == "true") { + const row2 = rows.find((f2, i4) => i4 == index2); + if (row2) { + if (superstate.spacesIndex.has(row2[PathPropertyName])) { + const pathState = superstate.pathsIndex.get(row2[PathPropertyName]); + if (pathState) + showSpaceContextMenu(superstate, pathState, e5, "", contextPath); + return; + } + showPathContextMenu( + superstate, + row2[PathPropertyName], + contextPath, + e5.target.getBoundingClientRect() + ); + return; + } + } + const menuOptions = []; + const propertiesProps = { + superstate, + pathState: superstate.pathsIndex.get(contextPath), + path: contextPath, + schema, + index: index2 + }; + menuOptions.push({ + name: i18n_default.menu.editProperties, + icon: "ui//list", + onClick: (e6) => { + superstate.ui.openCustomMenu( + e6.currentTarget.getBoundingClientRect(), + /* @__PURE__ */ import_react74.default.createElement(EditPropertiesSubmenu, { + ...propertiesProps + }), + propertiesProps + ); + } + }); + menuOptions.push({ + name: i18n_default.menu.deleteRow, + icon: "ui//trash", + onClick: (e6) => { + deleteRowInTable(superstate.spaceManager, context.space, schema, index2); + } + }); + superstate.ui.openMenu( + e5.target.getBoundingClientRect(), + defaultMenu(superstate.ui, menuOptions) + ); +}; + +// src/core/superstate/api.ts +var API = class { + constructor(superstate) { + this.frame = { + update: (property, value, path2, saveState) => { + if (property.startsWith("$contexts")) { + const { context, prop: prop2 } = parseContextNode(property); + if (context && prop2) + this.context.update(context, path2, prop2, value); + } else { + const linkedNode = parseLinkedNode(property); + if (linkedNode.node && linkedNode.prop) { + saveState({ + [linkedNode.node]: { + props: { + [linkedNode.prop]: value + } + } + }); + } + } + } + }; + this.properties = { + color: (property, value) => { + if (property?.type?.includes("option")) { + const fields = parseFieldValue(property.value, property.type); + const option = fields.options?.find((f2) => f2.value == value); + if (option?.color.length > 0) + return option.color; + } + return "var(--mk-ui-background-contrast)"; + }, + sticker: (property) => stickerForField(property), + value: (type, value) => { + if (!type) + return value; + return parseMDBValue(type, value); + } + }; + this.path = { + label: (path2) => { + return this.superstate.pathsIndex.get(path2)?.label; + }, + open: (path2, target) => { + this.superstate.ui.openPath(path2, target); + }, + create: (name317, space2, type, content3) => { + if (content3 instanceof Promise) { + return content3.then((c3) => { + newPathInSpace(this.superstate, this.superstate.spacesIndex.get(space2), type, name317, true, c3); + }); + } + return newPathInSpace(this.superstate, this.superstate.spacesIndex.get(space2), type, name317, true, content3); + }, + setProperty: (path2, property, value) => { + if (value instanceof Promise) { + value.then((v2) => { + saveProperties(this.superstate, path2, { + [property]: v2 + }); + }); + return; + } + saveProperties(this.superstate, path2, { + [property]: value + }); + }, + contextMenu: (e5, path2) => { + showPathContextMenu(this.superstate, path2, null, { x: e5.clientX, y: e5.clientY, width: 0, height: 0 }); + } + }; + this.commands = { + run: (action, parameters, contexts) => { + return this.superstate.cli.runCommand(action, { instanceProps: { ...parameters, $api: this, $contexts: contexts }, props: {}, iterations: 0 }); + }, + formula: (formula, parameters, contexts) => { + return runFormulaWithContext(this.superstate.formulaContext, this.superstate.pathsIndex, formula, contexts.$properties, parameters, contexts?.$contexts?.$space?.path); + } + }; + this.buttonCommand = (action, parameters, contexts, saveState) => { + alert("Button actions have been upgraded, please rebind your buttons to use the new API."); + }; + this.table = { + select: (path2, table) => { + return this.superstate.spaceManager.readTable(path2, table)?.then((f2) => f2?.rows); + }, + update: (path2, table, index2, row2) => { + const space2 = this.superstate.spacesIndex.get(path2); + if (space2) + return updateTableRow(this.superstate.spaceManager, space2.space, table, index2, row2); + }, + insert: (path2, schema, row2) => { + if (schema == defaultContextSchemaID) { + this.context.insert(path2, schema, row2[PathPropertyName], row2); + return; + } + const space2 = this.superstate.spacesIndex.get(path2); + if (space2) + return addRowInTable(this.superstate.spaceManager, row2, space2.space, schema); + return Promise.resolve(); + }, + create: (path2, table, properties3) => { + const newSchema = { + id: sanitizeTableName(table), + name: table, + type: "db" + }; + this.superstate.spaceManager.createTable( + path2, + newSchema + ); + }, + open: (space2, table, index2, target) => { + const context = this.superstate.contextsIndex.get(space2); + if (table == defaultContextSchemaID) { + const path2 = context?.tables[table]?.rows[index2]?.[PathPropertyName]; + this.superstate.ui.openPath(path2, target); + } else { + } + }, + contextMenu: (e5, space2, table, index2) => { + const context = this.superstate.contextsIndex.get(space2); + if (table == defaultContextSchemaID) { + const path2 = context?.tables[table]?.rows[index2]?.[PathPropertyName]; + showPathContextMenu(this.superstate, path2, space2, { x: e5.clientX, y: e5.clientY, width: 0, height: 0 }); + } else { + showRowContextMenu(e5, this.superstate, space2, table, index2); + } + } + }; + this.context = { + select: (path2, table) => { + return this.superstate.contextsIndex.get(path2)?.tables[table]?.rows; + }, + update: (path2, file, field, value) => { + const space2 = this.superstate.spacesIndex.get(path2); + if (space2) + updateValueInContext(this.superstate.spaceManager, file, field, value, space2.space); + }, + insert: (path2, schema, name317, row2) => { + if (schema == defaultContextSchemaID) { + newPathInSpace(this.superstate, this.superstate.spacesIndex.get(path2), "md", name317, true).then((f2) => { + if (row2) + saveProperties(this.superstate, f2, { + ...row2 + }); + }); + } else { + const table = this.superstate.contextsIndex.get(path2)?.tables?.[schema]; + if (table) { + const prop2 = table.cols.find((f2) => f2.primary == "true"); + const newRow = prop2 ? { + ...row2, + [prop2.name]: name317 + } : row2; + this.table.insert(path2, schema, newRow); + } + } + } + }; + this.date = { + parse: (date) => { + return new Date(date?.replace(/-/g, "/").replace(/T.+/, "")); + }, + daysInMonth: (date) => { + return new Date(date.getFullYear(), date.getMonth() + 1, 0).getDate(); + }, + format: (date, format8) => { + return formatDate(this.superstate, date, format8 ?? "yyyy-MM-dd"); + }, + component: (date, component) => { + if (component == "year") + return date.getFullYear(); + if (component == "month") + return date.getMonth() + 1; + if (component == "day") + return date.getDate(); + if (component == "dayOfWeek") + return date.getDay(); + if (component == "hour") + return date.getHours(); + if (component == "minute") + return date.getMinutes(); + if (component == "second") + return date.getSeconds(); + }, + offset: (date, offset2, type) => { + const newDate = new Date(date); + if (type == "day") + newDate.setDate(newDate.getDate() + offset2); + if (type == "month") + newDate.setMonth(newDate.getMonth() + offset2); + if (type == "year") + newDate.setFullYear(newDate.getFullYear() + offset2); + return newDate; + }, + now: () => { + return new Date(); + }, + range: (start, end, format8) => { + const dates = []; + const current3 = new Date(start); + while (current3 <= end) { + dates.push(formatDate(this.superstate, current3, format8 ?? "yyyy-MM-dd")); + current3.setDate(current3.getDate() + 1); + } + return dates; + } + }; + this.superstate = superstate; } - if (to2) { - if (isAfter(day, to2)) { - return { from: to2, to: day }; - } - return { from: day, to: to2 }; +}; + +// src/core/types/indexMap.ts +var _IndexMap = class { + constructor() { + this.map = /* @__PURE__ */ new Map(); + this.invMap = /* @__PURE__ */ new Map(); } - if (from) { - if (isBefore(day, from)) { - return { from: day, to: from }; + get(key2) { + const result = this.map.get(key2); + if (result) { + return new Set(result); + } else { + return /* @__PURE__ */ new Set(); } - return { from, to: day }; } - return { from: day, to: void 0 }; -} -var SelectRangeContext = (0, import_react41.createContext)(void 0); -function SelectRangeProvider(props) { - if (!isDayPickerRange(props.initialProps)) { - var emptyContextValue = { - selected: void 0, - modifiers: { - range_start: [], - range_end: [], - range_middle: [], - disabled: [] - } - }; - return jsxRuntimeExports.jsx(SelectRangeContext.Provider, { value: emptyContextValue, children: props.children }); + getInverse(value) { + return this.invMap.get(value) || _IndexMap.EMPTY_SET; } - return jsxRuntimeExports.jsx(SelectRangeProviderInternal, { initialProps: props.initialProps, children: props.children }); -} -function SelectRangeProviderInternal(_a) { - var initialProps = _a.initialProps, children = _a.children; - var selected = initialProps.selected; - var _b = selected || {}, selectedFrom = _b.from, selectedTo = _b.to; - var min5 = initialProps.min; - var max5 = initialProps.max; - var onDayClick = function(day, activeModifiers, e5) { - var _a2, _b2; - (_a2 = initialProps.onDayClick) === null || _a2 === void 0 ? void 0 : _a2.call(initialProps, day, activeModifiers, e5); - var newRange = addToRange(day, selected); - (_b2 = initialProps.onSelect) === null || _b2 === void 0 ? void 0 : _b2.call(initialProps, newRange, day, activeModifiers, e5); - }; - var modifiers = { - range_start: [], - range_end: [], - range_middle: [], - disabled: [] - }; - if (selectedFrom) { - modifiers.range_start = [selectedFrom]; - if (!selectedTo) { - modifiers.range_end = [selectedFrom]; - } else { - modifiers.range_end = [selectedTo]; - if (!isSameDay(selectedFrom, selectedTo)) { - modifiers.range_middle = [ - { - after: selectedFrom, - before: selectedTo - } - ]; + set(key2, values2) { + if (!values2.size) { + this.delete(key2); + return this; + } + const oldValues = this.map.get(key2); + if (oldValues) { + for (const value of oldValues) { + if (!values2.has(key2)) + this.invMap.get(value)?.delete(key2); } } - } else if (selectedTo) { - modifiers.range_start = [selectedTo]; - modifiers.range_end = [selectedTo]; + this.map.set(key2, values2); + for (const value of values2) { + if (!this.invMap.has(value)) + this.invMap.set(value, /* @__PURE__ */ new Set([key2])); + else + this.invMap.get(value)?.add(key2); + } + return this; } - if (min5) { - if (selectedFrom && !selectedTo) { - modifiers.disabled.push({ - after: subDays(selectedFrom, min5 - 1), - before: addDays(selectedFrom, min5 - 1) - }); + setInverse(key2, values2) { + if (!values2.size) { + this.deleteInverse(key2); + return this; } - if (selectedFrom && selectedTo) { - modifiers.disabled.push({ - after: selectedFrom, - before: addDays(selectedFrom, min5 - 1) - }); + const oldValues = this.invMap.get(key2); + if (oldValues) { + for (const value of oldValues) { + if (!values2.has(key2)) + this.map.get(value)?.delete(key2); + } } - if (!selectedFrom && selectedTo) { - modifiers.disabled.push({ - after: subDays(selectedTo, min5 - 1), - before: addDays(selectedTo, min5 - 1) - }); + this.invMap.set(key2, values2); + for (const value of values2) { + if (!this.map.has(value)) + this.map.set(value, /* @__PURE__ */ new Set([key2])); + else + this.map.get(value)?.add(key2); } + return this; } - if (max5) { - if (selectedFrom && !selectedTo) { - modifiers.disabled.push({ - before: addDays(selectedFrom, -max5 + 1) - }); - modifiers.disabled.push({ - after: addDays(selectedFrom, max5 - 1) - }); - } - if (selectedFrom && selectedTo) { - var selectedCount = differenceInCalendarDays(selectedTo, selectedFrom) + 1; - var offset2 = max5 - selectedCount; - modifiers.disabled.push({ - before: subDays(selectedFrom, offset2) - }); - modifiers.disabled.push({ - after: addDays(selectedTo, offset2) - }); + delete(key2) { + const oldValues = this.map.get(key2); + if (!oldValues) + return false; + this.map.delete(key2); + for (const value of oldValues) { + this.invMap.get(value)?.delete(key2); } - if (!selectedFrom && selectedTo) { - modifiers.disabled.push({ - before: addDays(selectedTo, -max5 + 1) - }); - modifiers.disabled.push({ - after: addDays(selectedTo, max5 - 1) - }); + return true; + } + deleteInverse(key2) { + const oldValues = this.invMap.get(key2); + if (!oldValues) + return false; + this.invMap.delete(key2); + for (const value of oldValues) { + this.map.get(value)?.delete(key2); } + return true; } - return jsxRuntimeExports.jsx(SelectRangeContext.Provider, { value: { selected, onDayClick, modifiers }, children }); -} -function useSelectRange() { - var context = (0, import_react41.useContext)(SelectRangeContext); - if (!context) { - throw new Error("useSelectRange must be used within a SelectRangeProvider"); + rename(oldKey, newKey) { + const oldValues = this.map.get(oldKey); + if (!oldValues) + return false; + this.delete(oldKey); + this.set(newKey, oldValues); + return true; } - return context; -} -function matcherToArray(matcher) { - if (Array.isArray(matcher)) { - return __spreadArray([], matcher, true); - } else if (matcher !== void 0) { - return [matcher]; - } else { + renameInverse(oldKey, newKey) { + const oldValues = this.invMap.get(oldKey); + if (!oldValues) + return false; + this.deleteInverse(oldKey); + this.setInverse(newKey, oldValues); + return true; + } + clear() { + this.map.clear(); + this.invMap.clear(); + } +}; +var IndexMap = _IndexMap; +IndexMap.EMPTY_SET = Object.freeze(/* @__PURE__ */ new Set()); + +// src/core/utils/spaces/query.ts +var filterPathsForAny = (paths, filters, props) => { + const newArray = filters.reduce((p, c3) => { + const [result, remaining] = p; + const filteredPaths = c3.type == "context" ? filterContext(remaining, c3, props) : c3.type == "path" ? filterPathCache(remaining, c3, props) : c3.type == "frontmatter" ? filterFM(remaining, c3, props) : filterPathProperties(remaining, c3, props); + const diffArray = remaining.filter((x2) => !filteredPaths.includes(x2)); + return [[...result, ...filteredPaths], diffArray]; + }, [[], paths]); + return newArray[0]; +}; +var filterPathsForAll2 = (paths, filters, props) => { + return filters.reduce((p, c3) => { + return c3.type == "context" ? filterContext(p, c3, props) : c3.type == "path" ? filterPathCache(p, c3, props) : c3.type == "frontmatter" ? filterFM(p, c3, props) : filterPathProperties(p, c3, props); + }, paths); +}; +var filterContext = (paths, def, props) => { + const filterFn = filterFnTypes[def.fn]; + if (!filterFn || filterFn.valueType != "none" && def.value.length == 0) { return []; } -} -function getCustomModifiers(dayModifiers) { - var customModifiers = {}; - Object.entries(dayModifiers).forEach(function(_a) { - var modifier = _a[0], matcher = _a[1]; - customModifiers[modifier] = matcherToArray(matcher); + return paths.filter((f2) => { + const [contextPath, field] = def.field.split("."); + const fm = f2.metadata?.property; + if (!f2.spaces?.includes(contextPath)) + return false; + if (!fm || !fm[field]) { + return false; + } + let result = true; + if (filterFn) { + const value = def.fType == "property" ? props[def.value] : def.value; + result = filterFn.fn(parseProperty(field, fm[field]), value); + } + return result; }); - return customModifiers; -} -var InternalModifier; -(function(InternalModifier2) { - InternalModifier2["Outside"] = "outside"; - InternalModifier2["Disabled"] = "disabled"; - InternalModifier2["Selected"] = "selected"; - InternalModifier2["Hidden"] = "hidden"; - InternalModifier2["Today"] = "today"; - InternalModifier2["RangeStart"] = "range_start"; - InternalModifier2["RangeEnd"] = "range_end"; - InternalModifier2["RangeMiddle"] = "range_middle"; -})(InternalModifier || (InternalModifier = {})); -var Selected = InternalModifier.Selected; -var Disabled = InternalModifier.Disabled; -var Hidden = InternalModifier.Hidden; -var Today = InternalModifier.Today; -var RangeEnd = InternalModifier.RangeEnd; -var RangeMiddle = InternalModifier.RangeMiddle; -var RangeStart = InternalModifier.RangeStart; -var Outside2 = InternalModifier.Outside; -function getInternalModifiers(dayPicker, selectMultiple, selectRange2) { - var _a; - var internalModifiers = (_a = {}, _a[Selected] = matcherToArray(dayPicker.selected), _a[Disabled] = matcherToArray(dayPicker.disabled), _a[Hidden] = matcherToArray(dayPicker.hidden), _a[Today] = [dayPicker.today], _a[RangeEnd] = [], _a[RangeMiddle] = [], _a[RangeStart] = [], _a[Outside2] = [], _a); - if (dayPicker.fromDate) { - internalModifiers[Disabled].push({ before: dayPicker.fromDate }); - } - if (dayPicker.toDate) { - internalModifiers[Disabled].push({ after: dayPicker.toDate }); +}; +var filterFM = (paths, def, props) => { + const filterFn = filterFnTypes[def.fn]; + if (!filterFn || filterFn.valueType != "none" && def.value.length == 0) { + return []; } - if (isDayPickerMultiple(dayPicker)) { - internalModifiers[Disabled] = internalModifiers[Disabled].concat(selectMultiple.modifiers[Disabled]); - } else if (isDayPickerRange(dayPicker)) { - internalModifiers[Disabled] = internalModifiers[Disabled].concat(selectRange2.modifiers[Disabled]); - internalModifiers[RangeStart] = selectRange2.modifiers[RangeStart]; - internalModifiers[RangeMiddle] = selectRange2.modifiers[RangeMiddle]; - internalModifiers[RangeEnd] = selectRange2.modifiers[RangeEnd]; + return paths.filter((f2) => { + const fm = f2.metadata?.property; + if (!fm || fm[def.field] === void 0) { + return false; + } + let result = true; + if (filterFn) { + const value = def.fType == "property" ? props[def.value] : def.value; + result = filterFn.fn(parseProperty(def.field, fm[def.field]), value); + } + return result; + }); +}; +var filterPathCache = (paths, def, props) => { + const filterFn = filterFnTypes[def.fn]; + if (!filterFn || filterFn.valueType != "none" && def.value.length == 0) { + return []; } - return internalModifiers; -} -var ModifiersContext = (0, import_react41.createContext)(void 0); -function ModifiersProvider(props) { - var dayPicker = useDayPicker(); - var selectMultiple = useSelectMultiple(); - var selectRange2 = useSelectRange(); - var internalModifiers = getInternalModifiers(dayPicker, selectMultiple, selectRange2); - var customModifiers = getCustomModifiers(dayPicker.modifiers); - var modifiers = __assign(__assign({}, internalModifiers), customModifiers); - return jsxRuntimeExports.jsx(ModifiersContext.Provider, { value: modifiers, children: props.children }); -} -function useModifiers() { - var context = (0, import_react41.useContext)(ModifiersContext); - if (!context) { - throw new Error("useModifiers must be used within a ModifiersProvider"); + return paths.filter((f2) => { + let value = ""; + if (def.field == "outlinks") { + value = serializeMultiString(f2.outlinks ?? []); + } else if (def.field == "inlinks") { + value = serializeMultiString(f2.inlinks ?? []); + } else if (def.field == "tags") { + value = serializeMultiString(f2.tags ?? []); + } + let result = true; + if (filterFn) { + const defValue = def.fType == "property" ? props[def.value] : def.value; + result = filterFn.fn(value, defValue); + } + return result; + }); +}; +var filterPathProperties = (paths, def, props) => { + const filterFn = filterFnTypes[def.fn]; + if (!filterFn || filterFn.valueType != "none" && def.value.length == 0) { + return []; } - return context; -} -function isDateInterval(matcher) { - return Boolean(matcher && typeof matcher === "object" && "before" in matcher && "after" in matcher); -} -function isDateRange(value) { - return Boolean(value && typeof value === "object" && "from" in value); -} -function isDateAfterType(value) { - return Boolean(value && typeof value === "object" && "after" in value); -} -function isDateBeforeType(value) { - return Boolean(value && typeof value === "object" && "before" in value); -} -function isDayOfWeekType(value) { - return Boolean(value && typeof value === "object" && "dayOfWeek" in value); -} -function isDateInRange(date, range2) { - var _a; - var from = range2.from, to2 = range2.to; - if (from && to2) { - var isRangeInverted = differenceInCalendarDays(to2, from) < 0; - if (isRangeInverted) { - _a = [to2, from], from = _a[0], to2 = _a[1]; + return paths.filter((f2) => { + let result = true; + if (filterFn) { + const value = def.fType == "property" ? props[def.value] : def.value; + result = filterFn.fn(f2.metadata?.[def.type]?.[def.field], value); + } + return result; + }); +}; +var pathByDef = (filters, path2, props) => { + const pathInFilter = filters.reduce((p, c3) => { + if (!p || c3.filters.length == 0) + return false; + const result = c3.type == "any" ? filterPathsForAny([path2], c3.filters, props).length > 0 : filterPathsForAll2([path2], c3.filters, props).length > 0; + return result; + }, true); + return pathInFilter; +}; + +// src/core/utils/superstate/parser.ts +var parsePathState = (cache2) => { + return safelyParseJSON(cache2); +}; + +// src/core/utils/superstate/serializer.ts +var serializePathState = (pathState) => { + return JSON.stringify(pathState); +}; +var stringifyJob = (job) => `${job.type}:${job.path}`; + +// src/core/superstate/superstate.ts +var import_lodash12 = __toESM(require_lodash()); + +// src/schemas/kits/slides.ts +var slidesNode = { + def: { + icon: "ui//gem" + }, + node: { + icon: "ui//gem", + schemaId: "slides", + parentId: "", + name: "Slides", + rank: 0, + id: "slides", + styles: {}, + type: "slides", + props: { + value: "" + }, + types: { + value: "string" } - var isInRange = differenceInCalendarDays(date, from) >= 0 && differenceInCalendarDays(to2, date) >= 0; - return isInRange; } - if (to2) { - return isSameDay(to2, date); +}; +var slideNode = { + def: { + icon: "ui//gem" + }, + node: { + icon: "ui//gem", + schemaId: "slide", + parentId: "", + name: "Slide", + rank: 0, + id: "slide", + styles: {}, + type: "slide", + props: { + value: "" + }, + types: { + value: "string" + } } - if (from) { - return isSameDay(from, date); +}; +var deltaNode = { + def: { + icon: "ui//gem" + }, + node: { + icon: "ui//gem", + schemaId: "delta", + parentId: "", + name: "Delta", + rank: 0, + id: "delta", + styles: {}, + type: "delta" } - return false; -} -function isDateType(value) { - return isDate(value); -} -function isArrayOfDates(value) { - return Array.isArray(value) && value.every(isDate); -} -function isMatch(day, matchers) { - return matchers.some(function(matcher) { - if (typeof matcher === "boolean") { - return matcher; - } - if (isDateType(matcher)) { - return isSameDay(day, matcher); +}; + +// src/schemas/kits/ui.ts +var groupableTypes = ["content", "group", "container", "column", "list", "slides", "slide"]; +var listNode = { + def: { + id: "list", + icon: "ui//list" + }, + node: { + icon: "ui//list", + schemaId: "list", + parentId: "", + name: "List", + rank: 0, + id: "list", + styles: {}, + type: "list", + props: { + value: "" + }, + types: { + value: "multi" } - if (isArrayOfDates(matcher)) { - return matcher.includes(day); + } +}; +var listItemNode = { + def: { + id: "listItem", + icon: "ui//list" + }, + node: { + icon: "ui//list", + schemaId: "listItem", + parentId: "", + name: "List Item", + rank: 0, + id: "listItem", + styles: {}, + type: "listItem", + props: { + value: "" + }, + types: { + value: "object" } - if (isDateRange(matcher)) { - return isDateInRange(day, matcher); + } +}; +var dividerNode = { + def: { + id: "divider", + icon: "ui//minus", + description: i18n_default.frames.divider.description + }, + node: { + icon: "ui//minus", + schemaId: "divider", + parentId: "", + name: i18n_default.frames.divider.label, + rank: 0, + id: "divider", + type: "frame", + styles: { + width: `'100%'`, + height: `'16px'`, + borderBottom: `'1px solid var(--mk-ui-divider)'` } - if (isDayOfWeekType(matcher)) { - return matcher.dayOfWeek.includes(day.getDay()); + } +}; +var countdownNode = { + def: { + id: "countdown", + icon: "ui//clock" + }, + node: { + icon: "ui//clock", + schemaId: "countdown", + parentId: "", + name: "Countdown", + rank: 0, + id: "countdown", + type: "group", + props: { + date: "" + }, + types: { + date: "date" } - if (isDateInterval(matcher)) { - var diffBefore = differenceInCalendarDays(matcher.before, day); - var diffAfter = differenceInCalendarDays(matcher.after, day); - var isDayBefore = diffBefore > 0; - var isDayAfter = diffAfter < 0; - var isClosedInterval = isAfter(matcher.before, matcher.after); - if (isClosedInterval) { - return isDayAfter && isDayBefore; - } else { - return isDayBefore || isDayAfter; + }, + children: [ + { + ...textNode, + node: { + ...textNode.node, + props: { + date: "", + value: `var _second = 1000; + var _minute = _second * 60; + var _hour = _minute * 60; + var _day = _hour * 24; + var timer; + var distance = new Date($root.props['date'])-$api.date.now(); + var days = Math.floor(distance / _day); + var hours = Math.floor((distance % _day) / _hour); + var minutes = Math.floor((distance % _hour) / _minute); + var seconds = Math.floor((distance % _minute) / _second); + return days + ":" + hours + ":" + minutes + ':' + seconds;` + }, + types: { + date: "date", + value: "string" + }, + actions: { + onRun: `setTimeout(() => $saveState({}), 1000)` + } } } - if (isDateAfterType(matcher)) { - return differenceInCalendarDays(day, matcher.after) > 0; - } - if (isDateBeforeType(matcher)) { - return differenceInCalendarDays(matcher.before, day) > 0; + ] +}; +var buttonNode = { + id: "button", + def: { + id: "button", + icon: "ui//mouse-pointer-click", + description: i18n_default.frames.button.description + }, + node: { + icon: "ui//mouse-pointer-click", + schemaId: "button", + parentId: "", + name: i18n_default.frames.button.label, + rank: 0, + id: "button", + type: "group", + props: { + icon: "", + label: "", + iconSize: "18", + action: "", + actionValue: "" + }, + types: { + icon: "icon", + iconSize: "number", + label: "text", + action: "option", + actionValue: "super" + }, + propsAttrs: { + action: JSON.stringify({ + name: i18n_default.properties.super.whenClicked, + icon: "ui//mouse-pointer-click" + }), + actionValue: JSON.stringify({ + name: i18n_default.properties.super.performAction + }) + }, + propsValue: { + icon: JSON.stringify({ + alias: "Icon" + }), + label: JSON.stringify({ + alias: "Label" + }), + iconSize: JSON.stringify({ + alias: "Icon Size" + }), + action: JSON.stringify({ + alias: "Action", + options: [], + source: "$super" + }), + actionValue: JSON.stringify({ + alias: "Action Properties", + dynamic: true, + field: "action" + }) + }, + actions: { + onClick: `$api.commands.run(button.props.action, button.props.actionValue, $contexts, $saveState)` + }, + styles: { + class: `'mk-button'`, + gap: `'4px'` } - if (typeof matcher === "function") { - return matcher(day); + }, + children: [ + { + ...iconNode, + node: { + ...iconNode.node, + props: { + value: `button.props.icon` + }, + styles: { + "--icon-size": 'button.props.iconSize+"px"' + } + } + }, + { ...textNode, node: { ...textNode.node, props: { value: `button.props.label` } } } + ] +}; +var tabsNode = { + id: "tabs", + def: { + id: "tabs", + icon: "ui//tabs" + }, + node: { + icon: "ui//tabs", + schemaId: "tabs", + parentId: "", + name: i18n_default.commands.tabs, + rank: 0, + id: "tabs", + type: "group", + props: { + currentTab: "0", + tabs: "[{'name': 'Tab 1', 'view': ''}, {'name': 'Tab 2', 'view': ''}]" + }, + propsValue: { + tabs: JSON.stringify({ + alias: "Tabs", + typeName: "Tab", + type: { + name: { + type: "text", + value: JSON.stringify({ alias: "Label" }) + }, + view: { + type: "link", + value: JSON.stringify({ alias: "Page" }) + } + } + }), + currentTab: JSON.stringify({ + alias: "Selected Tab" + }) + }, + types: { + tabs: "object-multi", + currentTab: "number" + }, + styles: { + layout: `'row'`, + width: `'100%'`, + gap: `'8px'` } - return false; - }); -} -function getActiveModifiers(day, modifiers, displayMonth) { - var matchedModifiers = Object.keys(modifiers).reduce(function(result, key2) { - var modifier = modifiers[key2]; - if (isMatch(day, modifier)) { - result.push(key2); + }, + children: [ + frameRootWithProps( + { ...listNode, children: [ + frameRootWithProps({ ...listItemNode, children: [ + frameRootWithProps( + textNode, + { + value: `listItem.props.value.name` + }, + { + padding: `'4px 8px'`, + color: `$root.props.currentTab == listItem.props._index ? 'var(--mk-ui-text-primary)' : 'var(--mk-ui-text-tertiary)'`, + borderBottom: `$root.props.currentTab == listItem.props._index ? '2px solid var(--mk-ui-active)' : 'none'` + }, + { + onClick: `$saveState({$root: {props: {currentTab: listItem.props._index}}})` + } + ) + ] }, {}) + ] }, + { value: `$root.props.tabs` }, + { + layout: `'row'`, + columnGap: `'8px'`, + flexWrap: `'wrap'`, + rowGap: `'4px'` + } + ), + frameRootWithProps( + flowNode, + { + value: `$root.props.tabs[$root.props.currentTab].view` + }, + { + padding: `'0px'`, + "--mk-expanded": `true`, + "--mk-min-mode": `true` + }, + {} + ) + ] +}; +var fieldNode = { + id: "field", + def: { + id: "field", + description: i18n_default.frames.field.description + }, + node: { + schemaId: "field", + parentId: "", + name: i18n_default.frames.field.label, + rank: 0, + id: "field", + type: "group", + props: { + type: "", + value: "", + sticker: "", + property: "" + }, + types: { + value: "text", + type: "text", + sticker: "text", + property: "object" + }, + styles: { + "--font-text-size": `'14px'`, + fontSize: `'14px'`, + hidden: `$root.props.value?.length == 0` } - return result; - }, []); - var activeModifiers = {}; - matchedModifiers.forEach(function(modifier) { - return activeModifiers[modifier] = true; - }); - if (displayMonth && !isSameMonth(day, displayMonth)) { - activeModifiers.outside = true; - } - return activeModifiers; -} -function getInitialFocusTarget(displayMonths, modifiers) { - var firstDayInMonth = startOfMonth(displayMonths[0]); - var lastDayInMonth = endOfMonth(displayMonths[displayMonths.length - 1]); - var firstFocusableDay; - var today; - var date = firstDayInMonth; - while (date <= lastDayInMonth) { - var activeModifiers = getActiveModifiers(date, modifiers); - var isFocusable = !activeModifiers.disabled && !activeModifiers.hidden; - if (!isFocusable) { - date = addDays(date, 1); - continue; + }, + children: [ + frameRootWithProps({ ...groupNode, children: [ + frameRootWithProps( + textNode, + { + value: `$root.props.value` + }, + { + padding: `'4px 8px'`, + borderRadius: `'4px'`, + background: `$api.properties.color($root.props.property, $root.props.value)`, + hidden: `$root.props.type != 'option'` + } + ), + frameRootWithProps( + textNode, + { + value: `$root.props.value` + }, + { + hidden: `$root.props.type != 'text' && $root.props.type != 'number' && $root.props.type != 'fileprop'` + } + ), + frameRootWithProps( + { ...groupNode, children: [ + frameRootWithProps(iconNode, { value: `'ui//check'` }, { background: `'var(--mk-ui-active)'`, "width": `'16px'`, height: `'16px'` }), + frameRootWithProps(textNode, { value: `$root.props.property?.name` }) + ] }, + {}, + { + layout: `'row'`, + gap: `'4px'`, + layoutAlign: `'w'`, + height: `'auto'`, + hidden: `$root.props.type != 'boolean'` + } + ), + frameRootWithProps( + imageNode, + { + value: `$root.props.value` + }, + { + width: `'50px'`, + height: `'50px'`, + hidden: `$root.props.type != 'image'` + } + ), + frameRootWithProps( + iconNode, + { + value: `$root.props.value` + }, + { + hidden: `$root.props.type != 'icon'` + } + ), + frameRootWithProps( + flowNode, + { + value: `$root.props.value` + }, + { + hidden: `$root.props.type != 'link' && $root.props.type != 'file' && $root.props.type != 'context'`, + padding: `'0px'` + } + ) + ] }, {}, { + layout: `'row'`, + layoutAlign: `'w'`, + height: `'auto'`, + gap: `'8px'`, + minHeight: `'24px'`, + hidden: `!($root.props.value?.length > 0) || $root.props.type?.contains('multi')` + }), + frameRootWithProps( + { ...listNode, children: [ + frameRootWithProps({ ...listItemNode, children: [ + frameRootWithProps( + textNode, + { + value: `listItem.props.value` + }, + { + padding: `'4px 8px'`, + borderRadius: `'4px'`, + background: `$api.properties.color($root.props.property, listItem.props.value)`, + hidden: `$root.props.type != 'option-multi' && $root.props.type != 'tags'` + } + ), + frameRootWithProps( + flowNode, + { + value: `listItem.props.value` + }, + { + hidden: `$root.props.type != 'link-multi' && $root.props.type != 'context-multi'`, + padding: `'0px'` + } + ) + ] }, {}) + ] }, + { value: `$api.properties.value($root.props.type, $root.props.value)` }, + { + layout: `'row'`, + columnGap: `'8px'`, + flexWrap: `'wrap'`, + rowGap: `'4px'`, + hidden: `!$root.props.type?.includes('multi')` + } + ) + ] +}; +var previewNode = { + id: "preview", + def: { + id: "preview" + }, + node: { + schemaId: "preview", + parentId: "", + name: "Preview", + rank: 0, + id: "preview", + type: "group", + props: { + path: "", + width: `"50px"`, + height: `'50px'`, + radius: `'8px'`, + padding: `'16px'` + }, + types: { + path: "link", + width: "text", + height: "text", + radius: "text", + padding: "text" + }, + styles: { + background: `'var(--background-secondary)'`, + height: `$root.props.height`, + borderRadius: `$root.props.radius`, + overflow: `'hidden'` } - if (activeModifiers.selected) { - return date; + }, + children: [ + frameRootWithProps( + imageNode, + { + value: `$api.path.label(preview.props.path)?.thumbnail` + }, + { + width: `$root.props.width`, + height: `$root.props.height`, + hidden: `$api.path.label(preview.props.path)?.thumbnail?.length == 0`, + borderRadius: `$root.props.radius` + } + ), + frameRootWithProps( + iconNode, + { + value: `$api.path.label(preview.props.path)?.sticker` + }, + { + width: `$root.props.width`, + height: `$root.props.height`, + hidden: `$api.path.label(preview.props.path)?.thumbnail?.length > 0`, + borderRadius: `$root.props.radius`, + background: `$api.path.label(preview.props.path)?.color`, + padding: `$root.props.padding`, + overflow: `'hidden'` + } + ) + ] +}; +var ratingNode = { + id: "rating", + def: { + id: "rating", + icon: "ui//star" + }, + node: { + icon: "ui//star", + schemaId: "rating", + parentId: "", + name: i18n_default.commands.rating, + rank: 0, + id: "rating", + type: "group", + props: { + value: "5", + icon: `'ui//star'` + }, + types: { + value: "number", + icon: "icon" + }, + styles: { + layout: `'row'`, + height: `'16px'` } - if (activeModifiers.today && !today) { - today = date; + }, + children: [ + frameRootWithProps(iconNode, { + value: `$root.props.icon` + }, { + width: `$root.styles.height`, + height: `$root.styles.height`, + hidden: `$root.props.value < 1` + }), + frameRootWithProps(iconNode, { + value: `$root.props.icon` + }, { + width: `$root.styles.height`, + height: `$root.styles.height`, + hidden: `$root.props.value < 2` + }), + frameRootWithProps(iconNode, { + value: `$root.props.icon` + }, { + width: `$root.styles.height`, + height: `$root.styles.height`, + hidden: `$root.props.value < 3` + }), + frameRootWithProps(iconNode, { + value: `$root.props.icon` + }, { + width: `$root.styles.height`, + height: `$root.styles.height`, + hidden: `$root.props.value < 4` + }), + frameRootWithProps(iconNode, { + value: `$root.props.icon` + }, { + width: `$root.styles.height`, + height: `$root.styles.height`, + hidden: `$root.props.value < 5` + }) + ] +}; +var callout = { + id: "callout", + def: { + id: "callout", + icon: "ui//callout" + }, + node: { + icon: "ui//callout", + schemaId: "callout", + parentId: "", + name: i18n_default.commands.callout, + rank: 0, + id: "callout", + type: "group", + props: { + icon: "", + note: "" + }, + types: { + icon: "icon", + note: "link" + }, + styles: { + borderRadius: `'8px'`, + background: `'var(--mk-ui-background-contrast)'`, + width: `'100%'`, + layout: `'row'`, + gap: `'8px'`, + padding: `'16px'` } - if (!firstFocusableDay) { - firstFocusableDay = date; + }, + children: [ + frameRootWithProps(iconNode, { + value: `callout.props.icon` + }, { + width: `'18px'`, + height: `'18px'` + }), + frameRootWithProps({ + ...contentNode, + children: [ + frameRootWithProps(flowNode, { + value: `callout.props.note` + }, { + width: `'100%'`, + "--mk-expanded": `true`, + "--mk-min-mode": `true` + }) + ] + }, {}, { + width: `'auto'`, + flex: `'1'` + }) + ] +}; +var toggleNode = { + id: "toggle", + def: { + id: "toggle", + icon: "ui//collapse-solid", + description: i18n_default.frames.toggle.description + }, + node: { + icon: "ui//collapse-solid", + schemaId: "toggle", + parentId: "", + name: i18n_default.commands.toggle, + rank: 0, + id: "toggle", + type: "group", + props: { + value: "false", + label: "", + note: "" + }, + types: { + value: "boolean", + label: "text", + note: "link" + }, + styles: { + width: `'100%'` } - date = addDays(date, 1); - } - if (today) { - return today; - } else { - return firstFocusableDay; - } -} -var MAX_RETRY = 365; -function getNextFocus(focusedDay, options) { - var moveBy = options.moveBy, direction = options.direction, context = options.context, modifiers = options.modifiers, _a = options.retry, retry = _a === void 0 ? { count: 0, lastFocused: focusedDay } : _a; - var weekStartsOn = context.weekStartsOn, fromDate = context.fromDate, toDate2 = context.toDate, locale2 = context.locale; - var moveFns = { - day: addDays, - week: addWeeks, - month: addMonths, - year: addYears, - startOfWeek: function(date) { - return context.ISOWeek ? startOfISOWeek(date) : startOfWeek(date, { locale: locale2, weekStartsOn }); + }, + children: [ + frameRootWithProps( + { + ...slidesNode, + children: [ + frameRootWithProps( + { + ...slideNode, + children: [ + frameRootWithProps( + { ...deltaNode, node: { ...deltaNode.node, ref: "icon" } }, + {}, + { + transform: `'rotate(90deg)'` + } + ) + ] + }, + { value: "true" } + ), + frameRootWithProps( + { + ...slideNode, + children: [ + frameRootWithProps( + { ...deltaNode, node: { ...deltaNode.node, ref: "icon" } }, + {}, + { + transform: `'rotate(0deg)'` + } + ) + ] + }, + { value: "false" } + ) + ] + }, + { + value: `'value'` + } + ), + frameRootWithProps({ + ...groupNode, + children: [ + { + ...iconNode, + node: { + ...iconNode.node, + props: { + value: `'ui//collapse-solid'` + }, + styles: { + width: `'16px'`, + height: `'16px'`, + transform: `'rotate(90deg)'` + }, + actions: { + onClick: `$saveState({ toggle: {props: { value: !toggle.props.value }} })` + } + } + }, + { ...textNode, node: { ...textNode.node, props: { value: `toggle.props.label` } } } + ] + }, {}, { + height: `'auto'`, + layoutAlign: `'w'`, + gap: `'8px'`, + layout: `'row'` + }), + frameRootWithProps({ + ...contentNode, + children: [ + frameRootWithProps(flowNode, { + value: `toggle.props.note` + }, { + width: `'auto'`, + flex: `'1'`, + "--mk-expanded": `true`, + "--mk-min-mode": `true` + }) + ] + }, {}, { paddingLeft: `'24px'`, hidden: `!toggle.props.value` }) + ] +}; +var progressNode = { + id: "progress", + def: { + id: "progress", + icon: "ui//pie-chart" + }, + node: { + icon: "ui//pie-chart", + schemaId: "progress", + parentId: "", + name: i18n_default.commands.progress, + rank: 0, + id: "progress", + type: "group", + props: { + value: "50", + max: "100", + color: "'var(--background-modifier-form-field)'", + backgroundColor: `'var(--color-orange)'` }, - endOfWeek: function(date) { - return context.ISOWeek ? endOfISOWeek(date) : endOfWeek(date, { locale: locale2, weekStartsOn }); + types: { + value: "number", + max: "number", + color: "color", + backgroundColor: "color" + }, + styles: { + background: `$root.props.color`, + height: `'10px'`, + width: `'100px'`, + borderRadius: `'5px'` } - }; - var newFocusedDay = moveFns[moveBy](focusedDay, direction === "after" ? 1 : -1); - if (direction === "before" && fromDate) { - newFocusedDay = max([fromDate, newFocusedDay]); - } else if (direction === "after" && toDate2) { - newFocusedDay = min([toDate2, newFocusedDay]); - } - var isFocusable = true; - if (modifiers) { - var activeModifiers = getActiveModifiers(newFocusedDay, modifiers); - isFocusable = !activeModifiers.disabled && !activeModifiers.hidden; - } - if (isFocusable) { - return newFocusedDay; - } else { - if (retry.count > MAX_RETRY) { - return retry.lastFocused; + }, + children: [ + { + ...groupNode, + node: { + ...groupNode.node, + styles: { + width: `$root.props.value/$root.props.max*100+'%'`, + height: `'100%'`, + borderRadius: `'5px'`, + background: `$root.props.backgroundColor`, + display: `'block'` + } + } } - return getNextFocus(newFocusedDay, { - moveBy, - direction, - context, - modifiers, - retry: __assign(__assign({}, retry), { count: retry.count + 1 }) - }); - } -} -var FocusContext = (0, import_react41.createContext)(void 0); -function FocusProvider(props) { - var navigation = useNavigation(); - var modifiers = useModifiers(); - var _a = (0, import_react41.useState)(), focusedDay = _a[0], setFocusedDay = _a[1]; - var _b = (0, import_react41.useState)(), lastFocused = _b[0], setLastFocused = _b[1]; - var initialFocusTarget = getInitialFocusTarget(navigation.displayMonths, modifiers); - var focusTarget = (focusedDay !== null && focusedDay !== void 0 ? focusedDay : lastFocused && navigation.isDateDisplayed(lastFocused)) ? lastFocused : initialFocusTarget; - var blur = function() { - setLastFocused(focusedDay); - setFocusedDay(void 0); - }; - var focus = function(date) { - setFocusedDay(date); - }; - var context = useDayPicker(); - var moveFocus = function(moveBy, direction) { - if (!focusedDay) - return; - var nextFocused = getNextFocus(focusedDay, { - moveBy, - direction, - context, - modifiers - }); - if (isSameDay(focusedDay, nextFocused)) - return void 0; - navigation.goToDate(nextFocused, focusedDay); - focus(nextFocused); - }; - var value = { - focusedDay, - focusTarget, - blur, - focus, - focusDayAfter: function() { - return moveFocus("day", "after"); - }, - focusDayBefore: function() { - return moveFocus("day", "before"); + ] +}; +var circularProgressNode = { + id: "circularProgress", + def: { + id: "circularProgress", + icon: "ui//pie-chart" + }, + node: { + icon: "ui//pie-chart", + schemaId: "circularProgress", + parentId: "", + name: i18n_default.commands.circularProgress, + rank: 0, + id: "circularProgress", + type: "group", + props: { + value: "50", + max: "100", + color: `'var(--color-orange)'`, + backgroundColor: "'var(--background-modifier-form-field)'", + ringWidth: "5" }, - focusWeekAfter: function() { - return moveFocus("week", "after"); + types: { + value: "number", + color: "color", + max: "number", + backgroundColor: "color", + ringWidth: "number" }, - focusWeekBefore: function() { - return moveFocus("week", "before"); + styles: { + height: `'100px'`, + width: `'100px'` + } + }, + children: [ + frameRootWithProps( + groupNode, + {}, + { + background: "`conic-gradient(${$root.props.color} ${$root.props.value/$root.props.max*100}%, ${$root.props.backgroundColor} 0)`", + "maskImage": "`radial-gradient(circle calc(calc(${$root.styles.width} - ${$root.props.ringWidth}px) / 2) at calc(50%) calc(50%),transparent 100%,black 0%)`", + height: `'100%'`, + width: `'100%'`, + borderRadius: `'50%'` + } + ) + ] +}; +var cardNode = { + id: "card", + def: { + id: "card", + icon: "ui//mouse-pointer-click" + }, + node: { + icon: "ui//mouse-pointer-click", + schemaId: "card", + parentId: "", + name: i18n_default.commands.card, + rank: 0, + id: "card", + type: "group", + props: { + icon: "", + label: "" }, - focusMonthBefore: function() { - return moveFocus("month", "before"); + types: { + icon: "icon", + label: "text" }, - focusMonthAfter: function() { - return moveFocus("month", "after"); + actions: {}, + styles: { + borderRadius: `'10px'`, + background: `'var(--background-primary-alt)'`, + width: `'160px'`, + height: `'80px'`, + padding: `'16px'`, + border: `'thin solid var(--mk-ui-divider)'` + } + }, + children: [ + { + ...iconNode, + node: { + ...iconNode.node, + props: { + value: `card.props.icon` + } + } }, - focusYearBefore: function() { - return moveFocus("year", "before"); + { ...textNode, node: { ...textNode.node, props: { value: `card.props.label` } } } + ] +}; +var linkNode = { + id: "link", + def: { + id: "link", + icon: "ui//link" + }, + node: { + icon: "ui//link", + schemaId: "link", + parentId: "", + name: i18n_default.commands.link, + rank: 0, + id: "link", + type: "group", + props: { + link: "", + label: `$api.path.label(link.props.link)?.name`, + sticker: `$api.path.label(link.props.link)?.sticker` }, - focusYearAfter: function() { - return moveFocus("year", "after"); + styles: { + class: `'mk-a'`, + layout: '"row"' }, - focusStartOfWeek: function() { - return moveFocus("startOfWeek", "before"); + actions: { + onClick: "$api.path.open(link.props.link, false)" }, - focusEndOfWeek: function() { - return moveFocus("endOfWeek", "after"); - } - }; - return jsxRuntimeExports.jsx(FocusContext.Provider, { value, children: props.children }); -} -function useFocusContext() { - var context = (0, import_react41.useContext)(FocusContext); - if (!context) { - throw new Error("useFocusContext must be used within a FocusProvider"); - } - return context; -} -function useActiveModifiers(day, displayMonth) { - var modifiers = useModifiers(); - var activeModifiers = getActiveModifiers(day, modifiers, displayMonth); - return activeModifiers; -} -var SelectSingleContext = (0, import_react41.createContext)(void 0); -function SelectSingleProvider(props) { - if (!isDayPickerSingle(props.initialProps)) { - var emptyContextValue = { - selected: void 0 - }; - return jsxRuntimeExports.jsx(SelectSingleContext.Provider, { value: emptyContextValue, children: props.children }); - } - return jsxRuntimeExports.jsx(SelectSingleProviderInternal, { initialProps: props.initialProps, children: props.children }); -} -function SelectSingleProviderInternal(_a) { - var initialProps = _a.initialProps, children = _a.children; - var onDayClick = function(day, activeModifiers, e5) { - var _a2, _b, _c; - (_a2 = initialProps.onDayClick) === null || _a2 === void 0 ? void 0 : _a2.call(initialProps, day, activeModifiers, e5); - if (activeModifiers.selected && !initialProps.required) { - (_b = initialProps.onSelect) === null || _b === void 0 ? void 0 : _b.call(initialProps, void 0, day, activeModifiers, e5); - return; - } - (_c = initialProps.onSelect) === null || _c === void 0 ? void 0 : _c.call(initialProps, day, day, activeModifiers, e5); - }; - var contextValue = { - selected: initialProps.selected, - onDayClick - }; - return jsxRuntimeExports.jsx(SelectSingleContext.Provider, { value: contextValue, children }); -} -function useSelectSingle() { - var context = (0, import_react41.useContext)(SelectSingleContext); - if (!context) { - throw new Error("useSelectSingle must be used within a SelectSingleProvider"); - } - return context; -} -function useDayEventHandlers(date, activeModifiers) { - var dayPicker = useDayPicker(); - var single = useSelectSingle(); - var multiple = useSelectMultiple(); - var range2 = useSelectRange(); - var _a = useFocusContext(), focusDayAfter = _a.focusDayAfter, focusDayBefore = _a.focusDayBefore, focusWeekAfter = _a.focusWeekAfter, focusWeekBefore = _a.focusWeekBefore, blur = _a.blur, focus = _a.focus, focusMonthBefore = _a.focusMonthBefore, focusMonthAfter = _a.focusMonthAfter, focusYearBefore = _a.focusYearBefore, focusYearAfter = _a.focusYearAfter, focusStartOfWeek = _a.focusStartOfWeek, focusEndOfWeek = _a.focusEndOfWeek; - var onClick = function(e5) { - var _a2, _b, _c, _d; - if (isDayPickerSingle(dayPicker)) { - (_a2 = single.onDayClick) === null || _a2 === void 0 ? void 0 : _a2.call(single, date, activeModifiers, e5); - } else if (isDayPickerMultiple(dayPicker)) { - (_b = multiple.onDayClick) === null || _b === void 0 ? void 0 : _b.call(multiple, date, activeModifiers, e5); - } else if (isDayPickerRange(dayPicker)) { - (_c = range2.onDayClick) === null || _c === void 0 ? void 0 : _c.call(range2, date, activeModifiers, e5); - } else { - (_d = dayPicker.onDayClick) === null || _d === void 0 ? void 0 : _d.call(dayPicker, date, activeModifiers, e5); - } - }; - var onFocus = function(e5) { - var _a2; - focus(date); - (_a2 = dayPicker.onDayFocus) === null || _a2 === void 0 ? void 0 : _a2.call(dayPicker, date, activeModifiers, e5); - }; - var onBlur = function(e5) { - var _a2; - blur(); - (_a2 = dayPicker.onDayBlur) === null || _a2 === void 0 ? void 0 : _a2.call(dayPicker, date, activeModifiers, e5); - }; - var onMouseEnter = function(e5) { - var _a2; - (_a2 = dayPicker.onDayMouseEnter) === null || _a2 === void 0 ? void 0 : _a2.call(dayPicker, date, activeModifiers, e5); - }; - var onMouseLeave = function(e5) { - var _a2; - (_a2 = dayPicker.onDayMouseLeave) === null || _a2 === void 0 ? void 0 : _a2.call(dayPicker, date, activeModifiers, e5); - }; - var onPointerEnter = function(e5) { - var _a2; - (_a2 = dayPicker.onDayPointerEnter) === null || _a2 === void 0 ? void 0 : _a2.call(dayPicker, date, activeModifiers, e5); - }; - var onPointerLeave = function(e5) { - var _a2; - (_a2 = dayPicker.onDayPointerLeave) === null || _a2 === void 0 ? void 0 : _a2.call(dayPicker, date, activeModifiers, e5); - }; - var onTouchCancel = function(e5) { - var _a2; - (_a2 = dayPicker.onDayTouchCancel) === null || _a2 === void 0 ? void 0 : _a2.call(dayPicker, date, activeModifiers, e5); - }; - var onTouchEnd = function(e5) { - var _a2; - (_a2 = dayPicker.onDayTouchEnd) === null || _a2 === void 0 ? void 0 : _a2.call(dayPicker, date, activeModifiers, e5); - }; - var onTouchMove = function(e5) { - var _a2; - (_a2 = dayPicker.onDayTouchMove) === null || _a2 === void 0 ? void 0 : _a2.call(dayPicker, date, activeModifiers, e5); - }; - var onTouchStart = function(e5) { - var _a2; - (_a2 = dayPicker.onDayTouchStart) === null || _a2 === void 0 ? void 0 : _a2.call(dayPicker, date, activeModifiers, e5); - }; - var onKeyUp = function(e5) { - var _a2; - (_a2 = dayPicker.onDayKeyUp) === null || _a2 === void 0 ? void 0 : _a2.call(dayPicker, date, activeModifiers, e5); - }; - var onKeyDown = function(e5) { - var _a2; - switch (e5.key) { - case "ArrowLeft": - e5.preventDefault(); - e5.stopPropagation(); - dayPicker.dir === "rtl" ? focusDayAfter() : focusDayBefore(); - break; - case "ArrowRight": - e5.preventDefault(); - e5.stopPropagation(); - dayPicker.dir === "rtl" ? focusDayBefore() : focusDayAfter(); - break; - case "ArrowDown": - e5.preventDefault(); - e5.stopPropagation(); - focusWeekAfter(); - break; - case "ArrowUp": - e5.preventDefault(); - e5.stopPropagation(); - focusWeekBefore(); - break; - case "PageUp": - e5.preventDefault(); - e5.stopPropagation(); - e5.shiftKey ? focusYearBefore() : focusMonthBefore(); - break; - case "PageDown": - e5.preventDefault(); - e5.stopPropagation(); - e5.shiftKey ? focusYearAfter() : focusMonthAfter(); - break; - case "Home": - e5.preventDefault(); - e5.stopPropagation(); - focusStartOfWeek(); - break; - case "End": - e5.preventDefault(); - e5.stopPropagation(); - focusEndOfWeek(); - break; + types: { + link: "link", + label: "text", + sticker: "sticker" } - (_a2 = dayPicker.onDayKeyDown) === null || _a2 === void 0 ? void 0 : _a2.call(dayPicker, date, activeModifiers, e5); - }; - var eventHandlers = { - onClick, - onFocus, - onBlur, - onKeyDown, - onKeyUp, - onMouseEnter, - onMouseLeave, - onPointerEnter, - onPointerLeave, - onTouchCancel, - onTouchEnd, - onTouchMove, - onTouchStart - }; - return eventHandlers; -} -function useSelectedDays() { - var dayPicker = useDayPicker(); - var single = useSelectSingle(); - var multiple = useSelectMultiple(); - var range2 = useSelectRange(); - var selectedDays = isDayPickerSingle(dayPicker) ? single.selected : isDayPickerMultiple(dayPicker) ? multiple.selected : isDayPickerRange(dayPicker) ? range2.selected : void 0; - return selectedDays; -} -function isInternalModifier(modifier) { - return Object.values(InternalModifier).includes(modifier); -} -function getDayClassNames(dayPicker, activeModifiers) { - var classNames13 = [dayPicker.classNames.day]; - Object.keys(activeModifiers).forEach(function(modifier) { - var customClassName = dayPicker.modifiersClassNames[modifier]; - if (customClassName) { - classNames13.push(customClassName); - } else if (isInternalModifier(modifier)) { - var internalClassName = dayPicker.classNames["day_".concat(modifier)]; - if (internalClassName) { - classNames13.push(internalClassName); + }, + children: [ + { ...iconNode, node: { ...iconNode.node, props: { value: `link.props.sticker` }, styles: { + width: `'18px'`, + height: `'18px'` + } } }, + { ...textNode, node: { ...textNode.node, props: { value: `link.props.label` } } } + ] +}; + +// src/schemas/kits/calendar.ts +var eventItem = { + def: { + id: "eventItem", + type: "listItem" + }, + node: { + type: "group", + id: "$root", + schemaId: "$root", + name: i18n_default.frames.event.label, + rank: 0 + }, + id: "$root", + children: [ + frameRootWithProps( + flowNode, + { + value: `$contexts.$context['_keyValue']` + }, + { + padding: `'0'`, + "--font-text-weight": `'bold'` } - } - }); - return classNames13; -} -function getDayStyle(dayPicker, activeModifiers) { - var style = __assign({}, dayPicker.styles.day); - Object.keys(activeModifiers).forEach(function(modifier) { - var _a; - style = __assign(__assign({}, style), (_a = dayPicker.modifiersStyles) === null || _a === void 0 ? void 0 : _a[modifier]); - }); - return style; -} -function useDayRender(day, displayMonth, buttonRef) { - var _a; - var _b, _c; - var dayPicker = useDayPicker(); - var focusContext = useFocusContext(); - var activeModifiers = useActiveModifiers(day, displayMonth); - var eventHandlers = useDayEventHandlers(day, activeModifiers); - var selectedDays = useSelectedDays(); - var isButton = Boolean(dayPicker.onDayClick || dayPicker.mode !== "default"); - (0, import_react41.useEffect)(function() { - var _a2; - if (activeModifiers.outside) - return; - if (!focusContext.focusedDay) - return; - if (!isButton) - return; - if (isSameDay(focusContext.focusedDay, day)) { - (_a2 = buttonRef.current) === null || _a2 === void 0 ? void 0 : _a2.focus(); - } - }, [ - focusContext.focusedDay, - day, - buttonRef, - isButton, - activeModifiers.outside - ]); - var className = getDayClassNames(dayPicker, activeModifiers).join(" "); - var style = getDayStyle(dayPicker, activeModifiers); - var isHidden = Boolean(activeModifiers.outside && !dayPicker.showOutsideDays || activeModifiers.hidden); - var DayContentComponent = (_c = (_b = dayPicker.components) === null || _b === void 0 ? void 0 : _b.DayContent) !== null && _c !== void 0 ? _c : DayContent; - var children = jsxRuntimeExports.jsx(DayContentComponent, { date: day, displayMonth, activeModifiers }); - var divProps = { - style, - className, - children, - role: "gridcell" - }; - var isFocusTarget = focusContext.focusTarget && isSameDay(focusContext.focusTarget, day) && !activeModifiers.outside; - var isFocused = focusContext.focusedDay && isSameDay(focusContext.focusedDay, day); - var buttonProps = __assign(__assign(__assign({}, divProps), (_a = { disabled: activeModifiers.disabled, role: "gridcell" }, _a["aria-selected"] = activeModifiers.selected, _a.tabIndex = isFocused || isFocusTarget ? 0 : -1, _a)), eventHandlers); - var dayRender = { - isButton, - isHidden, - activeModifiers, - selectedDays, - buttonProps, - divProps - }; - return dayRender; -} -function Day(props) { - var buttonRef = (0, import_react41.useRef)(null); - var dayRender = useDayRender(props.date, props.displayMonth, buttonRef); - if (dayRender.isHidden) { - return jsxRuntimeExports.jsx("div", { role: "gridcell" }); - } - if (!dayRender.isButton) { - return jsxRuntimeExports.jsx("div", __assign({}, dayRender.divProps)); - } - return jsxRuntimeExports.jsx(Button, __assign({ name: "day", ref: buttonRef }, dayRender.buttonProps)); -} -function WeekNumber(props) { - var weekNumber = props.number, dates = props.dates; - var _a = useDayPicker(), onWeekNumberClick = _a.onWeekNumberClick, styles2 = _a.styles, classNames13 = _a.classNames, locale2 = _a.locale, labelWeekNumber2 = _a.labels.labelWeekNumber, formatWeekNumber2 = _a.formatters.formatWeekNumber; - var content3 = formatWeekNumber2(Number(weekNumber), { locale: locale2 }); - if (!onWeekNumberClick) { - return jsxRuntimeExports.jsx("span", { className: classNames13.weeknumber, style: styles2.weeknumber, children: content3 }); - } - var label = labelWeekNumber2(Number(weekNumber), { locale: locale2 }); - var handleClick = function(e5) { - onWeekNumberClick(weekNumber, dates, e5); - }; - return jsxRuntimeExports.jsx(Button, { name: "week-number", "aria-label": label, className: classNames13.weeknumber, style: styles2.weeknumber, onClick: handleClick, children: content3 }); -} -function Row(props) { - var _a, _b; - var _c = useDayPicker(), styles2 = _c.styles, classNames13 = _c.classNames, showWeekNumber = _c.showWeekNumber, components = _c.components; - var DayComponent = (_a = components === null || components === void 0 ? void 0 : components.Day) !== null && _a !== void 0 ? _a : Day; - var WeeknumberComponent = (_b = components === null || components === void 0 ? void 0 : components.WeekNumber) !== null && _b !== void 0 ? _b : WeekNumber; - var weekNumberCell; - if (showWeekNumber) { - weekNumberCell = jsxRuntimeExports.jsx("td", { className: classNames13.cell, style: styles2.cell, children: jsxRuntimeExports.jsx(WeeknumberComponent, { number: props.weekNumber, dates: props.dates }) }); - } - return jsxRuntimeExports.jsxs("tr", { className: classNames13.row, style: styles2.row, children: [weekNumberCell, props.dates.map(function(date) { - return jsxRuntimeExports.jsx("td", { className: classNames13.cell, style: styles2.cell, role: "presentation", children: jsxRuntimeExports.jsx(DayComponent, { displayMonth: props.displayMonth, date }) }, getUnixTime(date)); - })] }); -} -function daysToMonthWeeks(fromDate, toDate2, options) { - var toWeek = (options === null || options === void 0 ? void 0 : options.ISOWeek) ? endOfISOWeek(toDate2) : endOfWeek(toDate2, options); - var fromWeek = (options === null || options === void 0 ? void 0 : options.ISOWeek) ? startOfISOWeek(fromDate) : startOfWeek(fromDate, options); - var nOfDays = differenceInCalendarDays(toWeek, fromWeek); - var days = []; - for (var i4 = 0; i4 <= nOfDays; i4++) { - days.push(addDays(fromWeek, i4)); - } - var weeksInMonth = days.reduce(function(result, date) { - var weekNumber = (options === null || options === void 0 ? void 0 : options.ISOWeek) ? getISOWeek(date) : getWeek(date, options); - var existingWeek = result.find(function(value) { - return value.weekNumber === weekNumber; - }); - if (existingWeek) { - existingWeek.dates.push(date); - return result; - } - result.push({ - weekNumber, - dates: [date] - }); - return result; - }, []); - return weeksInMonth; -} -function getMonthWeeks(month, options) { - var weeksInMonth = daysToMonthWeeks(startOfMonth(month), endOfMonth(month), options); - if (options === null || options === void 0 ? void 0 : options.useFixedWeeks) { - var nrOfMonthWeeks = getWeeksInMonth(month, options); - if (nrOfMonthWeeks < 6) { - var lastWeek = weeksInMonth[weeksInMonth.length - 1]; - var lastDate = lastWeek.dates[lastWeek.dates.length - 1]; - var toDate2 = addWeeks(lastDate, 6 - nrOfMonthWeeks); - var extraWeeks = daysToMonthWeeks(addWeeks(lastDate, 1), toDate2, options); - weeksInMonth.push.apply(weeksInMonth, extraWeeks); - } - } - return weeksInMonth; -} -function Table(props) { - var _a, _b, _c; - var _d = useDayPicker(), locale2 = _d.locale, classNames13 = _d.classNames, styles2 = _d.styles, hideHead = _d.hideHead, fixedWeeks = _d.fixedWeeks, components = _d.components, weekStartsOn = _d.weekStartsOn, firstWeekContainsDate = _d.firstWeekContainsDate, ISOWeek = _d.ISOWeek; - var weeks = getMonthWeeks(props.displayMonth, { - useFixedWeeks: Boolean(fixedWeeks), - ISOWeek, - locale: locale2, - weekStartsOn, - firstWeekContainsDate - }); - var HeadComponent = (_a = components === null || components === void 0 ? void 0 : components.Head) !== null && _a !== void 0 ? _a : Head; - var RowComponent = (_b = components === null || components === void 0 ? void 0 : components.Row) !== null && _b !== void 0 ? _b : Row; - var FooterComponent = (_c = components === null || components === void 0 ? void 0 : components.Footer) !== null && _c !== void 0 ? _c : Footer; - return jsxRuntimeExports.jsxs("table", { id: props.id, className: classNames13.table, style: styles2.table, role: "grid", "aria-labelledby": props["aria-labelledby"], children: [!hideHead && jsxRuntimeExports.jsx(HeadComponent, {}), jsxRuntimeExports.jsx("tbody", { className: classNames13.tbody, style: styles2.tbody, children: weeks.map(function(week) { - return jsxRuntimeExports.jsx(RowComponent, { displayMonth: props.displayMonth, dates: week.dates, weekNumber: week.weekNumber }, week.weekNumber); - }) }), jsxRuntimeExports.jsx(FooterComponent, { displayMonth: props.displayMonth })] }); -} -function canUseDOM2() { - return !!(typeof window !== "undefined" && window.document && window.document.createElement); -} -var useIsomorphicLayoutEffect2 = canUseDOM2() ? import_react41.useLayoutEffect : import_react41.useEffect; -var serverHandoffComplete = false; -var id2 = 0; -function genId2() { - return "react-day-picker-".concat(++id2); -} -function useId(providedId) { - var _a; - var initialId = providedId !== null && providedId !== void 0 ? providedId : serverHandoffComplete ? genId2() : null; - var _b = (0, import_react41.useState)(initialId), id3 = _b[0], setId = _b[1]; - useIsomorphicLayoutEffect2(function() { - if (id3 === null) { - setId(genId2()); - } - }, []); - (0, import_react41.useEffect)(function() { - if (serverHandoffComplete === false) { - serverHandoffComplete = true; - } - }, []); - return (_a = providedId !== null && providedId !== void 0 ? providedId : id3) !== null && _a !== void 0 ? _a : void 0; -} -function Month(props) { - var _a; - var _b; - var dayPicker = useDayPicker(); - var dir = dayPicker.dir, classNames13 = dayPicker.classNames, styles2 = dayPicker.styles, components = dayPicker.components; - var displayMonths = useNavigation().displayMonths; - var captionId = useId(dayPicker.id ? "".concat(dayPicker.id, "-").concat(props.displayIndex) : void 0); - var tableId = dayPicker.id ? "".concat(dayPicker.id, "-grid-").concat(props.displayIndex) : void 0; - var className = [classNames13.month]; - var style = styles2.month; - var isStart = props.displayIndex === 0; - var isEnd = props.displayIndex === displayMonths.length - 1; - var isCenter = !isStart && !isEnd; - if (dir === "rtl") { - _a = [isStart, isEnd], isEnd = _a[0], isStart = _a[1]; - } - if (isStart) { - className.push(classNames13.caption_start); - style = __assign(__assign({}, style), styles2.caption_start); - } - if (isEnd) { - className.push(classNames13.caption_end); - style = __assign(__assign({}, style), styles2.caption_end); - } - if (isCenter) { - className.push(classNames13.caption_between); - style = __assign(__assign({}, style), styles2.caption_between); - } - var CaptionComponent = (_b = components === null || components === void 0 ? void 0 : components.Caption) !== null && _b !== void 0 ? _b : Caption; - return jsxRuntimeExports.jsxs("div", { className: className.join(" "), style, children: [jsxRuntimeExports.jsx(CaptionComponent, { id: captionId, displayMonth: props.displayMonth, displayIndex: props.displayIndex }), jsxRuntimeExports.jsx(Table, { id: tableId, "aria-labelledby": captionId, displayMonth: props.displayMonth })] }, props.displayIndex); -} -function Months(props) { - var _a = useDayPicker(), classNames13 = _a.classNames, styles2 = _a.styles; - return jsxRuntimeExports.jsx("div", { className: classNames13.months, style: styles2.months, children: props.children }); -} -function Root(_a) { - var _b, _c; - var initialProps = _a.initialProps; - var dayPicker = useDayPicker(); - var focusContext = useFocusContext(); - var navigation = useNavigation(); - var _d = (0, import_react41.useState)(false), hasInitialFocus = _d[0], setHasInitialFocus = _d[1]; - (0, import_react41.useEffect)(function() { - if (!dayPicker.initialFocus) - return; - if (!focusContext.focusTarget) - return; - if (hasInitialFocus) - return; - focusContext.focus(focusContext.focusTarget); - setHasInitialFocus(true); - }, [ - dayPicker.initialFocus, - hasInitialFocus, - focusContext.focus, - focusContext.focusTarget, - focusContext - ]); - var classNames13 = [dayPicker.classNames.root, dayPicker.className]; - if (dayPicker.numberOfMonths > 1) { - classNames13.push(dayPicker.classNames.multiple_months); - } - if (dayPicker.showWeekNumber) { - classNames13.push(dayPicker.classNames.with_weeknumber); - } - var style = __assign(__assign({}, dayPicker.styles.root), dayPicker.style); - var dataAttributes = Object.keys(initialProps).filter(function(key2) { - return key2.startsWith("data-"); - }).reduce(function(attrs, key2) { - var _a2; - return __assign(__assign({}, attrs), (_a2 = {}, _a2[key2] = initialProps[key2], _a2)); - }, {}); - var MonthsComponent = (_c = (_b = initialProps.components) === null || _b === void 0 ? void 0 : _b.Months) !== null && _c !== void 0 ? _c : Months; - return jsxRuntimeExports.jsx("div", __assign({ className: classNames13.join(" "), style, dir: dayPicker.dir, id: dayPicker.id, nonce: initialProps.nonce, title: initialProps.title, lang: initialProps.lang }, dataAttributes, { children: jsxRuntimeExports.jsx(MonthsComponent, { children: navigation.displayMonths.map(function(month, i4) { - return jsxRuntimeExports.jsx(Month, { displayIndex: i4, displayMonth: month }, i4); - }) }) })); -} -function RootProvider(props) { - var children = props.children, initialProps = __rest(props, ["children"]); - return jsxRuntimeExports.jsx(DayPickerProvider, { initialProps, children: jsxRuntimeExports.jsx(NavigationProvider, { children: jsxRuntimeExports.jsx(SelectSingleProvider, { initialProps, children: jsxRuntimeExports.jsx(SelectMultipleProvider, { initialProps, children: jsxRuntimeExports.jsx(SelectRangeProvider, { initialProps, children: jsxRuntimeExports.jsx(ModifiersProvider, { children: jsxRuntimeExports.jsx(FocusProvider, { children }) }) }) }) }) }) }); -} -function DayPicker(props) { - return jsxRuntimeExports.jsx(RootProvider, __assign({}, props, { children: jsxRuntimeExports.jsx(Root, { initialProps: props }) })); -} + ) + ] +}; +var dateGroup = { + def: { + id: "dateGroup", + type: "listGroup" + }, + node: { + type: "group", + props: { _groupValue: "" }, + styles: { + layout: `'column'`, + background: `'var(--mk-ui-background-variant)'`, + padding: `'6px'`, + height: `'150px'`, + overflow: `'hidden'`, + width: `'100%'` + }, + id: "$root", + schemaId: "$root", + name: "Date", + rank: 0 + }, + id: "$root", + children: [ + frameRootWithProps( + textNode, + { + value: `$api.date.component($api.date.parse($root.props['_groupValue']), 'day')` + }, + { + padding: `'4px'`, + "--font-text-weight": `'bold'` + } + ), + frameRootWithProps( + contentNode, + {}, + { + gap: `'2px'`, + layout: `'column'` + } + ) + ] +}; +var calendarView = { + def: { + id: "calendarView", + type: "listView" + }, + node: { + type: "group", + props: { + year: `$api.date.component($api.date.offset($api.date.now(), $root.props.offset, 'month'), 'year')`, + month: `$api.date.component($api.date.offset($api.date.now(), $root.props.offset, 'month'), 'month')`, + offset: `0`, + startOfMonth: `$root.props.year+'-'+$root.props.month+'-01'`, + endOfMonth: `$root.props.year+'-'+$root.props.month+'-'+$api.date.daysInMonth($api.date.parse($root.props.startOfMonth))`, + dayOfWeek: `$api.date.component($api.date.parse($root.props.startOfMonth), 'dayOfWeek')`, + groupFilter: `'isSameDate'`, + groupOptions: `$api.date.range($api.date.parse($root.props.startOfMonth), $api.date.parse($root.props.endOfMonth))` + }, + id: "$root", + schemaId: "$root", + name: i18n_default.frames.calendar.label, + rank: 0 + }, + id: "$root", + children: [ + frameRootWithProps( + { ...groupNode, children: [ + frameRootWithProps( + { ...groupNode, children: [ + frameRootWithProps(textNode, { + value: `$api.date.format($api.date.parse($root.props.startOfMonth), 'MMMM')` + }, { + padding: `'8px'`, + "--font-text-weight": `'bold'`, + "class": `'mk-t-h1'` + }), + frameRootWithProps({ ...groupNode, children: [ + kitWithProps(buttonNode, { + icon: `'ui//chevron-left'` + }, {}, { + onClick: `$saveState({$root: {props: {offset: $root.props.offset - 1}}})` + }), + kitWithProps(buttonNode, { + label: `'Today'` + }, {}, { + onClick: `$saveState({$root: {props: {offset: 0}}})` + }), + kitWithProps(buttonNode, { + icon: `'ui//chevron-right'` + }, {}, { + onClick: `$saveState({$root: {props: {offset: $root.props.offset + 1}}})` + }) + ] }, {}, { layout: `'row'` }) + ] }, + {}, + { + width: `'100%'` + } + ) + ] }, + {} + ), + frameRootWithProps( + { + ...groupNode, + children: [ + frameRootWithProps(textNode, { + value: `'Sunday'` + }, { + padding: `'8px'`, + "--font-text-weight": `'bold'` + }), + frameRootWithProps(textNode, { + value: `'Monday'` + }, { + padding: `'8px'`, + "--font-text-weight": `'bold'` + }), + frameRootWithProps(textNode, { + value: `'Tuesday'` + }, { + padding: `'8px'`, + "--font-text-weight": `'bold'` + }), + frameRootWithProps(textNode, { + value: `'Wednesday'` + }, { + padding: `'8px'`, + "--font-text-weight": `'bold'` + }), + frameRootWithProps(textNode, { + value: `'Thursday'` + }, { + padding: `'8px'`, + "--font-text-weight": `'bold'` + }), + frameRootWithProps(textNode, { + value: `'Friday'` + }, { + padding: `'8px'`, + "--font-text-weight": `'bold'` + }), + frameRootWithProps(textNode, { + value: `'Saturday'` + }, { + padding: `'8px'`, + "--font-text-weight": `'bold'` + }) + ] + }, + {}, + { + width: `'100%'`, + height: `'auto'`, + layout: `'grid'`, + "--mk-grid-columns": `'7'`, + "--mk-grid-width": `'0'` + } + ), + frameRootWithProps( + { ...contentNode, children: [ + frameRootWithProps( + groupNode, + {}, + { + gridColumn: `'span '+$root.props.dayOfWeek` + } + ) + ] }, + {}, + { + padding: `'8px'`, + layout: `'grid'`, + "--mk-grid-columns": `'7'`, + "--mk-grid-width": `'0'`, + gap: `'1px'` + } + ) + ] +}; -// src/core/react/components/UI/Menus/properties/datePickerMenu.tsx -var showDatePickerMenu = (ui, rect, value, setValue, time, format8, anchor) => { - return ui.openCustomMenu( - rect, - /* @__PURE__ */ import_react42.default.createElement(DatePicker, { - ui, - value, - setValue, - time - }), - {}, - anchor - ); +// src/schemas/kits/list.ts +var fieldsView = { + id: "fieldsView", + def: { + id: "fieldsView" + }, + node: { + schemaId: "fieldsView", + parentId: "", + name: "Properties", + rank: 0, + id: "fieldsView", + type: "group" + }, + children: [frameRootWithProps({ ...listNode, children: [ + frameRootWithProps({ ...listItemNode, children: [ + kitWithProps(fieldNode, { + sticker: `$api.properties.sticker(listItem.props.value)`, + type: "listItem.props.value.type", + value: "$contexts[listItem.props.value.table?.length > 0 ? listItem.props.value.table : $contexts.$context._path]?.[listItem.props.value.name]", + property: "listItem.props.value" + }) + ] }, {}, { + layout: `'row'`, + gap: `'8px'`, + hidden: "!($contexts[listItem.props.value.table?.length > 0 ? listItem.props.value.table : $contexts.$context._path]?.[listItem.props.value.name]?.length > 0)" + }) + ] }, { + value: `$contexts.$context._properties?.filter(f => f.primary != 'true') ?? []` + }, { + layout: `'column'`, + gap: `'4px'` + })] }; -var DatePickerHeader = (props) => { - const { goToMonth, nextMonth, previousMonth } = useNavigation(); - return /* @__PURE__ */ import_react42.default.createElement("div", { - className: "mk-date-picker-header" - }, /* @__PURE__ */ import_react42.default.createElement("button", { - disabled: !previousMonth, - onClick: () => previousMonth && goToMonth(previousMonth), - dangerouslySetInnerHTML: { - __html: props.ui.getSticker("ui//chevron-left") - } - }), format(props.displayMonth, "MMM yyy"), /* @__PURE__ */ import_react42.default.createElement("button", { - disabled: !nextMonth, - onClick: () => nextMonth && goToMonth(nextMonth), - dangerouslySetInnerHTML: { - __html: props.ui.getSticker("ui//chevron-right") +var coverListItem = { + def: { + id: "coverListItem", + type: "listItem" + }, + node: { + type: "group", + id: "$root", + schemaId: "$root", + name: "Cover Item", + rank: 0, + props: {}, + styles: { + layout: `"column"` } - })); + }, + id: "$root", + children: [ + frameRootWithProps( + imageNode, + { + value: `$api.path.label($contexts.$context['_keyValue'])?.thumbnail` + }, + { + borderRadius: `'8px'`, + width: `'200px'`, + height: `'300px'` + } + ), + frameRootWithProps( + flowNode, + { + value: `$contexts.$context['_keyValue']` + }, + { + padding: `'4px'` + } + ) + ] }; -var DatePicker = (props) => { - const [hour, setHour] = (0, import_react42.useState)(0); - const [minutes, setMinutes] = (0, import_react42.useState)(0); - const [seconds, setSeconds] = (0, import_react42.useState)(0); - const [date, setDate] = (0, import_react42.useState)(props.value); - (0, import_react42.useEffect)(() => { - const date2 = props.value ?? new Date(); - setHour(date2.getHours()); - setMinutes(date2.getMinutes()); - setSeconds(date2.getSeconds()); - setDate(date2); - }, [props.value]); - const updateDate = () => { - const newDate = new Date(date); - if (props.time) { - newDate.setHours(hour); - newDate.setMinutes(minutes); - newDate.setSeconds(seconds); - } - props.setValue(newDate); - }; - return /* @__PURE__ */ import_react42.default.createElement("div", { - className: "mk-date-picker-container" - }, /* @__PURE__ */ import_react42.default.createElement(DayPicker, { - defaultMonth: date, - mode: "single", - selected: date, - classNames: { - root: "mk-date-picker", - day: "mk-date-picker-day", - cell: "mk-date-picker-cell", - months: "mk-date-picker-months", - month: "mk-date-picker-month", - day_today: "mk-date-picker-today", - day_selected: "mk-date-picker-selected" - }, - components: { - Caption: (_props) => DatePickerHeader({ ui: props.ui, ..._props }) +var imageListItem = { + def: { + id: "imageListItem", + type: "listItem" + }, + node: { + type: "group", + id: "$root", + schemaId: "$root", + name: "Image Item", + rank: 0, + props: { + _selected: `$root.props['_selectedIndex'] == $contexts.$context['_index']` }, - labels: { - labelMonthDropdown: () => void 0, - labelYearDropdown: () => void 0, - labelNext: () => void 0, - labelPrevious: () => void 0, - labelDay: () => void 0, - labelWeekday: () => void 0, - labelWeekNumber: () => void 0 + styles: { + layout: `"row"`, + padding: `'4px'` }, - onSelect: (date2, s4, a4, e5) => { - setDate(date2); - props.setValue(date2); - e5.stopPropagation(); - } - }), props.time != 0 /* None */ && /* @__PURE__ */ import_react42.default.createElement("div", { - className: "mk-date-picker-time" - }, /* @__PURE__ */ import_react42.default.createElement("div", { - dangerouslySetInnerHTML: { - __html: props.ui.getSticker("ui//clock") + actions: { + onClick: `$saveState({ $root: {props: {_selectedIndex: $contexts.$context['_index']}} });`, + onDoubleClick: `$api.table.open($contexts.$context['_keyValue'], false)`, + onContextMenu: `$api.table.contextMenu($event, $contexts.$context['_path'], $contexts.$context['_schema'], $contexts.$context['_index'])` } - }), /* @__PURE__ */ import_react42.default.createElement("input", { - type: "text", - value: hour.toString().padStart(2, "0"), - onKeyDown: (e5) => { - if (e5.key === "ArrowUp") { - setHour((hour + 1) % 24); - updateDate(); - } else if (e5.key === "ArrowDown") { - setHour((hour + 23) % 24); - updateDate(); + }, + id: "$root", + children: [ + frameRootWithProps( + imageNode, + { + value: `$api.path.label($contexts.$context['_keyValue'])?.thumbnail` + }, + { + borderRadius: `'8px'` } + ) + ] +}; +var flowListItem = { + def: { + id: "flowListItem", + type: "listItem" + }, + node: { + type: "group", + id: "$root", + schemaId: "$root", + name: "Flow Item", + rank: 0, + props: { + _selected: `$root.props['_selectedIndex'] == $contexts.$context['_index']`, + expanded: "true", + seamless: "false" }, - onChange: (e5) => { - setHour(+e5.target.value); - updateDate(); - } - }), ":", /* @__PURE__ */ import_react42.default.createElement("input", { - type: "text", - value: minutes.toString().padStart(2, "0"), - onKeyDown: (e5) => { - if (e5.key === "ArrowUp") { - setMinutes((minutes + 1) % 60); - updateDate(); - } else if (e5.key === "ArrowDown") { - setMinutes((minutes + 59) % 60); - updateDate(); + types: { + expanded: "boolean", + seamless: "boolean" + }, + propsValue: { + expanded: { + alias: "Expanded" + }, + seamless: { + alias: "Seamless" } }, - onChange: (e5) => { - setMinutes(+e5.target.value); - updateDate(); - } - }), /* @__PURE__ */ import_react42.default.createElement("button", { - className: "mk-date-picker-meridiem", - onClick: () => { - setHour((hour + 12) % 24); - updateDate(); - } - }, hour < 12 ? "AM" : "PM"), /* @__PURE__ */ import_react42.default.createElement("button", { - onClick: () => updateDate(), - dangerouslySetInnerHTML: { - __html: props.ui.getSticker("ui//close") - } - }))); -}; - -// src/core/utils/contexts/predicate/filterFns/filterFnLabels.ts -var filterFnLabels = { - isEmpty: i18n_default.filterTypes.isEmpty, - isNotEmpty: i18n_default.filterTypes.isNotEmpty, - include: i18n_default.filterTypes.contains, - notInclude: i18n_default.filterTypes.notContains, - is: i18n_default.filterTypes.is, - isNot: i18n_default.filterTypes.isNot, - isLink: i18n_default.filterTypes.is, - isNotLink: i18n_default.filterTypes.isNot, - equal: "=", - isGreatThan: ">", - isLessThan: "<", - isLessThanOrEqual: "\u2264", - isGreatThanOrEqual: "\u2265", - dateBefore: i18n_default.filterTypes.before, - dateAfter: i18n_default.filterTypes.after, - isSameDate: i18n_default.filterTypes.isSameDate, - isSameDateAsToday: i18n_default.filterTypes.isSameDateAsToday, - isExactList: i18n_default.filterTypes.is, - isAnyInList: i18n_default.filterTypes.anyOf, - isNoneInList: i18n_default.filterTypes.noneOf, - isTrue: i18n_default.filterTypes.checked, - isFalse: i18n_default.filterTypes.unchecked -}; - -// src/core/react/components/SpaceEditor/SpaceQuery.tsx -var import_react49 = __toESM(require_react()); - -// src/core/react/components/UI/Menus/navigator/showSpaceAddMenu.tsx -var import_react43 = __toESM(require_react()); -var defaultAddAction = (superstate, space2, location) => { - if (space2?.path == "spaces://$tags") { - superstate.ui.openModal("New Tag", (props) => { - return /* @__PURE__ */ import_react43.default.createElement(InputModal, { - value: "", - saveLabel: i18n_default.labels.saveView, - hide: props.hide, - saveValue: (value) => addTag(superstate, value) - }); - }); - } else if (space2) { - if (space2?.metadata.template?.length > 0) { - newTemplateInSpace(superstate, space2, space2.metadata.template, location); - return; - } else { - newPathInSpace(superstate, space2, "md", null, false, null, location); - } - } else { - defaultSpace( - superstate, - superstate.pathsIndex.get(superstate.ui.activePath) - ).then((f2) => { - if (f2) - newPathInSpace(superstate, f2, "md", null, false, null, location); - }); - } -}; -var showSpaceAddMenu = (superstate, offset2, space2, dontOpen) => { - const menuOptions = []; - if (space2.type == "default") { - menuOptions.push({ - name: "New Tag", - icon: "ui//tags", - onClick: (e5) => { - superstate.ui.openModal("New Tag", (props) => { - return /* @__PURE__ */ import_react43.default.createElement(InputModal, { - value: "", - saveLabel: i18n_default.labels.saveView, - hide: props.hide, - saveValue: (value) => addTag(superstate, value) - }); - }); + styles: { + layout: `"row"`, + gap: `'8px'` + }, + actions: {} + }, + id: "$root", + children: [ + frameRootWithProps( + flowNode, + { + value: `$contexts.$context['_keyValue']` + }, + { + "--mk-expanded": `$root.props.expanded`, + "--mk-min-mode": `$root.props.seamless`, + padding: `'4px'`, + marginBottom: `'8px'` } - }); - } else { - menuOptions.push({ - name: i18n_default.labels.createNote, - icon: "ui//edit", - onClick: (e5) => { - newPathInSpace( - superstate, - space2, - "md", - superstate.settings.newNotePlaceholder, - dontOpen - ); + ) + ] +}; +var cardsListItem = { + def: { + id: "cardsListItem", + type: "listItem" + }, + node: { + type: "group", + id: "$root", + schemaId: "$root", + name: "Cards Item", + rank: 0, + props: { + _selected: `$root.props['_selectedIndex'] == $contexts.$context['_index']`, + coverProperty: `'File'` + }, + types: { + coverProperty: "option" + }, + propsValue: { + coverProperty: { + alias: "Cover Image", + source: `$properties` } - }); - menuOptions.push({ - name: i18n_default.buttons.createCanvas, - icon: "ui//layout-dashboard", - onClick: (e5) => { - newPathInSpace(superstate, space2, "canvas", null, dontOpen); + }, + styles: { + layout: `"column"`, + overflow: `'hidden'`, + borderRadius: `'8px'`, + width: `'100%'`, + height: `'100%'`, + border: `'1px solid var(--mk-ui-border)'`, + boxShadow: `'var(--mk-shadow-card)'` + }, + actions: { + onClick: `$saveState({ $root: {props: {_selectedIndex: $contexts.$context['_index']}} });`, + onDoubleClick: `$api.table.open($contexts.$context['_keyValue'], false)`, + onContextMenu: `$api.table.contextMenu($event, $contexts.$context['_path'], $contexts.$context['_schema'], $contexts.$context['_index'])` + } + }, + id: "$root", + children: [ + frameRootWithProps( + { + ...slidesNode, + children: [ + frameRootWithProps( + { + ...slideNode, + children: [ + frameRootWithProps( + { ...deltaNode, node: { ...deltaNode.node, ref: "$root" } }, + {}, + { + background: `'var(--mk-ui-background-selected)'` + } + ) + ] + }, + { value: "true" } + ), + frameRootWithProps( + { + ...slideNode, + children: [ + frameRootWithProps( + { ...deltaNode, node: { ...deltaNode.node, ref: "$root" } }, + {}, + { + background: `'var(--mk-ui-background)'` + } + ) + ] + }, + { value: "false" } + ) + ] + }, + { + value: `'_selected'` } - }); - menuOptions.push({ - name: i18n_default.labels.createSection, - icon: "ui//folder-plus", - onClick: (e5) => { - superstate.ui.openModal( - i18n_default.labels.createSection, - (props) => /* @__PURE__ */ import_react43.default.createElement(InputModal, { - saveLabel: i18n_default.buttons.createFolder, - value: "", - hide: props.hide, - saveValue: (v2) => { - let pathState = superstate.pathsIndex.get(space2?.path); - if (!pathState) { - pathState = superstate.pathsIndex.get("/"); - } - const newName = v2.replace(/\//g, ""); - const parentPath = pathState?.subtype == "folder" ? pathState.path : pathState.parent ? pathState.parent : "/"; - const newPath = !parentPath || parentPath == "/" ? newName : parentPath + "/" + newName; - if (newName.length == 0) { - superstate.ui.notify(i18n_default.notice.newSpaceName); - return; - } - if (superstate.spacesIndex.has(newPath)) { - superstate.ui.notify(i18n_default.notice.duplicateSpaceName); - return; - } - createSpace(superstate, newPath, {}); - } - }) - ); + ), + frameRootWithProps( + { ...groupNode, children: [ + frameRootWithProps( + imageNode, + { + value: `$api.path.label($contexts[$contexts.$context['_path']]?.[$root.props.coverProperty])?.thumbnail` + }, + { + width: `'100%'`, + height: `'80px'` + } + ) + ] }, + {}, + { + width: `'100%'`, + height: `'80px'`, + background: `'var(--mk-ui-background-contrast)'` } - }); - if (space2.templates.length > 0) { - menuOptions.push(menuSeparator); - for (const template2 of space2.templates) { - menuOptions.push({ - name: template2, - icon: "ui//clipboard-pen", - onClick: (e5) => { - newTemplateInSpace(superstate, space2, template2); + ), + frameRootWithProps( + { ...groupNode, children: [ + frameRootWithProps( + iconNode, + { + value: `$api.path.label($contexts.$context['_keyValue'])?.sticker` + }, + { + width: `'32px'`, + height: `'32px'`, + padding: `'4px'`, + "--icon-size": `'24px'`, + borderRadius: `'4px'`, + overflow: `'hidden'`, + background: `$api.path.label($contexts.$context['_keyValue'])?.color` } - }); + ) + ] }, + {}, + { + width: `'32px'`, + height: `'32px'`, + marginTop: `'-16px'`, + marginLeft: `'4px'`, + borderRadius: `'4px'`, + background: `'var(--mk-ui-background-contrast)'` } + ), + { + ...groupNode, + node: { + ...groupNode.node, + styles: { + gap: `'8px'`, + padding: `'8px'`, + flex: `'1'` + } + }, + children: [ + frameRootWithProps( + textNode, + { + value: `$contexts.$context['_name']` + }, + { + "--font-text-weight": `'var(--bold-weight)'` + } + ), + kitWithProps(fieldsView, {}, { marginTop: `'8px'` }) + ] } - } - return superstate.ui.openMenu( - offset2, - defaultMenu(superstate.ui, menuOptions) - ); + ] }; - -// src/core/react/components/UI/Menus/properties/propertyMenu.tsx -var showSetValueMenu = (rect, superstate, property, onChangeValue, path2) => { - if (!property) - return; - if (property.type == "text") { - } else if (property.type == "number") { - const input = menuInput("", (value) => onChangeValue(value)); - superstate.ui.openMenu(rect, { - ...defaultMenu(superstate.ui, [input]) - }); - } else if (property.type == "date") { - showDatePickerMenu( - superstate.ui, - rect, - new Date(), - (date) => onChangeValue(date.toISOString()), - 0 /* None */ - ); - } else if (property.type == "option") { - const options = parseFieldValue(property.value, property.type, superstate, path2)?.options ?? []; - superstate.ui.openMenu(rect, { - ...defaultMenu(superstate.ui, options), - saveOptions: (options2, value) => { - onChangeValue(value[0]); +var cardListItem = { + def: { + id: "cardListItem", + type: "listItem" + }, + node: { + type: "group", + id: "$root", + schemaId: "$root", + name: "Card Item", + rank: 0, + props: { + _selected: `$root.props['_selectedIndex'] == $contexts.$context['_index']` + }, + styles: { + layout: `"column"`, + overflow: `'hidden'`, + borderRadius: `'8px'`, + width: `'100%'`, + border: `'1px solid var(--mk-ui-border)'` + }, + actions: { + onClick: `$saveState({ $root: {props: {_selectedIndex: $contexts.$context['_index']}} });`, + onDoubleClick: `$api.path.open($contexts.$context['_keyValue'], false)`, + onContextMenu: `$api.table.contextMenu($event, $contexts.$context['_path'], $contexts.$context['_schema'], $contexts.$context['_index'])` + } + }, + id: "$root", + children: [ + frameRootWithProps( + { + ...slidesNode, + children: [ + frameRootWithProps( + { + ...slideNode, + children: [ + frameRootWithProps( + { ...deltaNode, node: { ...deltaNode.node, ref: "$root" } }, + {}, + { + background: `'var(--mk-ui-background-selected)'` + } + ) + ] + }, + { value: "true" } + ), + frameRootWithProps( + { + ...slideNode, + children: [ + frameRootWithProps( + { ...deltaNode, node: { ...deltaNode.node, ref: "$root" } }, + {}, + { + background: `'var(--mk-ui-background)'` + } + ) + ] + }, + { value: "false" } + ) + ] + }, + { + value: `'_selected'` } - }); - } else if (property.type == "boolean") { - const options = [ - { name: "Yes", value: "true" }, - { name: "No", value: "false" } - ]; - superstate.ui.openMenu(rect, { - ...defaultMenu(superstate.ui, options), - saveOptions: (options2, value) => { - onChangeValue(value[0]); + ), + frameRootWithProps( + imageNode, + { + value: `$api.path.label($contexts.$context['_keyValue'])?.thumbnail` + }, + { + width: `'100%'`, + maxHeight: `'80px'` } - }); - } -}; - -// src/core/react/components/SpaceView/Contexts/FilterBar/FilterBar.tsx -var import_react48 = __toESM(require_react()); - -// src/core/react/components/SpaceView/Contexts/FilterBar/CustomVIewOption.tsx -var import_react44 = __toESM(require_react()); -var CustomViewOption = (props) => { - return /* @__PURE__ */ import_react44.default.createElement("div", { - className: "mk-menu-option", - onClick: () => { - props.onSelect(); - props.hide(); - } - }, /* @__PURE__ */ import_react44.default.createElement(Sticker, { - ui: props.ui, - sticker: props.icon - }), /* @__PURE__ */ import_react44.default.createElement("div", { - className: "mk-menu-options-inner" - }, /* @__PURE__ */ import_react44.default.createElement("span", null, props.type)), props.selected && /* @__PURE__ */ import_react44.default.createElement("div", { - dangerouslySetInnerHTML: { - __html: props.ui.getSticker("ui//check") + ), + { + ...groupNode, + node: { + ...groupNode.node, + styles: { + gap: `'8px'`, + padding: `'8px'`, + flex: `'1'` + } + }, + children: [ + frameRootWithProps( + textNode, + { + value: `$contexts.$context['_name']` + }, + { + "--font-text-weight": `'var(--bold-weight)'` + } + ), + kitWithProps(fieldsView, {}) + ] } - }), /* @__PURE__ */ import_react44.default.createElement("button", { - onClick: (e5) => { - e5.preventDefault(); - props.hide(); - props.onCustomize(); + ] +}; +var listItem = { + def: { + id: "rowItem", + type: "listItem" + }, + node: { + type: "group", + id: "$root", + schemaId: "$root", + name: "List View", + rank: 0, + props: { + _selected: `$root.props['_selectedIndex'] == $contexts.$context['_index']` }, - "aria-label": "Customize", - className: "mk-icon-small mk-inline-button", - dangerouslySetInnerHTML: { - __html: props.ui.getSticker("ui//brush") + styles: { + layout: `"row"`, + gap: `'12px'`, + padding: `'4px'`, + overflow: `'hidden'`, + width: `'100%'` + }, + actions: { + onClick: `$saveState({ $root: {props: {_selectedIndex: $contexts.$context['_index']}} });`, + onDoubleClick: `$api.table.open($contexts.$context['_index'], false)`, + onContextMenu: `$api.table.contextMenu($event, $contexts.$context['_path'], $contexts.$context['_schema'], $contexts.$context['_index'])` } - })); -}; - -// src/core/react/components/UI/Crumbs/ContextViewCrumb.tsx -var import_react45 = __toESM(require_react()); -var ContextViewCrumb = (props) => { - return /* @__PURE__ */ import_react45.default.createElement("div", { - onClick: (e5) => props.onSelect(e5), - onContextMenu: (e5) => props.onContextMenu(e5, props.schema), - className: "mk-context" - }, /* @__PURE__ */ import_react45.default.createElement("div", { - className: "mk-path-icon", - dangerouslySetInnerHTML: { - __html: props.superstate.ui.getSticker( - stickerForSchema(props.schema) - ) + }, + id: "$root", + children: [ + frameRootWithProps( + { + ...slidesNode, + children: [ + frameRootWithProps( + { + ...slideNode, + children: [ + frameRootWithProps( + { ...deltaNode, node: { ...deltaNode.node, ref: "$root" } }, + {}, + { + background: `'var(--mk-ui-background-selected)'` + } + ) + ] + }, + { value: "true" } + ), + frameRootWithProps( + { + ...slideNode, + children: [ + frameRootWithProps( + { ...deltaNode, node: { ...deltaNode.node, ref: "$root" } }, + {}, + { + background: `'transparent'` + } + ) + ] + }, + { value: "false" } + ) + ] + }, + { + value: `'_selected'` + } + ), + kitWithProps( + previewNode, + { + path: `$contexts.$context['_keyValue']`, + width: `'32px'`, + height: `'32px'`, + padding: `'8px'`, + radius: `'4px'` + }, + { + borderRadius: `'4px'`, + background: `'var(--background-secondary)'` + } + ), + { + ...groupNode, + node: { + ...groupNode.node, + styles: { + gap: `'8px'`, + flex: `'1'`, + padding: `'2px'`, + layout: `'column'`, + layoutAlign: `'w'` + } + }, + children: [ + frameRootWithProps( + textNode, + { + value: `$contexts.$context['_name']` + }, + { + "--font-text-size": `'14px'`, + "--font-text-weight": `'var(--bold-weight)'` + } + ) + ] } - }), defaultString(props.schema.name, "Untitled"), props.children); + ] }; - -// src/core/react/components/SpaceView/Contexts/FilterBar/ListSelector.tsx -var import_react46 = __toESM(require_react()); -var ListSelector = (props) => { - const { views, dbSchema, source } = (0, import_react46.useContext)(ContextEditorContext); - const { spaceState } = (0, import_react46.useContext)(SpaceContext); - const { - frameSchema: schema, - setFrameSchema: setSchema, - saveSchema, - deleteSchema - } = (0, import_react46.useContext)(FramesMDBContext); - const viewContextMenu = (e5, _schema) => { - const menuOptions = []; - menuOptions.push({ - name: i18n_default.menu.copyEmbedLink, - icon: "ui//link", - onClick: (e6) => { - navigator.clipboard.writeText( - contextViewEmbedStringFromContext(spaceState, _schema.id) - ); - } - }); - menuOptions.push({ - name: i18n_default.buttons.renameView, - icon: "ui//edit", - onClick: (e6) => { - props.superstate.ui.openModal( - i18n_default.labels.renameView, - (props2) => /* @__PURE__ */ import_react46.default.createElement(InputModal, { - value: _schema.name, - saveLabel: i18n_default.labels.renameView, - hide: props2.hide, - saveValue: (value) => saveSchema({ - ..._schema, - name: value - }) - }) - ); +var detailItem = { + def: { + id: "detailItem", + type: "listItem" + }, + node: { + type: "group", + id: "$root", + schemaId: "$root", + name: "Detail View", + rank: 0, + props: { + _selected: `$root.props['_selectedIndex'] == $contexts.$context['_index']` + }, + styles: { + layout: `"row"`, + gap: `'12px'`, + padding: `'8px'`, + overflow: `'hidden'`, + width: `'100%'` + }, + actions: { + onClick: `$saveState({ $root: {props: {_selectedIndex: $contexts.$context['_index']}} });`, + onDoubleClick: `$api.table.open($contexts.$context['_keyValue'], false)`, + onContextMenu: `$api.table.contextMenu($event, $contexts.$context['_path'], $contexts.$context['_schema'], $contexts.$context['_index'])` + } + }, + id: "$root", + children: [ + frameRootWithProps( + { + ...slidesNode, + children: [ + frameRootWithProps( + { + ...slideNode, + children: [ + frameRootWithProps( + { ...deltaNode, node: { ...deltaNode.node, ref: "$root" } }, + {}, + { + background: `'var(--mk-ui-background-selected)'` + } + ) + ] + }, + { value: "true" } + ), + frameRootWithProps( + { + ...slideNode, + children: [ + frameRootWithProps( + { ...deltaNode, node: { ...deltaNode.node, ref: "$root" } }, + {}, + { + background: `'transparent'` + } + ) + ] + }, + { value: "false" } + ) + ] + }, + { + value: `'_selected'` } - }); - menuOptions.push({ - name: i18n_default.buttons.delete, - icon: "ui//trash", - onClick: (e6) => { - deleteSchema(_schema); + ), + kitWithProps( + previewNode, + { + path: `$contexts.$context['_keyValue']`, + radius: `'4px'`, + width: `'50px'`, + height: `'50px'` + }, + { + height: `'50px'`, + borderRadius: `'8px'`, + background: `'var(--background-secondary)'` } - }); - props.superstate.ui.openMenu( - e5.target.getBoundingClientRect(), - defaultMenu(props.superstate.ui, menuOptions) - ); - }; - const selectView = (value) => { - setSchema(views.find((f2) => f2.id == value)); - if (props.setView) - props.setView(value); - }; - const ref2 = (0, import_react46.useRef)(null); - const showSaveViewModal = () => { - props.superstate.ui.openModal( - i18n_default.labels.saveView, - (props2) => /* @__PURE__ */ import_react46.default.createElement(InputModal, { - value: "", - saveLabel: i18n_default.labels.saveView, - hide: props2.hide, - saveValue: (value) => { - const newSchema = { - ...schema ?? { - name: dbSchema.name, - def: { - db: dbSchema.id - }, - type: "view" - }, - id: value.replace(/ /g, "_"), - name: value - }; - saveSchema(newSchema).then((f2) => selectView(newSchema.id)); + ), + { + ...groupNode, + node: { + ...groupNode.node, + styles: { + gap: `'8px'`, + flex: `'1'`, + padding: `'2px'`, + layout: `'column'`, + borderBottom: `'thin solid var(--mk-ui-border)'` } - }) - ); - }; - const selectViewMenu = (e5) => { - const options = []; - (views ?? []).forEach((f2) => { - options.push({ - name: defaultString(f2.name, "Untitled"), - value: f2.id, - icon: stickerForSchema(f2), - onClick: () => selectView(f2.id), - onMoreOptions: (e6) => viewContextMenu(e6, f2) - }); - }); - options.push(menuSeparator); - options.push({ - name: i18n_default.menu.newView, - icon: "ui//plus", - value: "", - onClick: () => showSaveViewModal() - }); - props.superstate.ui.openMenu( - e5.target.getBoundingClientRect(), - defaultMenu(props.superstate.ui, options), - "bottom" - ); - }; - return dbSchema && (schema ? /* @__PURE__ */ import_react46.default.createElement(import_react46.default.Fragment, null, /* @__PURE__ */ import_react46.default.createElement("div", { - className: "mk-view-selector", - ref: ref2 - }, props.expanded ? /* @__PURE__ */ import_react46.default.createElement(import_react46.default.Fragment, null, views.map((f2, i4) => /* @__PURE__ */ import_react46.default.createElement(ContextViewCrumb, { - key: i4, - superstate: props.superstate, - schema: f2, - onSelect: () => setSchema(views.find((g) => g.id == f2.id)), - onContextMenu: viewContextMenu - })), /* @__PURE__ */ import_react46.default.createElement("button", { - onClick: (e5) => showSaveViewModal() - }, "+")) : /* @__PURE__ */ import_react46.default.createElement(ContextViewCrumb, { - superstate: props.superstate, - schema, - onSelect: (e5) => selectViewMenu(e5), - onContextMenu: viewContextMenu - }, /* @__PURE__ */ import_react46.default.createElement(CollapseToggle, { - collapsed: false, - onToggle: null, - superstate: props.superstate - })))) : /* @__PURE__ */ import_react46.default.createElement("div", { - onClick: (e5) => selectViewMenu(e5), - className: "mk-context" - }, /* @__PURE__ */ import_react46.default.createElement("div", { - className: "mk-path-icon", - dangerouslySetInnerHTML: { - __html: props.superstate.ui.getSticker("ui//table") + }, + children: [ + frameRootWithProps( + textNode, + { + value: `$contexts.$context['_name']` + }, + { + "--font-text-size": `'18px'`, + "--font-text-weight": `'var(--bold-weight)'` + } + ), + frameRootWithProps(textNode, { + value: `$api.path.label($contexts.$context['_keyValue'])?.preview` + }, { + "--font-text-size": `'14px'`, + "--font-text-color": `'var(--mk-ui-text-tertiary)'` + }), + kitWithProps(fieldsView, {}) + ] } - }), dbSchema.name, /* @__PURE__ */ import_react46.default.createElement(CollapseToggle, { - collapsed: false, - onToggle: null, - superstate: props.superstate - }))); + ] }; - -// src/core/react/components/SpaceView/Contexts/FilterBar/SearchBar.tsx -var import_react47 = __toESM(require_react()); -var SearchBar = (props) => { - const [searchActive, setSearchActive] = import_react47.default.useState(false); - const clearSearch = () => { - setSearchActive(false); - props.setSearchString(""); - }; - const ref2 = import_react47.default.useRef(null); - (0, import_react47.useEffect)(() => { - if (searchActive) { - ref2.current?.focus(); - } - }, [searchActive]); - return !searchActive ? /* @__PURE__ */ import_react47.default.createElement("button", { - className: "mk-toolbar-button", - onClick: (e5) => { - e5.stopPropagation(); - setSearchActive(true); +var newItemNode = { + id: "newItem", + def: { + id: "newItem" + }, + node: { + schemaId: "newItem", + parentId: "", + name: "New Item", + rank: 0, + id: "newItem", + type: "group", + props: { + space: "", + schema: "", + key: "", + group: "", + groupValue: "" }, - dangerouslySetInnerHTML: { - __html: props.superstate.ui.getSticker("ui//search") - } - }) : /* @__PURE__ */ import_react47.default.createElement("div", { - className: "mk-view-search" - }, /* @__PURE__ */ import_react47.default.createElement("button", { - className: "mk-toolbar-button", - dangerouslySetInnerHTML: { - __html: props.superstate.ui.getSticker("ui//search") - } - }), /* @__PURE__ */ import_react47.default.createElement(import_react47.default.Fragment, null, /* @__PURE__ */ import_react47.default.createElement("input", { - onChange: (e5) => props.setSearchString(e5.target.value), - placeholder: i18n_default.labels.searchPlaceholder, - className: "mk-search-bar", - ref: ref2 - }), /* @__PURE__ */ import_react47.default.createElement("button", { - className: "mk-toolbar-button", - dangerouslySetInnerHTML: { - __html: props.superstate.ui.getSticker("ui//clear") + types: { + space: "text", + schema: "text", + key: "text", + group: "text", + groupValue: "text" }, - onClick: (e5) => { - e5.stopPropagation(); - clearSearch(); - } - }))); -}; - -// src/core/react/components/SpaceView/Contexts/FilterBar/FilterBar.tsx -var FilterBar = (props) => { - const { spaceState: spaceCache } = (0, import_react48.useContext)(SpaceContext); - const { - source, - dbSchema, - cols, - setSearchString, - setEditMode, - predicate, - savePredicate - } = (0, import_react48.useContext)(ContextEditorContext); - const { frameSchema, saveSchema, setFrameSchema } = (0, import_react48.useContext)(FramesMDBContext); - const properties3 = spaceCache?.propertyTypes ?? []; - const propertiesForFrame = (path2) => { - if (!path2) - return []; - const uri = props.superstate.spaceManager.uriByString(path2); - if (uri.authority == "$kit") { - const node = props.superstate.kitFrames.get(uri.ref).node; - return Object.keys(node.types).map((f2) => ({ - type: node.types[f2], - name: f2, - attrs: JSON.stringify(node.propsAttrs?.[f2]), - schemaId: node.schemaId, - value: JSON.stringify(node.propsValue?.[f2]) - })).filter((f2) => !f2.name.startsWith("_")); - } else { - return props.superstate.framesIndex.get(uri.path)?.frames[uri.ref].cols.filter((f2) => !f2.name.startsWith("_")); - } - }; - const filteredCols = cols.filter((f2) => f2.hidden != "true"); - const [expanded, setExpanded] = (0, import_react48.useState)(false); - const saveViewType = (type) => { - if (type == "table") { - savePredicate({ - view: "table", - listView: "", - listGroup: "", - listItem: "" - }); - } - if (type == "flow") { - savePredicate({ - view: "list", - listView: "spaces://$kit/#*listView", - listGroup: "spaces://$kit/#*listGroup", - listItem: "spaces://$kit/#*flowListItem" - }); - } - if (type == "list") { - savePredicate({ - view: "list", - listView: "spaces://$kit/#*listView", - listGroup: "spaces://$kit/#*listGroup", - listItem: "spaces://$kit/#*rowItem" - }); - } - if (type == "details") { - savePredicate({ - view: "list", - listView: "spaces://$kit/#*listView", - listGroup: "spaces://$kit/#*listGroup", - listItem: "spaces://$kit/#*detailItem" - }); - } - if (type == "board") { - savePredicate({ - view: "list", - listView: "spaces://$kit/#*columnView", - listGroup: "spaces://$kit/#*columnGroup", - listItem: "spaces://$kit/#*cardListItem" - }); - } - if (type == "cards") { - savePredicate({ - view: "list", - listView: "spaces://$kit/#*listView", - listGroup: "spaces://$kit/#*gridGroup", - listItem: "spaces://$kit/#*cardsListItem" - }); - } - if (type == "catalog") { - savePredicate({ - view: "list", - listView: "spaces://$kit/#*listView", - listGroup: "spaces://$kit/#*rowGroup", - listItem: "spaces://$kit/#*coverListItem" - }); - } - if (type == "gallery") { - savePredicate({ - view: "list", - listView: "spaces://$kit/#*listView", - listGroup: "spaces://$kit/#*masonryGroup", - listItem: "spaces://$kit/#*imageListItem" - }); - } - if (type == "calendar") { - savePredicate({ - view: "list", - listView: "spaces://$kit/#*calendarView", - listGroup: "spaces://$kit/#*dateGroup", - listItem: "spaces://$kit/#*eventItem" - }); - } - }; - const clearFilters = () => { - savePredicate({ - filters: [], - sort: [] - }); - }; - const clearHiddenCols = () => { - savePredicate({ - colsHidden: [] - }); - }; - const removeFilter = (filter4, index2) => { - const pred = predicate ?? defaultPredicateForSchema(dbSchema); - const newFilters = [...pred.filters.filter((f2, i4) => i4 != index2)]; - savePredicate({ - filters: newFilters - }); - }; - const showViewsMenu = (e5) => { - const menuOptions = []; - if (predicate?.listItem?.length > 0 && !predicate.listItem.startsWith("spaces://$kit")) { - menuOptions.push({ - name: i18n_default.menu.customView, - type: 5 /* Custom */, - fragment: (_props) => /* @__PURE__ */ import_react48.default.createElement(CustomViewOption, { - ui: props.superstate.ui, - icon: "ui//toy-brick", - type: i18n_default.menu.customView, - onSelect: () => null, - selected: true, - hide: _props.hide, - onCustomize: () => { - setEditMode(3 /* Group */); - } - }) - }); + actions: {}, + styles: { + gap: `'4px'` } - menuOptions.push({ - name: i18n_default.menu.listView, - type: 5 /* Custom */, - fragment: (_props) => /* @__PURE__ */ import_react48.default.createElement(CustomViewOption, { - ui: props.superstate.ui, - icon: "ui//list", - type: i18n_default.menu.listView, - onSelect: () => saveViewType("list"), - selected: predicate?.listItem == "spaces://$kit/#*rowItem", - hide: _props.hide, - onCustomize: () => { - saveViewType("list"); - setEditMode(3 /* Group */); - } - }) - }); - menuOptions.push({ - name: i18n_default.menu.cardView, - type: 5 /* Custom */, - fragment: (_props) => /* @__PURE__ */ import_react48.default.createElement(CustomViewOption, { - ui: props.superstate.ui, - icon: "ui//layout-grid", - type: i18n_default.menu.cardView, - onSelect: () => saveViewType("cards"), - hide: _props.hide, - selected: predicate?.listItem == "spaces://$kit/#*cardsListItem", - onCustomize: () => { - saveViewType("card"); - setEditMode(3 /* Group */); - } - }) - }); - menuOptions.push({ - name: i18n_default.menu.detailsView, - type: 5 /* Custom */, - fragment: (_props) => /* @__PURE__ */ import_react48.default.createElement(CustomViewOption, { - ui: props.superstate.ui, - icon: "ui//layout-list", - type: i18n_default.menu.detailsView, - onSelect: () => saveViewType("details"), - hide: _props.hide, - selected: predicate?.listItem == "spaces://$kit/#*detailItem", - onCustomize: () => { - saveViewType("details"); - setEditMode(3 /* Group */); + }, + children: [ + { + ...inputNode, + node: { + ...inputNode.node, + styles: { ...inputNode.node.styles, placeholder: `'+ New Item'`, border: `'none'`, background: `'transparent'` }, + actions: { + onEnter: `$api.table.insert($root.props.space, $root.props.schema, {[$root.props.group]: $root.props.groupValue, [$root.props.key]: $value}); $event.currentTarget.value = ''` } - }) - }); - menuOptions.push(menuSeparator); - menuOptions.push({ - name: i18n_default.menu.tableView, - icon: "ui//table-2", - onClick: (e6) => { - saveViewType("table"); } - }); - menuOptions.push({ - name: i18n_default.menu.boardView, - type: 5 /* Custom */, - fragment: (_props) => /* @__PURE__ */ import_react48.default.createElement(CustomViewOption, { - ui: props.superstate.ui, - icon: "ui//square-kanban", - type: i18n_default.menu.boardView, - onSelect: () => saveViewType("board"), - hide: _props.hide, - selected: predicate?.listItem == "spaces://$kit/#*cardListItem", - onCustomize: () => { - saveViewType("card"); - setEditMode(3 /* Group */); - } - }) - }); - menuOptions.push(menuSeparator); - menuOptions.push({ - name: i18n_default.menu.catalogView, - type: 5 /* Custom */, - fragment: (_props) => /* @__PURE__ */ import_react48.default.createElement(CustomViewOption, { - ui: props.superstate.ui, - icon: "ui//gallery-horizontal-end", - type: i18n_default.menu.catalogView, - hide: _props.hide, - onSelect: () => saveViewType("catalog"), - selected: predicate?.listItem == "spaces://$kit/#*coverListItem", - onCustomize: () => { - saveViewType("catalog"); - setEditMode(3 /* Group */); - } - }) - }); - menuOptions.push({ - name: i18n_default.menu.galleryView, - type: 5 /* Custom */, - fragment: (_props) => /* @__PURE__ */ import_react48.default.createElement(CustomViewOption, { - ui: props.superstate.ui, - icon: "ui//layout-dashboard", - type: i18n_default.menu.galleryView, - hide: _props.hide, - onSelect: () => saveViewType("gallery"), - selected: predicate?.listItem == "spaces://$kit/#*imageListItem", - onCustomize: () => { - saveViewType("gallery"); - setEditMode(3 /* Group */); - } - }) - }); - if (dbSchema?.primary) { - menuOptions.push({ - name: i18n_default.menu.flowView, - type: 5 /* Custom */, - fragment: (_props) => /* @__PURE__ */ import_react48.default.createElement(CustomViewOption, { - ui: props.superstate.ui, - icon: "ui//infinity", - type: i18n_default.menu.flowView, - onSelect: () => saveViewType("flow"), - hide: _props.hide, - selected: predicate?.listItem == "spaces://$kit/#*flowListItem", - onCustomize: () => { - saveViewType("flow"); - setEditMode(3 /* Group */); - } - }) - }); } - const offset2 = e5.target.getBoundingClientRect(); - props.superstate.ui.openMenu( - offset2, - defaultMenu(props.superstate.ui, menuOptions) - ); - }; - const selectSource = (e5) => { - showSpacesMenu(e5, props.superstate, (link) => { - const newSchema = { - ...frameSchema, - name: frameSchema.name, - def: { - db: dbSchema.id, - context: link - }, - type: "view" - }; - saveSchema(newSchema).then((f2) => setFrameSchema(newSchema)); - }); - }; - const showFilterMenu = (e5) => { - const menuOptions = []; - menuOptions.push(menuSeparator); - menuOptions.push({ - name: i18n_default.menu.groupBy, - icon: "ui//columns", - type: 6 /* Submenu */, - onSubmenu: (offset3) => { - return showGroupByMenu(offset3); - } - }); - menuOptions.push({ - name: i18n_default.menu.sortBy, - icon: "ui//sort-desc", - type: 6 /* Submenu */, - onSubmenu: (offset3) => { - return showSortMenu(offset3); + ] +}; +var listGroup = { + def: { + id: "listGroup", + type: "listGroup" + }, + node: { + type: "group", + props: { + _groupType: ``, + _groupField: ``, + _groupValue: ``, + showNew: "true" + }, + types: { + _groupType: "text", + _groupField: "text", + _groupValue: "text", + showNew: "boolean" + }, + propsValue: { + showNew: { + alias: "New Item Button" } - }); - menuOptions.push(menuSeparator); - menuOptions.push({ - name: i18n_default.menu.newFilter, - icon: "ui//filter", - onClick: (e6) => { - showAddFilterMenu(e6); + }, + id: "$root", + schemaId: "$root", + name: "Rows", + rank: 0 + }, + id: "$root", + children: [ + kitWithProps(fieldNode, { + type: `$root.props['_groupType']`, + value: `$root.props['_groupValue']` + }), + frameRootWithProps(contentNode, {}, { + layout: `'column'`, + alignItems: `'stretch'` + }), + kitWithProps(newItemNode, { + space: `$contexts.$context['_path']`, + schema: `$contexts.$context['_schema']`, + key: `$contexts.$context['_key']`, + group: `$root.props['_groupField']`, + groupValue: `$root.props['_groupValue']` + }, { + hidden: `!$root.props['showNew']` + }) + ] +}; +var columnGroup = { + def: { + id: "columnGroup", + type: "listGroup" + }, + node: { + type: "group", + props: { + _groupType: ``, + _groupField: "", + _groupValue: ``, + showNew: "true" + }, + types: { + _groupType: "text", + _groupField: "text", + _groupValue: "text", + showNew: "boolean" + }, + propsValue: { + showNew: { + alias: "New Item Button" } - }); - menuOptions.push({ - name: i18n_default.menu.clearFilters, - icon: "ui//x-square", - onClick: (e6) => { - clearFilters(); + }, + styles: { + layout: `'column'`, + width: `'262px'`, + background: `'var(--mk-ui-background-variant)'`, + borderRadius: `'8px'`, + padding: `'6px'` + }, + id: "$root", + schemaId: "$root", + name: "Columns", + rank: 0 + }, + id: "$root", + children: [ + kitWithProps(fieldNode, { + type: `$root.props['_groupType']`, + value: `$root.props['_groupValue']` + }), + frameRootWithProps( + contentNode, + {}, + { + gap: `'8px'`, + layout: `'column'`, + width: `'100%'`, + alignItems: `'stretch'` } - }); - menuOptions.push(menuSeparator); - const listViewOptions = propertiesForFrame(predicate?.listView); - const listGroupOptions = propertiesForFrame(predicate?.listGroup); - const listItemOptions = propertiesForFrame(predicate?.listItem); - const savePropValue = (type, prop2, value) => { - savePredicate({ - [type]: { - ...predicate[type], - [prop2]: value - } - }); - }; - listViewOptions.forEach((f2) => { - menuOptions.push({ - name: nameForField(f2, props.superstate), - icon: stickerForField(f2), - type: 1 /* Disclosure */, - onClick: (e6) => { - showSetValueMenu( - e6.target.getBoundingClientRect(), - props.superstate, - f2, - (value) => savePropValue( - "listViewProps", - f2.name, - parseMDBValue(f2.type, value) - ), - spaceCache.path - ); - } - }); - }); - listGroupOptions.forEach((f2) => { - menuOptions.push({ - name: nameForField(f2, props.superstate), - icon: stickerForField(f2), - type: 1 /* Disclosure */, - onClick: (e6) => { - showSetValueMenu( - e6.target.getBoundingClientRect(), - props.superstate, - f2, - (value) => savePropValue( - "listGroupProps", - f2.name, - parseMDBValue(f2.type, value) - ), - spaceCache.path - ); - } - }); - }); - listItemOptions.forEach((f2) => { - menuOptions.push({ - name: nameForField(f2, props.superstate), - icon: stickerForField(f2), - type: 1 /* Disclosure */, - onClick: (e6) => { - showSetValueMenu( - e6.target.getBoundingClientRect(), - props.superstate, - f2, - (value) => savePropValue( - "listItemProps", - f2.name, - parseMDBValue(f2.type, value) - ), - spaceCache.path - ); - } - }); - }); - menuOptions.push(menuSeparator); - if (dbSchema?.primary == "true") { - menuOptions.push({ - name: "Source", - icon: "ui//table", - type: 1 /* Disclosure */, - value: source, - onClick: (e6) => { - selectSource(e6); + ), + frameRootWithProps( + { ...groupNode, children: [kitWithProps( + newItemNode, + { + space: `$contexts.$context['_path']`, + schema: `$contexts.$context['_schema']`, + key: `$contexts.$context['_key']`, + group: `$root.props['_groupField']`, + groupValue: `$root.props['_groupValue']` + }, + { + hidden: `!$root.props['showNew']` } - }); - menuOptions.push(menuSeparator); - } - menuOptions.push({ - name: i18n_default.menu.unhideFields, - icon: "ui//eye", - onClick: (e6) => { - clearHiddenCols(); + )] }, + {}, + { + height: `'auto'`, + marginTop: `'8px'`, + borderRadius: `'8px'`, + width: `'250px'`, + border: `'1px solid var(--mk-ui-border)'`, + background: `'var(--mk-ui-background)'` } - }); - const offset2 = e5.target.getBoundingClientRect(); - props.superstate.ui.openMenu( - offset2, - defaultMenu(props.superstate.ui, menuOptions) - ); - }; - const addSort = (_15, sort2) => { - const field = sort2[0]; - const fieldObject = filteredCols.find((f2) => f2.name + f2.table == field); - const fieldType = fieldTypeForField(fieldObject); - if (fieldType) { - const type = defaultPredicateFnForType(fieldType, sortFnTypes); - const newSort = { - field, - fn: type - }; - savePredicate({ - sort: [ - ...predicate?.sort.filter((s4) => s4.field != newSort.field) ?? [], - newSort - ] - }); - } - }; - const saveGroupBy = (_15, groupBy2) => { - savePredicate({ - groupBy: groupBy2 - }); - }; - const removeSort = (sort2) => { - const newSort = [ - ...(predicate?.sort ?? []).filter((f2) => f2.field != sort2.field) - ]; - savePredicate({ - sort: newSort - }); - }; - const addFilter = (_15, filter4) => { - const field = filter4[0]; - const fieldObject = filteredCols.find((f2) => f2.name + f2.table == field); - const fieldType = fieldTypeForField(fieldObject); - if (fieldType) { - const type = defaultPredicateFnForType(fieldType, filterFnTypes); - if (!type) - return; - const newFilter = fieldType == "boolean" ? { - field, - fn: type, - fType: filterFnTypes[type].valueType, - value: "true" - } : { - field, - fn: type, - fType: filterFnTypes[type].valueType, - value: "" - }; - savePredicate({ - filters: [...predicate?.filters ?? [], newFilter] - }); - } - }; - const changeSortMenu = (e5, sort2) => { - const offset2 = e5.target.getBoundingClientRect(); - const saveSort = (_15, newType) => { - const type = newType[0]; - const newSort = { - ...sort2, - fn: type - }; - savePredicate({ - sort: [ - ...(predicate?.sort ?? []).filter((s4) => s4.field != newSort.field), - newSort - ] - }); - }; - const fieldObject = filteredCols.find( - (f2) => f2.name + f2.table == sort2.field - ); - const fieldType = fieldTypeForField(fieldObject); - const sortsForType = predicateFnsForType(fieldType, sortFnTypes); - props.superstate.ui.openMenu(offset2, { - ui: props.superstate.ui, - multi: false, - editable: false, - value: [], - options: sortsForType.map((f2) => ({ - name: sortFnTypes[f2].label, - value: f2 - })), - saveOptions: saveSort, - placeholder: i18n_default.labels.sortItemSelectPlaceholder, - searchable: false, - showAll: true - }); - }; - const showColsMenu = (e5) => { - const sourceCache = props.superstate.spacesIndex.get(source); - if (sourceCache) { - openSpaceEditorModal(props.superstate, sourceCache, 1); + ) + ] +}; +var rowGroup = { + def: { + id: "rowGroup", + type: "listGroup" + }, + node: { + type: "group", + props: { + _groupType: ``, + _groupField: "", + _groupValue: `` + }, + types: { + _groupType: "text", + _groupField: "text", + _groupValue: "text" + }, + styles: { + layout: `'column'`, + padding: `'6px'`, + gap: `'8px'` + }, + id: "$root", + schemaId: "$root", + name: "Catalog Group", + rank: 0 + }, + id: "$root", + children: [ + kitWithProps(fieldNode, { + type: `$root.props['_groupType']`, + value: `$root.props['_groupValue']` + }), + frameRootWithProps( + contentNode, + {}, + { + gap: `'8px'`, + layout: `'row'`, + width: `'100%'`, + overflow: `'scroll'` + } + ) + ] +}; +var gridGroup = { + def: { + id: "gridGroup", + type: "listGroup" + }, + node: { + type: "group", + props: { + _groupType: ``, + _groupField: "", + _groupValue: `` + }, + types: { + _groupType: "text", + _groupField: "text", + _groupValue: "text" + }, + styles: { + layout: `'column'`, + padding: `'6px'`, + gap: `'8px'` + }, + id: "$root", + schemaId: "$root", + name: "Grid Group", + rank: 0 + }, + id: "$root", + children: [ + kitWithProps(fieldNode, { + type: `$root.props['_groupType']`, + value: `$root.props['_groupValue']` + }), + frameRootWithProps( + contentNode, + {}, + { + gap: `'8px'`, + layout: `'grid'`, + width: `'100%'`, + "--mk-grid-columns": `'auto-fill'`, + "--mk-grid-width": `'250px'` + } + ) + ] +}; +var masonryGroup = { + def: { + id: "masonryGroup", + type: "listGroup" + }, + node: { + type: "group", + props: {}, + id: "$root", + schemaId: "$root", + name: "Masonry", + rank: 0, + styles: { + layout: `'column'` } - }; - const changeFilterMenu = (e5, filter4, index2) => { - const offset2 = e5.target.getBoundingClientRect(); - const saveFilter = (_15, newType) => { - const type = newType[0]; - const newFilter = { - ...filter4, - fn: type, - fType: filterFnTypes[type].valueType - }; - savePredicate({ - filters: (predicate?.filters ?? []).map( - (s4, i4) => i4 == index2 ? newFilter : s4 - ) - }); - }; - const field = filteredCols.find((f2) => f2.name + f2.table == filter4.field); - const fieldType = fieldTypeForField(field); - const filtersForType = predicateFnsForType(fieldType, filterFnTypes); - props.superstate.ui.openMenu(offset2, { - ui: props.superstate.ui, - multi: false, - editable: false, - value: [], - options: filtersForType.map((f2) => ({ - name: filterFnLabels[f2], - value: f2 - })), - saveOptions: saveFilter, - placeholder: i18n_default.labels.filterItemSelectPlaceholder, - searchable: false, - showAll: true - }); - }; - const showAddFilterMenu = (e5) => { - const offset2 = e5.target.getBoundingClientRect(); - props.superstate.ui.openMenu(offset2, { - ui: props.superstate.ui, - multi: false, - editable: false, - value: [], - options: filteredCols.filter( - (f2) => f2.type == "fileprop" || predicateFnsForType(f2.type, filterFnTypes).length > 0 - ).map((f2) => ({ - name: f2.name + f2.table, - value: f2.name + f2.table, - icon: stickerForField(f2) - })), - saveOptions: addFilter, - placeholder: i18n_default.labels.propertyItemSelectPlaceholder, - searchable: true, - showAll: true - }); - }; - const showSortMenu = (offset2) => { - return props.superstate.ui.openMenu(offset2, { - ui: props.superstate.ui, - multi: false, - editable: false, - value: [], - options: filteredCols.map((f2) => ({ - name: f2.name + f2.table, - icon: stickerForField(f2), - value: f2.name + f2.table - })), - saveOptions: addSort, - placeholder: i18n_default.labels.sortItemSelectPlaceholder, - searchable: true, - showAll: true - }); - }; - const showGroupByMenu = (offset2) => { - return props.superstate.ui.openMenu( - offset2, + }, + id: "$root", + children: [ + kitWithProps(fieldNode, { + type: `$root.props['_groupType']`, + value: `$root.props['_groupValue']` + }), + frameRootWithProps( + contentNode, + {}, { - ui: props.superstate.ui, - multi: false, - editable: false, - value: [], - options: filteredCols.map((f2) => ({ - name: f2.name + f2.table, - icon: stickerForField(f2), - value: f2.name + f2.table - })), - saveOptions: saveGroupBy, - placeholder: i18n_default.labels.propertyItemSelectPlaceholder, - searchable: false, - showAll: true - }, - "right" - ); - }; - const selectFilterValue = (e5, filter4, index2) => { - switch (filter4.fType ?? filterFnTypes[filter4.fn].valueType) { - case "property": - { - savePredicate({ - filters: (predicate?.filters ?? []).map( - (s4, i4) => i4 == index2 ? filter4 : s4 - ) - }); - } - break; - case "text": - case "number": - { - savePredicate({ - filters: (predicate?.filters ?? []).map( - (s4, i4) => i4 == index2 ? filter4 : s4 - ) - }); - } - break; - case "date": { - const saveValue = (date2) => { - const newFilter = { - ...filter4, - value: date2 ? format(date2, "yyyy-MM-dd") : "" - }; - savePredicate({ - filters: (predicate?.filters ?? []).map( - (s4, i4) => i4 == index2 ? newFilter : s4 - ) - }); - }; - const offset2 = e5.target.getBoundingClientRect(); - const date = new Date(filter4.value); - showDatePickerMenu( - props.superstate.ui, - offset2, - date.getTime() ? date : null, - saveValue, - 0 /* None */ - ); - break; + padding: `'8px'`, + layout: `'masonry'` } - case "link": - { - const col = cols.find((f2) => f2.name + f2.table == filter4.field); - if (col?.type.startsWith("context")) { - const space2 = parseFieldValue(col.value, col.type)?.space; - if (!space2) - return; - const contextData = props.superstate.contextsIndex.get(space2)?.paths ?? []; - const offset2 = e5.target.getBoundingClientRect(); - props.superstate.ui.openMenu(offset2, { - ui: props.superstate.ui, - multi: false, - editable: false, - value: parseMultiString(filter4.value), - options: contextData.map((f2) => ({ - name: pathToString(f2), - value: f2 - })) ?? [], - saveOptions: (options, values2) => { - const newFilter = { - ...filter4, - value: values2[0] - }; - savePredicate({ - filters: (predicate?.filters ?? []).map( - (s4, i4) => i4 == index2 ? newFilter : s4 - ) - }); - }, - placeholder: i18n_default.labels.optionItemSelectPlaceholder, - searchable: true, - showAll: true - }); - return; - } - const saveValue = (link) => { - const newFilter = { - ...filter4, - value: link - }; - savePredicate({ - filters: (predicate?.filters ?? []).map( - (s4, i4) => i4 == index2 ? newFilter : s4 - ) - }); - }; - showLinkMenu( - e5, - props.superstate, - (link) => { - saveValue(link); + ) + ] +}; +var listView = { + def: { + id: "listView", + type: "listView" + }, + node: { + type: "group", + props: {}, + id: "$root", + schemaId: "$root", + name: "List View", + rank: 0 + }, + id: "$root", + children: [ + contentNode + ] +}; +var columnView = { + def: { + id: "columnView", + type: "listView" + }, + node: { + type: "group", + props: {}, + id: "$root", + schemaId: "$root", + name: "Column View", + rank: 0 + }, + id: "$root", + children: [ + frameRootWithProps( + contentNode, + {}, + { + padding: `'8px'`, + layout: `'row'`, + gap: `'8px'` + } + ) + ] +}; + +// src/core/superstate/commands.ts +var SpacesCommandsAdapter = class { + constructor(manager, superstate) { + this.superstate = superstate; + this.scheme = "spaces"; + this.apiCommands = { + path: { + open: { + schema: { + id: "path.open", + name: "Open Path", + type: "api" + }, + fields: [{ + name: "path", + type: "link" + }] + }, + create: { + schema: { + id: "path.create", + name: "Create Item", + type: "api" + }, + fields: [{ + name: "name", + type: "text" + }, { + name: "space", + type: "space" + }, { + name: "content", + type: "text" + }] + }, + setProperty: { + schema: { + id: "path.setProperty", + name: "Save Property", + type: "api" + }, + fields: [ + { + name: "path", + type: "link" }, - { multi: true } - ); + { + name: "property", + type: "option", + value: JSON.stringify({ + source: "$properties" + }) + }, + { + name: "value", + type: "text" + } + ] } - break; - case "list": - { - const col = cols.find((f2) => f2.name + f2.table == filter4.field); - const saveOptions = (options, values2) => { - const newFilter = { - ...filter4, - value: serializeMultiString(values2) - }; - savePredicate({ - filters: (predicate?.filters ?? []).map( - (s4, i4) => i4 == index2 ? newFilter : s4 - ) - }); - }; - if (col.type.startsWith("option")) { - const offset2 = e5.target.getBoundingClientRect(); - const options = parseFieldValue(col.value, col.type).options; - props.superstate.ui.openMenu(offset2, { - ui: props.superstate.ui, - multi: true, - editable: false, - value: parseMultiString(filter4.value), - options: options ?? [], - saveOptions, - placeholder: i18n_default.labels.optionItemSelectPlaceholder, - searchable: true, - showAll: true - }); - } else if (col.type.startsWith("context")) { - const space2 = parseFieldValue(col.value, col.type)?.space; - if (!space2) - return; - const contextData = props.superstate.contextsIndex.get(space2)?.paths ?? []; - const offset2 = e5.target.getBoundingClientRect(); - props.superstate.ui.openMenu(offset2, { - ui: props.superstate.ui, - multi: true, - editable: false, - value: parseMultiString(filter4.value), - options: contextData.map((f2) => ({ - name: pathToString(f2), - value: f2 - })) ?? [], - saveOptions, - placeholder: i18n_default.labels.optionItemSelectPlaceholder, - searchable: true, - showAll: true - }); - } else if (col.type.startsWith("link")) { - showLinkMenu( - e5, - props.superstate, - (link) => { - saveOptions([link], [link]); - }, - { multi: true } - ); - } else if (col.type.startsWith("tags")) { - const contextData = props.superstate.spaceManager.readTags(); - const offset2 = e5.target.getBoundingClientRect(); - props.superstate.ui.openMenu(offset2, { - ui: props.superstate.ui, - multi: true, - editable: false, - value: parseMultiString(filter4.value), - options: contextData.map((f2) => ({ - name: f2, - value: f2 - })) ?? [], - saveOptions, - placeholder: i18n_default.labels.tagItemSelectPlaceholder, - searchable: true, - showAll: true - }); - } + }, + table: { + select: { + schema: { + id: "table.select", + name: "Get All List Items from Table", + type: "api" + }, + fields: [{ + name: "path", + type: "link" + }, { + name: "table", + type: "text" + }] + }, + update: { + schema: { + id: "table.update", + name: "Update List Item in Table", + type: "api" + }, + fields: [ + { + name: "path", + type: "link" + }, + { + name: "table", + type: "text" + }, + { + name: "index", + type: "number" + }, + { + name: "row", + type: "object" + } + ] + }, + insert: { + schema: { + id: "table.insert", + name: "Insert List Item into Table", + type: "api" + }, + fields: [{ + name: "path", + type: "link" + }, { + name: "schema", + type: "text" + }, { + name: "row", + type: "object" + }] } - break; - } - }; - return /* @__PURE__ */ import_react48.default.createElement(import_react48.default.Fragment, null, /* @__PURE__ */ import_react48.default.createElement("div", { - className: "mk-view-config" - }, !expanded && /* @__PURE__ */ import_react48.default.createElement(ListSelector, { - superstate: props.superstate, - expanded: false, - setView: props.setView - }), /* @__PURE__ */ import_react48.default.createElement("div", { - className: "mk-view-options" - }, /* @__PURE__ */ import_react48.default.createElement("span", null), /* @__PURE__ */ import_react48.default.createElement(SearchBar, { - superstate: props.superstate, - setSearchString - }), /* @__PURE__ */ import_react48.default.createElement("button", { - className: "mk-toolbar-button", - onClick: (e5) => showViewsMenu(e5), - dangerouslySetInnerHTML: { - __html: props.superstate.ui.getSticker("ui//layout-panel-left") - } - }), /* @__PURE__ */ import_react48.default.createElement("button", { - className: "mk-toolbar-button", - onClick: (e5) => showFilterMenu(e5), - dangerouslySetInnerHTML: { - __html: props.superstate.ui.getSticker("ui//view-options") - } - }), props.superstate.settings.experimental && /* @__PURE__ */ import_react48.default.createElement("button", { - className: "mk-toolbar-button", - onClick: (e5) => setEditMode((p) => p == 0 ? 3 /* Group */ : 0), - dangerouslySetInnerHTML: { - __html: props.superstate.ui.getSticker("ui//build") - } - }), dbSchema?.id == defaultContextSchemaID && /* @__PURE__ */ import_react48.default.createElement(import_react48.default.Fragment, null, /* @__PURE__ */ import_react48.default.createElement("button", { - className: "mk-toolbar-button", - onClick: (e5) => showColsMenu(e5), - dangerouslySetInnerHTML: { - __html: props.superstate.ui.getSticker("ui//list") - } - }), /* @__PURE__ */ import_react48.default.createElement("button", { - className: "mk-button-new", - onClick: (e5) => showSpaceAddMenu( - props.superstate, - e5.target.getBoundingClientRect(), - spaceCache, - true - ), - dangerouslySetInnerHTML: { - __html: props.superstate.ui.getSticker("ui//plus") - } - })))), (predicate?.filters.length > 0 || predicate?.sort.length > 0 || predicate?.groupBy.length > 0) && /* @__PURE__ */ import_react48.default.createElement("div", { - className: "mk-filter-bar" - }, predicate.groupBy.length > 0 && /* @__PURE__ */ import_react48.default.createElement("div", { - className: "mk-filter" - }, /* @__PURE__ */ import_react48.default.createElement("span", null, i18n_default.menu.groupBy), /* @__PURE__ */ import_react48.default.createElement("span", { - onClick: (e5) => showGroupByMenu( - e5.target.getBoundingClientRect() - ) - }, predicate.groupBy[0]), /* @__PURE__ */ import_react48.default.createElement("div", { - onClick: () => saveGroupBy(null, []), - dangerouslySetInnerHTML: { - __html: props.superstate.ui.getSticker("ui//close") - } - })), (predicate?.sort ?? []).map((f2, i4) => /* @__PURE__ */ import_react48.default.createElement("div", { - key: i4, - className: "mk-filter" - }, /* @__PURE__ */ import_react48.default.createElement("span", null, f2.field), /* @__PURE__ */ import_react48.default.createElement("span", { - onClick: (e5) => changeSortMenu(e5, f2) - }, sortFnTypes[f2.fn].label), /* @__PURE__ */ import_react48.default.createElement("div", { - onClick: () => removeSort(f2), - dangerouslySetInnerHTML: { - __html: props.superstate.ui.getSticker("ui//close") - } - }))), (predicate?.filters ?? [] ?? []).map((f2, i4) => /* @__PURE__ */ import_react48.default.createElement("div", { - key: i4, - className: "mk-filter" - }, /* @__PURE__ */ import_react48.default.createElement("span", null, f2.field), /* @__PURE__ */ import_react48.default.createElement("span", { - onClick: (e5) => changeFilterMenu(e5, f2, i4) - }, filterFnLabels[f2.fn]), /* @__PURE__ */ import_react48.default.createElement(FilterValueSpan, { - superstate: props.superstate, - fieldType: cols.find((c3) => c3.name + c3.table == f2.field)?.type, - filter: f2, - selectFilterValue: (e5, f3) => selectFilterValue(e5, f3, i4) - }), properties3.length > 0 && /* @__PURE__ */ import_react48.default.createElement("span", { - onClick: (e5) => { - e5.stopPropagation(); - props.superstate.ui.openMenu( - e5.currentTarget.getBoundingClientRect(), - { - ui: props.superstate.ui, - multi: false, - editable: false, - value: [], - options: properties3.map((f3) => ({ - name: f3.name, - value: f3.name, - section: f3.type - })), - saveOptions: (_15, value) => selectFilterValue( - e5, + }, + context: { + select: { + schema: { + id: "context.select", + name: "Select Items from Context", + type: "api" + }, + fields: [{ + name: "path", + type: "link" + }, { + name: "table", + type: "text" + }] + }, + update: { + schema: { + id: "context.update", + name: "Update Item in Context", + type: "api" + }, + fields: [{ + name: "path", + type: "space" + }, { + name: "file", + type: "link" + }, { + name: "field", + type: "text" + }, { + name: "value", + type: "text" + }] + }, + insert: { + schema: { + id: "context.insert", + name: "Insert Item into Context", + type: "api" + }, + fields: [ { - ...f2, - fType: "property", - value: value[0] + name: "path", + type: "link" }, - i4 - ), - placeholder: i18n_default.labels.contextItemSelectPlaceholder, - searchable: true, - showAll: true, - sections: [], - showSections: false + { + name: "schema", + type: "text" + }, + { + name: "name", + type: "text" + }, + { + name: "row", + type: "object" + } + ] } - ); + } + }; + this.manager = manager; + } + commandForAction(action) { + if (!action) + return null; + const uri = parseURI(action); + if (uri.authority == "$api") { + return this.apiCommands[uri.path]?.[uri.ref]; + } else if (uri.authority == "$actions") { + return this.superstate.actions.get(uri.path)?.find((f2) => f2.schema.id == uri.ref); + } else { + return this.superstate.actionsIndex.get(uri.path)?.find((f2) => f2.schema.id == uri.ref); } - }, /* @__PURE__ */ import_react48.default.createElement("div", { - className: "mk-icon-xsmall", - dangerouslySetInnerHTML: { - __html: props.superstate.ui.getSticker("ui//plug") + } + runCommand(action, instance) { + const command = this.commandForAction(action); + let result; + let error; + try { + if (command.schema.type == "api") { + const [namespace, method] = command.schema.id.split("."); + result = this.superstate.api[namespace]?.[method]?.(...command.fields.map((f2) => instance.instanceProps[f2.name])); + } + if (command.schema.type == "actions") + result = runActionString(this.superstate, command.code, instance); + if (command.schema.type == "script") + result = executeCode(command.code, instance.instanceProps); + if (command.schema.type == "formula") + result = runFormulaWithContext(this.superstate.formulaContext, this.superstate.pathsIndex, command.code, command.fields.reduce((p, c3) => ({ ...p, [c3.name]: c3 }), {}), instance.instanceProps); + } catch (e5) { + error = e5; } - })), /* @__PURE__ */ import_react48.default.createElement("div", { - onClick: () => removeFilter(f2, i4), - dangerouslySetInnerHTML: { - __html: props.superstate.ui.getSticker("ui//close") + console.log(result, error); + return result; + } + allCommands() { + const apiCommands = Object.keys(this.apiCommands).flatMap((f2) => Object.keys(this.apiCommands[f2]).map((g) => ({ scheme: "spaces", path: `spaces://$api/${f2}/#;${g}`, ...this.apiCommands[f2][g] }))); + const actionCommands = [...this.superstate.actions.entries()].flatMap((f2) => f2[1].map((g) => ({ scheme: "spaces", path: `spaces://$api/${f2[0]}/#;${g.schema.id}`, ...g }))); + return [...apiCommands, ...actionCommands]; + } +}; + +// src/core/utils/contexts/linkContextRow.ts +var propertyDependencies = (fields) => { + const graph = /* @__PURE__ */ new Map(); + fields.filter((f2) => f2.type == "fileprop" || f2.name.startsWith("tags")).forEach((f2) => { + const { value } = parseFieldValue(f2.value, f2.type); + const localDependencies = []; + try { + const deps = parse4(value).filter((f3) => f3.type == "FunctionNode").filter((f3) => f3.fn.name == "prop" && f3.args[0].type == "ConstantNode").map((f3) => f3.args[0]?.value); + localDependencies.push(...deps); + } catch (e5) { } - }))), (predicate?.filters ?? []).length > 0 && /* @__PURE__ */ import_react48.default.createElement("div", { - className: "mk-filter-add", - onClick: (e5) => showAddFilterMenu(e5) - }, /* @__PURE__ */ import_react48.default.createElement("span", null, /* @__PURE__ */ import_react48.default.createElement("span", { - className: "mk-icon-xsmall", - dangerouslySetInnerHTML: { - __html: props.superstate.ui.getSticker("ui//plus") + const key2 = f2.name; + if (!graph.has(key2)) { + graph.set(key2, /* @__PURE__ */ new Set()); + } + for (const dep of localDependencies) { + const depStr = dep; + if (depStr === key2) + continue; + graph.get(key2).add(depStr); + } + }); + const visited = /* @__PURE__ */ new Set(); + const result = []; + const temp = /* @__PURE__ */ new Set(); + const visit = (key2) => { + if (temp.has(key2)) + throw new Error("Circular dependency detected"); + if (!visited.has(key2)) { + temp.add(key2); + const edges = graph.get(key2) || /* @__PURE__ */ new Set(); + for (const dep of edges) { + visit(dep); + } + visited.add(key2); + temp.delete(key2); + result.push(key2); + } + }; + for (const key2 of fields) { + if (!visited.has(key2.name)) { + visit(key2.name); } - }), i18n_default.buttons.addFilter)), /* @__PURE__ */ import_react48.default.createElement("span", null))); + } + return result; }; -var FilterValueSpan = (props) => { - const { filter: filter4, selectFilterValue, fieldType } = props; - const fnType = filterFnTypes[filter4.fn]; - const [value, setValue] = (0, import_react48.useState)(filter4.value); - (0, import_react48.useEffect)(() => setValue(filter4.value), [filter4.value]); - if (filter4.fType == "property") { - return /* @__PURE__ */ import_react48.default.createElement("span", null, filter4.value); +var linkContextRow = (runContext, paths, row2, fields, path2, dependencies314) => { + if (!row2) + return {}; + const result = dependencies314 ?? propertyDependencies(fields); + const frontmatter = paths.get(row2[PathPropertyName])?.metadata?.property ?? {}; + const filteredFrontmatter = Object.keys(frontmatter).filter((f2) => fields.some((g) => g.name == f2)).reduce((p, c3) => ({ ...p, [c3]: parseProperty(c3, frontmatter[c3]) }), {}); + const fieldsSorted = result.map((f2) => fields.find((g) => g.name == f2)).filter((f2) => f2 && (f2.type == "fileprop" || f2.name == "tags")); + const properties3 = fields.reduce((p, c3) => ({ ...p, [c3.name]: c3 }), {}); + return { + ...row2, + ...filteredFrontmatter, + ...fieldsSorted.reduce((p, c3) => { + const { value } = parseFieldValue(c3.value, c3.type); + return { ...p, [c3.name]: runFormulaWithContext(runContext, paths, value, properties3, { ...row2, ...p }, path2) }; + }, {}) + }; +}; + +// src/core/types/metadata.ts +var labelProperties = [ + { + id: "label.sticker", + label: i18n_default.metadataTypes.sticker, + field: "sticker", + vType: "text", + defaultFilter: "isEmpty", + type: "label", + description: "Sticker label for the item" + }, + { + id: "label.color", + label: i18n_default.metadataTypes.color, + field: "color", + vType: "color", + defaultFilter: "equals", + type: "label", + description: "Color label for the item" } - if (!fieldType || !fnType || fnType.valueType == "none") { - return /* @__PURE__ */ import_react48.default.createElement(import_react48.default.Fragment, null); - } else if (fnType.valueType == "text" || fnType.valueType == "number") { - return /* @__PURE__ */ import_react48.default.createElement("input", { - type: "text", - onChange: (e5) => setValue(e5.currentTarget.value), - onBlur: (e5) => { - selectFilterValue(null, { ...filter4, value }); - }, - onKeyDown: (e5) => { - if (e5.key == "Escape") { - setValue(filter4.value); - e5.currentTarget.blur(); - } - if (e5.key == "Enter") { - e5.currentTarget.blur(); - } - }, - value - }); - } else if (fieldType.startsWith("option") || fieldType.startsWith("context") || fieldType.startsWith("link") || fieldType.startsWith("tag")) { - const options = parseMultiString(filter4.value); - return /* @__PURE__ */ import_react48.default.createElement("span", { - onClick: (e5) => selectFilterValue(e5, filter4) - }, options.length == 0 ? i18n_default.labels.select : options.map( - (f2, i4) => fieldType.startsWith("option") ? /* @__PURE__ */ import_react48.default.createElement("span", { - key: i4 - }, f2) : /* @__PURE__ */ import_react48.default.createElement(PathCrumb, { - superstate: props.superstate, - key: i4, - path: f2 - }) - )); - } else if (!filter4.value || filter4.value.length == 0) { - return /* @__PURE__ */ import_react48.default.createElement("span", { - onClick: (e5) => selectFilterValue(e5, filter4) - }, i18n_default.labels.select); +]; +var fileProperties = [ + { + id: "file.name", + label: i18n_default.metadataTypes.fileName, + field: "name", + vType: "text", + defaultFilter: "contains", + type: "file", + description: "Name for a space or note" + }, + { + id: "file.path", + label: i18n_default.metadataTypes.path, + field: "path", + vType: "link", + defaultFilter: "contains", + type: "file", + description: "Path for a space or note" + }, + { + id: "file.parent", + label: i18n_default.metadataTypes.folder, + field: "parent", + vType: "space", + defaultFilter: "contains", + type: "file", + description: "Folder the note or space is in" + }, + { + id: "file.ctime", + label: i18n_default.metadataTypes.created, + field: "ctime", + vType: "date", + defaultFilter: "isSameDate", + type: "file", + description: "Creation date for the note or space" + }, + { + id: "file.mtime", + label: i18n_default.metadataTypes.lastModified, + field: "mtime", + vType: "date", + defaultFilter: "isSameDate", + type: "file", + description: "Last modified date for the note or space" + }, + { + id: "file.extension", + label: i18n_default.metadataTypes.extension, + field: "extension", + vType: "text", + defaultFilter: "is", + type: "file", + description: "File extension" + }, + { + id: "file.size", + label: i18n_default.metadataTypes.size, + field: "size", + vType: "number", + defaultFilter: "lessThan", + type: "file", + description: "File size" } - return /* @__PURE__ */ import_react48.default.createElement("span", { - onClick: (e5) => selectFilterValue(e5, filter4) - }, filter4.value); -}; +]; +var pathCacheMetadata = [ + { + id: "path.tags", + label: i18n_default.metadataTypes.tags, + field: "tags", + vType: "tags-multi", + defaultFilter: "contains", + type: "path", + description: "Tags for the note or space" + }, + { + id: "path.inlinks", + label: i18n_default.metadataTypes.inlinks, + field: "inlinks", + vType: "link-multi", + defaultFilter: "contains", + type: "path", + description: "Links to the note or space" + }, + { + id: "path.outlinks", + label: i18n_default.metadataTypes.outlinks, + field: "outlinks", + vType: "link-multi", + defaultFilter: "contains", + type: "path", + description: "Links from the note or space" + } +]; -// src/core/react/components/SpaceEditor/SpaceQuery.tsx -var SpaceQuery = (props) => { - (0, import_react49.useEffect)(() => { - props.superstate.refreshMetadata(); - }, []); - const { filters, setFilters } = props; - const selectFilterValue = (e5, filter4, i4, k2) => { - const saveFilterValue = (value) => { - setDefFilterValue(value, i4, k2); - }; - if (filter4.fType == "property") { - setFilters( - filters.map( - (f2, groupIndex) => i4 == groupIndex ? { - ...f2, - filters: f2.filters.map( - (g, filterIndex) => k2 == filterIndex ? { - ...g, - fType: "property", - value: filter4.value - } : g - ) - } : f2 - ) - ); +// src/core/utils/metadata.ts +var allMetadata = (superstate) => ({ + label: { + name: i18n_default.metadataTypes.label, + properties: labelProperties + }, + file: { + name: i18n_default.metadataTypes.fileMetadata, + properties: fileProperties + }, + path: { + name: i18n_default.metadataTypes.outlinks, + properties: pathCacheMetadata + }, + frontmatter: { + name: i18n_default.metadataTypes.frontmatter, + properties: superstate.spaceManager.keysForCacheType("frontmatter").map((f2) => ({ + id: "frontmatter." + f2, + label: f2, + field: f2, + vType: "any", + defaultFilter: "contains", + type: "frontmatter", + description: "Frontmatter property" + })) + }, + context: { + name: i18n_default.metadataTypes.contexts, + properties: [...superstate.contextsIndex.values()].flatMap((f2) => f2.cols.filter((f3) => f3.primary != "true").map((g) => ({ + id: "contexts." + f2.path + "." + g.name, + label: g.name, + field: f2.path + "." + g.name, + vType: fieldTypeForField(g), + defaultFilter: "contains", + type: "context", + description: f2.path + " context property" + }))) + } +}); + +// inline-worker:__inline-worker +function inlineWorker(scriptText, name317) { + let blob = new Blob([scriptText], { type: "text/javascript" }); + let url = URL.createObjectURL(blob); + let worker = new Worker(url, name317); + URL.revokeObjectURL(url); + return worker; +} + +// src/core/superstate/workers/indexer/indexer.worker.ts +function Worker2() { + return inlineWorker(`"use strict";var Dk=Object.create;var bb=Object.defineProperty;var Sk=Object.getOwnPropertyDescriptor;var Nk=Object.getOwnPropertyNames;var Ak=Object.getPrototypeOf,Mk=Object.prototype.hasOwnProperty;var vn=(e,r)=>()=>(r||e((r={exports:{}}).exports,r),r.exports),Ck=(e,r)=>{for(var t in r)bb(e,t,{get:r[t],enumerable:!0})},Ek=(e,r,t,n)=>{if(r&&typeof r=="object"||typeof r=="function")for(let a of Nk(r))!Mk.call(e,a)&&a!==t&&bb(e,a,{get:()=>r[a],enumerable:!(n=Sk(r,a))||n.enumerable});return e};var ca=(e,r,t)=>(t=e!=null?Dk(Ak(e)):{},Ek(r||!e||!e.__esModule?bb(t,"default",{value:e,enumerable:!0}):t,e));var fm=vn((gu,Sc)=>{(function(){var e,r="4.17.21",t=200,n="Unsupported core-js use. Try https://npms.io/search?q=ponyfill.",a="Expected a function",i="Invalid \`variable\` option passed into \`_.template\`",u="__lodash_hash_undefined__",l=500,c="__lodash_placeholder__",o=1,s=2,m=4,d=1,h=2,x=1,v=2,y=4,w=8,C=16,b=32,M=64,A=128,S=256,O=512,_=30,E="...",T=800,R=16,q=1,W=2,G=3,H=1/0,L=9007199254740991,k=17976931348623157e292,K=0/0,z=4294967295,oe=z-1,pe=z>>>1,ae=[["ary",A],["bind",x],["bindKey",v],["curry",w],["curryRight",C],["flip",O],["partial",b],["partialRight",M],["rearg",S]],$="[object Arguments]",le="[object Array]",Ee="[object AsyncFunction]",me="[object Boolean]",ge="[object Date]",Se="[object DOMException]",xe="[object Error]",be="[object Function]",De="[object GeneratorFunction]",Ae="[object Map]",We="[object Number]",Je="[object Null]",J="[object Object]",re="[object Promise]",ye="[object Proxy]",j="[object RegExp]",ne="[object Set]",ue="[object String]",Me="[object Symbol]",Ce="[object Undefined]",Le="[object WeakMap]",Ie="[object WeakSet]",fr="[object ArrayBuffer]",or="[object DataView]",Ke="[object Float32Array]",Pr="[object Float64Array]",ee="[object Int8Array]",ce="[object Int16Array]",we="[object Int32Array]",Be="[object Uint8Array]",ke="[object Uint8ClampedArray]",Te="[object Uint16Array]",Re="[object Uint32Array]",Ye=/\\b__p \\+= '';/g,B=/\\b(__p \\+=) '' \\+/g,Q=/(__e\\(.*?\\)|\\b__t\\)) \\+\\n'';/g,ve=/&(?:amp|lt|gt|quot|#39);/g,Pe=/[&<>"']/g,tr=RegExp(ve.source),cr=RegExp(Pe.source),Xr=/<%-([\\s\\S]+?)%>/g,Pt=/<%([\\s\\S]+?)%>/g,Xt=/<%=([\\s\\S]+?)%>/g,li=/\\.|\\[(?:[^[\\]]*|(["'])(?:(?!\\1)[^\\\\]|\\\\.)*?\\1)\\]/,Wa=/^\\w*$/,Ef=/[^.[\\]]+|\\[(?:(-?\\d+(?:\\.\\d+)?)|(["'])((?:(?!\\2)[^\\\\]|\\\\.)*?)\\2)\\]|(?=(?:\\.|\\[\\])(?:\\.|\\[\\]|$))/g,Ya=/[\\\\^$.*+?()[\\]{}|]/g,oo=RegExp(Ya.source),nr=/^\\s+/,Tf=/\\s/,Ff=/\\{(?:\\n\\/\\* \\[wrapped with .+\\] \\*\\/)?\\n?/,mn=/\\{\\n\\/\\* \\[wrapped with (.+)\\] \\*/,Jo=/,? & /,ot=/[^\\x00-\\x2f\\x3a-\\x40\\x5b-\\x60\\x7b-\\x7f]+/g,Pi=/[()=,{}\\[\\]\\/\\s]/,_f=/\\\\(\\\\)?/g,Gt=/\\$\\{([^\\\\}]*(?:\\\\.[^\\\\}]*)*)\\}/g,zn=/\\w*$/,Un=/^[-+]0x[0-9a-f]+$/i,Tt=/^0b[01]+$/i,On=/^\\[object .+?Constructor\\]$/,ta=/^0o[0-7]+$/i,Ha=/^(?:0|[1-9]\\d*)$/,Of=/[\\xc0-\\xd6\\xd8-\\xf6\\xf8-\\xff\\u0100-\\u017f]/g,so=/($^)/,Bf=/['\\n\\r\\u2028\\u2029\\\\]/g,vt="\\\\ud800-\\\\udfff",uo="\\\\u0300-\\\\u036f",Pf="\\\\ufe20-\\\\ufe2f",Ls="\\\\u20d0-\\\\u20ff",Ko=uo+Pf+Ls,zs="\\\\u2700-\\\\u27bf",Us="a-z\\\\xdf-\\\\xf6\\\\xf8-\\\\xff",Ii="\\\\xac\\\\xb1\\\\xd7\\\\xf7",et="\\\\x00-\\\\x2f\\\\x3a-\\\\x40\\\\x5b-\\\\x60\\\\x7b-\\\\xbf",on="\\\\u2000-\\\\u206f",If=" \\\\t\\\\x0b\\\\f\\\\xa0\\\\ufeff\\\\n\\\\r\\\\u2028\\\\u2029\\\\u1680\\\\u180e\\\\u2000\\\\u2001\\\\u2002\\\\u2003\\\\u2004\\\\u2005\\\\u2006\\\\u2007\\\\u2008\\\\u2009\\\\u200a\\\\u202f\\\\u205f\\\\u3000",mi="A-Z\\\\xc0-\\\\xd6\\\\xd8-\\\\xde",$a="\\\\ufe0e\\\\ufe0f",Ws=Ii+et+on+If,Rf="['\\u2019]",gy="["+vt+"]",kf="["+Ws+"]",pi="["+Ko+"]",qf="\\\\d+",xy="["+zs+"]",Vc="["+Us+"]",fo="[^"+vt+Ws+qf+zs+Us+mi+"]",co="\\\\ud83c[\\\\udffb-\\\\udfff]",Zc="(?:"+pi+"|"+co+")",lo="[^"+vt+"]",na="(?:\\\\ud83c[\\\\udde6-\\\\uddff]){2}",Lf="[\\\\ud800-\\\\udbff][\\\\udc00-\\\\udfff]",mo="["+mi+"]",Qc="\\\\u200d",Xc="(?:"+Vc+"|"+fo+")",yy="(?:"+mo+"|"+fo+")",Jc="(?:"+Rf+"(?:d|ll|m|re|s|t|ve))?",Kc="(?:"+Rf+"(?:D|LL|M|RE|S|T|VE))?",jc=Zc+"?",Ys="["+$a+"]?",by="(?:"+Qc+"(?:"+[lo,na,Lf].join("|")+")"+Ys+jc+")*",el="\\\\d*(?:1st|2nd|3rd|(?![123])\\\\dth)(?=\\\\b|[A-Z_])",wy="\\\\d*(?:1ST|2ND|3RD|(?![123])\\\\dTH)(?=\\\\b|[a-z_])",rl=Ys+jc+by,Dy="(?:"+[xy,na,Lf].join("|")+")"+rl,Sy="(?:"+[lo+pi+"?",pi,na,Lf,gy].join("|")+")",Ny=RegExp(Rf,"g"),Ay=RegExp(pi,"g"),zf=RegExp(co+"(?="+co+")|"+Sy+rl,"g"),My=RegExp([mo+"?"+Vc+"+"+Jc+"(?="+[kf,mo,"$"].join("|")+")",yy+"+"+Kc+"(?="+[kf,mo+Xc,"$"].join("|")+")",mo+"?"+Xc+"+"+Jc,mo+"+"+Kc,wy,el,qf,Dy].join("|"),"g"),Cy=RegExp("["+Qc+vt+Ko+$a+"]"),Ey=/[a-z][A-Z]|[A-Z]{2}[a-z]|[0-9][a-zA-Z]|[a-zA-Z][0-9]|[^a-zA-Z0-9 ]/,Ty=["Array","Buffer","DataView","Date","Error","Float32Array","Float64Array","Function","Int8Array","Int16Array","Int32Array","Map","Math","Object","Promise","RegExp","Set","String","Symbol","TypeError","Uint8Array","Uint8ClampedArray","Uint16Array","Uint32Array","WeakMap","_","clearTimeout","isFinite","parseInt","setTimeout"],Fy=-1,yt={};yt[Ke]=yt[Pr]=yt[ee]=yt[ce]=yt[we]=yt[Be]=yt[ke]=yt[Te]=yt[Re]=!0,yt[$]=yt[le]=yt[fr]=yt[me]=yt[or]=yt[ge]=yt[xe]=yt[be]=yt[Ae]=yt[We]=yt[J]=yt[j]=yt[ne]=yt[ue]=yt[Le]=!1;var gt={};gt[$]=gt[le]=gt[fr]=gt[or]=gt[me]=gt[ge]=gt[Ke]=gt[Pr]=gt[ee]=gt[ce]=gt[we]=gt[Ae]=gt[We]=gt[J]=gt[j]=gt[ne]=gt[ue]=gt[Me]=gt[Be]=gt[ke]=gt[Te]=gt[Re]=!0,gt[xe]=gt[be]=gt[Le]=!1;var _y={\\u00C0:"A",\\u00C1:"A",\\u00C2:"A",\\u00C3:"A",\\u00C4:"A",\\u00C5:"A",\\u00E0:"a",\\u00E1:"a",\\u00E2:"a",\\u00E3:"a",\\u00E4:"a",\\u00E5:"a",\\u00C7:"C",\\u00E7:"c",\\u00D0:"D",\\u00F0:"d",\\u00C8:"E",\\u00C9:"E",\\u00CA:"E",\\u00CB:"E",\\u00E8:"e",\\u00E9:"e",\\u00EA:"e",\\u00EB:"e",\\u00CC:"I",\\u00CD:"I",\\u00CE:"I",\\u00CF:"I",\\u00EC:"i",\\u00ED:"i",\\u00EE:"i",\\u00EF:"i",\\u00D1:"N",\\u00F1:"n",\\u00D2:"O",\\u00D3:"O",\\u00D4:"O",\\u00D5:"O",\\u00D6:"O",\\u00D8:"O",\\u00F2:"o",\\u00F3:"o",\\u00F4:"o",\\u00F5:"o",\\u00F6:"o",\\u00F8:"o",\\u00D9:"U",\\u00DA:"U",\\u00DB:"U",\\u00DC:"U",\\u00F9:"u",\\u00FA:"u",\\u00FB:"u",\\u00FC:"u",\\u00DD:"Y",\\u00FD:"y",\\u00FF:"y",\\u00C6:"Ae",\\u00E6:"ae",\\u00DE:"Th",\\u00FE:"th",\\u00DF:"ss",\\u0100:"A",\\u0102:"A",\\u0104:"A",\\u0101:"a",\\u0103:"a",\\u0105:"a",\\u0106:"C",\\u0108:"C",\\u010A:"C",\\u010C:"C",\\u0107:"c",\\u0109:"c",\\u010B:"c",\\u010D:"c",\\u010E:"D",\\u0110:"D",\\u010F:"d",\\u0111:"d",\\u0112:"E",\\u0114:"E",\\u0116:"E",\\u0118:"E",\\u011A:"E",\\u0113:"e",\\u0115:"e",\\u0117:"e",\\u0119:"e",\\u011B:"e",\\u011C:"G",\\u011E:"G",\\u0120:"G",\\u0122:"G",\\u011D:"g",\\u011F:"g",\\u0121:"g",\\u0123:"g",\\u0124:"H",\\u0126:"H",\\u0125:"h",\\u0127:"h",\\u0128:"I",\\u012A:"I",\\u012C:"I",\\u012E:"I",\\u0130:"I",\\u0129:"i",\\u012B:"i",\\u012D:"i",\\u012F:"i",\\u0131:"i",\\u0134:"J",\\u0135:"j",\\u0136:"K",\\u0137:"k",\\u0138:"k",\\u0139:"L",\\u013B:"L",\\u013D:"L",\\u013F:"L",\\u0141:"L",\\u013A:"l",\\u013C:"l",\\u013E:"l",\\u0140:"l",\\u0142:"l",\\u0143:"N",\\u0145:"N",\\u0147:"N",\\u014A:"N",\\u0144:"n",\\u0146:"n",\\u0148:"n",\\u014B:"n",\\u014C:"O",\\u014E:"O",\\u0150:"O",\\u014D:"o",\\u014F:"o",\\u0151:"o",\\u0154:"R",\\u0156:"R",\\u0158:"R",\\u0155:"r",\\u0157:"r",\\u0159:"r",\\u015A:"S",\\u015C:"S",\\u015E:"S",\\u0160:"S",\\u015B:"s",\\u015D:"s",\\u015F:"s",\\u0161:"s",\\u0162:"T",\\u0164:"T",\\u0166:"T",\\u0163:"t",\\u0165:"t",\\u0167:"t",\\u0168:"U",\\u016A:"U",\\u016C:"U",\\u016E:"U",\\u0170:"U",\\u0172:"U",\\u0169:"u",\\u016B:"u",\\u016D:"u",\\u016F:"u",\\u0171:"u",\\u0173:"u",\\u0174:"W",\\u0175:"w",\\u0176:"Y",\\u0177:"y",\\u0178:"Y",\\u0179:"Z",\\u017B:"Z",\\u017D:"Z",\\u017A:"z",\\u017C:"z",\\u017E:"z",\\u0132:"IJ",\\u0133:"ij",\\u0152:"Oe",\\u0153:"oe",\\u0149:"'n",\\u017F:"s"},Uf={"&":"&","<":"<",">":">",'"':""","'":"'"},Wf={"&":"&","<":"<",">":">",""":'"',"'":"'"},Oy={"\\\\":"\\\\","'":"'","\\n":"n","\\r":"r","\\u2028":"u2028","\\u2029":"u2029"},tl=parseFloat,nl=parseInt,al=typeof global=="object"&&global&&global.Object===Object&&global,By=typeof self=="object"&&self&&self.Object===Object&&self,Vt=al||By||Function("return this")(),Yf=typeof gu=="object"&&gu&&!gu.nodeType&&gu,di=Yf&&typeof Sc=="object"&&Sc&&!Sc.nodeType&&Sc,bt=di&&di.exports===Yf,Ri=bt&&al.process,sn=function(){try{var de=di&&di.require&&di.require("util").types;return de||Ri&&Ri.binding&&Ri.binding("util")}catch{}}(),il=sn&&sn.isArrayBuffer,Hf=sn&&sn.isDate,ol=sn&&sn.isMap,sl=sn&&sn.isRegExp,jo=sn&&sn.isSet,Ga=sn&&sn.isTypedArray;function pn(de,_e,Ne){switch(Ne.length){case 0:return de.call(_e);case 1:return de.call(_e,Ne[0]);case 2:return de.call(_e,Ne[0],Ne[1]);case 3:return de.call(_e,Ne[0],Ne[1],Ne[2])}return de.apply(_e,Ne)}function Py(de,_e,Ne,ir){for(var Ar=-1,rt=de==null?0:de.length;++Ar-1}function $f(de,_e,Ne){for(var ir=-1,Ar=de==null?0:de.length;++ir-1;);return Ne}function dl(de,_e){for(var Ne=de.length;Ne--&&po(_e,de[Ne],0)>-1;);return Ne}function zy(de,_e){for(var Ne=de.length,ir=0;Ne--;)de[Ne]===_e&&++ir;return ir}var hl=es(_y),Uy=es(Uf);function Wy(de){return"\\\\"+Oy[de]}function Yy(de,_e){return de==null?e:de[_e]}function wa(de){return Cy.test(de)}function Hy(de){return Ey.test(de)}function $y(de){for(var _e,Ne=[];!(_e=de.next()).done;)Ne.push(_e.value);return Ne}function jf(de){var _e=-1,Ne=Array(de.size);return de.forEach(function(ir,Ar){Ne[++_e]=[Ar,ir]}),Ne}function rs(de,_e){return function(Ne){return de(_e(Ne))}}function aa(de,_e){for(var Ne=-1,ir=de.length,Ar=0,rt=[];++Ne-1}function Fl(f,p){var D=this.__data__,P=Hn(D,f);return P<0?(++this.size,D.push([f,p])):D[P][1]=p,this}Qa.prototype.clear=y1,Qa.prototype.delete=Tl,Qa.prototype.get=b1,Qa.prototype.has=w1,Qa.prototype.set=Fl;function Xa(f){var p=-1,D=f==null?0:f.length;for(this.clear();++p=p?f:p)),f}function Pn(f,p,D,P,Y,X){var ie,fe=p&o,he=p&s,qe=p&m;if(D&&(ie=Y?D(f,P,Y,X):D(f)),ie!==e)return ie;if(!_t(f))return f;var ze=Br(f);if(ze){if(ie=J5(f),!fe)return $n(f,ie)}else{var He=wn(f),er=He==be||He==De;if(Ao(f))return XS(f,fe);if(He==J||He==$||er&&!Y){if(ie=he||er?{}:hN(f),!fe)return he?z5(f,F1(ie,f)):L5(f,nc(ie,f))}else{if(!gt[He])return Y?f:{};ie=K5(f,He,fe)}}X||(X=new ia);var mr=X.get(f);if(mr)return mr;X.set(f,ie),HN(f)?f.forEach(function(Sr){ie.add(Pn(Sr,p,D,Sr,f,X))}):WN(f)&&f.forEach(function(Sr,Yr){ie.set(Yr,Pn(Sr,p,D,Yr,f,X))});var Dr=qe?he?J1:X1:he?Vn:un,qr=ze?e:Dr(f);return It(qr||f,function(Sr,Yr){qr&&(Yr=Sr,Sr=f[Yr]),ls(ie,Yr,Pn(Sr,p,D,Yr,f,X))}),ie}function ac(f){var p=un(f);return function(D){return Il(D,f,p)}}function Il(f,p,D){var P=D.length;if(f==null)return!P;for(f=zr(f);P--;){var Y=D[P],X=p[Y],ie=f[Y];if(ie===e&&!(Y in f)||!X(ie))return!1}return!0}function Rl(f,p,D){if(typeof f!="function")throw new Wn(a);return pc(function(){f.apply(e,D)},p)}function In(f,p,D,P){var Y=-1,X=$s,ie=!0,fe=f.length,he=[],qe=p.length;if(!fe)return he;D&&(p=dt(p,bn(D))),P?(X=$f,ie=!1):p.length>=t&&(X=ho,ie=!1,p=new zi(p));e:for(;++YY?0:Y+D),P=P===e||P>Y?Y:Rr(P),P<0&&(P+=Y),P=D>P?0:GN(P);D0&&D(fe)?p>1?Jt(fe,p-1,D,P,Y):ba(Y,fe):P||(Y[Y.length]=fe)}return Y}var ic=tN(),Ll=tN(!0);function Da(f,p){return f&&ic(f,p,un)}function oc(f,p){return f&&Ll(f,p,un)}function Sa(f,p){return hi(p,function(D){return Gi(f[D])})}function Wi(f,p){p=So(p,f);for(var D=0,P=p.length;f!=null&&Dp}function B1(f,p){return f!=null&&ut.call(f,p)}function P1(f,p){return f!=null&&p in zr(f)}function I1(f,p,D){return f>=Ft(p,D)&&f=120&&ze.length>=120)?new zi(ie&&ze):e}ze=f[0];var He=-1,er=fe[0];e:for(;++He-1;)fe!==f&&qi.call(fe,he,1),qi.call(f,he,1);return f}function WS(f,p){for(var D=f?p.length:0,P=D-1;D--;){var Y=p[D];if(D==P||Y!==X){var X=Y;$i(Y)?qi.call(f,Y,1):Y1(f,Y)}}return f}function z1(f,p){return f+is(Cl()*(p-f+1))}function E5(f,p,D,P){for(var Y=-1,X=Rt(eu((p-f)/(D||1)),0),ie=Ne(X);X--;)ie[P?X:++Y]=f,f+=D;return ie}function U1(f,p){var D="";if(!f||p<1||p>L)return D;do p%2&&(D+=f),p=is(p/2),p&&(f+=f);while(p);return D}function Ur(f,p){return ab(xN(f,p,Zn),f+"")}function T5(f){return Pl(hu(f))}function F5(f,p){var D=hu(f);return Jl(D,Ui(p,0,D.length))}function cc(f,p,D,P){if(!_t(f))return f;p=So(p,f);for(var Y=-1,X=p.length,ie=X-1,fe=f;fe!=null&&++YY?0:Y+p),D=D>Y?Y:D,D<0&&(D+=Y),Y=p>D?0:D-p>>>0,p>>>=0;for(var X=Ne(Y);++P>>1,ie=f[X];ie!==null&&!sa(ie)&&(D?ie<=p:ie=t){var qe=p?null:H5(f);if(qe)return vo(qe);ie=!1,Y=ho,he=new zi}else he=p?[]:fe;e:for(;++P=P?f:Ma(f,p,D)}var QS=n1||function(f){return Vt.clearTimeout(f)};function XS(f,p){if(p)return f.slice();var D=f.length,P=bl?bl(D):new f.constructor(D);return f.copy(P),P}function V1(f){var p=new f.constructor(f.byteLength);return new Js(p).set(new Js(f)),p}function I5(f,p){var D=p?V1(f.buffer):f.buffer;return new f.constructor(D,f.byteOffset,f.byteLength)}function R5(f){var p=new f.constructor(f.source,zn.exec(f));return p.lastIndex=f.lastIndex,p}function k5(f){return cs?zr(cs.call(f)):{}}function JS(f,p){var D=p?V1(f.buffer):f.buffer;return new f.constructor(D,f.byteOffset,f.length)}function KS(f,p){if(f!==p){var D=f!==e,P=f===null,Y=f===f,X=sa(f),ie=p!==e,fe=p===null,he=p===p,qe=sa(p);if(!fe&&!qe&&!X&&f>p||X&&ie&&he&&!fe&&!qe||P&&ie&&he||!D&&he||!Y)return 1;if(!P&&!X&&!qe&&f=fe)return he;var qe=D[P];return he*(qe=="desc"?-1:1)}}return f.index-p.index}function jS(f,p,D,P){for(var Y=-1,X=f.length,ie=D.length,fe=-1,he=p.length,qe=Rt(X-ie,0),ze=Ne(he+qe),He=!P;++fe1?D[Y-1]:e,ie=Y>2?D[2]:e;for(X=f.length>3&&typeof X=="function"?(Y--,X):e,ie&&Rn(D[0],D[1],ie)&&(X=Y<3?e:X,Y=1),p=zr(p);++P-1?Y[X?p[ie]:ie]:e}}function iN(f){return Hi(function(p){var D=p.length,P=D,Y=Yn.prototype.thru;for(f&&p.reverse();P--;){var X=p[P];if(typeof X!="function")throw new Wn(a);if(Y&&!ie&&Ql(X)=="wrapper")var ie=new Yn([],!0)}for(P=ie?P:D;++P1&&Zr.reverse(),ze&&hefe))return!1;var qe=X.get(f),ze=X.get(p);if(qe&&ze)return qe==p&&ze==f;var He=-1,er=!0,mr=D&h?new zi:e;for(X.set(f,p),X.set(p,f);++He1?"& ":"")+p[P],p=p.join(D>2?", ":" "),f.replace(Ff,\`{ +/* [wrapped with \`+p+\`] */ +\`)}function e8(f){return Br(f)||vs(f)||!!(Sl&&f&&f[Sl])}function $i(f,p){var D=typeof f;return p=p??L,!!p&&(D=="number"||D!="symbol"&&Ha.test(f))&&f>-1&&f%1==0&&f0){if(++p>=T)return arguments[0]}else p=0;return f.apply(e,arguments)}}function Jl(f,p){var D=-1,P=f.length,Y=P-1;for(p=p===e?P:p;++D1?f[p-1]:e;return D=typeof D=="function"?(f.pop(),D):e,FN(f,D)});function _N(f){var p=Z(f);return p.__chain__=!0,p}function l6(f,p){return p(f),f}function Kl(f,p){return p(f)}var m6=Hi(function(f){var p=f.length,D=p?f[0]:0,P=this.__wrapped__,Y=function(X){return fu(X,f)};return p>1||this.__actions__.length||!(P instanceof kr)||!$i(D)?this.thru(Y):(P=P.slice(D,+D+(p?1:0)),P.__actions__.push({func:Kl,args:[Y],thisArg:e}),new Yn(P,this.__chain__).thru(function(X){return p&&!X.length&&X.push(e),X}))});function p6(){return _N(this)}function d6(){return new Yn(this.value(),this.__chain__)}function h6(){this.__values__===e&&(this.__values__=$N(this.value()));var f=this.__index__>=this.__values__.length,p=f?e:this.__values__[this.__index__++];return{done:f,value:p}}function v6(){return this}function g6(f){for(var p,D=this;D instanceof iu;){var P=NN(D);P.__index__=0,P.__values__=e,p?Y.__wrapped__=P:p=P;var Y=P;D=D.__wrapped__}return Y.__wrapped__=f,p}function x6(){var f=this.__wrapped__;if(f instanceof kr){var p=f;return this.__actions__.length&&(p=new kr(this)),p=p.reverse(),p.__actions__.push({func:Kl,args:[ib],thisArg:e}),new Yn(p,this.__chain__)}return this.thru(ib)}function y6(){return VS(this.__wrapped__,this.__actions__)}var b6=Hl(function(f,p,D){ut.call(f,D)?++f[D]:Ja(f,D,1)});function w6(f,p,D){var P=Br(f)?Hs:_1;return D&&Rn(f,p,D)&&(p=e),P(f,xr(p,3))}function D6(f,p){var D=Br(f)?hi:ql;return D(f,xr(p,3))}var S6=aN(AN),N6=aN(MN);function A6(f,p){return Jt(jl(f,p),1)}function M6(f,p){return Jt(jl(f,p),H)}function C6(f,p,D){return D=D===e?1:Rr(D),Jt(jl(f,p),D)}function ON(f,p){var D=Br(f)?It:bi;return D(f,xr(p,3))}function BN(f,p){var D=Br(f)?Iy:kl;return D(f,xr(p,3))}var E6=Hl(function(f,p,D){ut.call(f,D)?f[D].push(p):Ja(f,D,[p])});function T6(f,p,D,P){f=Gn(f)?f:hu(f),D=D&&!P?Rr(D):0;var Y=f.length;return D<0&&(D=Rt(Y+D,0)),am(f)?D<=Y&&f.indexOf(p,D)>-1:!!Y&&po(f,p,D)>-1}var F6=Ur(function(f,p,D){var P=-1,Y=typeof p=="function",X=Gn(f)?Ne(f.length):[];return bi(f,function(ie){X[++P]=Y?pn(p,ie,D):Na(ie,p,D)}),X}),_6=Hl(function(f,p,D){Ja(f,D,p)});function jl(f,p){var D=Br(f)?dt:Fe;return D(f,xr(p,3))}function O6(f,p,D,P){return f==null?[]:(Br(p)||(p=p==null?[]:[p]),D=P?e:D,Br(D)||(D=D==null?[]:[D]),ja(f,p,D))}var B6=Hl(function(f,p,D){f[D?0:1].push(p)},function(){return[[],[]]});function P6(f,p,D){var P=Br(f)?Gf:ml,Y=arguments.length<3;return P(f,xr(p,4),D,Y,bi)}function I6(f,p,D){var P=Br(f)?Ry:ml,Y=arguments.length<3;return P(f,xr(p,4),D,Y,kl)}function R6(f,p){var D=Br(f)?hi:ql;return D(f,tm(xr(p,3)))}function k6(f){var p=Br(f)?Pl:T5;return p(f)}function q6(f,p,D){(D?Rn(f,p,D):p===e)?p=1:p=Rr(p);var P=Br(f)?C1:F5;return P(f,p)}function L6(f){var p=Br(f)?E1:O5;return p(f)}function z6(f){if(f==null)return 0;if(Gn(f))return am(f)?vi(f):f.length;var p=wn(f);return p==Ae||p==ne?f.size:U(f).length}function U6(f,p,D){var P=Br(f)?Vf:B5;return D&&Rn(f,p,D)&&(p=e),P(f,xr(p,3))}var W6=Ur(function(f,p){if(f==null)return[];var D=p.length;return D>1&&Rn(f,p[0],p[1])?p=[]:D>2&&Rn(p[0],p[1],p[2])&&(p=[p[0]]),ja(f,Jt(p,1),[])}),em=a1||function(){return Vt.Date.now()};function Y6(f,p){if(typeof p!="function")throw new Wn(a);return f=Rr(f),function(){if(--f<1)return p.apply(this,arguments)}}function PN(f,p,D){return p=D?e:p,p=f&&p==null?f.length:p,Yi(f,A,e,e,e,e,p)}function IN(f,p){var D;if(typeof p!="function")throw new Wn(a);return f=Rr(f),function(){return--f>0&&(D=p.apply(this,arguments)),f<=1&&(p=e),D}}var sb=Ur(function(f,p,D){var P=x;if(D.length){var Y=aa(D,pu(sb));P|=b}return Yi(f,P,p,D,Y)}),RN=Ur(function(f,p,D){var P=x|v;if(D.length){var Y=aa(D,pu(RN));P|=b}return Yi(p,P,f,D,Y)});function kN(f,p,D){p=D?e:p;var P=Yi(f,w,e,e,e,e,e,p);return P.placeholder=kN.placeholder,P}function qN(f,p,D){p=D?e:p;var P=Yi(f,C,e,e,e,e,e,p);return P.placeholder=qN.placeholder,P}function LN(f,p,D){var P,Y,X,ie,fe,he,qe=0,ze=!1,He=!1,er=!0;if(typeof f!="function")throw new Wn(a);p=Ea(p)||0,_t(D)&&(ze=!!D.leading,He="maxWait"in D,X=He?Rt(Ea(D.maxWait)||0,p):X,er="trailing"in D?!!D.trailing:er);function mr(Wt){var ri=P,Zi=Y;return P=Y=e,qe=Wt,ie=f.apply(Zi,ri),ie}function Dr(Wt){return qe=Wt,fe=pc(Yr,p),ze?mr(Wt):ie}function qr(Wt){var ri=Wt-he,Zi=Wt-qe,aA=p-ri;return He?Ft(aA,X-Zi):aA}function Sr(Wt){var ri=Wt-he,Zi=Wt-qe;return he===e||ri>=p||ri<0||He&&Zi>=X}function Yr(){var Wt=em();if(Sr(Wt))return Zr(Wt);fe=pc(Yr,qr(Wt))}function Zr(Wt){return fe=e,er&&P?mr(Wt):(P=Y=e,ie)}function ua(){fe!==e&&QS(fe),qe=0,P=he=Y=fe=e}function kn(){return fe===e?ie:Zr(em())}function fa(){var Wt=em(),ri=Sr(Wt);if(P=arguments,Y=this,he=Wt,ri){if(fe===e)return Dr(he);if(He)return QS(fe),fe=pc(Yr,p),mr(he)}return fe===e&&(fe=pc(Yr,p)),ie}return fa.cancel=ua,fa.flush=kn,fa}var H6=Ur(function(f,p){return Rl(f,1,p)}),$6=Ur(function(f,p,D){return Rl(f,Ea(p)||0,D)});function G6(f){return Yi(f,O)}function rm(f,p){if(typeof f!="function"||p!=null&&typeof p!="function")throw new Wn(a);var D=function(){var P=arguments,Y=p?p.apply(this,P):P[0],X=D.cache;if(X.has(Y))return X.get(Y);var ie=f.apply(this,P);return D.cache=X.set(Y,ie)||X,ie};return D.cache=new(rm.Cache||Xa),D}rm.Cache=Xa;function tm(f){if(typeof f!="function")throw new Wn(a);return function(){var p=arguments;switch(p.length){case 0:return!f.call(this);case 1:return!f.call(this,p[0]);case 2:return!f.call(this,p[0],p[1]);case 3:return!f.call(this,p[0],p[1],p[2])}return!f.apply(this,p)}}function V6(f){return IN(2,f)}var Z6=P5(function(f,p){p=p.length==1&&Br(p[0])?dt(p[0],bn(xr())):dt(Jt(p,1),bn(xr()));var D=p.length;return Ur(function(P){for(var Y=-1,X=Ft(P.length,D);++Y=p}),vs=Ul(function(){return arguments}())?Ul:function(f){return kt(f)&&ut.call(f,"callee")&&!Dl.call(f,"callee")},Br=Ne.isArray,f7=il?bn(il):R1;function Gn(f){return f!=null&&nm(f.length)&&!Gi(f)}function Ut(f){return kt(f)&&Gn(f)}function c7(f){return f===!0||f===!1||kt(f)&&dn(f)==me}var Ao=Nl||yb,l7=Hf?bn(Hf):k1;function m7(f){return kt(f)&&f.nodeType===1&&!dc(f)}function p7(f){if(f==null)return!0;if(Gn(f)&&(Br(f)||typeof f=="string"||typeof f.splice=="function"||Ao(f)||du(f)||vs(f)))return!f.length;var p=wn(f);if(p==Ae||p==ne)return!f.size;if(mc(f))return!U(f).length;for(var D in f)if(ut.call(f,D))return!1;return!0}function d7(f,p){return ms(f,p)}function h7(f,p,D){D=typeof D=="function"?D:e;var P=D?D(f,p):e;return P===e?ms(f,p,e,D):!!P}function fb(f){if(!kt(f))return!1;var p=dn(f);return p==xe||p==Se||typeof f.message=="string"&&typeof f.name=="string"&&!dc(f)}function v7(f){return typeof f=="number"&&os(f)}function Gi(f){if(!_t(f))return!1;var p=dn(f);return p==be||p==De||p==Ee||p==ye}function UN(f){return typeof f=="number"&&f==Rr(f)}function nm(f){return typeof f=="number"&&f>-1&&f%1==0&&f<=L}function _t(f){var p=typeof f;return f!=null&&(p=="object"||p=="function")}function kt(f){return f!=null&&typeof f=="object"}var WN=ol?bn(ol):fc;function g7(f,p){return f===p||wi(f,p,j1(p))}function x7(f,p,D){return D=typeof D=="function"?D:e,wi(f,p,j1(p),D)}function y7(f){return YN(f)&&f!=+f}function b7(f){if(n8(f))throw new Ar(n);return ps(f)}function w7(f){return f===null}function D7(f){return f==null}function YN(f){return typeof f=="number"||kt(f)&&dn(f)==We}function dc(f){if(!kt(f)||dn(f)!=J)return!1;var p=Ks(f);if(p===null)return!0;var D=ut.call(p,"constructor")&&p.constructor;return typeof D=="function"&&D instanceof D&&ns.call(D)==e1}var cb=sl?bn(sl):Vr;function S7(f){return UN(f)&&f>=-L&&f<=L}var HN=jo?bn(jo):g;function am(f){return typeof f=="string"||!Br(f)&&kt(f)&&dn(f)==ue}function sa(f){return typeof f=="symbol"||kt(f)&&dn(f)==Me}var du=Ga?bn(Ga):N;function N7(f){return f===e}function A7(f){return kt(f)&&wn(f)==Le}function M7(f){return kt(f)&&dn(f)==Ie}var C7=Zl(se),E7=Zl(function(f,p){return f<=p});function $N(f){if(!f)return[];if(Gn(f))return am(f)?Bn(f):$n(f);if(as&&f[as])return $y(f[as]());var p=wn(f),D=p==Ae?jf:p==ne?vo:hu;return D(f)}function Vi(f){if(!f)return f===0?f:0;if(f=Ea(f),f===H||f===-H){var p=f<0?-1:1;return p*k}return f===f?f:0}function Rr(f){var p=Vi(f),D=p%1;return p===p?D?p-D:p:0}function GN(f){return f?Ui(Rr(f),0,z):0}function Ea(f){if(typeof f=="number")return f;if(sa(f))return K;if(_t(f)){var p=typeof f.valueOf=="function"?f.valueOf():f;f=_t(p)?p+"":p}if(typeof f!="string")return f===0?f:+f;f=pl(f);var D=Tt.test(f);return D||ta.test(f)?nl(f.slice(2),D?2:8):Un.test(f)?K:+f}function VN(f){return Di(f,Vn(f))}function T7(f){return f?Ui(Rr(f),-L,L):f===0?f:0}function ft(f){return f==null?"":oa(f)}var F7=lu(function(f,p){if(mc(p)||Gn(p)){Di(p,un(p),f);return}for(var D in p)ut.call(p,D)&&ls(f,D,p[D])}),ZN=lu(function(f,p){Di(p,Vn(p),f)}),im=lu(function(f,p,D,P){Di(p,Vn(p),f,P)}),_7=lu(function(f,p,D,P){Di(p,un(p),f,P)}),O7=Hi(fu);function B7(f,p){var D=wo(f);return p==null?D:nc(D,p)}var P7=Ur(function(f,p){f=zr(f);var D=-1,P=p.length,Y=P>2?p[2]:e;for(Y&&Rn(p[0],p[1],Y)&&(P=1);++D1),X}),Di(f,J1(f),D),P&&(D=Pn(D,o|s|m,$5));for(var Y=p.length;Y--;)Y1(D,p[Y]);return D});function K7(f,p){return XN(f,tm(xr(p)))}var j7=Hi(function(f,p){return f==null?{}:M5(f,p)});function XN(f,p){if(f==null)return{};var D=dt(J1(f),function(P){return[P]});return p=xr(p),US(f,D,function(P,Y){return p(P,Y[0])})}function e9(f,p,D){p=So(p,f);var P=-1,Y=p.length;for(Y||(Y=1,f=e);++Pp){var P=f;f=p,p=P}if(D||f%1||p%1){var Y=Cl();return Ft(f+Y*(p-f+tl("1e-"+((Y+"").length-1))),p)}return z1(f,p)}var l9=mu(function(f,p,D){return p=p.toLowerCase(),f+(D?jN(p):p)});function jN(f){return pb(ft(f).toLowerCase())}function eA(f){return f=ft(f),f&&f.replace(Of,hl).replace(Ay,"")}function m9(f,p,D){f=ft(f),p=oa(p);var P=f.length;D=D===e?P:Ui(Rr(D),0,P);var Y=D;return D-=p.length,D>=0&&f.slice(D,Y)==p}function p9(f){return f=ft(f),f&&cr.test(f)?f.replace(Pe,Uy):f}function d9(f){return f=ft(f),f&&oo.test(f)?f.replace(Ya,"\\\\$&"):f}var h9=mu(function(f,p,D){return f+(D?"-":"")+p.toLowerCase()}),v9=mu(function(f,p,D){return f+(D?" ":"")+p.toLowerCase()}),g9=nN("toLowerCase");function x9(f,p,D){f=ft(f),p=Rr(p);var P=p?vi(f):0;if(!p||P>=p)return f;var Y=(p-P)/2;return Vl(is(Y),D)+f+Vl(eu(Y),D)}function y9(f,p,D){f=ft(f),p=Rr(p);var P=p?vi(f):0;return p&&P>>0,D?(f=ft(f),f&&(typeof p=="string"||p!=null&&!cb(p))&&(p=oa(p),!p&&wa(f))?No(Bn(f),0,D):f.split(p,D)):[]}var M9=mu(function(f,p,D){return f+(D?" ":"")+pb(p)});function C9(f,p,D){return f=ft(f),D=D==null?0:Ui(Rr(D),0,f.length),p=oa(p),f.slice(D,D+p.length)==p}function E9(f,p,D){var P=Z.templateSettings;D&&Rn(f,p,D)&&(p=e),f=ft(f),p=im({},p,P,cN);var Y=im({},p.imports,P.imports,cN),X=un(Y),ie=Kf(Y,X),fe,he,qe=0,ze=p.interpolate||so,He="__p += '",er=Va((p.escape||so).source+"|"+ze.source+"|"+(ze===Xt?Gt:so).source+"|"+(p.evaluate||so).source+"|$","g"),mr="//# sourceURL="+(ut.call(p,"sourceURL")?(p.sourceURL+"").replace(/\\s/g," "):"lodash.templateSources["+ ++Fy+"]")+\` +\`;f.replace(er,function(Sr,Yr,Zr,ua,kn,fa){return Zr||(Zr=ua),He+=f.slice(qe,fa).replace(Bf,Wy),Yr&&(fe=!0,He+=\`' + +__e(\`+Yr+\`) + +'\`),kn&&(he=!0,He+=\`'; +\`+kn+\`; +__p += '\`),Zr&&(He+=\`' + +((__t = (\`+Zr+\`)) == null ? '' : __t) + +'\`),qe=fa+Sr.length,Sr}),He+=\`'; +\`;var Dr=ut.call(p,"variable")&&p.variable;if(!Dr)He=\`with (obj) { +\`+He+\` +} +\`;else if(Pi.test(Dr))throw new Ar(i);He=(he?He.replace(Ye,""):He).replace(B,"$1").replace(Q,"$1;"),He="function("+(Dr||"obj")+\`) { +\`+(Dr?"":\`obj || (obj = {}); +\`)+"var __t, __p = ''"+(fe?", __e = _.escape":"")+(he?\`, __j = Array.prototype.join; +function print() { __p += __j.call(arguments, '') } +\`:\`; +\`)+He+\`return __p +}\`;var qr=tA(function(){return rt(X,mr+"return "+He).apply(e,ie)});if(qr.source=He,fb(qr))throw qr;return qr}function T9(f){return ft(f).toLowerCase()}function F9(f){return ft(f).toUpperCase()}function _9(f,p,D){if(f=ft(f),f&&(D||p===e))return pl(f);if(!f||!(p=oa(p)))return f;var P=Bn(f),Y=Bn(p),X=xt(P,Y),ie=dl(P,Y)+1;return No(P,X,ie).join("")}function O9(f,p,D){if(f=ft(f),f&&(D||p===e))return f.slice(0,Vs(f)+1);if(!f||!(p=oa(p)))return f;var P=Bn(f),Y=dl(P,Bn(p))+1;return No(P,0,Y).join("")}function B9(f,p,D){if(f=ft(f),f&&(D||p===e))return f.replace(nr,"");if(!f||!(p=oa(p)))return f;var P=Bn(f),Y=xt(P,Bn(p));return No(P,Y).join("")}function P9(f,p){var D=_,P=E;if(_t(p)){var Y="separator"in p?p.separator:Y;D="length"in p?Rr(p.length):D,P="omission"in p?oa(p.omission):P}f=ft(f);var X=f.length;if(wa(f)){var ie=Bn(f);X=ie.length}if(D>=X)return f;var fe=D-vi(P);if(fe<1)return P;var he=ie?No(ie,0,fe).join(""):f.slice(0,fe);if(Y===e)return he+P;if(ie&&(fe+=he.length-fe),cb(Y)){if(f.slice(fe).search(Y)){var qe,ze=he;for(Y.global||(Y=Va(Y.source,ft(zn.exec(Y))+"g")),Y.lastIndex=0;qe=Y.exec(ze);)var He=qe.index;he=he.slice(0,He===e?fe:He)}}else if(f.indexOf(oa(Y),fe)!=fe){var er=he.lastIndexOf(Y);er>-1&&(he=he.slice(0,er))}return he+P}function I9(f){return f=ft(f),f&&tr.test(f)?f.replace(ve,Zy):f}var R9=mu(function(f,p,D){return f+(D?" ":"")+p.toUpperCase()}),pb=nN("toUpperCase");function rA(f,p,D){return f=ft(f),p=D?e:p,p===e?Hy(f)?Jy(f):qy(f):f.match(p)||[]}var tA=Ur(function(f,p){try{return pn(f,e,p)}catch(D){return fb(D)?D:new Ar(D)}}),k9=Hi(function(f,p){return It(p,function(D){D=Si(D),Ja(f,D,sb(f[D],f))}),f});function q9(f){var p=f==null?0:f.length,D=xr();return f=p?dt(f,function(P){if(typeof P[1]!="function")throw new Wn(a);return[D(P[0]),P[1]]}):[],Ur(function(P){for(var Y=-1;++YL)return[];var D=z,P=Ft(f,z);p=xr(p),f-=z;for(var Y=Jf(P,p);++D0||p<0)?new kr(D):(f<0?D=D.takeRight(-f):f&&(D=D.drop(f)),p!==e&&(p=Rr(p),D=p<0?D.dropRight(-p):D.take(p-f)),D)},kr.prototype.takeRightWhile=function(f){return this.reverse().takeWhile(f).reverse()},kr.prototype.toArray=function(){return this.take(z)},Da(kr.prototype,function(f,p){var D=/^(?:filter|find|map|reject)|While$/.test(p),P=/^(?:head|last)$/.test(p),Y=Z[P?"take"+(p=="last"?"Right":""):p],X=P||/^find/.test(p);!Y||(Z.prototype[p]=function(){var ie=this.__wrapped__,fe=P?[1]:arguments,he=ie instanceof kr,qe=fe[0],ze=he||Br(ie),He=function(Yr){var Zr=Y.apply(Z,ba([Yr],fe));return P&&er?Zr[0]:Zr};ze&&D&&typeof qe=="function"&&qe.length!=1&&(he=ze=!1);var er=this.__chain__,mr=!!this.__actions__.length,Dr=X&&!er,qr=he&&!mr;if(!X&&ze){ie=qr?ie:new kr(this);var Sr=f.apply(ie,fe);return Sr.__actions__.push({func:Kl,args:[He],thisArg:e}),new Yn(Sr,er)}return Dr&&qr?f.apply(this,fe):(Sr=this.thru(He),Dr?P?Sr.value()[0]:Sr.value():Sr)})}),It(["pop","push","shift","sort","splice","unshift"],function(f){var p=ts[f],D=/^(?:push|sort|unshift)$/.test(f)?"tap":"thru",P=/^(?:pop|shift)$/.test(f);Z.prototype[f]=function(){var Y=arguments;if(P&&!this.__chain__){var X=this.value();return p.apply(Br(X)?X:[],Y)}return this[D](function(ie){return p.apply(Br(ie)?ie:[],Y)})}}),Da(kr.prototype,function(f,p){var D=Z[p];if(D){var P=D.name+"";ut.call(bo,P)||(bo[P]=[]),bo[P].push({name:p,func:D})}}),bo[$l(e,v).name]=[{name:"wrapper",func:e}],kr.prototype.clone=m1,kr.prototype.reverse=p1,kr.prototype.value=d1,Z.prototype.at=m6,Z.prototype.chain=p6,Z.prototype.commit=d6,Z.prototype.next=h6,Z.prototype.plant=g6,Z.prototype.reverse=x6,Z.prototype.toJSON=Z.prototype.valueOf=Z.prototype.value=y6,Z.prototype.first=Z.prototype.head,as&&(Z.prototype[as]=v6),Z},gi=Ky();typeof define=="function"&&typeof define.amd=="object"&&define.amd?(Vt._=gi,define(function(){return gi})):di?((di.exports=gi)._=gi,Yf._=gi):Vt._=gi}).call(gu)});var Am=vn((Wb,Yb)=>{(function(e,r){typeof Wb=="object"&&typeof Yb<"u"?Yb.exports=r():typeof define=="function"&&define.amd?define(r):(e=typeof globalThis<"u"?globalThis:e||self,e["'typed'"]=r())})(Wb,function(){"use strict";function e(){return!0}function r(){return!1}function t(){}let n="Argument is not a typed-function.";function a(){function u(ee){return typeof ee=="object"&&ee!==null&&ee.constructor===Object}let l=[{name:"number",test:function(ee){return typeof ee=="number"}},{name:"string",test:function(ee){return typeof ee=="string"}},{name:"boolean",test:function(ee){return typeof ee=="boolean"}},{name:"Function",test:function(ee){return typeof ee=="function"}},{name:"Array",test:Array.isArray},{name:"Date",test:function(ee){return ee instanceof Date}},{name:"RegExp",test:function(ee){return ee instanceof RegExp}},{name:"Object",test:u},{name:"null",test:function(ee){return ee===null}},{name:"undefined",test:function(ee){return ee===void 0}}],c={name:"any",test:e,isAny:!0},o,s,m=0,d={createCount:0};function h(ee){let ce=o.get(ee);if(ce)return ce;let we='Unknown type "'+ee+'"',Be=ee.toLowerCase(),ke;for(ke of s)if(ke.toLowerCase()===Be){we+='. Did you mean "'+ke+'" ?';break}throw new TypeError(we)}function x(ee){let ce=arguments.length>1&&arguments[1]!==void 0?arguments[1]:"any",we=ce?h(ce).index:s.length,Be=[];for(let Te=0;Te{let Be=o.get(we);return!Be.isAny&&Be.test(ee)});return ce.length?ce:["any"]}function C(ee){return ee&&typeof ee=="function"&&"_typedFunctionData"in ee}function b(ee,ce,we){if(!C(ee))throw new TypeError(n);let Be=we&&we.exact,ke=Array.isArray(ce)?ce.join(","):ce,Te=T(ke),Re=S(Te);if(!Be||Re in ee.signatures){let ve=ee._typedFunctionData.signatureMap.get(Re);if(ve)return ve}let Ye=Te.length,B;if(Be){B=[];let ve;for(ve in ee.signatures)B.push(ee._typedFunctionData.signatureMap.get(ve))}else B=ee._typedFunctionData.signatures;for(let ve=0;ve!Pt.has(Xt.name)))continue}tr.push(cr)}}if(B=tr,B.length===0)break}let Q;for(Q of B)if(Q.params.length<=Ye)return Q;throw new TypeError("Signature not found (signature: "+(ee.name||"unnamed")+"("+S(Te,", ")+"))")}function M(ee,ce,we){return b(ee,ce,we).implementation}function A(ee,ce){let we=h(ce);if(we.test(ee))return ee;let Be=we.conversionsTo;if(Be.length===0)throw new Error("There are no conversions to "+ce+" defined.");for(let ke=0;ke1&&arguments[1]!==void 0?arguments[1]:",";return ee.map(we=>we.name).join(ce)}function O(ee){let ce=ee.indexOf("...")===0,Be=(ce?ee.length>3?ee.slice(3):"any":ee).split("|").map(Ye=>h(Ye.trim())),ke=!1,Te=ce?"...":"";return{types:Be.map(function(Ye){return ke=Ye.isAny||ke,Te+=Ye.name+"|",{name:Ye.name,typeIndex:Ye.index,test:Ye.test,isAny:Ye.isAny,conversion:null,conversionIndex:-1}}),name:Te.slice(0,-1),hasAny:ke,hasConversion:!1,restParam:ce}}function _(ee){let ce=ee.types.map(Re=>Re.name),we=$(ce),Be=ee.hasAny,ke=ee.name,Te=we.map(function(Re){let Ye=h(Re.from);return Be=Ye.isAny||Be,ke+="|"+Re.from,{name:Re.from,typeIndex:Ye.index,test:Ye.test,isAny:Ye.isAny,conversion:Re,conversionIndex:Re.index}});return{types:ee.types.concat(Te),name:ke,hasAny:Be,hasConversion:Te.length>0,restParam:ee.restParam}}function E(ee){return ee.typeSet||(ee.typeSet=new Set,ee.types.forEach(ce=>ee.typeSet.add(ce.name))),ee.typeSet}function T(ee){let ce=[];if(typeof ee!="string")throw new TypeError("Signatures must be strings");let we=ee.trim();if(we==="")return ce;let Be=we.split(",");for(let ke=0;ke=ke+1}}else return ee.length===0?function(Te){return Te.length===0}:ee.length===1?(we=q(ee[0]),function(Te){return we(Te[0])&&Te.length===1}):ee.length===2?(we=q(ee[0]),Be=q(ee[1]),function(Te){return we(Te[0])&&Be(Te[1])&&Te.length===2}):(ce=ee.map(q),function(Te){for(let Re=0;Re{let ke=H(Be.params,ce),Te;for(Te of ke)we.add(Te)}),we.has("any")?["any"]:Array.from(we)}function K(ee,ce,we){let Be,ke,Te=ee||"unnamed",Re=we,Ye;for(Ye=0;Ye{let cr=G(tr.params,Ye),Xr=q(cr);(Ye0){let tr=w(ce[Ye]);return Be=new TypeError("Unexpected type of argument in function "+Te+" (expected: "+ke.join(" or ")+", actual: "+tr.join(" | ")+", index: "+Ye+")"),Be.data={category:"wrongType",fn:Te,index:Ye,actual:tr,expected:ke},Be}}else Re=Pe}let B=Re.map(function(Pe){return R(Pe.params)?1/0:Pe.params.length});if(ce.lengthQ)return Be=new TypeError("Too many arguments in function "+Te+" (expected: "+Q+", actual: "+ce.length+")"),Be.data={category:"tooManyArgs",fn:Te,index:ce.length,expectedLength:Q},Be;let ve=[];for(let Pe=0;Pe0)return 1;let Be=oe(ee)-oe(ce);return Be<0?-1:Be>0?1:0}function ae(ee,ce){let we=ee.params,Be=ce.params,ke=J(we),Te=J(Be),Re=R(we),Ye=R(Be);if(Re&&ke.hasAny){if(!Ye||!Te.hasAny)return 1}else if(Ye&&Te.hasAny)return-1;let B=0,Q=0,ve;for(ve of we)ve.hasAny&&++B,ve.hasConversion&&++Q;let Pe=0,tr=0;for(ve of Be)ve.hasAny&&++Pe,ve.hasConversion&&++tr;if(B!==Pe)return B-Pe;if(Re&&ke.hasConversion){if(!Ye||!Te.hasConversion)return 1}else if(Ye&&Te.hasConversion)return-1;if(Q!==tr)return Q-tr;if(Re){if(!Ye)return 1}else if(Ye)return-1;let cr=(we.length-Be.length)*(Re?-1:1);if(cr!==0)return cr;let Xr=[],Pt=0;for(let li=0;li1&&ce.sort((ke,Te)=>ke.index-Te.index);let we=ce[0].conversionsTo;if(ee.length===1)return we;we=we.concat([]);let Be=new Set(ee);for(let ke=1;keke.hasConversion)){let ke=R(ee),Te=ee.map(Ee);we=function(){let Ye=[],B=ke?arguments.length-1:arguments.length;for(let Q=0;QB.name).join("|"),hasAny:Ye.some(B=>B.isAny),hasConversion:!1,restParam:!0}),Re.push(Te)}else Re=Te.types.map(function(Ye){return{types:[Ye],name:Ye.name,hasAny:Ye.isAny,hasConversion:Ye.conversion,restParam:!1}});return j(Re,function(Ye){return ce(we,Be+1,ke.concat([Ye]))})}else return[ke]}return ce(ee,0,[])}function ge(ee,ce){let we=Math.max(ee.length,ce.length);for(let Ye=0;Ye=Be:Re?Be>=ke:Be===ke}function Se(ee){return ee.map(ce=>Le(ce)?Me(ce.referToSelf.callback):Ce(ce)?ue(ce.referTo.references,ce.referTo.callback):ce)}function xe(ee,ce,we){let Be=[],ke;for(ke of ee){let Te=we[ke];if(typeof Te!="number")throw new TypeError('No definition for referenced signature "'+ke+'"');if(Te=ce[Te],typeof Te!="function")return!1;Be.push(Te)}return Be}function be(ee,ce,we){let Be=Se(ee),ke=new Array(Be.length).fill(!1),Te=!0;for(;Te;){Te=!1;let Re=!0;for(let Ye=0;Ye{let Be=ee[we];if(ce.test(Be.toString()))throw new SyntaxError("Using \`this\` to self-reference a function is deprecated since typed-function@3. Use typed.referTo and typed.referToSelf instead.")})}function Ae(ee,ce){if(d.createCount++,Object.keys(ce).length===0)throw new SyntaxError("No signatures provided");d.warnAgainstDeprecatedThis&&De(ce);let we=[],Be=[],ke={},Te=[],Re;for(Re in ce){if(!Object.prototype.hasOwnProperty.call(ce,Re))continue;let et=T(Re);if(!et)continue;we.forEach(function($a){if(ge($a,et))throw new TypeError('Conflicting signatures "'+S($a)+'" and "'+S(et)+'".')}),we.push(et);let on=Be.length;Be.push(ce[Re]);let If=et.map(_),mi;for(mi of me(If)){let $a=S(mi);Te.push({params:mi,name:$a,fn:on}),mi.every(Ws=>!Ws.hasConversion)&&(ke[$a]=on)}}Te.sort(ae);let Ye=be(Be,ke,Ii),B;for(B in ke)Object.prototype.hasOwnProperty.call(ke,B)&&(ke[B]=Ye[ke[B]]);let Q=[],ve=new Map;for(B of Te)ve.has(B.name)||(B.fn=Ye[B.fn],Q.push(B),ve.set(B.name,B));let Pe=Q[0]&&Q[0].params.length<=2&&!R(Q[0].params),tr=Q[1]&&Q[1].params.length<=2&&!R(Q[1].params),cr=Q[2]&&Q[2].params.length<=2&&!R(Q[2].params),Xr=Q[3]&&Q[3].params.length<=2&&!R(Q[3].params),Pt=Q[4]&&Q[4].params.length<=2&&!R(Q[4].params),Xt=Q[5]&&Q[5].params.length<=2&&!R(Q[5].params),li=Pe&&tr&&cr&&Xr&&Pt&&Xt;for(let et=0;etet.test),zs=Q.map(et=>et.implementation),Us=function(){for(let on=Pf;onS(T(we))),ce=J(arguments);if(typeof ce!="function")throw new TypeError("Callback function expected as last argument");return ue(ee,ce)}function ue(ee,ce){return{referTo:{references:ee,callback:ce}}}function Me(ee){if(typeof ee!="function")throw new TypeError("Callback function expected as first argument");return{referToSelf:{callback:ee}}}function Ce(ee){return ee&&typeof ee.referTo=="object"&&Array.isArray(ee.referTo.references)&&typeof ee.referTo.callback=="function"}function Le(ee){return ee&&typeof ee.referToSelf=="object"&&typeof ee.referToSelf.callback=="function"}function Ie(ee,ce){if(!ee)return ce;if(ce&&ce!==ee){let we=new Error("Function names do not match (expected: "+ee+", actual: "+ce+")");throw we.data={actual:ce,expected:ee},we}return ee}function fr(ee){let ce;for(let we in ee)Object.prototype.hasOwnProperty.call(ee,we)&&(C(ee[we])||typeof ee[we].signature=="string")&&(ce=Ie(ce,ee[we].name));return ce}function or(ee,ce){let we;for(we in ce)if(Object.prototype.hasOwnProperty.call(ce,we)){if(we in ee&&ce[we]!==ee[we]){let Be=new Error('Signature "'+we+'" is defined twice');throw Be.data={signature:we,sourceFunction:ce[we],destFunction:ee[we]},Be}ee[we]=ce[we]}}let Ke=d;d=function(ee){let ce=typeof ee=="string",we=ce?1:0,Be=ce?ee:"",ke={};for(let Te=we;Teke.from===ee.from);if(!we)throw new Error("Attempt to remove nonexistent conversion from "+ee.from+" to "+ee.to);if(we.convert!==ee.convert)throw new Error("Conversion to remove does not match existing conversion");let Be=ce.conversionsTo.indexOf(we);ce.conversionsTo.splice(Be,1)},d.resolve=function(ee,ce){if(!C(ee))throw new TypeError(n);let we=ee._typedFunctionData.signatures;for(let Be=0;Be{(function(e){"use strict";var r=Math.cosh||function(o){return Math.abs(o)<1e-9?1-o:(Math.exp(o)+Math.exp(-o))*.5},t=Math.sinh||function(o){return Math.abs(o)<1e-9?o:(Math.exp(o)-Math.exp(-o))*.5},n=function(o){var s=Math.PI/4;if(-s>o||o>s)return Math.cos(o)-1;var m=o*o;return m*(m*(m*(m*(m*(m*(m*(m/20922789888e3-1/87178291200)+1/479001600)-1/3628800)+1/40320)-1/720)+1/24)-1/2)},a=function(o,s){var m=Math.abs(o),d=Math.abs(s);return m<3e3&&d<3e3?Math.sqrt(m*m+d*d):(m0&&i();break;case"number":m.im=0,m.re=o;break;default:i()}return isNaN(m.re)||isNaN(m.im),m};function c(o,s){if(!(this instanceof c))return new c(o,s);var m=l(o,s);this.re=m.re,this.im=m.im}c.prototype={re:0,im:0,sign:function(){var o=this.abs();return new c(this.re/o,this.im/o)},add:function(o,s){var m=new c(o,s);return this.isInfinite()&&m.isInfinite()?c.NAN:this.isInfinite()||m.isInfinite()?c.INFINITY:new c(this.re+m.re,this.im+m.im)},sub:function(o,s){var m=new c(o,s);return this.isInfinite()&&m.isInfinite()?c.NAN:this.isInfinite()||m.isInfinite()?c.INFINITY:new c(this.re-m.re,this.im-m.im)},mul:function(o,s){var m=new c(o,s);return this.isInfinite()&&m.isZero()||this.isZero()&&m.isInfinite()?c.NAN:this.isInfinite()||m.isInfinite()?c.INFINITY:m.im===0&&this.im===0?new c(this.re*m.re,0):new c(this.re*m.re-this.im*m.im,this.re*m.im+this.im*m.re)},div:function(o,s){var m=new c(o,s);if(this.isZero()&&m.isZero()||this.isInfinite()&&m.isInfinite())return c.NAN;if(this.isInfinite()||m.isZero())return c.INFINITY;if(this.isZero()||m.isInfinite())return c.ZERO;o=this.re,s=this.im;var d=m.re,h=m.im,x,v;return h===0?new c(o/d,s/d):Math.abs(d)0)return new c(Math.pow(o,m.re),0);if(o===0)switch((m.re%4+4)%4){case 0:return new c(Math.pow(s,m.re),0);case 1:return new c(0,Math.pow(s,m.re));case 2:return new c(-Math.pow(s,m.re),0);case 3:return new c(0,-Math.pow(s,m.re))}}if(o===0&&s===0&&m.re>0&&m.im>=0)return c.ZERO;var d=Math.atan2(s,o),h=u(o,s);return o=Math.exp(m.re*h-m.im*d),s=m.im*h+m.re*d,new c(o*Math.cos(s),o*Math.sin(s))},sqrt:function(){var o=this.re,s=this.im,m=this.abs(),d,h;if(o>=0){if(s===0)return new c(Math.sqrt(o),0);d=.5*Math.sqrt(2*(m+o))}else d=Math.abs(s)/Math.sqrt(2*(m-o));return o<=0?h=.5*Math.sqrt(2*(m-o)):h=Math.abs(s)/Math.sqrt(2*(m+o)),new c(d,s<0?-h:h)},exp:function(){var o=Math.exp(this.re);return this.im,new c(o*Math.cos(this.im),o*Math.sin(this.im))},expm1:function(){var o=this.re,s=this.im;return new c(Math.expm1(o)*Math.cos(s)+n(s),Math.exp(o)*Math.sin(s))},log:function(){var o=this.re,s=this.im;return s===0&&o>0,new c(u(o,s),Math.atan2(s,o))},abs:function(){return a(this.re,this.im)},arg:function(){return Math.atan2(this.im,this.re)},sin:function(){var o=this.re,s=this.im;return new c(Math.sin(o)*r(s),Math.cos(o)*t(s))},cos:function(){var o=this.re,s=this.im;return new c(Math.cos(o)*r(s),-Math.sin(o)*t(s))},tan:function(){var o=2*this.re,s=2*this.im,m=Math.cos(o)+r(s);return new c(Math.sin(o)/m,t(s)/m)},cot:function(){var o=2*this.re,s=2*this.im,m=Math.cos(o)-r(s);return new c(-Math.sin(o)/m,t(s)/m)},sec:function(){var o=this.re,s=this.im,m=.5*r(2*s)+.5*Math.cos(2*o);return new c(Math.cos(o)*r(s)/m,Math.sin(o)*t(s)/m)},csc:function(){var o=this.re,s=this.im,m=.5*r(2*s)-.5*Math.cos(2*o);return new c(Math.sin(o)*r(s)/m,-Math.cos(o)*t(s)/m)},asin:function(){var o=this.re,s=this.im,m=new c(s*s-o*o+1,-2*o*s).sqrt(),d=new c(m.re-s,m.im+o).log();return new c(d.im,-d.re)},acos:function(){var o=this.re,s=this.im,m=new c(s*s-o*o+1,-2*o*s).sqrt(),d=new c(m.re-s,m.im+o).log();return new c(Math.PI/2-d.im,d.re)},atan:function(){var o=this.re,s=this.im;if(o===0){if(s===1)return new c(0,1/0);if(s===-1)return new c(0,-1/0)}var m=o*o+(1-s)*(1-s),d=new c((1-s*s-o*o)/m,-2*o/m).log();return new c(-.5*d.im,.5*d.re)},acot:function(){var o=this.re,s=this.im;if(s===0)return new c(Math.atan2(1,o),0);var m=o*o+s*s;return m!==0?new c(o/m,-s/m).atan():new c(o!==0?o/0:0,s!==0?-s/0:0).atan()},asec:function(){var o=this.re,s=this.im;if(o===0&&s===0)return new c(0,1/0);var m=o*o+s*s;return m!==0?new c(o/m,-s/m).acos():new c(o!==0?o/0:0,s!==0?-s/0:0).acos()},acsc:function(){var o=this.re,s=this.im;if(o===0&&s===0)return new c(Math.PI/2,1/0);var m=o*o+s*s;return m!==0?new c(o/m,-s/m).asin():new c(o!==0?o/0:0,s!==0?-s/0:0).asin()},sinh:function(){var o=this.re,s=this.im;return new c(t(o)*Math.cos(s),r(o)*Math.sin(s))},cosh:function(){var o=this.re,s=this.im;return new c(r(o)*Math.cos(s),t(o)*Math.sin(s))},tanh:function(){var o=2*this.re,s=2*this.im,m=r(o)+Math.cos(s);return new c(t(o)/m,Math.sin(s)/m)},coth:function(){var o=2*this.re,s=2*this.im,m=r(o)-Math.cos(s);return new c(t(o)/m,-Math.sin(s)/m)},csch:function(){var o=this.re,s=this.im,m=Math.cos(2*s)-r(2*o);return new c(-2*t(o)*Math.cos(s)/m,2*r(o)*Math.sin(s)/m)},sech:function(){var o=this.re,s=this.im,m=Math.cos(2*s)+r(2*o);return new c(2*r(o)*Math.cos(s)/m,-2*t(o)*Math.sin(s)/m)},asinh:function(){var o=this.im;this.im=-this.re,this.re=o;var s=this.asin();return this.re=-this.im,this.im=o,o=s.re,s.re=-s.im,s.im=o,s},acosh:function(){var o=this.acos();if(o.im<=0){var s=o.re;o.re=-o.im,o.im=s}else{var s=o.im;o.im=-o.re,o.re=s}return o},atanh:function(){var o=this.re,s=this.im,m=o>1&&s===0,d=1-o,h=1+o,x=d*d+s*s,v=x!==0?new c((h*d-s*s)/x,(s*d+h*s)/x):new c(o!==-1?o/0:0,s!==0?s/0:0),y=v.re;return v.re=u(v.re,v.im)/2,v.im=Math.atan2(v.im,y)/2,m&&(v.im=-v.im),v},acoth:function(){var o=this.re,s=this.im;if(o===0&&s===0)return new c(0,Math.PI/2);var m=o*o+s*s;return m!==0?new c(o/m,-s/m).atanh():new c(o!==0?o/0:0,s!==0?-s/0:0).atanh()},acsch:function(){var o=this.re,s=this.im;if(s===0)return new c(o!==0?Math.log(o+Math.sqrt(o*o+1)):1/0,0);var m=o*o+s*s;return m!==0?new c(o/m,-s/m).asinh():new c(o!==0?o/0:0,s!==0?-s/0:0).asinh()},asech:function(){var o=this.re,s=this.im;if(this.isZero())return c.INFINITY;var m=o*o+s*s;return m!==0?new c(o/m,-s/m).acosh():new c(o!==0?o/0:0,s!==0?-s/0:0).acosh()},inverse:function(){if(this.isZero())return c.INFINITY;if(this.isInfinite())return c.ZERO;var o=this.re,s=this.im,m=o*o+s*s;return new c(o/m,-s/m)},conjugate:function(){return new c(this.re,-this.im)},neg:function(){return new c(-this.re,-this.im)},ceil:function(o){return o=Math.pow(10,o||0),new c(Math.ceil(this.re*o)/o,Math.ceil(this.im*o)/o)},floor:function(o){return o=Math.pow(10,o||0),new c(Math.floor(this.re*o)/o,Math.floor(this.im*o)/o)},round:function(o){return o=Math.pow(10,o||0),new c(Math.round(this.re*o)/o,Math.round(this.im*o)/o)},equals:function(o,s){var m=new c(o,s);return Math.abs(m.re-this.re)<=c.EPSILON&&Math.abs(m.im-this.im)<=c.EPSILON},clone:function(){return new c(this.re,this.im)},toString:function(){var o=this.re,s=this.im,m="";return this.isNaN()?"NaN":this.isInfinite()?"Infinity":(Math.abs(o){(function(e){"use strict";var r=2e3,t={s:1,n:0,d:1};function n(v,y){if(isNaN(v=parseInt(v,10)))throw h();return v*y}function a(v,y){if(y===0)throw d();var w=Object.create(m.prototype);w.s=v<0?-1:1,v=v<0?-v:v;var C=s(v,y);return w.n=v/C,w.d=y/C,w}function i(v){for(var y={},w=v,C=2,b=4;b<=w;){for(;w%C===0;)w/=C,y[C]=(y[C]||0)+1;b+=1+2*C++}return w!==v?w>1&&(y[w]=(y[w]||0)+1):y[v]=(y[v]||0)+1,y}var u=function(v,y){var w=0,C=1,b=1,M=0,A=0,S=0,O=1,_=1,E=0,T=1,R=1,q=1,W=1e7,G;if(v!=null)if(y!==void 0){if(w=v,C=y,b=w*C,w%1!==0||C%1!==0)throw x()}else switch(typeof v){case"object":{if("d"in v&&"n"in v)w=v.n,C=v.d,"s"in v&&(w*=v.s);else if(0 in v)w=v[0],1 in v&&(C=v[1]);else throw h();b=w*C;break}case"number":{if(v<0&&(b=v,v=-v),v%1===0)w=v;else if(v>0){for(v>=1&&(_=Math.pow(10,Math.floor(1+Math.log(v)/Math.LN10)),v/=_);T<=W&&q<=W;)if(G=(E+R)/(T+q),v===G){T+q<=W?(w=E+R,C=T+q):q>T?(w=R,C=q):(w=E,C=T);break}else v>G?(E+=R,T+=q):(R+=E,q+=T),T>W?(w=R,C=q):(w=E,C=T);w*=_}else(isNaN(v)||isNaN(y))&&(C=w=NaN);break}case"string":{if(T=v.match(/\\d+|./g),T===null)throw h();if(T[E]==="-"?(b=-1,E++):T[E]==="+"&&E++,T.length===E+1?A=n(T[E++],b):T[E+1]==="."||T[E]==="."?(T[E]!=="."&&(M=n(T[E++],b)),E++,(E+1===T.length||T[E+1]==="("&&T[E+3]===")"||T[E+1]==="'"&&T[E+3]==="'")&&(A=n(T[E],b),O=Math.pow(10,T[E].length),E++),(T[E]==="("&&T[E+2]===")"||T[E]==="'"&&T[E+2]==="'")&&(S=n(T[E+1],b),_=Math.pow(10,T[E+1].length)-1,E+=3)):T[E+1]==="/"||T[E+1]===":"?(A=n(T[E],b),O=n(T[E+2],1),E+=3):T[E+3]==="/"&&T[E+1]===" "&&(M=n(T[E],b),A=n(T[E+2],b),O=n(T[E+4],1),E+=5),T.length<=E){C=O*_,b=w=S+C*M+_*A;break}}default:throw h()}if(C===0)throw d();t.s=b<0?-1:1,t.n=Math.abs(w),t.d=Math.abs(C)};function l(v,y,w){for(var C=1;y>0;v=v*v%w,y>>=1)y&1&&(C=C*v%w);return C}function c(v,y){for(;y%2===0;y/=2);for(;y%5===0;y/=5);if(y===1)return 0;for(var w=10%y,C=1;w!==1;C++)if(w=w*10%y,C>r)return 0;return C}function o(v,y,w){for(var C=1,b=l(10,w,y),M=0;M<300;M++){if(C===b)return M;C=C*10%y,b=b*10%y}return 0}function s(v,y){if(!v)return y;if(!y)return v;for(;;){if(v%=y,!v)return y;if(y%=v,!y)return v}}function m(v,y){if(u(v,y),this instanceof m)v=s(t.d,t.n),this.s=t.s,this.n=t.n/v,this.d=t.d/v;else return a(t.s*t.n,t.d)}var d=function(){return new Error("Division by Zero")},h=function(){return new Error("Invalid argument")},x=function(){return new Error("Parameters must be integer")};m.prototype={s:1,n:0,d:1,abs:function(){return a(this.n,this.d)},neg:function(){return a(-this.s*this.n,this.d)},add:function(v,y){return u(v,y),a(this.s*this.n*t.d+t.s*this.d*t.n,this.d*t.d)},sub:function(v,y){return u(v,y),a(this.s*this.n*t.d-t.s*this.d*t.n,this.d*t.d)},mul:function(v,y){return u(v,y),a(this.s*t.s*this.n*t.n,this.d*t.d)},div:function(v,y){return u(v,y),a(this.s*t.s*this.n*t.d,this.d*t.n)},clone:function(){return a(this.s*this.n,this.d)},mod:function(v,y){if(isNaN(this.n)||isNaN(this.d))return new m(NaN);if(v===void 0)return a(this.s*this.n%this.d,1);if(u(v,y),t.n===0&&this.d===0)throw d();return a(this.s*(t.d*this.n)%(t.n*this.d),t.d*this.d)},gcd:function(v,y){return u(v,y),a(s(t.n,this.n)*s(t.d,this.d),t.d*this.d)},lcm:function(v,y){return u(v,y),t.n===0&&this.n===0?a(0,1):a(t.n*this.n,s(t.n,this.n)*s(t.d,this.d))},ceil:function(v){return v=Math.pow(10,v||0),isNaN(this.n)||isNaN(this.d)?new m(NaN):a(Math.ceil(v*this.s*this.n/this.d),v)},floor:function(v){return v=Math.pow(10,v||0),isNaN(this.n)||isNaN(this.d)?new m(NaN):a(Math.floor(v*this.s*this.n/this.d),v)},round:function(v){return v=Math.pow(10,v||0),isNaN(this.n)||isNaN(this.d)?new m(NaN):a(Math.round(v*this.s*this.n/this.d),v)},inverse:function(){return a(this.s*this.d,this.n)},pow:function(v,y){if(u(v,y),t.d===1)return t.s<0?a(Math.pow(this.s*this.d,t.n),Math.pow(this.n,t.n)):a(Math.pow(this.s*this.n,t.n),Math.pow(this.d,t.n));if(this.s<0)return null;var w=i(this.n),C=i(this.d),b=1,M=1;for(var A in w)if(A!=="1"){if(A==="0"){b=0;break}if(w[A]*=t.n,w[A]%t.d===0)w[A]/=t.d;else return null;b*=Math.pow(A,w[A])}for(var A in C)if(A!=="1"){if(C[A]*=t.n,C[A]%t.d===0)C[A]/=t.d;else return null;M*=Math.pow(A,C[A])}return t.s<0?a(M,b):a(b,M)},equals:function(v,y){return u(v,y),this.s*this.n*t.d===t.s*t.n*this.d},compare:function(v,y){u(v,y);var w=this.s*this.n*t.d-t.s*t.n*this.d;return(0=0;M--)b=b.inverse().add(w[M]);if(Math.abs(b.sub(y).valueOf())0&&(w+=y,w+=" ",C%=b),w+=C,w+="/",w+=b),w},toLatex:function(v){var y,w="",C=this.n,b=this.d;return this.s<0&&(w+="-"),b===1?w+=C:(v&&(y=Math.floor(C/b))>0&&(w+=y,C%=b),w+="\\\\frac{",w+=C,w+="}{",w+=b,w+="}"),w},toContinued:function(){var v,y=this.n,w=this.d,C=[];if(isNaN(y)||isNaN(w))return C;do C.push(Math.floor(y/w)),v=y%w,y=w,w=v;while(y!==1);return C},toString:function(v){var y=this.n,w=this.d;if(isNaN(y)||isNaN(w))return"NaN";v=v||15;var C=c(y,w),b=o(y,w,C),M=this.s<0?"-":"";if(M+=y/w|0,y%=w,y*=10,y&&(M+="."),C){for(var A=b;A--;)M+=y/w|0,y%=w,y*=10;M+="(";for(var A=C;A--;)M+=y/w|0,y%=w,y*=10;M+=")"}else for(var A=v;y&&A--;)M+=y/w|0,y%=w,y*=10;return M}},typeof mw=="object"?(Object.defineProperty(m,"__esModule",{value:!0}),m.default=m,m.Fraction=m,qM.exports=m):e.Fraction=m})(mw)});var eE=vn((Tce,jC)=>{jC.exports=function e(r,t){"use strict";var n=/(^([+\\-]?(?:0|[1-9]\\d*)(?:\\.\\d*)?(?:[eE][+\\-]?\\d+)?)?$|^0x[0-9a-f]+$|\\d+)/gi,a=/(^[ ]*|[ ]*$)/g,i=/(^([\\w ]+,?[\\w ]+)?[\\w ]+,?[\\w ]+\\d+:\\d+(:\\d+)?[\\w ]?|^\\d{1,4}[\\/\\-]\\d{1,4}[\\/\\-]\\d{1,4}|^\\w+, \\w+ \\d+, \\d{4})/,u=/^0x[0-9a-f]+$/i,l=/^0/,c=function(b){return e.insensitive&&(""+b).toLowerCase()||""+b},o=c(r).replace(a,"")||"",s=c(t).replace(a,"")||"",m=o.replace(n,"\\0$1\\0").replace(/\\0$/,"").replace(/^\\0/,"").split("\\0"),d=s.replace(n,"\\0$1\\0").replace(/\\0$/,"").replace(/^\\0/,"").split("\\0"),h=parseInt(o.match(u),16)||m.length!==1&&o.match(i)&&Date.parse(o),x=parseInt(s.match(u),16)||h&&s.match(i)&&Date.parse(s)||null,v,y;if(x){if(hx)return 1}for(var w=0,C=Math.max(m.length,d.length);wy)return 1}return 0}});var nT=vn((Ghe,tT)=>{"use strict";var gD=Object.assign||function(e){for(var r=1;r1&&arguments[1]!==void 0?arguments[1]:{},t=r.preserveFormatting,n=t===void 0?!1:t,a=r.escapeMapFn,i=a===void 0?I$:a,u=String(e),l="",c=i(gD({},B$),n?gD({},P$):{}),o=Object.keys(c),s=function(){var d=!1;o.forEach(function(h,x){d||u.length>=h.length&&u.slice(0,h.length)===h&&(l+=c[o[x]],u=u.slice(h.length,u.length),d=!0)}),d||(l+=u.slice(0,1),u=u.slice(1,u.length))};u;)s();return l}});var BB=vn((OB,AD)=>{(function(e,r,t){function n(l){var c=this,o=u();c.next=function(){var s=2091639*c.s0+c.c*23283064365386963e-26;return c.s0=c.s1,c.s1=c.s2,c.s2=s-(c.c=s|0)},c.c=1,c.s0=o(" "),c.s1=o(" "),c.s2=o(" "),c.s0-=o(l),c.s0<0&&(c.s0+=1),c.s1-=o(l),c.s1<0&&(c.s1+=1),c.s2-=o(l),c.s2<0&&(c.s2+=1),o=null}function a(l,c){return c.c=l.c,c.s0=l.s0,c.s1=l.s1,c.s2=l.s2,c}function i(l,c){var o=new n(l),s=c&&c.state,m=o.next;return m.int32=function(){return o.next()*4294967296|0},m.double=function(){return m()+(m()*2097152|0)*11102230246251565e-32},m.quick=m,s&&(typeof s=="object"&&a(s,o),m.state=function(){return a(o,{})}),m}function u(){var l=4022871197,c=function(o){o=String(o);for(var s=0;s>>0,m-=l,m*=l,l=m>>>0,m-=l,l+=m*4294967296}return(l>>>0)*23283064365386963e-26};return c}r&&r.exports?r.exports=i:t&&t.amd?t(function(){return i}):this.alea=i})(OB,typeof AD=="object"&&AD,typeof define=="function"&&define)});var IB=vn((PB,MD)=>{(function(e,r,t){function n(u){var l=this,c="";l.x=0,l.y=0,l.z=0,l.w=0,l.next=function(){var s=l.x^l.x<<11;return l.x=l.y,l.y=l.z,l.z=l.w,l.w^=l.w>>>19^s^s>>>8},u===(u|0)?l.x=u:c+=u;for(var o=0;o>>0)/4294967296};return s.double=function(){do var m=c.next()>>>11,d=(c.next()>>>0)/4294967296,h=(m+d)/(1<<21);while(h===0);return h},s.int32=c.next,s.quick=s,o&&(typeof o=="object"&&a(o,c),s.state=function(){return a(c,{})}),s}r&&r.exports?r.exports=i:t&&t.amd?t(function(){return i}):this.xor128=i})(PB,typeof MD=="object"&&MD,typeof define=="function"&&define)});var kB=vn((RB,CD)=>{(function(e,r,t){function n(u){var l=this,c="";l.next=function(){var s=l.x^l.x>>>2;return l.x=l.y,l.y=l.z,l.z=l.w,l.w=l.v,(l.d=l.d+362437|0)+(l.v=l.v^l.v<<4^(s^s<<1))|0},l.x=0,l.y=0,l.z=0,l.w=0,l.v=0,u===(u|0)?l.x=u:c+=u;for(var o=0;o>>4),l.next()}function a(u,l){return l.x=u.x,l.y=u.y,l.z=u.z,l.w=u.w,l.v=u.v,l.d=u.d,l}function i(u,l){var c=new n(u),o=l&&l.state,s=function(){return(c.next()>>>0)/4294967296};return s.double=function(){do var m=c.next()>>>11,d=(c.next()>>>0)/4294967296,h=(m+d)/(1<<21);while(h===0);return h},s.int32=c.next,s.quick=s,o&&(typeof o=="object"&&a(o,c),s.state=function(){return a(c,{})}),s}r&&r.exports?r.exports=i:t&&t.amd?t(function(){return i}):this.xorwow=i})(RB,typeof CD=="object"&&CD,typeof define=="function"&&define)});var LB=vn((qB,ED)=>{(function(e,r,t){function n(u){var l=this;l.next=function(){var o=l.x,s=l.i,m,d,h;return m=o[s],m^=m>>>7,d=m^m<<24,m=o[s+1&7],d^=m^m>>>10,m=o[s+3&7],d^=m^m>>>3,m=o[s+4&7],d^=m^m<<7,m=o[s+7&7],m=m^m<<13,d^=m^m<<9,o[s]=d,l.i=s+1&7,d};function c(o,s){var m,d,h=[];if(s===(s|0))d=h[0]=s;else for(s=""+s,m=0;m0;--m)o.next()}c(l,u)}function a(u,l){return l.x=u.x.slice(),l.i=u.i,l}function i(u,l){u==null&&(u=+new Date);var c=new n(u),o=l&&l.state,s=function(){return(c.next()>>>0)/4294967296};return s.double=function(){do var m=c.next()>>>11,d=(c.next()>>>0)/4294967296,h=(m+d)/(1<<21);while(h===0);return h},s.int32=c.next,s.quick=s,o&&(o.x&&a(o,c),s.state=function(){return a(c,{})}),s}r&&r.exports?r.exports=i:t&&t.amd?t(function(){return i}):this.xorshift7=i})(qB,typeof ED=="object"&&ED,typeof define=="function"&&define)});var UB=vn((zB,TD)=>{(function(e,r,t){function n(u){var l=this;l.next=function(){var o=l.w,s=l.X,m=l.i,d,h;return l.w=o=o+1640531527|0,h=s[m+34&127],d=s[m=m+1&127],h^=h<<13,d^=d<<17,h^=h>>>15,d^=d>>>12,h=s[m]=h^d,l.i=m,h+(o^o>>>16)|0};function c(o,s){var m,d,h,x,v,y=[],w=128;for(s===(s|0)?(d=s,s=null):(s=s+"\\0",d=0,w=Math.max(w,s.length)),h=0,x=-32;x>>15,d^=d<<4,d^=d>>>13,x>=0&&(v=v+1640531527|0,m=y[x&127]^=d+v,h=m==0?h+1:0);for(h>=128&&(y[(s&&s.length||0)&127]=-1),h=127,x=4*128;x>0;--x)d=y[h+34&127],m=y[h=h+1&127],d^=d<<13,m^=m<<17,d^=d>>>15,m^=m>>>12,y[h]=d^m;o.w=v,o.X=y,o.i=h}c(l,u)}function a(u,l){return l.i=u.i,l.w=u.w,l.X=u.X.slice(),l}function i(u,l){u==null&&(u=+new Date);var c=new n(u),o=l&&l.state,s=function(){return(c.next()>>>0)/4294967296};return s.double=function(){do var m=c.next()>>>11,d=(c.next()>>>0)/4294967296,h=(m+d)/(1<<21);while(h===0);return h},s.int32=c.next,s.quick=s,o&&(o.X&&a(o,c),s.state=function(){return a(c,{})}),s}r&&r.exports?r.exports=i:t&&t.amd?t(function(){return i}):this.xor4096=i})(zB,typeof TD=="object"&&TD,typeof define=="function"&&define)});var YB=vn((WB,FD)=>{(function(e,r,t){function n(u){var l=this,c="";l.next=function(){var s=l.b,m=l.c,d=l.d,h=l.a;return s=s<<25^s>>>7^m,m=m-d|0,d=d<<24^d>>>8^h,h=h-s|0,l.b=s=s<<20^s>>>12^m,l.c=m=m-d|0,l.d=d<<16^m>>>16^h,l.a=h-s|0},l.a=0,l.b=0,l.c=-1640531527,l.d=1367130551,u===Math.floor(u)?(l.a=u/4294967296|0,l.b=u|0):c+=u;for(var o=0;o>>0)/4294967296};return s.double=function(){do var m=c.next()>>>11,d=(c.next()>>>0)/4294967296,h=(m+d)/(1<<21);while(h===0);return h},s.int32=c.next,s.quick=s,o&&(typeof o=="object"&&a(o,c),s.state=function(){return a(c,{})}),s}r&&r.exports?r.exports=i:t&&t.amd?t(function(){return i}):this.tychei=i})(WB,typeof FD=="object"&&FD,typeof define=="function"&&define)});var HB=vn(()=>{});var GB=vn(($B,Ug)=>{(function(e,r,t){var n=256,a=6,i=52,u="random",l=t.pow(n,a),c=t.pow(2,i),o=c*2,s=n-1,m;function d(b,M,A){var S=[];M=M==!0?{entropy:!0}:M||{};var O=y(v(M.entropy?[b,C(r)]:b??w(),3),S),_=new h(S),E=function(){for(var T=_.g(a),R=l,q=0;T=o;)T/=2,R/=2,q>>>=1;return(T+q)/R};return E.int32=function(){return _.g(4)|0},E.quick=function(){return _.g(4)/4294967296},E.double=E,y(C(_.S),r),(M.pass||A||function(T,R,q,W){return W&&(W.S&&x(W,_),T.state=function(){return x(_,{})}),q?(t[u]=T,R):T})(E,O,"global"in M?M.global:this==t,M.state)}function h(b){var M,A=b.length,S=this,O=0,_=S.i=S.j=0,E=S.S=[];for(A||(b=[A++]);O{var KG=BB(),jG=IB(),eV=kB(),rV=LB(),tV=UB(),nV=YB(),Os=GB();Os.alea=KG;Os.xor128=jG;Os.xorwow=eV;Os.xorshift7=rV;Os.xor4096=tV;Os.tychei=nV;VB.exports=Os});var QR=vn((OIe,CS)=>{function MS(){}MS.prototype={on:function(e,r,t){var n=this.e||(this.e={});return(n[e]||(n[e]=[])).push({fn:r,ctx:t}),this},once:function(e,r,t){var n=this;function a(){n.off(e,a),r.apply(t,arguments)}return a._=r,this.on(e,a,t)},emit:function(e){var r=[].slice.call(arguments,1),t=((this.e||(this.e={}))[e]||[]).slice(),n=0,a=t.length;for(n;n{(function(e,r){typeof ES=="object"&&typeof Nf<"u"?Nf.exports=r():typeof define=="function"&&define.amd?define(r):e.moment=r()})(ES,function(){"use strict";var e;function r(){return e.apply(null,arguments)}function t(g){e=g}function n(g){return g instanceof Array||Object.prototype.toString.call(g)==="[object Array]"}function a(g){return g!=null&&Object.prototype.toString.call(g)==="[object Object]"}function i(g,N){return Object.prototype.hasOwnProperty.call(g,N)}function u(g){if(Object.getOwnPropertyNames)return Object.getOwnPropertyNames(g).length===0;var N;for(N in g)if(i(g,N))return!1;return!0}function l(g){return g===void 0}function c(g){return typeof g=="number"||Object.prototype.toString.call(g)==="[object Number]"}function o(g){return g instanceof Date||Object.prototype.toString.call(g)==="[object Date]"}function s(g,N){var I=[],U,V=g.length;for(U=0;U>>0,U;for(U=0;U0)for(I=0;I=0;return(se?I?"+":"":"-")+Math.pow(10,Math.max(0,V)).toString().substr(1)+U}var z=/(\\[[^\\[]*\\])|(\\\\)?([Hh]mm(ss)?|Mo|MM?M?M?|Do|DDDo|DD?D?D?|ddd?d?|do?|w[o|w]?|W[o|W]?|Qo?|N{1,5}|YYYYYY|YYYYY|YYYY|YY|y{2,4}|yo?|gg(ggg?)?|GG(GGG?)?|e|E|a|A|hh?|HH?|kk?|mm?|ss?|S{1,9}|x|X|zz?|ZZ?|.)/g,oe=/(\\[[^\\[]*\\])|(\\\\)?(LTS|LT|LL?L?L?|l{1,4})/g,pe={},ae={};function $(g,N,I,U){var V=U;typeof U=="string"&&(V=function(){return this[U]()}),g&&(ae[g]=V),N&&(ae[N[0]]=function(){return K(V.apply(this,arguments),N[1],N[2])}),I&&(ae[I]=function(){return this.localeData().ordinal(V.apply(this,arguments),g)})}function le(g){return g.match(/\\[[\\s\\S]/)?g.replace(/^\\[|\\]$/g,""):g.replace(/\\\\/g,"")}function Ee(g){var N=g.match(z),I,U;for(I=0,U=N.length;I=0&&oe.test(g);)g=g.replace(oe,U),oe.lastIndex=0,I-=1;return g}var Se={LTS:"h:mm:ss A",LT:"h:mm A",L:"MM/DD/YYYY",LL:"MMMM D, YYYY",LLL:"MMMM D, YYYY h:mm A",LLLL:"dddd, MMMM D, YYYY h:mm A"};function xe(g){var N=this._longDateFormat[g],I=this._longDateFormat[g.toUpperCase()];return N||!I?N:(this._longDateFormat[g]=I.match(z).map(function(U){return U==="MMMM"||U==="MM"||U==="DD"||U==="dddd"?U.slice(1):U}).join(""),this._longDateFormat[g])}var be="Invalid date";function De(){return this._invalidDate}var Ae="%d",We=/\\d{1,2}/;function Je(g){return this._ordinal.replace("%d",g)}var J={future:"in %s",past:"%s ago",s:"a few seconds",ss:"%d seconds",m:"a minute",mm:"%d minutes",h:"an hour",hh:"%d hours",d:"a day",dd:"%d days",w:"a week",ww:"%d weeks",M:"a month",MM:"%d months",y:"a year",yy:"%d years"};function re(g,N,I,U){var V=this._relativeTime[I];return R(V)?V(g,N,I,U):V.replace(/%d/i,g)}function ye(g,N){var I=this._relativeTime[g>0?"future":"past"];return R(I)?I(N):I.replace(/%s/i,N)}var j={};function ne(g,N){var I=g.toLowerCase();j[I]=j[I+"s"]=j[N]=g}function ue(g){return typeof g=="string"?j[g]||j[g.toLowerCase()]:void 0}function Me(g){var N={},I,U;for(U in g)i(g,U)&&(I=ue(U),I&&(N[I]=g[U]));return N}var Ce={};function Le(g,N){Ce[g]=N}function Ie(g){var N=[],I;for(I in g)i(g,I)&&N.push({unit:I,priority:Ce[I]});return N.sort(function(U,V){return U.priority-V.priority}),N}function fr(g){return g%4===0&&g%100!==0||g%400===0}function or(g){return g<0?Math.ceil(g)||0:Math.floor(g)}function Ke(g){var N=+g,I=0;return N!==0&&isFinite(N)&&(I=or(N)),I}function Pr(g,N){return function(I){return I!=null?(ce(this,g,I),r.updateOffset(this,N),this):ee(this,g)}}function ee(g,N){return g.isValid()?g._d["get"+(g._isUTC?"UTC":"")+N]():NaN}function ce(g,N,I){g.isValid()&&!isNaN(I)&&(N==="FullYear"&&fr(g.year())&&g.month()===1&&g.date()===29?(I=Ke(I),g._d["set"+(g._isUTC?"UTC":"")+N](I,g.month(),uo(I,g.month()))):g._d["set"+(g._isUTC?"UTC":"")+N](I))}function we(g){return g=ue(g),R(this[g])?this[g]():this}function Be(g,N){if(typeof g=="object"){g=Me(g);var I=Ie(g),U,V=I.length;for(U=0;U68?1900:2e3)};var qf=Pr("FullYear",!0);function xy(){return fr(this.year())}function Vc(g,N,I,U,V,se,Fe){var dr;return g<100&&g>=0?(dr=new Date(g+400,N,I,U,V,se,Fe),isFinite(dr.getFullYear())&&dr.setFullYear(g)):dr=new Date(g,N,I,U,V,se,Fe),dr}function fo(g){var N,I;return g<100&&g>=0?(I=Array.prototype.slice.call(arguments),I[0]=g+400,N=new Date(Date.UTC.apply(null,I)),isFinite(N.getUTCFullYear())&&N.setUTCFullYear(g)):N=new Date(Date.UTC.apply(null,arguments)),N}function co(g,N,I){var U=7+N-I,V=(7+fo(g,0,U).getUTCDay()-N)%7;return-V+U-1}function Zc(g,N,I,U,V){var se=(7+I-U)%7,Fe=co(g,U,V),dr=1+7*(N-1)+se+Fe,Or,tt;return dr<=0?(Or=g-1,tt=pi(Or)+dr):dr>pi(g)?(Or=g+1,tt=dr-pi(g)):(Or=g,tt=dr),{year:Or,dayOfYear:tt}}function lo(g,N,I){var U=co(g.year(),N,I),V=Math.floor((g.dayOfYear()-U-1)/7)+1,se,Fe;return V<1?(Fe=g.year()-1,se=V+na(Fe,N,I)):V>na(g.year(),N,I)?(se=V-na(g.year(),N,I),Fe=g.year()+1):(Fe=g.year(),se=V),{week:se,year:Fe}}function na(g,N,I){var U=co(g,N,I),V=co(g+1,N,I);return(pi(g)-U+V)/7}$("w",["ww",2],"wo","week"),$("W",["WW",2],"Wo","isoWeek"),ne("week","w"),ne("isoWeek","W"),Le("week",5),Le("isoWeek",5),nr("w",Q),nr("ww",Q,Te),nr("W",Q),nr("WW",Q,Te),Pi(["w","ww","W","WW"],function(g,N,I,U){N[U.substr(0,1)]=Ke(g)});function Lf(g){return lo(g,this._week.dow,this._week.doy).week}var mo={dow:0,doy:6};function Qc(){return this._week.dow}function Xc(){return this._week.doy}function yy(g){var N=this.localeData().week(this);return g==null?N:this.add((g-N)*7,"d")}function Jc(g){var N=lo(this,1,4).week;return g==null?N:this.add((g-N)*7,"d")}$("d",0,"do","day"),$("dd",0,0,function(g){return this.localeData().weekdaysMin(this,g)}),$("ddd",0,0,function(g){return this.localeData().weekdaysShort(this,g)}),$("dddd",0,0,function(g){return this.localeData().weekdays(this,g)}),$("e",0,0,"weekday"),$("E",0,0,"isoWeekday"),ne("day","d"),ne("weekday","e"),ne("isoWeekday","E"),Le("day",11),Le("weekday",11),Le("isoWeekday",11),nr("d",Q),nr("e",Q),nr("E",Q),nr("dd",function(g,N){return N.weekdaysMinRegex(g)}),nr("ddd",function(g,N){return N.weekdaysShortRegex(g)}),nr("dddd",function(g,N){return N.weekdaysRegex(g)}),Pi(["dd","ddd","dddd"],function(g,N,I,U){var V=I._locale.weekdaysParse(g,U,I._strict);V!=null?N.d=V:x(I).invalidWeekday=g}),Pi(["d","e","E"],function(g,N,I,U){N[U]=Ke(g)});function Kc(g,N){return typeof g!="string"?g:isNaN(g)?(g=N.weekdaysParse(g),typeof g=="number"?g:null):parseInt(g,10)}function jc(g,N){return typeof g=="string"?N.weekdaysParse(g)%7||7:isNaN(g)?null:g}function Ys(g,N){return g.slice(N,7).concat(g.slice(0,N))}var by="Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday".split("_"),el="Sun_Mon_Tue_Wed_Thu_Fri_Sat".split("_"),wy="Su_Mo_Tu_We_Th_Fr_Sa".split("_"),rl=Ya,Dy=Ya,Sy=Ya;function Ny(g,N){var I=n(this._weekdays)?this._weekdays:this._weekdays[g&&g!==!0&&this._weekdays.isFormat.test(N)?"format":"standalone"];return g===!0?Ys(I,this._week.dow):g?I[g.day()]:I}function Ay(g){return g===!0?Ys(this._weekdaysShort,this._week.dow):g?this._weekdaysShort[g.day()]:this._weekdaysShort}function zf(g){return g===!0?Ys(this._weekdaysMin,this._week.dow):g?this._weekdaysMin[g.day()]:this._weekdaysMin}function My(g,N,I){var U,V,se,Fe=g.toLocaleLowerCase();if(!this._weekdaysParse)for(this._weekdaysParse=[],this._shortWeekdaysParse=[],this._minWeekdaysParse=[],U=0;U<7;++U)se=d([2e3,1]).day(U),this._minWeekdaysParse[U]=this.weekdaysMin(se,"").toLocaleLowerCase(),this._shortWeekdaysParse[U]=this.weekdaysShort(se,"").toLocaleLowerCase(),this._weekdaysParse[U]=this.weekdays(se,"").toLocaleLowerCase();return I?N==="dddd"?(V=vt.call(this._weekdaysParse,Fe),V!==-1?V:null):N==="ddd"?(V=vt.call(this._shortWeekdaysParse,Fe),V!==-1?V:null):(V=vt.call(this._minWeekdaysParse,Fe),V!==-1?V:null):N==="dddd"?(V=vt.call(this._weekdaysParse,Fe),V!==-1||(V=vt.call(this._shortWeekdaysParse,Fe),V!==-1)?V:(V=vt.call(this._minWeekdaysParse,Fe),V!==-1?V:null)):N==="ddd"?(V=vt.call(this._shortWeekdaysParse,Fe),V!==-1||(V=vt.call(this._weekdaysParse,Fe),V!==-1)?V:(V=vt.call(this._minWeekdaysParse,Fe),V!==-1?V:null)):(V=vt.call(this._minWeekdaysParse,Fe),V!==-1||(V=vt.call(this._weekdaysParse,Fe),V!==-1)?V:(V=vt.call(this._shortWeekdaysParse,Fe),V!==-1?V:null))}function Cy(g,N,I){var U,V,se;if(this._weekdaysParseExact)return My.call(this,g,N,I);for(this._weekdaysParse||(this._weekdaysParse=[],this._minWeekdaysParse=[],this._shortWeekdaysParse=[],this._fullWeekdaysParse=[]),U=0;U<7;U++){if(V=d([2e3,1]).day(U),I&&!this._fullWeekdaysParse[U]&&(this._fullWeekdaysParse[U]=new RegExp("^"+this.weekdays(V,"").replace(".","\\\\.?")+"$","i"),this._shortWeekdaysParse[U]=new RegExp("^"+this.weekdaysShort(V,"").replace(".","\\\\.?")+"$","i"),this._minWeekdaysParse[U]=new RegExp("^"+this.weekdaysMin(V,"").replace(".","\\\\.?")+"$","i")),this._weekdaysParse[U]||(se="^"+this.weekdays(V,"")+"|^"+this.weekdaysShort(V,"")+"|^"+this.weekdaysMin(V,""),this._weekdaysParse[U]=new RegExp(se.replace(".",""),"i")),I&&N==="dddd"&&this._fullWeekdaysParse[U].test(g))return U;if(I&&N==="ddd"&&this._shortWeekdaysParse[U].test(g))return U;if(I&&N==="dd"&&this._minWeekdaysParse[U].test(g))return U;if(!I&&this._weekdaysParse[U].test(g))return U}}function Ey(g){if(!this.isValid())return g!=null?this:NaN;var N=this._isUTC?this._d.getUTCDay():this._d.getDay();return g!=null?(g=Kc(g,this.localeData()),this.add(g-N,"d")):N}function Ty(g){if(!this.isValid())return g!=null?this:NaN;var N=(this.day()+7-this.localeData()._week.dow)%7;return g==null?N:this.add(g-N,"d")}function Fy(g){if(!this.isValid())return g!=null?this:NaN;if(g!=null){var N=jc(g,this.localeData());return this.day(this.day()%7?N:N-7)}else return this.day()||7}function yt(g){return this._weekdaysParseExact?(i(this,"_weekdaysRegex")||Uf.call(this),g?this._weekdaysStrictRegex:this._weekdaysRegex):(i(this,"_weekdaysRegex")||(this._weekdaysRegex=rl),this._weekdaysStrictRegex&&g?this._weekdaysStrictRegex:this._weekdaysRegex)}function gt(g){return this._weekdaysParseExact?(i(this,"_weekdaysRegex")||Uf.call(this),g?this._weekdaysShortStrictRegex:this._weekdaysShortRegex):(i(this,"_weekdaysShortRegex")||(this._weekdaysShortRegex=Dy),this._weekdaysShortStrictRegex&&g?this._weekdaysShortStrictRegex:this._weekdaysShortRegex)}function _y(g){return this._weekdaysParseExact?(i(this,"_weekdaysRegex")||Uf.call(this),g?this._weekdaysMinStrictRegex:this._weekdaysMinRegex):(i(this,"_weekdaysMinRegex")||(this._weekdaysMinRegex=Sy),this._weekdaysMinStrictRegex&&g?this._weekdaysMinStrictRegex:this._weekdaysMinRegex)}function Uf(){function g(hn,Aa){return Aa.length-hn.length}var N=[],I=[],U=[],V=[],se,Fe,dr,Or,tt;for(se=0;se<7;se++)Fe=d([2e3,1]).day(se),dr=mn(this.weekdaysMin(Fe,"")),Or=mn(this.weekdaysShort(Fe,"")),tt=mn(this.weekdays(Fe,"")),N.push(dr),I.push(Or),U.push(tt),V.push(dr),V.push(Or),V.push(tt);N.sort(g),I.sort(g),U.sort(g),V.sort(g),this._weekdaysRegex=new RegExp("^("+V.join("|")+")","i"),this._weekdaysShortRegex=this._weekdaysRegex,this._weekdaysMinRegex=this._weekdaysRegex,this._weekdaysStrictRegex=new RegExp("^("+U.join("|")+")","i"),this._weekdaysShortStrictRegex=new RegExp("^("+I.join("|")+")","i"),this._weekdaysMinStrictRegex=new RegExp("^("+N.join("|")+")","i")}function Wf(){return this.hours()%12||12}function Oy(){return this.hours()||24}$("H",["HH",2],0,"hour"),$("h",["hh",2],0,Wf),$("k",["kk",2],0,Oy),$("hmm",0,0,function(){return""+Wf.apply(this)+K(this.minutes(),2)}),$("hmmss",0,0,function(){return""+Wf.apply(this)+K(this.minutes(),2)+K(this.seconds(),2)}),$("Hmm",0,0,function(){return""+this.hours()+K(this.minutes(),2)}),$("Hmmss",0,0,function(){return""+this.hours()+K(this.minutes(),2)+K(this.seconds(),2)});function tl(g,N){$(g,0,0,function(){return this.localeData().meridiem(this.hours(),this.minutes(),N)})}tl("a",!0),tl("A",!1),ne("hour","h"),Le("hour",13);function nl(g,N){return N._meridiemParse}nr("a",nl),nr("A",nl),nr("H",Q),nr("h",Q),nr("k",Q),nr("HH",Q,Te),nr("hh",Q,Te),nr("kk",Q,Te),nr("hmm",ve),nr("hmmss",Pe),nr("Hmm",ve),nr("Hmmss",Pe),ot(["H","HH"],Tt),ot(["k","kk"],function(g,N,I){var U=Ke(g);N[Tt]=U===24?0:U}),ot(["a","A"],function(g,N,I){I._isPm=I._locale.isPM(g),I._meridiem=g}),ot(["h","hh"],function(g,N,I){N[Tt]=Ke(g),x(I).bigHour=!0}),ot("hmm",function(g,N,I){var U=g.length-2;N[Tt]=Ke(g.substr(0,U)),N[On]=Ke(g.substr(U)),x(I).bigHour=!0}),ot("hmmss",function(g,N,I){var U=g.length-4,V=g.length-2;N[Tt]=Ke(g.substr(0,U)),N[On]=Ke(g.substr(U,2)),N[ta]=Ke(g.substr(V)),x(I).bigHour=!0}),ot("Hmm",function(g,N,I){var U=g.length-2;N[Tt]=Ke(g.substr(0,U)),N[On]=Ke(g.substr(U))}),ot("Hmmss",function(g,N,I){var U=g.length-4,V=g.length-2;N[Tt]=Ke(g.substr(0,U)),N[On]=Ke(g.substr(U,2)),N[ta]=Ke(g.substr(V))});function al(g){return(g+"").toLowerCase().charAt(0)==="p"}var By=/[ap]\\.?m?\\.?/i,Vt=Pr("Hours",!0);function Yf(g,N,I){return g>11?I?"pm":"PM":I?"am":"AM"}var di={calendar:L,longDateFormat:Se,invalidDate:be,ordinal:Ae,dayOfMonthOrdinalParse:We,relativeTime:J,months:Pf,monthsShort:Ls,week:mo,weekdays:by,weekdaysMin:wy,weekdaysShort:el,meridiemParse:By},bt={},Ri={},sn;function il(g,N){var I,U=Math.min(g.length,N.length);for(I=0;I0;){if(V=jo(se.slice(0,I).join("-")),V)return V;if(U&&U.length>=I&&il(se,U)>=I-1)break;I--}N++}return sn}function sl(g){return g.match("^[^/\\\\\\\\]*$")!=null}function jo(g){var N=null,I;if(bt[g]===void 0&&typeof Nf<"u"&&Nf&&Nf.exports&&sl(g))try{N=sn._abbr,I=require,I("./locale/"+g),Ga(N)}catch{bt[g]=null}return bt[g]}function Ga(g,N){var I;return g&&(l(N)?I=It(g):I=pn(g,N),I?sn=I:typeof console<"u"&&console.warn&&console.warn("Locale "+g+" not found. Did you forget to load it?")),sn._abbr}function pn(g,N){if(N!==null){var I,U=di;if(N.abbr=g,bt[g]!=null)T("defineLocaleOverride","use moment.updateLocale(localeName, config) to change an existing locale. moment.defineLocale(localeName, config) should only be used for creating a new locale See http://momentjs.com/guides/#/warnings/define-locale/ for more info."),U=bt[g]._config;else if(N.parentLocale!=null)if(bt[N.parentLocale]!=null)U=bt[N.parentLocale]._config;else if(I=jo(N.parentLocale),I!=null)U=I._config;else return Ri[N.parentLocale]||(Ri[N.parentLocale]=[]),Ri[N.parentLocale].push({name:g,config:N}),null;return bt[g]=new G(W(U,N)),Ri[g]&&Ri[g].forEach(function(V){pn(V.name,V.config)}),Ga(g),bt[g]}else return delete bt[g],null}function Py(g,N){if(N!=null){var I,U,V=di;bt[g]!=null&&bt[g].parentLocale!=null?bt[g].set(W(bt[g]._config,N)):(U=jo(g),U!=null&&(V=U._config),N=W(V,N),U==null&&(N.abbr=g),I=new G(N),I.parentLocale=bt[g],bt[g]=I),Ga(g)}else bt[g]!=null&&(bt[g].parentLocale!=null?(bt[g]=bt[g].parentLocale,g===Ga()&&Ga(g)):bt[g]!=null&&delete bt[g]);return bt[g]}function It(g){var N;if(g&&g._locale&&g._locale._abbr&&(g=g._locale._abbr),!g)return sn;if(!n(g)){if(N=jo(g),N)return N;g=[g]}return ol(g)}function Iy(){return H(bt)}function Hs(g){var N,I=g._a;return I&&x(g).overflow===-2&&(N=I[zn]<0||I[zn]>11?zn:I[Un]<1||I[Un]>uo(I[Gt],I[zn])?Un:I[Tt]<0||I[Tt]>24||I[Tt]===24&&(I[On]!==0||I[ta]!==0||I[Ha]!==0)?Tt:I[On]<0||I[On]>59?On:I[ta]<0||I[ta]>59?ta:I[Ha]<0||I[Ha]>999?Ha:-1,x(g)._overflowDayOfYear&&(NUn)&&(N=Un),x(g)._overflowWeeks&&N===-1&&(N=Of),x(g)._overflowWeekday&&N===-1&&(N=so),x(g).overflow=N),g}var hi=/^\\s*((?:[+-]\\d{6}|\\d{4})-(?:\\d\\d-\\d\\d|W\\d\\d-\\d|W\\d\\d|\\d\\d\\d|\\d\\d))(?:(T| )(\\d\\d(?::\\d\\d(?::\\d\\d(?:[.,]\\d+)?)?)?)([+-]\\d\\d(?::?\\d\\d)?|\\s*Z)?)?$/,$s=/^\\s*((?:[+-]\\d{6}|\\d{4})(?:\\d\\d\\d\\d|W\\d\\d\\d|W\\d\\d|\\d\\d\\d|\\d\\d|))(?:(T| )(\\d\\d(?:\\d\\d(?:\\d\\d(?:[.,]\\d+)?)?)?)([+-]\\d\\d(?::?\\d\\d)?|\\s*Z)?)?$/,$f=/Z|[+-]\\d\\d(?::?\\d\\d)?/,dt=[["YYYYYY-MM-DD",/[+-]\\d{6}-\\d\\d-\\d\\d/],["YYYY-MM-DD",/\\d{4}-\\d\\d-\\d\\d/],["GGGG-[W]WW-E",/\\d{4}-W\\d\\d-\\d/],["GGGG-[W]WW",/\\d{4}-W\\d\\d/,!1],["YYYY-DDD",/\\d{4}-\\d{3}/],["YYYY-MM",/\\d{4}-\\d\\d/,!1],["YYYYYYMMDD",/[+-]\\d{10}/],["YYYYMMDD",/\\d{8}/],["GGGG[W]WWE",/\\d{4}W\\d{3}/],["GGGG[W]WW",/\\d{4}W\\d{2}/,!1],["YYYYDDD",/\\d{7}/],["YYYYMM",/\\d{6}/,!1],["YYYY",/\\d{4}/,!1]],ba=[["HH:mm:ss.SSSS",/\\d\\d:\\d\\d:\\d\\d\\.\\d+/],["HH:mm:ss,SSSS",/\\d\\d:\\d\\d:\\d\\d,\\d+/],["HH:mm:ss",/\\d\\d:\\d\\d:\\d\\d/],["HH:mm",/\\d\\d:\\d\\d/],["HHmmss.SSSS",/\\d\\d\\d\\d\\d\\d\\.\\d+/],["HHmmss,SSSS",/\\d\\d\\d\\d\\d\\d,\\d+/],["HHmmss",/\\d\\d\\d\\d\\d\\d/],["HHmm",/\\d\\d\\d\\d/],["HH",/\\d\\d/]],Gf=/^\\/?Date\\((-?\\d+)/i,Ry=/^(?:(Mon|Tue|Wed|Thu|Fri|Sat|Sun),?\\s)?(\\d{1,2})\\s(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\\s(\\d{2,4})\\s(\\d\\d):(\\d\\d)(?::(\\d\\d))?\\s(?:(UT|GMT|[ECMP][SD]T)|([Zz])|([+-]\\d{4}))$/,Vf={UT:0,GMT:0,EDT:-4*60,EST:-5*60,CDT:-5*60,CST:-6*60,MDT:-6*60,MST:-7*60,PDT:-7*60,PST:-8*60};function ul(g){var N,I,U=g._i,V=hi.exec(U)||$s.exec(U),se,Fe,dr,Or,tt=dt.length,hn=ba.length;if(V){for(x(g).iso=!0,N=0,I=tt;Npi(Fe)||g._dayOfYear===0)&&(x(g)._overflowDayOfYear=!0),I=fo(Fe,0,g._dayOfYear),g._a[zn]=I.getUTCMonth(),g._a[Un]=I.getUTCDate()),N=0;N<3&&g._a[N]==null;++N)g._a[N]=U[N]=V[N];for(;N<7;N++)g._a[N]=U[N]=g._a[N]==null?N===2?1:0:g._a[N];g._a[Tt]===24&&g._a[On]===0&&g._a[ta]===0&&g._a[Ha]===0&&(g._nextDay=!0,g._a[Tt]=0),g._d=(g._useUTC?fo:Vc).apply(null,U),se=g._useUTC?g._d.getUTCDay():g._d.getDay(),g._tzm!=null&&g._d.setUTCMinutes(g._d.getUTCMinutes()-g._tzm),g._nextDay&&(g._a[Tt]=24),g._w&&typeof g._w.d<"u"&&g._w.d!==se&&(x(g).weekdayMismatch=!0)}}function ml(g){var N,I,U,V,se,Fe,dr,Or,tt;N=g._w,N.GG!=null||N.W!=null||N.E!=null?(se=1,Fe=4,I=ki(N.GG,g._a[Gt],lo(xt(),1,4).year),U=ki(N.W,1),V=ki(N.E,1),(V<1||V>7)&&(Or=!0)):(se=g._locale._week.dow,Fe=g._locale._week.doy,tt=lo(xt(),se,Fe),I=ki(N.gg,g._a[Gt],tt.year),U=ki(N.w,tt.week),N.d!=null?(V=N.d,(V<0||V>6)&&(Or=!0)):N.e!=null?(V=N.e+se,(N.e<0||N.e>6)&&(Or=!0)):V=se),U<1||U>na(I,se,Fe)?x(g)._overflowWeeks=!0:Or!=null?x(g)._overflowWeekday=!0:(dr=Zc(I,U,V,se,Fe),g._a[Gt]=dr.year,g._dayOfYear=dr.dayOfYear)}r.ISO_8601=function(){},r.RFC_2822=function(){};function Qf(g){if(g._f===r.ISO_8601){ul(g);return}if(g._f===r.RFC_2822){cl(g);return}g._a=[],x(g).empty=!0;var N=""+g._i,I,U,V,se,Fe,dr=N.length,Or=0,tt,hn;for(V=ge(g._f,g._locale).match(z)||[],hn=V.length,I=0;I0&&x(g).unusedInput.push(Fe),N=N.slice(N.indexOf(U)+U.length),Or+=U.length),ae[se]?(U?x(g).empty=!1:x(g).unusedTokens.push(se),_f(se,U,g)):g._strict&&!U&&x(g).unusedTokens.push(se);x(g).charsLeftOver=dr-Or,N.length>0&&x(g).unusedInput.push(N),g._a[Tt]<=12&&x(g).bigHour===!0&&g._a[Tt]>0&&(x(g).bigHour=void 0),x(g).parsedDateParts=g._a.slice(0),x(g).meridiem=g._meridiem,g._a[Tt]=Xf(g._locale,g._a[Tt],g._meridiem),tt=x(g).era,tt!==null&&(g._a[Gt]=g._locale.erasConvertYear(tt,g._a[Gt])),es(g),Hs(g)}function Xf(g,N,I){var U;return I==null?N:g.meridiemHour!=null?g.meridiemHour(N,I):(g.isPM!=null&&(U=g.isPM(I),U&&N<12&&(N+=12),!U&&N===12&&(N=0)),N)}function Jf(g){var N,I,U,V,se,Fe,dr=!1,Or=g._f.length;if(Or===0){x(g).invalidFormat=!0,g._d=new Date(NaN);return}for(V=0;Vthis?this:g:w()});function hl(g,N){var I,U;if(N.length===1&&n(N[0])&&(N=N[0]),!N.length)return xt();for(I=N[0],U=1;Uthis.clone().month(0).utcOffset()||this.utcOffset()>this.clone().month(5).utcOffset()}function _e(){if(!l(this._isDSTShifted))return this._isDSTShifted;var g={},N;return M(g,this),g=bn(g),g._a?(N=g._isUTC?d(g._a):xt(g._a),this._isDSTShifted=this.isValid()&&Gy(g._a,N.toArray())>0):this._isDSTShifted=!1,this._isDSTShifted}function Ne(){return this.isValid()?!this._isUTC:!1}function ir(){return this.isValid()?this._isUTC:!1}function Ar(){return this.isValid()?this._isUTC&&this._offset===0:!1}var rt=/^(-|\\+)?(?:(\\d*)[. ])?(\\d+):(\\d+)(?::(\\d+)(\\.\\d*)?)?$/,zt=/^(-|\\+)?P(?:([-+]?[0-9,.]*)Y)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)W)?(?:([-+]?[0-9,.]*)D)?(?:T(?:([-+]?[0-9,.]*)H)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)S)?)?$/;function zr(g,N){var I=g,U=null,V,se,Fe;return aa(g)?I={ms:g._milliseconds,d:g._days,M:g._months}:c(g)||!isNaN(+g)?(I={},N?I[N]=+g:I.milliseconds=+g):(U=rt.exec(g))?(V=U[1]==="-"?-1:1,I={y:0,d:Ke(U[Un])*V,h:Ke(U[Tt])*V,m:Ke(U[On])*V,s:Ke(U[ta])*V,ms:Ke(vo(U[Ha]*1e3))*V}):(U=zt.exec(g))?(V=U[1]==="-"?-1:1,I={y:Va(U[2],V),M:Va(U[3],V),w:Va(U[4],V),d:Va(U[5],V),h:Va(U[6],V),m:Va(U[7],V),s:Va(U[8],V)}):I==null?I={}:typeof I=="object"&&("from"in I||"to"in I)&&(Fe=Wn(xt(I.from),xt(I.to)),I={},I.ms=Fe.milliseconds,I.M=Fe.months),se=new rs(I),aa(g)&&i(g,"_locale")&&(se._locale=g._locale),aa(g)&&i(g,"_isValid")&&(se._isValid=g._isValid),se}zr.fn=rs.prototype,zr.invalid=jf;function Va(g,N){var I=g&&parseFloat(g.replace(",","."));return(isNaN(I)?0:I)*N}function gl(g,N){var I={};return I.months=N.month()-g.month()+(N.year()-g.year())*12,g.clone().add(I.months,"M").isAfter(N)&&--I.months,I.milliseconds=+N-+g.clone().add(I.months,"M"),I}function Wn(g,N){var I;return g.isValid()&&N.isValid()?(N=Bn(N,g),g.isBefore(N)?I=gl(g,N):(I=gl(N,g),I.milliseconds=-I.milliseconds,I.months=-I.months),I):{milliseconds:0,months:0}}function ts(g,N){return function(I,U){var V,se;return U!==null&&!isNaN(+U)&&(T(N,"moment()."+N+"(period, number) is deprecated. Please use moment()."+N+"(number, period). See http://momentjs.com/guides/#/warnings/add-inverted-param/ for more info."),se=I,I=U,U=se),V=zr(I,U),xl(this,V,g),this}}function xl(g,N,I,U){var V=N._milliseconds,se=vo(N._days),Fe=vo(N._months);!g.isValid()||(U=U??!0,Fe&&mi(g,ee(g,"Month")+Fe*I),se&&ce(g,"Date",ee(g,"Date")+se*I),V&&g._d.setTime(g._d.valueOf()+V*I),U&&r.updateOffset(g,se||Fe))}var go=ts(1,"add"),Zs=ts(-1,"subtract");function ns(g){return typeof g=="string"||g instanceof String}function ut(g){return S(g)||o(g)||ns(g)||c(g)||yl(g)||jy(g)||g===null||g===void 0}function jy(g){var N=a(g)&&!u(g),I=!1,U=["years","year","y","months","month","M","days","day","d","dates","date","D","hours","hour","h","minutes","minute","m","seconds","second","s","milliseconds","millisecond","ms"],V,se,Fe=U.length;for(V=0;VI.valueOf():I.valueOf()9999?me(I,N?"YYYYYY-MM-DD[T]HH:mm:ss.SSS[Z]":"YYYYYY-MM-DD[T]HH:mm:ss.SSSZ"):R(Date.prototype.toISOString)?N?this.toDate().toISOString():new Date(this.valueOf()+this.utcOffset()*60*1e3).toISOString().replace("Z",me(I,"Z")):me(I,N?"YYYY-MM-DD[T]HH:mm:ss.SSS[Z]":"YYYY-MM-DD[T]HH:mm:ss.SSSZ")}function Li(){if(!this.isValid())return"moment.invalid(/* "+this._i+" */)";var g="moment",N="",I,U,V,se;return this.isLocal()||(g=this.utcOffset()===0?"moment.utc":"moment.parseZone",N="Z"),I="["+g+'("]',U=0<=this.year()&&this.year()<=9999?"YYYY":"YYYYYY",V="-MM-DD[T]HH:mm:ss.SSS",se=N+'[")]',this.format(I+U+V+se)}function js(g){g||(g=this.isUtc()?r.defaultFormatUtc:r.defaultFormat);var N=me(this,g);return this.localeData().postformat(N)}function n1(g,N){return this.isValid()&&(S(g)&&g.isValid()||xt(g).isValid())?zr({to:this,from:g}).locale(this.locale()).humanize(!N):this.localeData().invalidDate()}function a1(g){return this.from(xt(),g)}function i1(g,N){return this.isValid()&&(S(g)&&g.isValid()||xt(g).isValid())?zr({from:this,to:g}).locale(this.locale()).humanize(!N):this.localeData().invalidDate()}function eu(g){return this.to(xt(),g)}function is(g){var N;return g===void 0?this._locale._abbr:(N=It(g),N!=null&&(this._locale=N),this)}var ru=_("moment().lang() is deprecated. Instead, use moment().localeData() to get the language configuration. Use moment().locale() to change languages.",function(g){return g===void 0?this.localeData():this.locale(g)});function Nl(){return this._locale}var os=1e3,xo=60*os,tu=60*xo,Rt=(365*400+97)*24*tu;function Ft(g,N){return(g%N+N)%N}function Al(g,N,I){return g<100&&g>=0?new Date(g+400,N,I)-Rt:new Date(g,N,I).valueOf()}function Ml(g,N,I){return g<100&&g>=0?Date.UTC(g+400,N,I)-Rt:Date.UTC(g,N,I)}function Cl(g){var N,I;if(g=ue(g),g===void 0||g==="millisecond"||!this.isValid())return this;switch(I=this._isUTC?Ml:Al,g){case"year":N=I(this.year(),0,1);break;case"quarter":N=I(this.year(),this.month()-this.month()%3,1);break;case"month":N=I(this.year(),this.month(),1);break;case"week":N=I(this.year(),this.month(),this.date()-this.weekday());break;case"isoWeek":N=I(this.year(),this.month(),this.date()-(this.isoWeekday()-1));break;case"day":case"date":N=I(this.year(),this.month(),this.date());break;case"hour":N=this._d.valueOf(),N-=Ft(N+(this._isUTC?0:this.utcOffset()*xo),tu);break;case"minute":N=this._d.valueOf(),N-=Ft(N,xo);break;case"second":N=this._d.valueOf(),N-=Ft(N,os);break}return this._d.setTime(N),r.updateOffset(this,!0),this}function o1(g){var N,I;if(g=ue(g),g===void 0||g==="millisecond"||!this.isValid())return this;switch(I=this._isUTC?Ml:Al,g){case"year":N=I(this.year()+1,0,1)-1;break;case"quarter":N=I(this.year(),this.month()-this.month()%3+3,1)-1;break;case"month":N=I(this.year(),this.month()+1,1)-1;break;case"week":N=I(this.year(),this.month(),this.date()-this.weekday()+7)-1;break;case"isoWeek":N=I(this.year(),this.month(),this.date()-(this.isoWeekday()-1)+7)-1;break;case"day":case"date":N=I(this.year(),this.month(),this.date()+1)-1;break;case"hour":N=this._d.valueOf(),N+=tu-Ft(N+(this._isUTC?0:this.utcOffset()*xo),tu)-1;break;case"minute":N=this._d.valueOf(),N+=xo-Ft(N,xo)-1;break;case"second":N=this._d.valueOf(),N+=os-Ft(N,os)-1;break}return this._d.setTime(N),r.updateOffset(this,!0),this}function ec(){return this._d.valueOf()-(this._offset||0)*6e4}function ss(){return Math.floor(this.valueOf()/1e3)}function rc(){return new Date(this.valueOf())}function yo(){var g=this;return[g.year(),g.month(),g.date(),g.hour(),g.minute(),g.second(),g.millisecond()]}function us(){var g=this;return{years:g.year(),months:g.month(),date:g.date(),hours:g.hours(),minutes:g.minutes(),seconds:g.seconds(),milliseconds:g.milliseconds()}}function fs(){return this.isValid()?this.toISOString():null}function nu(){return y(this)}function bo(){return m({},x(this))}function s1(){return x(this).overflow}function u1(){return{input:this._i,format:this._f,locale:this._locale,isUTC:this._isUTC,strict:this._strict}}$("N",0,0,"eraAbbr"),$("NN",0,0,"eraAbbr"),$("NNN",0,0,"eraAbbr"),$("NNNN",0,0,"eraName"),$("NNNNN",0,0,"eraNarrow"),$("y",["y",1],"yo","eraYear"),$("y",["yy",2],0,"eraYear"),$("y",["yyy",3],0,"eraYear"),$("y",["yyyy",4],0,"eraYear"),nr("N",kr),nr("NN",kr),nr("NNN",kr),nr("NNNN",m1),nr("NNNNN",p1),ot(["N","NN","NNN","NNNN","NNNNN"],function(g,N,I,U){var V=I._locale.erasParse(g,U,I._strict);V?x(I).era=V:x(I).invalidEra=g}),nr("y",Pt),nr("yy",Pt),nr("yyy",Pt),nr("yyyy",Pt),nr("yo",d1),ot(["y","yy","yyy","yyyy"],Gt),ot(["yo"],function(g,N,I,U){var V;I._locale._eraYearOrdinalRegex&&(V=g.match(I._locale._eraYearOrdinalRegex)),I._locale.eraYearOrdinalParse?N[Gt]=I._locale.eraYearOrdinalParse(g,V):N[Gt]=parseInt(g,10)});function f1(g,N){var I,U,V,se=this._eras||It("en")._eras;for(I=0,U=se.length;I=0)return se[U]}function l1(g,N){var I=g.since<=g.until?1:-1;return N===void 0?r(g.since).year():r(g.since).year()+(N-g.offset)*I}function au(){var g,N,I,U=this.localeData().eras();for(g=0,N=U.length;gse&&(N=se),b1.call(this,g,N,I,U,V))}function b1(g,N,I,U,V){var se=Zc(g,N,I,U,V),Fe=fo(se.year,0,se.dayOfYear);return this.year(Fe.getUTCFullYear()),this.month(Fe.getUTCMonth()),this.date(Fe.getUTCDate()),this}$("Q",0,"Qo","quarter"),ne("quarter","Q"),Le("quarter",7),nr("Q",ke),ot("Q",function(g,N){N[zn]=(Ke(g)-1)*3});function w1(g){return g==null?Math.ceil((this.month()+1)/3):this.month((g-1)*3+this.month()%3)}$("D",["DD",2],"Do","date"),ne("date","D"),Le("date",9),nr("D",Q),nr("DD",Q,Te),nr("Do",function(g,N){return g?N._dayOfMonthOrdinalParse||N._ordinalParse:N._dayOfMonthOrdinalParseLenient}),ot(["D","DD"],Un),ot("Do",function(g,N){N[Un]=Ke(g.match(Q)[0])});var Fl=Pr("Date",!0);$("DDD",["DDDD",3],"DDDo","dayOfYear"),ne("dayOfYear","DDD"),Le("dayOfYear",4),nr("DDD",tr),nr("DDDD",Re),ot(["DDD","DDDD"],function(g,N,I){I._dayOfYear=Ke(g)});function Xa(g){var N=Math.round((this.clone().startOf("day")-this.clone().startOf("year"))/864e5)+1;return g==null?N:this.add(g-N,"d")}$("m",["mm",2],0,"minute"),ne("minute","m"),Le("minute",14),nr("m",Q),nr("mm",Q,Te),ot(["m","mm"],On);var D1=Pr("Minutes",!1);$("s",["ss",2],0,"second"),ne("second","s"),Le("second",15),nr("s",Q),nr("ss",Q,Te),ot(["s","ss"],ta);var S1=Pr("Seconds",!1);$("S",0,0,function(){return~~(this.millisecond()/100)}),$(0,["SS",2],0,function(){return~~(this.millisecond()/10)}),$(0,["SSS",3],0,"millisecond"),$(0,["SSSS",4],0,function(){return this.millisecond()*10}),$(0,["SSSSS",5],0,function(){return this.millisecond()*100}),$(0,["SSSSSS",6],0,function(){return this.millisecond()*1e3}),$(0,["SSSSSSS",7],0,function(){return this.millisecond()*1e4}),$(0,["SSSSSSSS",8],0,function(){return this.millisecond()*1e5}),$(0,["SSSSSSSSS",9],0,function(){return this.millisecond()*1e6}),ne("millisecond","ms"),Le("millisecond",16),nr("S",tr,ke),nr("SS",tr,Te),nr("SSS",tr,Re);var yi,_l;for(yi="SSSS";yi.length<=9;yi+="S")nr(yi,Pt);function N1(g,N){N[Ha]=Ke(("0."+g)*1e3)}for(yi="S";yi.length<=9;yi+="S")ot(yi,N1);_l=Pr("Milliseconds",!1),$("z",0,0,"zoneAbbr"),$("zz",0,0,"zoneName");function zi(){return this._isUTC?"UTC":""}function A1(){return this._isUTC?"Coordinated Universal Time":""}var Ve=A.prototype;Ve.add=go,Ve.calendar=r1,Ve.clone=t1,Ve.diff=Dl,Ve.endOf=o1,Ve.format=js,Ve.from=n1,Ve.fromNow=a1,Ve.to=i1,Ve.toNow=eu,Ve.get=we,Ve.invalidAt=s1,Ve.isAfter=Xs,Ve.isBefore=xi,Ve.isBetween=Js,Ve.isSame=bl,Ve.isSameOrAfter=Ks,Ve.isSameOrBefore=wl,Ve.isValid=nu,Ve.lang=ru,Ve.locale=is,Ve.localeData=Nl,Ve.max=zy,Ve.min=dl,Ve.parsingFlags=bo,Ve.set=Be,Ve.startOf=Cl,Ve.subtract=Zs,Ve.toArray=yo,Ve.toObject=us,Ve.toDate=rc,Ve.toISOString=as,Ve.inspect=Li,typeof Symbol<"u"&&Symbol.for!=null&&(Ve[Symbol.for("nodejs.util.inspect.custom")]=function(){return"Moment<"+this.format()+">"}),Ve.toJSON=fs,Ve.toString=Sl,Ve.unix=ss,Ve.valueOf=ec,Ve.creationData=u1,Ve.eraName=au,Ve.eraNarrow=cs,Ve.eraAbbr=El,Ve.eraYear=Z,Ve.year=qf,Ve.isLeapYear=xy,Ve.weekYear=h1,Ve.isoWeekYear=v1,Ve.quarter=Ve.quarters=w1,Ve.month=$a,Ve.daysInMonth=Ws,Ve.week=Ve.weeks=yy,Ve.isoWeek=Ve.isoWeeks=Jc,Ve.weeksInYear=Qa,Ve.weeksInWeekYear=y1,Ve.isoWeeksInYear=g1,Ve.isoWeeksInISOWeekYear=x1,Ve.date=Fl,Ve.day=Ve.days=Ey,Ve.weekday=Ty,Ve.isoWeekday=Fy,Ve.dayOfYear=Xa,Ve.hour=Ve.hours=Vt,Ve.minute=Ve.minutes=D1,Ve.second=Ve.seconds=S1,Ve.millisecond=Ve.milliseconds=_l,Ve.utcOffset=Zy,Ve.utc=Xy,Ve.local=Jy,Ve.parseZone=Ky,Ve.hasAlignedHourOffset=gi,Ve.isDST=de,Ve.isLocal=Ne,Ve.isUtcOffset=ir,Ve.isUtc=Ar,Ve.isUTC=Ar,Ve.zoneAbbr=zi,Ve.zoneName=A1,Ve.dates=_("dates accessor is deprecated. Use date instead.",Fl),Ve.months=_("months accessor is deprecated. Use month instead",$a),Ve.years=_("years accessor is deprecated. Use year instead",qf),Ve.zone=_("moment().zone is deprecated, use moment().utcOffset instead. http://momentjs.com/guides/#/warnings/zone/",Qy),Ve.isDSTShifted=_("isDSTShifted is deprecated. See http://momentjs.com/guides/#/warnings/dst-shifted/ for more information",_e);function ia(g){return xt(g*1e3)}function M1(){return xt.apply(null,arguments).parseZone()}function Ol(g){return g}var Jr=G.prototype;Jr.calendar=k,Jr.longDateFormat=xe,Jr.invalidDate=De,Jr.ordinal=Je,Jr.preparse=Ol,Jr.postformat=Ol,Jr.relativeTime=re,Jr.pastFuture=ye,Jr.set=q,Jr.eras=f1,Jr.erasParse=c1,Jr.erasConvertYear=l1,Jr.erasAbbrRegex=iu,Jr.erasNameRegex=wo,Jr.erasNarrowRegex=Yn,Jr.months=Ii,Jr.monthsShort=et,Jr.monthsParse=If,Jr.monthsRegex=gy,Jr.monthsShortRegex=Rf,Jr.week=Lf,Jr.firstDayOfYear=Xc,Jr.firstDayOfWeek=Qc,Jr.weekdays=Ny,Jr.weekdaysMin=zf,Jr.weekdaysShort=Ay,Jr.weekdaysParse=Cy,Jr.weekdaysRegex=yt,Jr.weekdaysShortRegex=gt,Jr.weekdaysMinRegex=_y,Jr.isPM=al,Jr.meridiem=Yf;function su(g,N,I,U){var V=It(),se=d().set(U,N);return V[I](se,g)}function Bl(g,N,I){if(c(g)&&(N=g,g=void 0),g=g||"",N!=null)return su(g,N,I,"month");var U,V=[];for(U=0;U<12;U++)V[U]=su(g,U,I,"month");return V}function uu(g,N,I,U){typeof g=="boolean"?(c(N)&&(I=N,N=void 0),N=N||""):(N=g,I=N,g=!1,c(N)&&(I=N,N=void 0),N=N||"");var V=It(),se=g?V._week.dow:0,Fe,dr=[];if(I!=null)return su(N,(I+se)%7,U,"day");for(Fe=0;Fe<7;Fe++)dr[Fe]=su(N,(Fe+se)%7,U,"day");return dr}function Pl(g,N){return Bl(g,N,"months")}function C1(g,N){return Bl(g,N,"monthsShort")}function E1(g,N,I){return uu(g,N,I,"weekdays")}function tc(g,N,I){return uu(g,N,I,"weekdaysShort")}function ls(g,N,I){return uu(g,N,I,"weekdaysMin")}Ga("en",{eras:[{since:"0001-01-01",until:1/0,offset:1,name:"Anno Domini",narrow:"AD",abbr:"AD"},{since:"0000-12-31",until:-1/0,offset:1,name:"Before Christ",narrow:"BC",abbr:"BC"}],dayOfMonthOrdinalParse:/\\d{1,2}(th|st|nd|rd)/,ordinal:function(g){var N=g%10,I=Ke(g%100/10)===1?"th":N===1?"st":N===2?"nd":N===3?"rd":"th";return g+I}}),r.lang=_("moment.lang is deprecated. Use moment.locale instead.",Ga),r.langData=_("moment.langData is deprecated. Use moment.localeData instead.",It);var Hn=Math.abs;function T1(){var g=this._data;return this._milliseconds=Hn(this._milliseconds),this._days=Hn(this._days),this._months=Hn(this._months),g.milliseconds=Hn(g.milliseconds),g.seconds=Hn(g.seconds),g.minutes=Hn(g.minutes),g.hours=Hn(g.hours),g.months=Hn(g.months),g.years=Hn(g.years),this}function nc(g,N,I,U){var V=zr(N,I);return g._milliseconds+=U*V._milliseconds,g._days+=U*V._days,g._months+=U*V._months,g._bubble()}function F1(g,N){return nc(this,g,N,1)}function Ja(g,N){return nc(this,g,N,-1)}function fu(g){return g<0?Math.floor(g):Math.ceil(g)}function Ui(){var g=this._milliseconds,N=this._days,I=this._months,U=this._data,V,se,Fe,dr,Or;return g>=0&&N>=0&&I>=0||g<=0&&N<=0&&I<=0||(g+=fu(ac(I)+N)*864e5,N=0,I=0),U.milliseconds=g%1e3,V=or(g/1e3),U.seconds=V%60,se=or(V/60),U.minutes=se%60,Fe=or(se/60),U.hours=Fe%24,N+=or(Fe/24),Or=or(Pn(N)),I+=Or,N-=fu(ac(Or)),dr=or(I/12),I%=12,U.days=N,U.months=I,U.years=dr,this}function Pn(g){return g*4800/146097}function ac(g){return g*146097/4800}function Il(g){if(!this.isValid())return NaN;var N,I,U=this._milliseconds;if(g=ue(g),g==="month"||g==="quarter"||g==="year")switch(N=this._days+U/864e5,I=this._months+Pn(N),g){case"month":return I;case"quarter":return I/3;case"year":return I/12}else switch(N=this._days+Math.round(ac(this._months)),g){case"week":return N/7+U/6048e5;case"day":return N+U/864e5;case"hour":return N*24+U/36e5;case"minute":return N*1440+U/6e4;case"second":return N*86400+U/1e3;case"millisecond":return Math.floor(N*864e5)+U;default:throw new Error("Unknown unit "+g)}}function Rl(){return this.isValid()?this._milliseconds+this._days*864e5+this._months%12*2592e6+Ke(this._months/12)*31536e6:NaN}function In(g){return function(){return this.as(g)}}var bi=In("ms"),kl=In("s"),_1=In("m"),cu=In("h"),O1=In("d"),ql=In("w"),Jt=In("M"),ic=In("Q"),Ll=In("y");function Da(){return zr(this)}function oc(g){return g=ue(g),this.isValid()?this[g+"s"]():NaN}function Sa(g){return function(){return this.isValid()?this._data[g]:NaN}}var Wi=Sa("milliseconds"),zl=Sa("seconds"),dn=Sa("minutes"),sc=Sa("hours"),B1=Sa("days"),P1=Sa("months"),I1=Sa("years");function uc(){return or(this.days()/7)}var Ka=Math.round,Na={ss:44,s:45,m:45,h:22,d:26,w:null,M:11};function Ul(g,N,I,U,V){return V.relativeTime(N||1,!!I,g,U)}function R1(g,N,I,U){var V=zr(g).abs(),se=Ka(V.as("s")),Fe=Ka(V.as("m")),dr=Ka(V.as("h")),Or=Ka(V.as("d")),tt=Ka(V.as("M")),hn=Ka(V.as("w")),Aa=Ka(V.as("y")),ja=se<=I.ss&&["s",se]||se0,ja[4]=U,Ul.apply(null,ja)}function k1(g){return g===void 0?Ka:typeof g=="function"?(Ka=g,!0):!1}function ms(g,N){return Na[g]===void 0?!1:N===void 0?Na[g]:(Na[g]=N,g==="s"&&(Na.ss=N-1),!0)}function q1(g,N){if(!this.isValid())return this.localeData().invalidDate();var I=!1,U=Na,V,se;return typeof g=="object"&&(N=g,g=!1),typeof g=="boolean"&&(I=g),typeof N=="object"&&(U=Object.assign({},Na,N),N.s!=null&&N.ss==null&&(U.ss=N.s-1)),V=this.localeData(),se=R1(this,!I,U,V),I&&(se=V.pastFuture(+this,se)),V.postformat(se)}var fc=Math.abs;function wi(g){return(g>0)-(g<0)||+g}function ps(){if(!this.isValid())return this.localeData().invalidDate();var g=fc(this._milliseconds)/1e3,N=fc(this._days),I=fc(this._months),U,V,se,Fe,dr=this.asSeconds(),Or,tt,hn,Aa;return dr?(U=or(g/60),V=or(U/60),g%=60,U%=60,se=or(I/12),I%=12,Fe=g?g.toFixed(3).replace(/\\.?0+$/,""):"",Or=dr<0?"-":"",tt=wi(this._months)!==wi(dr)?"-":"",hn=wi(this._days)!==wi(dr)?"-":"",Aa=wi(this._milliseconds)!==wi(dr)?"-":"",Or+"P"+(se?tt+se+"Y":"")+(I?tt+I+"M":"")+(N?hn+N+"D":"")+(V||U||g?"T":"")+(V?Aa+V+"H":"")+(U?Aa+U+"M":"")+(g?Aa+Fe+"S":"")):"P0D"}var Vr=rs.prototype;Vr.isValid=$y,Vr.abs=T1,Vr.add=F1,Vr.subtract=Ja,Vr.as=Il,Vr.asMilliseconds=bi,Vr.asSeconds=kl,Vr.asMinutes=_1,Vr.asHours=cu,Vr.asDays=O1,Vr.asWeeks=ql,Vr.asMonths=Jt,Vr.asQuarters=ic,Vr.asYears=Ll,Vr.valueOf=Rl,Vr._bubble=Ui,Vr.clone=Da,Vr.get=oc,Vr.milliseconds=Wi,Vr.seconds=zl,Vr.minutes=dn,Vr.hours=sc,Vr.days=B1,Vr.weeks=uc,Vr.months=P1,Vr.years=I1,Vr.humanize=q1,Vr.toISOString=ps,Vr.toString=ps,Vr.toJSON=ps,Vr.locale=is,Vr.localeData=Nl,Vr.toIsoString=_("toIsoString() is deprecated. Please use toISOString() instead (notice the capitals)",ps),Vr.lang=ru,$("X",0,0,"unix"),$("x",0,0,"valueOf"),nr("x",Xt),nr("X",Ef),ot("X",function(g,N,I){I._d=new Date(parseFloat(g)*1e3)}),ot("x",function(g,N,I){I._d=new Date(Ke(g))});return r.version="2.29.4",t(xt),r.fn=Ve,r.min=Uy,r.max=Wy,r.now=Yy,r.utc=d,r.unix=ia,r.months=Pl,r.isDate=o,r.locale=Ga,r.invalid=w,r.duration=zr,r.isMoment=S,r.weekdays=E1,r.parseZone=M1,r.localeData=It,r.isDuration=aa,r.monthsShort=C1,r.weekdaysMin=ls,r.defineLocale=pn,r.updateLocale=Py,r.locales=Iy,r.weekdaysShort=tc,r.normalizeUnits=ue,r.relativeTimeRounding=k1,r.relativeTimeThreshold=ms,r.calendarFormat=e1,r.prototype=Ve,r.HTML5_FMT={DATETIME_LOCAL:"YYYY-MM-DDTHH:mm",DATETIME_LOCAL_SECONDS:"YYYY-MM-DDTHH:mm:ss",DATETIME_LOCAL_MS:"YYYY-MM-DDTHH:mm:ss.SSS",DATE:"YYYY-MM-DD",TIME:"HH:mm",TIME_SECONDS:"HH:mm:ss",TIME_MS:"HH:mm:ss.SSS",WEEK:"GGGG-[W]WW",MONTH:"YYYY-MM"},r})});function Ta(e){return Ta=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(r){return typeof r}:function(r){return r&&typeof Symbol=="function"&&r.constructor===Symbol&&r!==Symbol.prototype?"symbol":typeof r},Ta(e)}function Dn(e){if(e===null||e===!0||e===!1)return NaN;var r=Number(e);return isNaN(r)?r:r<0?Math.ceil(r):Math.floor(r)}function nt(e,r){if(r.length1?"s":"")+" required, but only "+r.length+" present")}function Yt(e){nt(1,arguments);var r=Object.prototype.toString.call(e);return e instanceof Date||Ta(e)==="object"&&r==="[object Date]"?new Date(e.getTime()):typeof e=="number"||r==="[object Number]"?new Date(e):((typeof e=="string"||r==="[object String]")&&typeof console<"u"&&(console.warn("Starting with v2.0.0-beta.1 date-fns doesn't accept strings as date arguments. Please use \`parseISO\` to parse strings. See: https://github.com/date-fns/date-fns/blob/master/docs/upgradeGuide.md#string-arguments"),console.warn(new Error().stack)),new Date(NaN))}function wb(e,r){nt(2,arguments);var t=Yt(e).getTime(),n=Dn(r);return new Date(t+n)}var Tk={};function Mo(){return Tk}function Db(e){var r=new Date(Date.UTC(e.getFullYear(),e.getMonth(),e.getDate(),e.getHours(),e.getMinutes(),e.getSeconds(),e.getMilliseconds()));return r.setUTCFullYear(e.getFullYear()),e.getTime()-r.getTime()}var Fk=365.2425,_k=Math.pow(10,8)*24*60*60*1e3,Sb=6e4,Nb=36e5;var rQ=-_k;var Ok=3600;var iA=Ok*24,tQ=iA*7,Bk=iA*Fk,Pk=Bk/12,nQ=Pk*3;function Ab(e){return nt(1,arguments),e instanceof Date||Ta(e)==="object"&&Object.prototype.toString.call(e)==="[object Date]"}function Mb(e){if(nt(1,arguments),!Ab(e)&&typeof e!="number")return!1;var r=Yt(e);return!isNaN(Number(r))}function Cb(e,r){nt(2,arguments);var t=Dn(r);return wb(e,-t)}var Ik=864e5;function Eb(e){nt(1,arguments);var r=Yt(e),t=r.getTime();r.setUTCMonth(0,1),r.setUTCHours(0,0,0,0);var n=r.getTime(),a=t-n;return Math.floor(a/Ik)+1}function Co(e){nt(1,arguments);var r=1,t=Yt(e),n=t.getUTCDay(),a=(n=a.getTime()?t+1:r.getTime()>=u.getTime()?t:t-1}function Tb(e){nt(1,arguments);var r=hc(e),t=new Date(0);t.setUTCFullYear(r,0,4),t.setUTCHours(0,0,0,0);var n=Co(t);return n}var Rk=6048e5;function Fb(e){nt(1,arguments);var r=Yt(e),t=Co(r).getTime()-Tb(r).getTime();return Math.round(t/Rk)+1}function Eo(e,r){var t,n,a,i,u,l,c,o;nt(1,arguments);var s=Mo(),m=Dn((t=(n=(a=(i=r?.weekStartsOn)!==null&&i!==void 0?i:r==null||(u=r.locale)===null||u===void 0||(l=u.options)===null||l===void 0?void 0:l.weekStartsOn)!==null&&a!==void 0?a:s.weekStartsOn)!==null&&n!==void 0?n:(c=s.locale)===null||c===void 0||(o=c.options)===null||o===void 0?void 0:o.weekStartsOn)!==null&&t!==void 0?t:0);if(!(m>=0&&m<=6))throw new RangeError("weekStartsOn must be between 0 and 6 inclusively");var d=Yt(e),h=d.getUTCDay(),x=(h=1&&h<=7))throw new RangeError("firstWeekContainsDate must be between 1 and 7 inclusively");var x=new Date(0);x.setUTCFullYear(m+1,0,h),x.setUTCHours(0,0,0,0);var v=Eo(x,r),y=new Date(0);y.setUTCFullYear(m,0,h),y.setUTCHours(0,0,0,0);var w=Eo(y,r);return s.getTime()>=v.getTime()?m+1:s.getTime()>=w.getTime()?m:m-1}function _b(e,r){var t,n,a,i,u,l,c,o;nt(1,arguments);var s=Mo(),m=Dn((t=(n=(a=(i=r?.firstWeekContainsDate)!==null&&i!==void 0?i:r==null||(u=r.locale)===null||u===void 0||(l=u.options)===null||l===void 0?void 0:l.firstWeekContainsDate)!==null&&a!==void 0?a:s.firstWeekContainsDate)!==null&&n!==void 0?n:(c=s.locale)===null||c===void 0||(o=c.options)===null||o===void 0?void 0:o.firstWeekContainsDate)!==null&&t!==void 0?t:1),d=vc(e,r),h=new Date(0);h.setUTCFullYear(d,0,m),h.setUTCHours(0,0,0,0);var x=Eo(h,r);return x}var kk=6048e5;function Ob(e,r){nt(1,arguments);var t=Yt(e),n=Eo(t,r).getTime()-_b(t,r).getTime();return Math.round(n/kk)+1}function st(e,r){for(var t=e<0?"-":"",n=Math.abs(e).toString();n.length0?n:1-n;return st(t==="yy"?a%100:a,t.length)},M:function(r,t){var n=r.getUTCMonth();return t==="M"?String(n+1):st(n+1,2)},d:function(r,t){return st(r.getUTCDate(),t.length)},a:function(r,t){var n=r.getUTCHours()/12>=1?"pm":"am";switch(t){case"a":case"aa":return n.toUpperCase();case"aaa":return n;case"aaaaa":return n[0];case"aaaa":default:return n==="am"?"a.m.":"p.m."}},h:function(r,t){return st(r.getUTCHours()%12||12,t.length)},H:function(r,t){return st(r.getUTCHours(),t.length)},m:function(r,t){return st(r.getUTCMinutes(),t.length)},s:function(r,t){return st(r.getUTCSeconds(),t.length)},S:function(r,t){var n=t.length,a=r.getUTCMilliseconds(),i=Math.floor(a*Math.pow(10,n-3));return st(i,t.length)}},Qi=qk;var vu={am:"am",pm:"pm",midnight:"midnight",noon:"noon",morning:"morning",afternoon:"afternoon",evening:"evening",night:"night"},Lk={G:function(r,t,n){var a=r.getUTCFullYear()>0?1:0;switch(t){case"G":case"GG":case"GGG":return n.era(a,{width:"abbreviated"});case"GGGGG":return n.era(a,{width:"narrow"});case"GGGG":default:return n.era(a,{width:"wide"})}},y:function(r,t,n){if(t==="yo"){var a=r.getUTCFullYear(),i=a>0?a:1-a;return n.ordinalNumber(i,{unit:"year"})}return Qi.y(r,t)},Y:function(r,t,n,a){var i=vc(r,a),u=i>0?i:1-i;if(t==="YY"){var l=u%100;return st(l,2)}return t==="Yo"?n.ordinalNumber(u,{unit:"year"}):st(u,t.length)},R:function(r,t){var n=hc(r);return st(n,t.length)},u:function(r,t){var n=r.getUTCFullYear();return st(n,t.length)},Q:function(r,t,n){var a=Math.ceil((r.getUTCMonth()+1)/3);switch(t){case"Q":return String(a);case"QQ":return st(a,2);case"Qo":return n.ordinalNumber(a,{unit:"quarter"});case"QQQ":return n.quarter(a,{width:"abbreviated",context:"formatting"});case"QQQQQ":return n.quarter(a,{width:"narrow",context:"formatting"});case"QQQQ":default:return n.quarter(a,{width:"wide",context:"formatting"})}},q:function(r,t,n){var a=Math.ceil((r.getUTCMonth()+1)/3);switch(t){case"q":return String(a);case"qq":return st(a,2);case"qo":return n.ordinalNumber(a,{unit:"quarter"});case"qqq":return n.quarter(a,{width:"abbreviated",context:"standalone"});case"qqqqq":return n.quarter(a,{width:"narrow",context:"standalone"});case"qqqq":default:return n.quarter(a,{width:"wide",context:"standalone"})}},M:function(r,t,n){var a=r.getUTCMonth();switch(t){case"M":case"MM":return Qi.M(r,t);case"Mo":return n.ordinalNumber(a+1,{unit:"month"});case"MMM":return n.month(a,{width:"abbreviated",context:"formatting"});case"MMMMM":return n.month(a,{width:"narrow",context:"formatting"});case"MMMM":default:return n.month(a,{width:"wide",context:"formatting"})}},L:function(r,t,n){var a=r.getUTCMonth();switch(t){case"L":return String(a+1);case"LL":return st(a+1,2);case"Lo":return n.ordinalNumber(a+1,{unit:"month"});case"LLL":return n.month(a,{width:"abbreviated",context:"standalone"});case"LLLLL":return n.month(a,{width:"narrow",context:"standalone"});case"LLLL":default:return n.month(a,{width:"wide",context:"standalone"})}},w:function(r,t,n,a){var i=Ob(r,a);return t==="wo"?n.ordinalNumber(i,{unit:"week"}):st(i,t.length)},I:function(r,t,n){var a=Fb(r);return t==="Io"?n.ordinalNumber(a,{unit:"week"}):st(a,t.length)},d:function(r,t,n){return t==="do"?n.ordinalNumber(r.getUTCDate(),{unit:"date"}):Qi.d(r,t)},D:function(r,t,n){var a=Eb(r);return t==="Do"?n.ordinalNumber(a,{unit:"dayOfYear"}):st(a,t.length)},E:function(r,t,n){var a=r.getUTCDay();switch(t){case"E":case"EE":case"EEE":return n.day(a,{width:"abbreviated",context:"formatting"});case"EEEEE":return n.day(a,{width:"narrow",context:"formatting"});case"EEEEEE":return n.day(a,{width:"short",context:"formatting"});case"EEEE":default:return n.day(a,{width:"wide",context:"formatting"})}},e:function(r,t,n,a){var i=r.getUTCDay(),u=(i-a.weekStartsOn+8)%7||7;switch(t){case"e":return String(u);case"ee":return st(u,2);case"eo":return n.ordinalNumber(u,{unit:"day"});case"eee":return n.day(i,{width:"abbreviated",context:"formatting"});case"eeeee":return n.day(i,{width:"narrow",context:"formatting"});case"eeeeee":return n.day(i,{width:"short",context:"formatting"});case"eeee":default:return n.day(i,{width:"wide",context:"formatting"})}},c:function(r,t,n,a){var i=r.getUTCDay(),u=(i-a.weekStartsOn+8)%7||7;switch(t){case"c":return String(u);case"cc":return st(u,t.length);case"co":return n.ordinalNumber(u,{unit:"day"});case"ccc":return n.day(i,{width:"abbreviated",context:"standalone"});case"ccccc":return n.day(i,{width:"narrow",context:"standalone"});case"cccccc":return n.day(i,{width:"short",context:"standalone"});case"cccc":default:return n.day(i,{width:"wide",context:"standalone"})}},i:function(r,t,n){var a=r.getUTCDay(),i=a===0?7:a;switch(t){case"i":return String(i);case"ii":return st(i,t.length);case"io":return n.ordinalNumber(i,{unit:"day"});case"iii":return n.day(a,{width:"abbreviated",context:"formatting"});case"iiiii":return n.day(a,{width:"narrow",context:"formatting"});case"iiiiii":return n.day(a,{width:"short",context:"formatting"});case"iiii":default:return n.day(a,{width:"wide",context:"formatting"})}},a:function(r,t,n){var a=r.getUTCHours(),i=a/12>=1?"pm":"am";switch(t){case"a":case"aa":return n.dayPeriod(i,{width:"abbreviated",context:"formatting"});case"aaa":return n.dayPeriod(i,{width:"abbreviated",context:"formatting"}).toLowerCase();case"aaaaa":return n.dayPeriod(i,{width:"narrow",context:"formatting"});case"aaaa":default:return n.dayPeriod(i,{width:"wide",context:"formatting"})}},b:function(r,t,n){var a=r.getUTCHours(),i;switch(a===12?i=vu.noon:a===0?i=vu.midnight:i=a/12>=1?"pm":"am",t){case"b":case"bb":return n.dayPeriod(i,{width:"abbreviated",context:"formatting"});case"bbb":return n.dayPeriod(i,{width:"abbreviated",context:"formatting"}).toLowerCase();case"bbbbb":return n.dayPeriod(i,{width:"narrow",context:"formatting"});case"bbbb":default:return n.dayPeriod(i,{width:"wide",context:"formatting"})}},B:function(r,t,n){var a=r.getUTCHours(),i;switch(a>=17?i=vu.evening:a>=12?i=vu.afternoon:a>=4?i=vu.morning:i=vu.night,t){case"B":case"BB":case"BBB":return n.dayPeriod(i,{width:"abbreviated",context:"formatting"});case"BBBBB":return n.dayPeriod(i,{width:"narrow",context:"formatting"});case"BBBB":default:return n.dayPeriod(i,{width:"wide",context:"formatting"})}},h:function(r,t,n){if(t==="ho"){var a=r.getUTCHours()%12;return a===0&&(a=12),n.ordinalNumber(a,{unit:"hour"})}return Qi.h(r,t)},H:function(r,t,n){return t==="Ho"?n.ordinalNumber(r.getUTCHours(),{unit:"hour"}):Qi.H(r,t)},K:function(r,t,n){var a=r.getUTCHours()%12;return t==="Ko"?n.ordinalNumber(a,{unit:"hour"}):st(a,t.length)},k:function(r,t,n){var a=r.getUTCHours();return a===0&&(a=24),t==="ko"?n.ordinalNumber(a,{unit:"hour"}):st(a,t.length)},m:function(r,t,n){return t==="mo"?n.ordinalNumber(r.getUTCMinutes(),{unit:"minute"}):Qi.m(r,t)},s:function(r,t,n){return t==="so"?n.ordinalNumber(r.getUTCSeconds(),{unit:"second"}):Qi.s(r,t)},S:function(r,t){return Qi.S(r,t)},X:function(r,t,n,a){var i=a._originalDate||r,u=i.getTimezoneOffset();if(u===0)return"Z";switch(t){case"X":return sA(u);case"XXXX":case"XX":return gs(u);case"XXXXX":case"XXX":default:return gs(u,":")}},x:function(r,t,n,a){var i=a._originalDate||r,u=i.getTimezoneOffset();switch(t){case"x":return sA(u);case"xxxx":case"xx":return gs(u);case"xxxxx":case"xxx":default:return gs(u,":")}},O:function(r,t,n,a){var i=a._originalDate||r,u=i.getTimezoneOffset();switch(t){case"O":case"OO":case"OOO":return"GMT"+oA(u,":");case"OOOO":default:return"GMT"+gs(u,":")}},z:function(r,t,n,a){var i=a._originalDate||r,u=i.getTimezoneOffset();switch(t){case"z":case"zz":case"zzz":return"GMT"+oA(u,":");case"zzzz":default:return"GMT"+gs(u,":")}},t:function(r,t,n,a){var i=a._originalDate||r,u=Math.floor(i.getTime()/1e3);return st(u,t.length)},T:function(r,t,n,a){var i=a._originalDate||r,u=i.getTime();return st(u,t.length)}};function oA(e,r){var t=e>0?"-":"+",n=Math.abs(e),a=Math.floor(n/60),i=n%60;if(i===0)return t+String(a);var u=r||"";return t+String(a)+u+st(i,2)}function sA(e,r){if(e%60===0){var t=e>0?"-":"+";return t+st(Math.abs(e)/60,2)}return gs(e,r)}function gs(e,r){var t=r||"",n=e>0?"-":"+",a=Math.abs(e),i=st(Math.floor(a/60),2),u=st(a%60,2);return n+i+t+u}var uA=Lk;var fA=function(r,t){switch(r){case"P":return t.date({width:"short"});case"PP":return t.date({width:"medium"});case"PPP":return t.date({width:"long"});case"PPPP":default:return t.date({width:"full"})}},cA=function(r,t){switch(r){case"p":return t.time({width:"short"});case"pp":return t.time({width:"medium"});case"ppp":return t.time({width:"long"});case"pppp":default:return t.time({width:"full"})}},zk=function(r,t){var n=r.match(/(P+)(p+)?/)||[],a=n[1],i=n[2];if(!i)return fA(r,t);var u;switch(a){case"P":u=t.dateTime({width:"short"});break;case"PP":u=t.dateTime({width:"medium"});break;case"PPP":u=t.dateTime({width:"long"});break;case"PPPP":default:u=t.dateTime({width:"full"});break}return u.replace("{{date}}",fA(a,t)).replace("{{time}}",cA(i,t))},Uk={p:cA,P:zk},lA=Uk;var Wk=["D","DD"],Yk=["YY","YYYY"];function mA(e){return Wk.indexOf(e)!==-1}function pA(e){return Yk.indexOf(e)!==-1}function Bb(e,r,t){if(e==="YYYY")throw new RangeError("Use \`yyyy\` instead of \`YYYY\` (in \`".concat(r,"\`) for formatting years to the input \`").concat(t,"\`; see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md"));if(e==="YY")throw new RangeError("Use \`yy\` instead of \`YY\` (in \`".concat(r,"\`) for formatting years to the input \`").concat(t,"\`; see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md"));if(e==="D")throw new RangeError("Use \`d\` instead of \`D\` (in \`".concat(r,"\`) for formatting days of the month to the input \`").concat(t,"\`; see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md"));if(e==="DD")throw new RangeError("Use \`dd\` instead of \`DD\` (in \`".concat(r,"\`) for formatting days of the month to the input \`").concat(t,"\`; see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md"))}var Hk={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"}},$k=function(r,t,n){var a,i=Hk[r];return typeof i=="string"?a=i:t===1?a=i.one:a=i.other.replace("{{count}}",t.toString()),n!=null&&n.addSuffix?n.comparison&&n.comparison>0?"in "+a:a+" ago":a},dA=$k;function gc(e){return function(){var r=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},t=r.width?String(r.width):e.defaultWidth,n=e.formats[t]||e.formats[e.defaultWidth];return n}}var Gk={full:"EEEE, MMMM do, y",long:"MMMM do, y",medium:"MMM d, y",short:"MM/dd/yyyy"},Vk={full:"h:mm:ss a zzzz",long:"h:mm:ss a z",medium:"h:mm:ss a",short:"h:mm a"},Zk={full:"{{date}} 'at' {{time}}",long:"{{date}} 'at' {{time}}",medium:"{{date}}, {{time}}",short:"{{date}}, {{time}}"},Qk={date:gc({formats:Gk,defaultWidth:"full"}),time:gc({formats:Vk,defaultWidth:"full"}),dateTime:gc({formats:Zk,defaultWidth:"full"})},hA=Qk;var Xk={lastWeek:"'last' eeee 'at' p",yesterday:"'yesterday at' p",today:"'today at' p",tomorrow:"'tomorrow at' p",nextWeek:"eeee 'at' p",other:"P"},Jk=function(r,t,n,a){return Xk[r]},vA=Jk;function xs(e){return function(r,t){var n=t!=null&&t.context?String(t.context):"standalone",a;if(n==="formatting"&&e.formattingValues){var i=e.defaultFormattingWidth||e.defaultWidth,u=t!=null&&t.width?String(t.width):i;a=e.formattingValues[u]||e.formattingValues[i]}else{var l=e.defaultWidth,c=t!=null&&t.width?String(t.width):e.defaultWidth;a=e.values[c]||e.values[l]}var o=e.argumentCallback?e.argumentCallback(r):r;return a[o]}}var Kk={narrow:["B","A"],abbreviated:["BC","AD"],wide:["Before Christ","Anno Domini"]},jk={narrow:["1","2","3","4"],abbreviated:["Q1","Q2","Q3","Q4"],wide:["1st quarter","2nd quarter","3rd quarter","4th quarter"]},eq={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"]},rq={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"]},tq={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"}},nq={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"}},aq=function(r,t){var n=Number(r),a=n%100;if(a>20||a<10)switch(a%10){case 1:return n+"st";case 2:return n+"nd";case 3:return n+"rd"}return n+"th"},iq={ordinalNumber:aq,era:xs({values:Kk,defaultWidth:"wide"}),quarter:xs({values:jk,defaultWidth:"wide",argumentCallback:function(r){return r-1}}),month:xs({values:eq,defaultWidth:"wide"}),day:xs({values:rq,defaultWidth:"wide"}),dayPeriod:xs({values:tq,defaultWidth:"wide",formattingValues:nq,defaultFormattingWidth:"wide"})},gA=iq;function ys(e){return function(r){var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},n=t.width,a=n&&e.matchPatterns[n]||e.matchPatterns[e.defaultMatchWidth],i=r.match(a);if(!i)return null;var u=i[0],l=n&&e.parsePatterns[n]||e.parsePatterns[e.defaultParseWidth],c=Array.isArray(l)?sq(l,function(m){return m.test(u)}):oq(l,function(m){return m.test(u)}),o;o=e.valueCallback?e.valueCallback(c):c,o=t.valueCallback?t.valueCallback(o):o;var s=r.slice(u.length);return{value:o,rest:s}}}function oq(e,r){for(var t in e)if(e.hasOwnProperty(t)&&r(e[t]))return t}function sq(e,r){for(var t=0;t1&&arguments[1]!==void 0?arguments[1]:{},n=r.match(e.matchPattern);if(!n)return null;var a=n[0],i=r.match(e.parsePattern);if(!i)return null;var u=e.valueCallback?e.valueCallback(i[0]):i[0];u=t.valueCallback?t.valueCallback(u):u;var l=r.slice(a.length);return{value:u,rest:l}}}var uq=/^(\\d+)(th|st|nd|rd)?/i,fq=/\\d+/i,cq={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},lq={any:[/^b/i,/^(a|c)/i]},mq={narrow:/^[1234]/i,abbreviated:/^q[1234]/i,wide:/^[1234](th|st|nd|rd)? quarter/i},pq={any:[/1/i,/2/i,/3/i,/4/i]},dq={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},hq={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]},vq={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},gq={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]},xq={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},yq={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}},bq={ordinalNumber:Pb({matchPattern:uq,parsePattern:fq,valueCallback:function(r){return parseInt(r,10)}}),era:ys({matchPatterns:cq,defaultMatchWidth:"wide",parsePatterns:lq,defaultParseWidth:"any"}),quarter:ys({matchPatterns:mq,defaultMatchWidth:"wide",parsePatterns:pq,defaultParseWidth:"any",valueCallback:function(r){return r+1}}),month:ys({matchPatterns:dq,defaultMatchWidth:"wide",parsePatterns:hq,defaultParseWidth:"any"}),day:ys({matchPatterns:vq,defaultMatchWidth:"wide",parsePatterns:gq,defaultParseWidth:"any"}),dayPeriod:ys({matchPatterns:xq,defaultMatchWidth:"any",parsePatterns:yq,defaultParseWidth:"any"})},xA=bq;var wq={code:"en-US",formatDistance:dA,formatLong:hA,formatRelative:vA,localize:gA,match:xA,options:{weekStartsOn:0,firstWeekContainsDate:1}},yA=wq;var bA=yA;var Dq=/[yYQqMLwIdDecihHKkms]o|(\\w)\\1*|''|'(''|[^'])+('|$)|./g,Sq=/P+p+|P+|p+|''|'(''|[^'])+('|$)|./g,Nq=/^'([^]*?)'?$/,Aq=/''/g,Mq=/[a-zA-Z]/;function Ni(e,r,t){var n,a,i,u,l,c,o,s,m,d,h,x,v,y,w,C,b,M;nt(2,arguments);var A=String(r),S=Mo(),O=(n=(a=t?.locale)!==null&&a!==void 0?a:S.locale)!==null&&n!==void 0?n:bA,_=Dn((i=(u=(l=(c=t?.firstWeekContainsDate)!==null&&c!==void 0?c:t==null||(o=t.locale)===null||o===void 0||(s=o.options)===null||s===void 0?void 0:s.firstWeekContainsDate)!==null&&l!==void 0?l:S.firstWeekContainsDate)!==null&&u!==void 0?u:(m=S.locale)===null||m===void 0||(d=m.options)===null||d===void 0?void 0:d.firstWeekContainsDate)!==null&&i!==void 0?i:1);if(!(_>=1&&_<=7))throw new RangeError("firstWeekContainsDate must be between 1 and 7 inclusively");var E=Dn((h=(x=(v=(y=t?.weekStartsOn)!==null&&y!==void 0?y:t==null||(w=t.locale)===null||w===void 0||(C=w.options)===null||C===void 0?void 0:C.weekStartsOn)!==null&&v!==void 0?v:S.weekStartsOn)!==null&&x!==void 0?x:(b=S.locale)===null||b===void 0||(M=b.options)===null||M===void 0?void 0:M.weekStartsOn)!==null&&h!==void 0?h:0);if(!(E>=0&&E<=6))throw new RangeError("weekStartsOn must be between 0 and 6 inclusively");if(!O.localize)throw new RangeError("locale must contain localize property");if(!O.formatLong)throw new RangeError("locale must contain formatLong property");var T=Yt(e);if(!Mb(T))throw new RangeError("Invalid time value");var R=Db(T),q=Cb(T,R),W={firstWeekContainsDate:_,weekStartsOn:E,locale:O,_originalDate:T},G=A.match(Sq).map(function(H){var L=H[0];if(L==="p"||L==="P"){var k=lA[L];return k(H,O.formatLong)}return H}).join("").match(Dq).map(function(H){if(H==="''")return"'";var L=H[0];if(L==="'")return Cq(H);var k=uA[L];if(k)return!(t!=null&&t.useAdditionalWeekYearTokens)&&pA(H)&&Bb(H,r,String(e)),!(t!=null&&t.useAdditionalDayOfYearTokens)&&mA(H)&&Bb(H,r,String(e)),k(q,H,O.localize,W);if(L.match(Mq))throw new RangeError("Format string contains an unescaped latin alphabet character \`"+L+"\`");return H}).join("");return G}function Cq(e){var r=e.match(Nq);return r?r[1].replace(Aq,"'"):e}function Ib(e,r){if(Ta(e)!="object"||!e)return e;var t=e[Symbol.toPrimitive];if(t!==void 0){var n=t.call(e,r||"default");if(Ta(n)!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return(r==="string"?String:Number)(e)}function Rb(e){var r=Ib(e,"string");return Ta(r)=="symbol"?r:r+""}function Hr(e,r,t){return r=Rb(r),r in e?Object.defineProperty(e,r,{value:t,enumerable:!0,configurable:!0,writable:!0}):e[r]=t,e}function sm(e,r){var t;nt(1,arguments);var n=Dn((t=r?.additionalDigits)!==null&&t!==void 0?t:2);if(n!==2&&n!==1&&n!==0)throw new RangeError("additionalDigits must be 0, 1 or 2");if(!(typeof e=="string"||Object.prototype.toString.call(e)==="[object String]"))return new Date(NaN);var a=_q(e),i;if(a.date){var u=Oq(a.date,n);i=Bq(u.restDateString,u.year)}if(!i||isNaN(i.getTime()))return new Date(NaN);var l=i.getTime(),c=0,o;if(a.time&&(c=Pq(a.time),isNaN(c)))return new Date(NaN);if(a.timezone){if(o=Iq(a.timezone),isNaN(o))return new Date(NaN)}else{var s=new Date(l+c),m=new Date(0);return m.setFullYear(s.getUTCFullYear(),s.getUTCMonth(),s.getUTCDate()),m.setHours(s.getUTCHours(),s.getUTCMinutes(),s.getUTCSeconds(),s.getUTCMilliseconds()),m}return new Date(l+c+o)}var om={dateTimeDelimiter:/[T ]/,timeZoneDelimiter:/[Z ]/i,timezone:/([Z+-].*)$/},Eq=/^-?(?:(\\d{3})|(\\d{2})(?:-?(\\d{2}))?|W(\\d{2})(?:-?(\\d{1}))?|)$/,Tq=/^(\\d{2}(?:[.,]\\d*)?)(?::?(\\d{2}(?:[.,]\\d*)?))?(?::?(\\d{2}(?:[.,]\\d*)?))?$/,Fq=/^([+-])(\\d{2})(?::?(\\d{2}))?$/;function _q(e){var r={},t=e.split(om.dateTimeDelimiter),n;if(t.length>2)return r;if(/:/.test(t[0])?n=t[0]:(r.date=t[0],n=t[1],om.timeZoneDelimiter.test(r.date)&&(r.date=e.split(om.timeZoneDelimiter)[0],n=e.substr(r.date.length,e.length))),n){var a=om.timezone.exec(n);a?(r.time=n.replace(a[1],""),r.timezone=a[1]):r.time=n}return r}function Oq(e,r){var t=new RegExp("^(?:(\\\\d{4}|[+-]\\\\d{"+(4+r)+"})|(\\\\d{2}|[+-]\\\\d{"+(2+r)+"})$)"),n=e.match(t);if(!n)return{year:NaN,restDateString:""};var a=n[1]?parseInt(n[1]):null,i=n[2]?parseInt(n[2]):null;return{year:i===null?a:i*100,restDateString:e.slice((n[1]||n[2]).length)}}function Bq(e,r){if(r===null)return new Date(NaN);var t=e.match(Eq);if(!t)return new Date(NaN);var n=!!t[4],a=xc(t[1]),i=xc(t[2])-1,u=xc(t[3]),l=xc(t[4]),c=xc(t[5])-1;if(n)return zq(r,l,c)?Rq(r,l,c):new Date(NaN);var o=new Date(0);return!qq(r,i,u)||!Lq(r,a)?new Date(NaN):(o.setUTCFullYear(r,i,Math.max(a,u)),o)}function xc(e){return e?parseInt(e):1}function Pq(e){var r=e.match(Tq);if(!r)return NaN;var t=kb(r[1]),n=kb(r[2]),a=kb(r[3]);return Uq(t,n,a)?t*Nb+n*Sb+a*1e3:NaN}function kb(e){return e&&parseFloat(e.replace(",","."))||0}function Iq(e){if(e==="Z")return 0;var r=e.match(Fq);if(!r)return 0;var t=r[1]==="+"?-1:1,n=parseInt(r[2]),a=r[3]&&parseInt(r[3])||0;return Wq(n,a)?t*(n*Nb+a*Sb):NaN}function Rq(e,r,t){var n=new Date(0);n.setUTCFullYear(e,0,4);var a=n.getUTCDay()||7,i=(r-1)*7+t+1-a;return n.setUTCDate(n.getUTCDate()+i),n}var kq=[31,null,31,30,31,30,31,31,30,31,30,31];function wA(e){return e%400===0||e%4===0&&e%100!==0}function qq(e,r,t){return r>=0&&r<=11&&t>=1&&t<=(kq[r]||(wA(e)?29:28))}function Lq(e,r){return r>=1&&r<=(wA(e)?366:365)}function zq(e,r,t){return r>=1&&r<=53&&t>=0&&t<=6}function Uq(e,r,t){return e===24?r===0&&t===0:t>=0&&t<60&&r>=0&&r<60&&e>=0&&e<25}function Wq(e,r){return r>=0&&r<=59}var Fa="File";var yc=e=>e.lastIndexOf("/")!=-1?e.lastIndexOf(".")!=-1?DA(e.substring(e.lastIndexOf("/")+1,e.lastIndexOf("."))):e.substring(e.lastIndexOf("/")+1):e.lastIndexOf(".")!=-1?e.substring(0,e.lastIndexOf(".")):e;function um(e){return Array.isArray(e)?e:typeof e=="string"?[e]:[]}var SA=(e,r)=>r.indexOf(e)>0?r.indexOf(e):r.length;var bc=e=>"spaces://"+e;var DA=e=>e.charAt(0)=="/"?e.substring(1):e;var ti=e=>[...new Set(e)];var NA=(e,r)=>e.sort(function(t,n){let a=r.indexOf(t),i=r.indexOf(n);return a>i?a!=-1&&i==-1?-1:1:i!=-1&&a==-1?1:-1});var qb=(e,r)=>{if(e instanceof Date)return"date";if(typeof e=="string"){if(/\\/\\/(\\S+?(?:jpe?g|png|gif|svg))/gi.test(e)||e.includes("unsplash"))return"image";if(/^\\d{4}-\\d{2}-\\d{2}$/.test(e))return"date";if(r=="tag"||r=="tags")return"tags-multi";if(/\\[\\[.*?\\]\\]/.test(e))return"link"}else{if(typeof e=="number")return"number";if(typeof e=="boolean")return"boolean";if(e)if(Array.isArray(e)||typeof e=="string"&&e.indexOf(",")>-1){let t=Array.isArray(e)?e:[];if(typeof e=="string"&&e.indexOf(",")>-1&&(t=Sn(e)),r=="tag"||r=="tags")return"tags-multi";if(t.length==1&&Array.isArray(t[0])&&t[0].length==1&&typeof t[0][0]=="string")return"link";let n=ti(t.map(a=>qb(a,r)));return n.length==1&&n[0]=="link"?"link-multi":n.some(a=>a=="object")?"object-multi":"option-multi"}else{if(e.isLuxonDateTime)return"date";if(e.isLuxonDuration)return"duration";if(e.type=="file")return"link";if(typeof e=="object"&&!Array.isArray(e)&&e!==null)return"object"}else return"unknown"}return"text"};var AA=e=>e.map(r=>r.replace(",","\\\\,")).join(", "),bs=e=>JSON.stringify(e);var Sn=e=>e?.startsWith("[")?um(wc(e)):Yq(e),Yq=e=>(e?.replace("\\\\,",",")?.match(/(\\\\.|[^,])+/g)??[]).map(r=>r.trim()),ws=(e,r)=>{switch(qb(r,e)){case"tags-multi":return r;case"object":case"object-multi":return JSON.stringify(r);case"number":return r.toString();case"boolean":return r?"true":"false";case"date":{if(r instanceof Date){let n=Ni(r,"yyyy-MM-dd");return typeof n=="string"?n:""}return typeof r!="string"?"":r}break;case"duration":return AA(Object.keys(r.values).reduce((n,a)=>[...n,...r.values[a]>0?[r.values[a]+" "+a]:[]],[]));case"option-multi":case"link-multi":return typeof r=="string"?Dc(r):bs(r.map(n=>n?typeof n=="string"?Dc(n):n.path?n.path:Array.isArray(r)&&n.length==1&&Array.isArray(n[0])&&n[0].length==1&&typeof n[0][0]=="string"?n[0][0]:JSON.stringify(n):""));case"link":return Array.isArray(r)&&r.length==1&&Array.isArray(r[0])&&r[0].length==1&&typeof r[0][0]=="string"?r[0][0]:typeof r=="string"?Dc(r):r.path;case"text":case"tag":case"image":return r}return""};var wc=e=>{let r;try{r=JSON.parse(e)}catch{}return r};var Dc=e=>{if(!e)return"";let r=/\\[\\[(.*?)\\]\\]/g.exec(e),t=r?.length>1?r[1].substring(0,SA("|",r[1])):e;return t||e};var xu=ca(fm());var MA=e=>(0,xu.isNumber)(e)?new Date(e):(0,xu.isString)(e)?sm(e):(0,xu.isDate)(e)?e:new Date;var CA=(e,r,t)=>{if(e.length!==1)return"";let n=e.map(function(i){return i.compile().evaluate(t)});return t.get("$paths").get(n[0])};CA.rawArgs=!0;var EA=(e,r,t)=>t?.get("$current");EA.rawArgs=!0;var TA=(e,r,t)=>{if(e.length!==2)return"";let n=e[0].compile().evaluate?e[0].compile().evaluate(t):e[0];return Array.isArray(n)?n.find(a=>{t.set("$current",a),r.evaluate("current = current()",t);let i=e[1].compile().evaluate?e[1].compile().evaluate(t):e[1];return a===i})??"":""};TA.rawArgs=!0;var FA=(e,r,t)=>{if(e.length!==2)return"";let n=e[0].compile().evaluate?e[0].compile().evaluate(t):e[0];return Array.isArray(n)?n.findIndex(a=>{t.set("$current",a),r.evaluate("current = current()",t);let i=e[1].compile().evaluate?e[1].compile().evaluate(t):e[1];return a===i}):""};FA.rawArgs=!0;var _A=(e,r,t)=>{if(e.length!==2)return"";let n=e[0].compile().evaluate?e[0].compile().evaluate(t):e[0];return Array.isArray(n)?n.filter(a=>(t.set("$current",a),r.evaluate("current = current()",t),e[1].compile().evaluate(t))):""};_A.rawArgs=!0;var OA=(e,r,t)=>{if(e.length!==2)return"";let n=e[0].compile().evaluate?e[0].compile().evaluate(t):e[0];return Array.isArray(n)?n.map(a=>(t.set("$current",a),r.evaluate("current = current()",t),e[1].compile().evaluate(t))):""};OA.rawArgs=!0;var BA=(e,r,t)=>{if(e.length!==2)return"";let n=e[0].compile().evaluate?e[0].compile().evaluate(t):e[0];return Array.isArray(n)?n.some(a=>(t.set("$current",a),r.evaluate("current = current()",t),e[1].compile().evaluate(t))):""};BA.rawArgs=!0;var PA=(e,r,t)=>{if(e.length!==2)return"";let n=e[0].compile().evaluate?e[0].compile().evaluate(t):e[0];return Array.isArray(n)?n.every(a=>(t.set("$current",a),r.evaluate("current = current()",t),e[1].compile().evaluate(t))):""};PA.rawArgs=!0;var IA=(e,r,t)=>{if(e.length!==1)return"";let n=e[0].compile().evaluate?e[0].compile().evaluate(t):e[0];return Array.isArray(n)?n.flat():""};IA.rawArgs=!0;var RA=(e,r,t)=>{if(e.length!==1)return"";let n=e.map(function(u){return u.compile().evaluate(t)}),a=t.get(n[0]),i=t.get("$properties")?.[n[0]]?.type;return(i=="file"||i=="link"||i=="context")&&(i.includes("multi")?a=Sn(a).map(u=>t.get("$paths").get(u)??u):a=t.get("$paths").get(a)??a),a??""};RA.rawArgs=!0;var kA=(e,r,t)=>{if((e.length-1)%2!==0)return"";for(let n=0;n{if(e.length<1||e.length>2)return"";let n=e[0].compile().evaluate(t);n instanceof Date||(n=new Date(n));let a=e[1]?.compile().evaluate(t);return a?.length>0?Ni(n,a):Ni(n,t.get("$settings")?.dateFormat??"yyyy-MM-dd")};qA.rawArgs=!0;var la=e=>typeof e=="string"||e instanceof String?e:e instanceof Date?Ni(e,"yyyy-MM-dd"):typeof e=="number"?e.toFixed(0):e.path?e.path:"",Lb={prop:RA,current:EA,slice:(e,r,t)=>(e=la(e),e.slice(r,t)),if:(e,r,t)=>e===!0?r:t,ifs:kA,empty:e=>e.length!==1?"":e[0]===""?"true":"false",length:e=>e.length,substring:(e,r,t)=>(e=la(e),t?e.substring(r,t):e.substring(r)),contains:(e,r)=>(e=la(e),r=la(r),e.includes(r)),test:(e,r)=>(e=la(e),new RegExp(r).test(e)),match:(e,r)=>(e=la(e),e.match(new RegExp(r))),replace:(e,r,t)=>(e=la(e),e.replace(new RegExp(r),t)),replaceAll:(e,r,t)=>(e=la(e),r=la(r),t=la(t),e.replace(new RegExp(r,"g"),t)),lower:e=>(e=la(e),e.toLowerCase()),upper:e=>(e=la(e),e.toUpperCase()),repeat:(e,r)=>e.repeat(r),format:la,toNumber:e=>e instanceof Date?e.getTime():typeof e=="string"?parseFloat(e):e,now:()=>new Date,minute:e=>e.getMinutes(),hour:e=>e.getHours(),day:e=>e.getDay(),date:e=>e.getDate(),week:e=>Ni(e,"w"),month:e=>e.getMonth()+1,year:e=>e.getFullYear(),pad:(e,r,t)=>e.padStart(r,t),dateAdd:(e,r,t)=>(t==="day"&&e.setDate(e.getDate()+r),t==="month"&&e.setMonth(e.getMonth()+r),t==="year"&&e.setFullYear(e.getFullYear()+r),t==="quarter"&&e.setMonth(e.getMonth()+r*3),t==="week"&&e.setDate(e.getDate()+r*7),t==="hour"&&e.setHours(e.getHours()+r),t==="minute"&&e.setMinutes(e.getMinutes()+r),t==="second"&&e.setSeconds(e.getSeconds()+r),e),dateSubtract:(e,r,t)=>(t==="day"&&e.setDate(e.getDate()-r),t==="month"&&e.setMonth(e.getMonth()-r),t==="year"&&e.setFullYear(e.getFullYear()-r),t==="quarter"&&e.setMonth(e.getMonth()-r*3),t==="week"&&e.setDate(e.getDate()-r*7),t==="hour"&&e.setHours(e.getHours()-r),t==="minute"&&e.setMinutes(e.getMinutes()-r),t==="second"&&e.setSeconds(e.getSeconds()-r),e),dateBetween:(e,r,t)=>{let u=Math.abs(r.getTime()-e.getTime());switch(t){case"days":return Math.round(u/864e5);case"months":return Math.round(u/2592e6);case"years":return Math.round(u/31536e6);case"hours":return Math.round(u/(60*60*1e3));case"minutes":return Math.round(u/(60*1e3));case"seconds":return Math.round(u/1e3);case"weeks":return Math.round(u/(864e5*7));case"quarters":return Math.round(u/(2592e6*3));default:return Math.round(u/864e5)}},style:(e,r)=>e,timeStamp:e=>e.getTime(),at:(e,r)=>e[r],first:e=>e[0],last:e=>e[e.length-1],concat:(e,r)=>e.concat(r),sort:e=>e.sort((r,t)=>t-r),reverse:e=>e.reverse(),join:(e,r)=>e.join(r),includes:(e,r)=>e.includes(r),split:(e,r)=>e.split(r),formatDate:qA,parseDate:e=>MA(e),find:TA,findIndex:FA,filter:_A,map:OA,some:BA,every:PA,flat:IA,path:CA};function ht(){return ht=Object.assign?Object.assign.bind():function(e){for(var r=1;re[r])}var Sm=["Matrix","Array"],Nm=["number","BigNumber","Fraction"];function HA(e,r){function t(n){if(n){var a=wu(e,ar);YA(n,"matrix",Sm),YA(n,"number",Nm),zb(e,n);var i=wu(e,ar),u=wu(n,ar);return r("config",i,a,u),i}else return wu(e,ar)}return t.MATRIX_OPTIONS=Sm,t.NUMBER_OPTIONS=Nm,Object.keys(Ds).forEach(n=>{Object.defineProperty(t,n,{get:()=>e[n],enumerable:!0,configurable:!0})}),t}function Hq(e,r){return e.indexOf(r)!==-1}function YA(e,r,t){e[r]!==void 0&&!Hq(t,e[r])&&console.warn('Warning: Unknown value "'+e[r]+'" for configuration option "'+r+'". Available options: '+t.map(n=>JSON.stringify(n)).join(", ")+".")}var Oe=function(r){if(r)throw new Error(\`The global config is readonly. +Please create a mathjs instance if you want to change the default configuration. +Example: + + import { create, all } from 'mathjs'; + const mathjs = create(all); + mathjs.config({ number: 'BigNumber' }); +\`);return Object.freeze(Ds)};ht(Oe,Ds,{MATRIX_OPTIONS:Sm,NUMBER_OPTIONS:Nm});var PD={};Ck(PD,{createAbs:()=>Ap,createAccessorNode:()=>Sv,createAcos:()=>Oh,createAcosh:()=>Bh,createAcot:()=>Ph,createAcoth:()=>Ih,createAcsc:()=>Rh,createAcsch:()=>kh,createAdd:()=>pv,createAddScalar:()=>Cp,createAnd:()=>ju,createAndTransform:()=>Ux,createApply:()=>qo,createApplyTransform:()=>wx,createArg:()=>jp,createArrayNode:()=>Av,createAsec:()=>qh,createAsech:()=>Lh,createAsin:()=>zh,createAsinh:()=>Uh,createAssignmentNode:()=>Tv,createAtan:()=>Wh,createAtan2:()=>Yh,createAtanh:()=>Hh,createAtomicMass:()=>j0,createAvogadro:()=>ex,createBellNumbers:()=>Gg,createBigNumberClass:()=>Hm,createBignumber:()=>hp,createBin:()=>Id,createBitAnd:()=>qu,createBitAndTransform:()=>Yx,createBitNot:()=>Jp,createBitOr:()=>Lu,createBitOrTransform:()=>Hx,createBitXor:()=>Kp,createBlockNode:()=>_v,createBohrMagneton:()=>B0,createBohrRadius:()=>L0,createBoltzmann:()=>rx,createBoolean:()=>dp,createCatalan:()=>Vg,createCbrt:()=>Tp,createCeil:()=>Fp,createChain:()=>vg,createChainClass:()=>dg,createClassicalElectronRadius:()=>z0,createClone:()=>Jm,createColumn:()=>Wu,createColumnTransform:()=>Dx,createCombinations:()=>Bg,createCombinationsWithRep:()=>Pg,createCompare:()=>ah,createCompareNatural:()=>ih,createCompareText:()=>oh,createCompile:()=>tg,createComplex:()=>vp,createComplexClass:()=>$m,createComposition:()=>Zg,createConcat:()=>Uu,createConcatTransform:()=>Bx,createConditionalNode:()=>Bv,createConductanceQuantum:()=>P0,createConj:()=>ed,createConstantNode:()=>kv,createCorr:()=>Og,createCos:()=>$h,createCosh:()=>Gh,createCot:()=>Vh,createCoth:()=>Zh,createCoulomb:()=>_0,createCount:()=>id,createCreateUnit:()=>_h,createCross:()=>od,createCsc:()=>Qh,createCsch:()=>Xh,createCtranspose:()=>Ad,createCube:()=>_p,createCumSum:()=>af,createCumSumTransform:()=>qx,createDeepEqual:()=>xh,createDenseMatrixClass:()=>Xm,createDerivative:()=>r0,createDet:()=>gg,createDeuteronMass:()=>G0,createDiag:()=>sd,createDiff:()=>Yu,createDiffTransform:()=>Px,createDistance:()=>Cg,createDivide:()=>Mg,createDivideScalar:()=>Wd,createDot:()=>vv,createDotDivide:()=>Qd,createDotMultiply:()=>Qp,createDotPow:()=>Zd,createE:()=>d0,createEfimovFactor:()=>K0,createEigs:()=>bg,createElectricConstant:()=>T0,createElectronMass:()=>U0,createElementaryCharge:()=>O0,createEqual:()=>uh,createEqualScalar:()=>cp,createEqualText:()=>fh,createErf:()=>Fd,createEvaluate:()=>ng,createExp:()=>Op,createExpm:()=>wg,createExpm1:()=>Bp,createFactorial:()=>kg,createFalse:()=>u0,createFaraday:()=>tx,createFermiCoupling:()=>W0,createFft:()=>Cd,createFibonacciHeapClass:()=>Ah,createFilter:()=>ud,createFilterTransform:()=>Sx,createFineStructure:()=>Y0,createFirstRadiation:()=>nx,createFix:()=>Pp,createFlatten:()=>fd,createFloor:()=>Pu,createForEach:()=>cd,createForEachTransform:()=>Nx,createFormat:()=>Pd,createFraction:()=>gp,createFractionClass:()=>Gm,createFreqz:()=>a0,createFunctionAssignmentNode:()=>Lv,createFunctionNode:()=>eg,createGamma:()=>Ig,createGasConstant:()=>ix,createGcd:()=>Ip,createGetMatrixDataType:()=>ld,createGravitationConstant:()=>A0,createGravity:()=>dx,createHartreeEnergy:()=>H0,createHasNumericValue:()=>ap,createHelp:()=>hg,createHelpClass:()=>pg,createHex:()=>kd,createHypot:()=>dv,createI:()=>D0,createIdentity:()=>md,createIfft:()=>Ed,createIm:()=>rd,createImmutableDenseMatrixClass:()=>Sh,createIndex:()=>xv,createIndexClass:()=>Nh,createIndexNode:()=>Uv,createIndexTransform:()=>Ax,createInfinity:()=>c0,createIntersect:()=>Eg,createInv:()=>xg,createInverseConductanceQuantum:()=>I0,createInvmod:()=>Vp,createIsInteger:()=>ep,createIsNaN:()=>sp,createIsNegative:()=>tp,createIsNumeric:()=>np,createIsPositive:()=>ip,createIsPrime:()=>zd,createIsZero:()=>op,createKldivergence:()=>qg,createKlitzing:()=>q0,createKron:()=>pd,createLN10:()=>g0,createLN2:()=>v0,createLOG10E:()=>y0,createLOG2E:()=>x0,createLarger:()=>hh,createLargerEq:()=>gh,createLcm:()=>Rp,createLeafCount:()=>Qg,createLeftShift:()=>eh,createLgamma:()=>Rg,createLog:()=>$d,createLog10:()=>kp,createLog1p:()=>Gd,createLog2:()=>qp,createLoschmidt:()=>ax,createLsolve:()=>Xd,createLsolveAll:()=>Kd,createLup:()=>og,createLusolve:()=>lg,createLyap:()=>Ag,createMad:()=>_g,createMagneticConstant:()=>E0,createMagneticFluxQuantum:()=>R0,createMap:()=>dd,createMapTransform:()=>Mx,createMatrix:()=>xp,createMatrixClass:()=>Zm,createMatrixFromColumns:()=>wp,createMatrixFromFunction:()=>yp,createMatrixFromRows:()=>bp,createMax:()=>ef,createMaxTransform:()=>Cx,createMean:()=>of,createMeanTransform:()=>Ex,createMedian:()=>Fg,createMin:()=>rf,createMinTransform:()=>Tx,createMod:()=>Iu,createMode:()=>Od,createMolarMass:()=>mx,createMolarMassC12:()=>px,createMolarPlanckConstant:()=>ox,createMolarVolume:()=>sx,createMultinomial:()=>Lg,createMultiply:()=>zp,createMultiplyScalar:()=>Lp,createNaN:()=>l0,createNeutronMass:()=>V0,createNode:()=>bv,createNorm:()=>hv,createNot:()=>nd,createNthRoot:()=>Up,createNthRoots:()=>Vd,createNuclearMagneton:()=>k0,createNull:()=>f0,createNumber:()=>mp,createNumeric:()=>Ud,createObjectNode:()=>Yv,createOct:()=>Rd,createOnes:()=>hd,createOperatorNode:()=>$v,createOr:()=>zu,createOrTransform:()=>Wx,createParenthesisNode:()=>Vv,createParse:()=>rg,createParser:()=>ig,createParserClass:()=>ag,createPartitionSelect:()=>wh,createPermutations:()=>zg,createPhi:()=>h0,createPi:()=>m0,createPickRandom:()=>Wg,createPinv:()=>yg,createPlanckCharge:()=>xx,createPlanckConstant:()=>M0,createPlanckLength:()=>hx,createPlanckMass:()=>vx,createPlanckTemperature:()=>yx,createPlanckTime:()=>gx,createPolynomialRoot:()=>mg,createPow:()=>Yd,createPrint:()=>Qu,createPrintTransform:()=>zx,createProd:()=>Bd,createProtonMass:()=>$0,createQr:()=>sg,createQuantileSeq:()=>uf,createQuantileSeqTransform:()=>kx,createQuantumOfCirculation:()=>Z0,createRandom:()=>Yg,createRandomInt:()=>Hg,createRange:()=>$u,createRangeClass:()=>Vm,createRangeNode:()=>Qv,createRangeTransform:()=>Fx,createRationalize:()=>t0,createRe:()=>td,createReducedPlanckConstant:()=>C0,createRelationalNode:()=>Jv,createReplacer:()=>o0,createReshape:()=>xd,createResize:()=>yd,createResolve:()=>jg,createResultSet:()=>Rm,createReviver:()=>i0,createRightArithShift:()=>rh,createRightLogShift:()=>th,createRotate:()=>bd,createRotationMatrix:()=>wd,createRound:()=>Hd,createRow:()=>Gu,createRowTransform:()=>_x,createRydberg:()=>Q0,createSQRT1_2:()=>b0,createSQRT2:()=>w0,createSackurTetrode:()=>ux,createSchur:()=>Ng,createSec:()=>Jh,createSech:()=>Kh,createSecondRadiation:()=>fx,createSetCartesian:()=>nv,createSetDifference:()=>av,createSetDistinct:()=>iv,createSetIntersect:()=>ov,createSetIsSubset:()=>sv,createSetMultiplicity:()=>uv,createSetPowerset:()=>fv,createSetSize:()=>cv,createSetSymDifference:()=>lv,createSetUnion:()=>mv,createSign:()=>Wp,createSimplify:()=>Xg,createSimplifyConstant:()=>Jg,createSimplifyCore:()=>Kg,createSin:()=>jh,createSinh:()=>ev,createSize:()=>Dd,createSlu:()=>cg,createSmaller:()=>lh,createSmallerEq:()=>ph,createSolveODE:()=>Td,createSort:()=>Dh,createSpaClass:()=>Mh,createSparse:()=>Fh,createSparseMatrixClass:()=>lp,createSpeedOfLight:()=>N0,createSplitUnit:()=>Dp,createSqrt:()=>Yp,createSqrtm:()=>Dg,createSquare:()=>Hp,createSqueeze:()=>Sd,createStd:()=>ff,createStdTransform:()=>Ix,createStefanBoltzmann:()=>cx,createStirlingS2:()=>$g,createString:()=>pp,createSubset:()=>Vu,createSubsetTransform:()=>Ox,createSubtract:()=>$p,createSubtractScalar:()=>Ep,createSum:()=>nf,createSumTransform:()=>Rx,createSylvester:()=>Sg,createSymbolNode:()=>Kv,createSymbolicEqual:()=>e0,createTan:()=>rv,createTanh:()=>tv,createTau:()=>p0,createThomsonCrossSection:()=>X0,createTo:()=>Ld,createTrace:()=>gv,createTranspose:()=>Nd,createTrue:()=>s0,createTypeOf:()=>up,createTyped:()=>Im,createUnaryMinus:()=>Sp,createUnaryPlus:()=>Np,createUnequal:()=>bh,createUnitClass:()=>Eh,createUnitFunction:()=>Th,createUppercaseE:()=>mP,createUppercasePi:()=>lP,createUsolve:()=>Jd,createUsolveAll:()=>jd,createVacuumImpedance:()=>F0,createVariance:()=>sf,createVarianceTransform:()=>Lx,createVersion:()=>S0,createWeakMixingAngle:()=>J0,createWienDisplacement:()=>lx,createXgcd:()=>Gp,createXor:()=>ad,createZeros:()=>Md,createZeta:()=>_d,createZpk2tf:()=>n0});var aw=ca(Am(),1);function Ze(e){return typeof e=="boolean"?!0:isFinite(e)?e===Math.round(e):!1}var Oa=Math.sign||function(e){return e>0?1:e<0?-1:0},VA=Math.log2||function(r){return Math.log(r)/Math.LN2},ZA=Math.log10||function(r){return Math.log(r)/Math.LN10},Mm=Math.log1p||function(e){return Math.log(e+1)},QA=Math.cbrt||function(r){if(r===0)return r;var t=r<0,n;return t&&(r=-r),isFinite(r)?(n=Math.exp(Math.log(r)/3),n=(r/(n*n)+2*n)/3):n=r,t?-n:n},XA=Math.expm1||function(r){return r>=2e-4||r<=-2e-4?Math.exp(r)-1:r+r*r/2+r*r*r/6};function Hb(e,r,t){var n={2:"0b",8:"0o",16:"0x"},a=n[r],i="";if(t){if(t<1)throw new Error("size must be in greater than 0");if(!Ze(t))throw new Error("size must be an integer");if(e>2**(t-1)-1||e<-(2**(t-1)))throw new Error("Value must be in range [-2^".concat(t-1,", 2^").concat(t-1,"-1]"));if(!Ze(e))throw new Error("Value must be an integer");e<0&&(e=e+2**t),i="i".concat(t)}var u="";return e<0&&(e=-e,u="-"),"".concat(u).concat(a).concat(e.toString(r)).concat(i)}function ai(e,r){if(typeof r=="function")return r(e);if(e===1/0)return"Infinity";if(e===-1/0)return"-Infinity";if(isNaN(e))return"NaN";var{notation:t,precision:n,wordSize:a}=$b(r);switch(t){case"fixed":return Gb(e,n);case"exponential":return JA(e,n);case"engineering":return $q(e,n);case"bin":return Hb(e,2,a);case"oct":return Hb(e,8,a);case"hex":return Hb(e,16,a);case"auto":return Gq(e,n,r).replace(/((\\.\\d*?)(0+))($|e)/,function(){var i=arguments[2],u=arguments[4];return i!=="."?i+u:u});default:throw new Error('Unknown notation "'+t+'". Choose "auto", "exponential", "fixed", "bin", "oct", or "hex.')}}function $b(e){var r="auto",t,n;if(e!==void 0)if(sr(e))t=e;else if(rr(e))t=e.toNumber();else if(Mi(e))e.precision!==void 0&&(t=$A(e.precision,()=>{throw new Error('Option "precision" must be a number or BigNumber')})),e.wordSize!==void 0&&(n=$A(e.wordSize,()=>{throw new Error('Option "wordSize" must be a number or BigNumber')})),e.notation&&(r=e.notation);else throw new Error("Unsupported type of options, number, BigNumber, or object expected");return{notation:r,precision:t,wordSize:n}}function Nu(e){var r=String(e).toLowerCase().match(/^(-?)(\\d+\\.?\\d*)(e([+-]?\\d+))?$/);if(!r)throw new SyntaxError("Invalid number "+e);var t=r[1],n=r[2],a=parseFloat(r[4]||"0"),i=n.indexOf(".");a+=i!==-1?i-1:n.length-1;var u=n.replace(".","").replace(/^0*/,function(l){return a-=l.length,""}).replace(/0*$/,"").split("").map(function(l){return parseInt(l)});return u.length===0&&(u.push(0),a++),{sign:t,coefficients:u,exponent:a}}function $q(e,r){if(isNaN(e)||!isFinite(e))return String(e);var t=Nu(e),n=Cm(t,r),a=n.exponent,i=n.coefficients,u=a%3===0?a:a<0?a-3-a%3:a-a%3;if(sr(r))for(;r>i.length||a-u+1>i.length;)i.push(0);else for(var l=Math.abs(a-u)-(i.length-1),c=0;c0;)s++,o--;var m=i.slice(s).join(""),d=sr(r)&&m.length||m.match(/[1-9]/)?"."+m:"",h=i.slice(0,s).join("")+d+"e"+(a>=0?"+":"")+u.toString();return n.sign+h}function Gb(e,r){if(isNaN(e)||!isFinite(e))return String(e);var t=Nu(e),n=typeof r=="number"?Cm(t,t.exponent+1+r):t,a=n.coefficients,i=n.exponent+1,u=i+(r||0);return a.length0?"."+a.join(""):"")+"e"+(i>=0?"+":"")+i}function Gq(e,r,t){if(isNaN(e)||!isFinite(e))return String(e);var n=GA(t?.lowerExp,-3),a=GA(t?.upperExp,5),i=Nu(e),u=r?Cm(i,r):i;if(u.exponent=a)return JA(e,r);var l=u.coefficients,c=u.exponent;l.length0?c:0;return or){var a=n.splice(r,n.length-r);if(a[0]>=5){var i=r-1;for(n[i]++;n[i]===10;)n.pop(),i===0&&(n.unshift(0),t.exponent++,i++),i--,n[i]++}}return t}function Su(e){for(var r=[],t=0;t0?!0:e<0?!1:1/e===1/0,n=r>0?!0:r<0?!1:1/r===1/0;return t^n?-e:e}function $A(e,r){if(sr(e))return e;if(rr(e))return e.toNumber();r()}function GA(e,r){return sr(e)?e:rr(e)?e.toNumber():r}function Vb(e,r,t){var n=e.constructor,a=new n(2),i="";if(t){if(t<1)throw new Error("size must be in greater than 0");if(!Ze(t))throw new Error("size must be an integer");if(e.greaterThan(a.pow(t-1).sub(1))||e.lessThan(a.pow(t-1).mul(-1)))throw new Error("Value must be in range [-2^".concat(t-1,", 2^").concat(t-1,"-1]"));if(!e.isInteger())throw new Error("Value must be an integer");e.lessThan(0)&&(e=e.add(a.pow(t))),i="i".concat(t)}switch(r){case 2:return"".concat(e.toBinary()).concat(i);case 8:return"".concat(e.toOctal()).concat(i);case 16:return"".concat(e.toHexadecimal()).concat(i);default:throw new Error("Base ".concat(r," not supported "))}}function oM(e,r){if(typeof r=="function")return r(e);if(!e.isFinite())return e.isNaN()?"NaN":e.gt(0)?"Infinity":"-Infinity";var{notation:t,precision:n,wordSize:a}=$b(r);switch(t){case"fixed":return Qq(e,n);case"exponential":return aM(e,n);case"engineering":return Zq(e,n);case"bin":return Vb(e,2,a);case"oct":return Vb(e,8,a);case"hex":return Vb(e,16,a);case"auto":{var i=iM(r?.lowerExp,-3),u=iM(r?.upperExp,5);if(e.isZero())return"0";var l,c=e.toSignificantDigits(n),o=c.e;return o>=i&&o=0?"+":"")+n.toString()}function aM(e,r){return r!==void 0?e.toExponential(r-1):e.toExponential()}function Qq(e,r){return e.toFixed(r)}function iM(e,r){return sr(e)?e:rr(e)?e.toNumber():r}function uM(e,r){var t=e.length-r.length,n=e.length;return e.substring(t,n)===r}function lr(e,r){var t=Xq(e,r);return r&&typeof r=="object"&&"truncate"in r&&t.length>r.truncate?t.substring(0,r.truncate-3)+"...":t}function Xq(e,r){if(typeof e=="number")return ai(e,r);if(rr(e))return oM(e,r);if(Jq(e))return!r||r.fraction!=="decimal"?e.s*e.n+"/"+e.d:e.toString();if(Array.isArray(e))return fM(e,r);if(St(e))return Ss(e);if(typeof e=="function")return e.syntax?String(e.syntax):"function";if(e&&typeof e=="object"){if(typeof e.format=="function")return e.format(r);if(e&&e.toString(r)!=={}.toString())return e.toString(r);var t=Object.keys(e).map(n=>Ss(n)+": "+lr(e[n],r));return"{"+t.join(", ")+"}"}return String(e)}function Ss(e){for(var r=String(e),t="",n=0;n/g,">"),r}function fM(e,r){if(Array.isArray(e)){for(var t="[",n=e.length,a=0;ar?1:-1}function pr(e,r,t){if(!(this instanceof pr))throw new SyntaxError("Constructor must be called with the new operator");this.actual=e,this.expected=r,this.relation=t,this.message="Dimension mismatch ("+(Array.isArray(e)?"["+e.join(", ")+"]":e)+" "+(this.relation||"!=")+" "+(Array.isArray(r)?"["+r.join(", ")+"]":r)+")",this.stack=new Error().stack}pr.prototype=new RangeError;pr.prototype.constructor=RangeError;pr.prototype.name="DimensionError";pr.prototype.isDimensionError=!0;function tn(e,r,t){if(!(this instanceof tn))throw new SyntaxError("Constructor must be called with the new operator");this.index=e,arguments.length<3?(this.min=0,this.max=r):(this.min=r,this.max=t),this.min!==void 0&&this.index=this.max?this.message="Index out of range ("+this.index+" > "+(this.max-1)+")":this.message="Index out of range ("+this.index+")",this.stack=new Error().stack}tn.prototype=new RangeError;tn.prototype.constructor=RangeError;tn.prototype.name="IndexError";tn.prototype.isIndexError=!0;function ur(e){for(var r=[];Array.isArray(e);)r.push(e.length),e=e[0];return r}function cM(e,r,t){var n,a=e.length;if(a!==r[t])throw new pr(a,r[t]);if(t")}function Qb(e,r){var t=r.length===0;if(t){if(Array.isArray(e))throw new pr(e.length,0)}else cM(e,r,0)}function Ac(e,r){var t=e.isMatrix?e._size:ur(e),n=r._sourceSize;n.forEach((a,i)=>{if(a!==null&&a!==t[i])throw new pr(a,t[i])})}function Kr(e,r){if(e!==void 0){if(!sr(e)||!Ze(e))throw new TypeError("Index must be an integer (value: "+e+")");if(e<0||typeof r=="number"&&e>=r)throw new tn(e,r)}}function Ns(e){for(var r=0;r=0,c=r%t===0;if(l)if(c)n[i]=-r/t;else throw new Error("Could not replace wildcard, since "+r+" is no multiple of "+-t);return n}function lM(e){return e.reduce((r,t)=>r*t,1)}function Kq(e,r){for(var t=e,n,a=r.length-1;a>0;a--){var i=r[a];n=[];for(var u=t.length/i,l=0;lr.test(t))}function Xb(e,r){return Array.prototype.join.call(e,r)}function Ji(e){if(!Array.isArray(e))throw new TypeError("Array input expected");if(e.length===0)return e;var r=[],t=0;r[0]={value:e[0],identifier:0};for(var n=1;n1)return e.slice(1).reduce(function(t,n){return dM(t,n,r,0)},e[0]);throw new Error("Wrong number of arguments in function concat")}function jq(){for(var e=arguments.length,r=new Array(e),t=0;td.length),a=Math.max(...n),i=new Array(a).fill(null),u=0;ui[s]&&(i[s]=l[o])}for(var m=0;m1||e[a]>r[i])throw new Error("shape missmatch: missmatch is found in arg with shape (".concat(e,") not possible to broadcast dimension ").concat(n," with size ").concat(e[a]," to size ").concat(r[i]))}}function jb(e,r){var t=ur(e);if(ni(t,r))return e;Ec(t,r);var n=jq(t,r),a=n.length,i=[...Array(a-t.length).fill(1),...t],u=rL(e);t.length!nL(i)).every(i=>t[i]!==void 0);if(!n){var a=r.filter(i=>t[i]===void 0);throw new Error('Cannot create function "'.concat(e,'", ')+"some dependencies are missing: ".concat(a.map(i=>'"'.concat(i,'"')).join(", "),"."))}}function nL(e){return e&&e[0]==="?"}function ew(e){return e&&e[0]==="?"?e.slice(1):e}function wt(e,r){if(xM(e)&&vM(e,r))return e[r];throw typeof e[r]=="function"&&Bm(e,r)?new Error('Cannot access method "'+r+'" as a property'):new Error('No access to property "'+r+'"')}function Ei(e,r,t){if(xM(e)&&vM(e,r))return e[r]=t,t;throw new Error('No access to property "'+r+'"')}function hM(e,r){return r in e}function vM(e,r){return!e||typeof e!="object"?!1:Xe(aL,r)?!0:!(r in Object.prototype||r in Function.prototype)}function gM(e,r){if(!Bm(e,r))throw new Error('No access to method "'+r+'"');return e[r]}function Bm(e,r){return e==null||typeof e[r]!="function"||Xe(e,r)&&Object.getPrototypeOf&&r in Object.getPrototypeOf(e)?!1:Xe(iL,r)?!0:!(r in Object.prototype||r in Function.prototype)}function xM(e){return typeof e=="object"&&e&&e.constructor===Object}var aL={length:!0,name:!0},iL={toString:!0,valueOf:!0,toLocaleString:!0};var Ms=class{constructor(r){this.wrappedObject=r,this[Symbol.iterator]=this.entries}keys(){return Object.keys(this.wrappedObject).values()}get(r){return wt(this.wrappedObject,r)}set(r,t){return Ei(this.wrappedObject,r,t),this}has(r){return hM(this.wrappedObject,r)}entries(){return yM(this.keys(),r=>[r,this.get(r)])}forEach(r){for(var t of this.keys())r(this.get(t),t,this)}delete(r){delete this.wrappedObject[r]}clear(){for(var r of this.keys())this.delete(r)}get size(){return Object.keys(this.wrappedObject).length}},Eu=class{constructor(r,t,n){this.a=r,this.b=t,this.bKeys=n,this[Symbol.iterator]=this.entries}get(r){return this.bKeys.has(r)?this.b.get(r):this.a.get(r)}set(r,t){return this.bKeys.has(r)?this.b.set(r,t):this.a.set(r,t),this}has(r){return this.b.has(r)||this.a.has(r)}keys(){return new Set([...this.a.keys(),...this.b.keys()])[Symbol.iterator]()}entries(){return yM(this.keys(),r=>[r,this.get(r)])}forEach(r){for(var t of this.keys())r(this.get(t),t,this)}delete(r){return this.bKeys.has(r)?this.b.delete(r):this.a.delete(r)}clear(){this.a.clear(),this.b.clear()}get size(){return[...this.keys()].length}};function yM(e,r){return{next:()=>{var t=e.next();return t.done?t:{value:r(t.value),done:!1}}}}function Oo(){return new Map}function Ki(e){if(!e)return Oo();if(rw(e))return e;if(Mi(e))return new Ms(e);throw new Error("createMap can create maps from objects or Maps")}function bM(e){if(e instanceof Ms)return e.wrappedObject;var r={};for(var t of e.keys()){var n=e.get(t);Ei(r,t,n)}return r}function rw(e){return e?e instanceof Map||e instanceof Ms||typeof e.set=="function"&&typeof e.get=="function"&&typeof e.keys=="function"&&typeof e.has=="function":!1}var wM=function(){return wM=aw.default.create,aw.default},oL=["?BigNumber","?Complex","?DenseMatrix","?Fraction"],Im=F("typed",oL,function(r){var{BigNumber:t,Complex:n,DenseMatrix:a,Fraction:i}=r,u=wM();return u.clear(),u.addTypes([{name:"number",test:sr},{name:"Complex",test:Kt},{name:"BigNumber",test:rr},{name:"Fraction",test:ma},{name:"Unit",test:Ht},{name:"identifier",test:l=>St&&/^(?:[A-Za-z\\xAA\\xB5\\xBA\\xC0-\\xD6\\xD8-\\xF6\\xF8-\\u02C1\\u02C6-\\u02D1\\u02E0-\\u02E4\\u02EC\\u02EE\\u0370-\\u0374\\u0376\\u0377\\u037A-\\u037D\\u037F\\u0386\\u0388-\\u038A\\u038C\\u038E-\\u03A1\\u03A3-\\u03F5\\u03F7-\\u0481\\u048A-\\u052F\\u0531-\\u0556\\u0559\\u0560-\\u0588\\u05D0-\\u05EA\\u05EF-\\u05F2\\u0620-\\u064A\\u066E\\u066F\\u0671-\\u06D3\\u06D5\\u06E5\\u06E6\\u06EE\\u06EF\\u06FA-\\u06FC\\u06FF\\u0710\\u0712-\\u072F\\u074D-\\u07A5\\u07B1\\u07CA-\\u07EA\\u07F4\\u07F5\\u07FA\\u0800-\\u0815\\u081A\\u0824\\u0828\\u0840-\\u0858\\u0860-\\u086A\\u0870-\\u0887\\u0889-\\u088E\\u08A0-\\u08C9\\u0904-\\u0939\\u093D\\u0950\\u0958-\\u0961\\u0971-\\u0980\\u0985-\\u098C\\u098F\\u0990\\u0993-\\u09A8\\u09AA-\\u09B0\\u09B2\\u09B6-\\u09B9\\u09BD\\u09CE\\u09DC\\u09DD\\u09DF-\\u09E1\\u09F0\\u09F1\\u09FC\\u0A05-\\u0A0A\\u0A0F\\u0A10\\u0A13-\\u0A28\\u0A2A-\\u0A30\\u0A32\\u0A33\\u0A35\\u0A36\\u0A38\\u0A39\\u0A59-\\u0A5C\\u0A5E\\u0A72-\\u0A74\\u0A85-\\u0A8D\\u0A8F-\\u0A91\\u0A93-\\u0AA8\\u0AAA-\\u0AB0\\u0AB2\\u0AB3\\u0AB5-\\u0AB9\\u0ABD\\u0AD0\\u0AE0\\u0AE1\\u0AF9\\u0B05-\\u0B0C\\u0B0F\\u0B10\\u0B13-\\u0B28\\u0B2A-\\u0B30\\u0B32\\u0B33\\u0B35-\\u0B39\\u0B3D\\u0B5C\\u0B5D\\u0B5F-\\u0B61\\u0B71\\u0B83\\u0B85-\\u0B8A\\u0B8E-\\u0B90\\u0B92-\\u0B95\\u0B99\\u0B9A\\u0B9C\\u0B9E\\u0B9F\\u0BA3\\u0BA4\\u0BA8-\\u0BAA\\u0BAE-\\u0BB9\\u0BD0\\u0C05-\\u0C0C\\u0C0E-\\u0C10\\u0C12-\\u0C28\\u0C2A-\\u0C39\\u0C3D\\u0C58-\\u0C5A\\u0C5D\\u0C60\\u0C61\\u0C80\\u0C85-\\u0C8C\\u0C8E-\\u0C90\\u0C92-\\u0CA8\\u0CAA-\\u0CB3\\u0CB5-\\u0CB9\\u0CBD\\u0CDD\\u0CDE\\u0CE0\\u0CE1\\u0CF1\\u0CF2\\u0D04-\\u0D0C\\u0D0E-\\u0D10\\u0D12-\\u0D3A\\u0D3D\\u0D4E\\u0D54-\\u0D56\\u0D5F-\\u0D61\\u0D7A-\\u0D7F\\u0D85-\\u0D96\\u0D9A-\\u0DB1\\u0DB3-\\u0DBB\\u0DBD\\u0DC0-\\u0DC6\\u0E01-\\u0E30\\u0E32\\u0E33\\u0E40-\\u0E46\\u0E81\\u0E82\\u0E84\\u0E86-\\u0E8A\\u0E8C-\\u0EA3\\u0EA5\\u0EA7-\\u0EB0\\u0EB2\\u0EB3\\u0EBD\\u0EC0-\\u0EC4\\u0EC6\\u0EDC-\\u0EDF\\u0F00\\u0F40-\\u0F47\\u0F49-\\u0F6C\\u0F88-\\u0F8C\\u1000-\\u102A\\u103F\\u1050-\\u1055\\u105A-\\u105D\\u1061\\u1065\\u1066\\u106E-\\u1070\\u1075-\\u1081\\u108E\\u10A0-\\u10C5\\u10C7\\u10CD\\u10D0-\\u10FA\\u10FC-\\u1248\\u124A-\\u124D\\u1250-\\u1256\\u1258\\u125A-\\u125D\\u1260-\\u1288\\u128A-\\u128D\\u1290-\\u12B0\\u12B2-\\u12B5\\u12B8-\\u12BE\\u12C0\\u12C2-\\u12C5\\u12C8-\\u12D6\\u12D8-\\u1310\\u1312-\\u1315\\u1318-\\u135A\\u1380-\\u138F\\u13A0-\\u13F5\\u13F8-\\u13FD\\u1401-\\u166C\\u166F-\\u167F\\u1681-\\u169A\\u16A0-\\u16EA\\u16F1-\\u16F8\\u1700-\\u1711\\u171F-\\u1731\\u1740-\\u1751\\u1760-\\u176C\\u176E-\\u1770\\u1780-\\u17B3\\u17D7\\u17DC\\u1820-\\u1878\\u1880-\\u1884\\u1887-\\u18A8\\u18AA\\u18B0-\\u18F5\\u1900-\\u191E\\u1950-\\u196D\\u1970-\\u1974\\u1980-\\u19AB\\u19B0-\\u19C9\\u1A00-\\u1A16\\u1A20-\\u1A54\\u1AA7\\u1B05-\\u1B33\\u1B45-\\u1B4C\\u1B83-\\u1BA0\\u1BAE\\u1BAF\\u1BBA-\\u1BE5\\u1C00-\\u1C23\\u1C4D-\\u1C4F\\u1C5A-\\u1C7D\\u1C80-\\u1C88\\u1C90-\\u1CBA\\u1CBD-\\u1CBF\\u1CE9-\\u1CEC\\u1CEE-\\u1CF3\\u1CF5\\u1CF6\\u1CFA\\u1D00-\\u1DBF\\u1E00-\\u1F15\\u1F18-\\u1F1D\\u1F20-\\u1F45\\u1F48-\\u1F4D\\u1F50-\\u1F57\\u1F59\\u1F5B\\u1F5D\\u1F5F-\\u1F7D\\u1F80-\\u1FB4\\u1FB6-\\u1FBC\\u1FBE\\u1FC2-\\u1FC4\\u1FC6-\\u1FCC\\u1FD0-\\u1FD3\\u1FD6-\\u1FDB\\u1FE0-\\u1FEC\\u1FF2-\\u1FF4\\u1FF6-\\u1FFC\\u2071\\u207F\\u2090-\\u209C\\u2102\\u2107\\u210A-\\u2113\\u2115\\u2119-\\u211D\\u2124\\u2126\\u2128\\u212A-\\u212D\\u212F-\\u2139\\u213C-\\u213F\\u2145-\\u2149\\u214E\\u2183\\u2184\\u2C00-\\u2CE4\\u2CEB-\\u2CEE\\u2CF2\\u2CF3\\u2D00-\\u2D25\\u2D27\\u2D2D\\u2D30-\\u2D67\\u2D6F\\u2D80-\\u2D96\\u2DA0-\\u2DA6\\u2DA8-\\u2DAE\\u2DB0-\\u2DB6\\u2DB8-\\u2DBE\\u2DC0-\\u2DC6\\u2DC8-\\u2DCE\\u2DD0-\\u2DD6\\u2DD8-\\u2DDE\\u2E2F\\u3005\\u3006\\u3031-\\u3035\\u303B\\u303C\\u3041-\\u3096\\u309D-\\u309F\\u30A1-\\u30FA\\u30FC-\\u30FF\\u3105-\\u312F\\u3131-\\u318E\\u31A0-\\u31BF\\u31F0-\\u31FF\\u3400-\\u4DBF\\u4E00-\\uA48C\\uA4D0-\\uA4FD\\uA500-\\uA60C\\uA610-\\uA61F\\uA62A\\uA62B\\uA640-\\uA66E\\uA67F-\\uA69D\\uA6A0-\\uA6E5\\uA717-\\uA71F\\uA722-\\uA788\\uA78B-\\uA7CA\\uA7D0\\uA7D1\\uA7D3\\uA7D5-\\uA7D9\\uA7F2-\\uA801\\uA803-\\uA805\\uA807-\\uA80A\\uA80C-\\uA822\\uA840-\\uA873\\uA882-\\uA8B3\\uA8F2-\\uA8F7\\uA8FB\\uA8FD\\uA8FE\\uA90A-\\uA925\\uA930-\\uA946\\uA960-\\uA97C\\uA984-\\uA9B2\\uA9CF\\uA9E0-\\uA9E4\\uA9E6-\\uA9EF\\uA9FA-\\uA9FE\\uAA00-\\uAA28\\uAA40-\\uAA42\\uAA44-\\uAA4B\\uAA60-\\uAA76\\uAA7A\\uAA7E-\\uAAAF\\uAAB1\\uAAB5\\uAAB6\\uAAB9-\\uAABD\\uAAC0\\uAAC2\\uAADB-\\uAADD\\uAAE0-\\uAAEA\\uAAF2-\\uAAF4\\uAB01-\\uAB06\\uAB09-\\uAB0E\\uAB11-\\uAB16\\uAB20-\\uAB26\\uAB28-\\uAB2E\\uAB30-\\uAB5A\\uAB5C-\\uAB69\\uAB70-\\uABE2\\uAC00-\\uD7A3\\uD7B0-\\uD7C6\\uD7CB-\\uD7FB\\uF900-\\uFA6D\\uFA70-\\uFAD9\\uFB00-\\uFB06\\uFB13-\\uFB17\\uFB1D\\uFB1F-\\uFB28\\uFB2A-\\uFB36\\uFB38-\\uFB3C\\uFB3E\\uFB40\\uFB41\\uFB43\\uFB44\\uFB46-\\uFBB1\\uFBD3-\\uFD3D\\uFD50-\\uFD8F\\uFD92-\\uFDC7\\uFDF0-\\uFDFB\\uFE70-\\uFE74\\uFE76-\\uFEFC\\uFF21-\\uFF3A\\uFF41-\\uFF5A\\uFF66-\\uFFBE\\uFFC2-\\uFFC7\\uFFCA-\\uFFCF\\uFFD2-\\uFFD7\\uFFDA-\\uFFDC]|\\uD800[\\uDC00-\\uDC0B\\uDC0D-\\uDC26\\uDC28-\\uDC3A\\uDC3C\\uDC3D\\uDC3F-\\uDC4D\\uDC50-\\uDC5D\\uDC80-\\uDCFA\\uDE80-\\uDE9C\\uDEA0-\\uDED0\\uDF00-\\uDF1F\\uDF2D-\\uDF40\\uDF42-\\uDF49\\uDF50-\\uDF75\\uDF80-\\uDF9D\\uDFA0-\\uDFC3\\uDFC8-\\uDFCF]|\\uD801[\\uDC00-\\uDC9D\\uDCB0-\\uDCD3\\uDCD8-\\uDCFB\\uDD00-\\uDD27\\uDD30-\\uDD63\\uDD70-\\uDD7A\\uDD7C-\\uDD8A\\uDD8C-\\uDD92\\uDD94\\uDD95\\uDD97-\\uDDA1\\uDDA3-\\uDDB1\\uDDB3-\\uDDB9\\uDDBB\\uDDBC\\uDE00-\\uDF36\\uDF40-\\uDF55\\uDF60-\\uDF67\\uDF80-\\uDF85\\uDF87-\\uDFB0\\uDFB2-\\uDFBA]|\\uD802[\\uDC00-\\uDC05\\uDC08\\uDC0A-\\uDC35\\uDC37\\uDC38\\uDC3C\\uDC3F-\\uDC55\\uDC60-\\uDC76\\uDC80-\\uDC9E\\uDCE0-\\uDCF2\\uDCF4\\uDCF5\\uDD00-\\uDD15\\uDD20-\\uDD39\\uDD80-\\uDDB7\\uDDBE\\uDDBF\\uDE00\\uDE10-\\uDE13\\uDE15-\\uDE17\\uDE19-\\uDE35\\uDE60-\\uDE7C\\uDE80-\\uDE9C\\uDEC0-\\uDEC7\\uDEC9-\\uDEE4\\uDF00-\\uDF35\\uDF40-\\uDF55\\uDF60-\\uDF72\\uDF80-\\uDF91]|\\uD803[\\uDC00-\\uDC48\\uDC80-\\uDCB2\\uDCC0-\\uDCF2\\uDD00-\\uDD23\\uDE80-\\uDEA9\\uDEB0\\uDEB1\\uDF00-\\uDF1C\\uDF27\\uDF30-\\uDF45\\uDF70-\\uDF81\\uDFB0-\\uDFC4\\uDFE0-\\uDFF6]|\\uD804[\\uDC03-\\uDC37\\uDC71\\uDC72\\uDC75\\uDC83-\\uDCAF\\uDCD0-\\uDCE8\\uDD03-\\uDD26\\uDD44\\uDD47\\uDD50-\\uDD72\\uDD76\\uDD83-\\uDDB2\\uDDC1-\\uDDC4\\uDDDA\\uDDDC\\uDE00-\\uDE11\\uDE13-\\uDE2B\\uDE3F\\uDE40\\uDE80-\\uDE86\\uDE88\\uDE8A-\\uDE8D\\uDE8F-\\uDE9D\\uDE9F-\\uDEA8\\uDEB0-\\uDEDE\\uDF05-\\uDF0C\\uDF0F\\uDF10\\uDF13-\\uDF28\\uDF2A-\\uDF30\\uDF32\\uDF33\\uDF35-\\uDF39\\uDF3D\\uDF50\\uDF5D-\\uDF61]|\\uD805[\\uDC00-\\uDC34\\uDC47-\\uDC4A\\uDC5F-\\uDC61\\uDC80-\\uDCAF\\uDCC4\\uDCC5\\uDCC7\\uDD80-\\uDDAE\\uDDD8-\\uDDDB\\uDE00-\\uDE2F\\uDE44\\uDE80-\\uDEAA\\uDEB8\\uDF00-\\uDF1A\\uDF40-\\uDF46]|\\uD806[\\uDC00-\\uDC2B\\uDCA0-\\uDCDF\\uDCFF-\\uDD06\\uDD09\\uDD0C-\\uDD13\\uDD15\\uDD16\\uDD18-\\uDD2F\\uDD3F\\uDD41\\uDDA0-\\uDDA7\\uDDAA-\\uDDD0\\uDDE1\\uDDE3\\uDE00\\uDE0B-\\uDE32\\uDE3A\\uDE50\\uDE5C-\\uDE89\\uDE9D\\uDEB0-\\uDEF8]|\\uD807[\\uDC00-\\uDC08\\uDC0A-\\uDC2E\\uDC40\\uDC72-\\uDC8F\\uDD00-\\uDD06\\uDD08\\uDD09\\uDD0B-\\uDD30\\uDD46\\uDD60-\\uDD65\\uDD67\\uDD68\\uDD6A-\\uDD89\\uDD98\\uDEE0-\\uDEF2\\uDF02\\uDF04-\\uDF10\\uDF12-\\uDF33\\uDFB0]|\\uD808[\\uDC00-\\uDF99]|\\uD809[\\uDC80-\\uDD43]|\\uD80B[\\uDF90-\\uDFF0]|[\\uD80C\\uD81C-\\uD820\\uD822\\uD840-\\uD868\\uD86A-\\uD86C\\uD86F-\\uD872\\uD874-\\uD879\\uD880-\\uD883\\uD885-\\uD887][\\uDC00-\\uDFFF]|\\uD80D[\\uDC00-\\uDC2F\\uDC41-\\uDC46]|\\uD811[\\uDC00-\\uDE46]|\\uD81A[\\uDC00-\\uDE38\\uDE40-\\uDE5E\\uDE70-\\uDEBE\\uDED0-\\uDEED\\uDF00-\\uDF2F\\uDF40-\\uDF43\\uDF63-\\uDF77\\uDF7D-\\uDF8F]|\\uD81B[\\uDE40-\\uDE7F\\uDF00-\\uDF4A\\uDF50\\uDF93-\\uDF9F\\uDFE0\\uDFE1\\uDFE3]|\\uD821[\\uDC00-\\uDFF7]|\\uD823[\\uDC00-\\uDCD5\\uDD00-\\uDD08]|\\uD82B[\\uDFF0-\\uDFF3\\uDFF5-\\uDFFB\\uDFFD\\uDFFE]|\\uD82C[\\uDC00-\\uDD22\\uDD32\\uDD50-\\uDD52\\uDD55\\uDD64-\\uDD67\\uDD70-\\uDEFB]|\\uD82F[\\uDC00-\\uDC6A\\uDC70-\\uDC7C\\uDC80-\\uDC88\\uDC90-\\uDC99]|\\uD835[\\uDC00-\\uDC54\\uDC56-\\uDC9C\\uDC9E\\uDC9F\\uDCA2\\uDCA5\\uDCA6\\uDCA9-\\uDCAC\\uDCAE-\\uDCB9\\uDCBB\\uDCBD-\\uDCC3\\uDCC5-\\uDD05\\uDD07-\\uDD0A\\uDD0D-\\uDD14\\uDD16-\\uDD1C\\uDD1E-\\uDD39\\uDD3B-\\uDD3E\\uDD40-\\uDD44\\uDD46\\uDD4A-\\uDD50\\uDD52-\\uDEA5\\uDEA8-\\uDEC0\\uDEC2-\\uDEDA\\uDEDC-\\uDEFA\\uDEFC-\\uDF14\\uDF16-\\uDF34\\uDF36-\\uDF4E\\uDF50-\\uDF6E\\uDF70-\\uDF88\\uDF8A-\\uDFA8\\uDFAA-\\uDFC2\\uDFC4-\\uDFCB]|\\uD837[\\uDF00-\\uDF1E\\uDF25-\\uDF2A]|\\uD838[\\uDC30-\\uDC6D\\uDD00-\\uDD2C\\uDD37-\\uDD3D\\uDD4E\\uDE90-\\uDEAD\\uDEC0-\\uDEEB]|\\uD839[\\uDCD0-\\uDCEB\\uDFE0-\\uDFE6\\uDFE8-\\uDFEB\\uDFED\\uDFEE\\uDFF0-\\uDFFE]|\\uD83A[\\uDC00-\\uDCC4\\uDD00-\\uDD43\\uDD4B]|\\uD83B[\\uDE00-\\uDE03\\uDE05-\\uDE1F\\uDE21\\uDE22\\uDE24\\uDE27\\uDE29-\\uDE32\\uDE34-\\uDE37\\uDE39\\uDE3B\\uDE42\\uDE47\\uDE49\\uDE4B\\uDE4D-\\uDE4F\\uDE51\\uDE52\\uDE54\\uDE57\\uDE59\\uDE5B\\uDE5D\\uDE5F\\uDE61\\uDE62\\uDE64\\uDE67-\\uDE6A\\uDE6C-\\uDE72\\uDE74-\\uDE77\\uDE79-\\uDE7C\\uDE7E\\uDE80-\\uDE89\\uDE8B-\\uDE9B\\uDEA1-\\uDEA3\\uDEA5-\\uDEA9\\uDEAB-\\uDEBB]|\\uD869[\\uDC00-\\uDEDF\\uDF00-\\uDFFF]|\\uD86D[\\uDC00-\\uDF39\\uDF40-\\uDFFF]|\\uD86E[\\uDC00-\\uDC1D\\uDC20-\\uDFFF]|\\uD873[\\uDC00-\\uDEA1\\uDEB0-\\uDFFF]|\\uD87A[\\uDC00-\\uDFE0]|\\uD87E[\\uDC00-\\uDE1D]|\\uD884[\\uDC00-\\uDF4A\\uDF50-\\uDFFF]|\\uD888[\\uDC00-\\uDFAF])(?:[0-9A-Za-z\\xAA\\xB5\\xBA\\xC0-\\xD6\\xD8-\\xF6\\xF8-\\u02C1\\u02C6-\\u02D1\\u02E0-\\u02E4\\u02EC\\u02EE\\u0370-\\u0374\\u0376\\u0377\\u037A-\\u037D\\u037F\\u0386\\u0388-\\u038A\\u038C\\u038E-\\u03A1\\u03A3-\\u03F5\\u03F7-\\u0481\\u048A-\\u052F\\u0531-\\u0556\\u0559\\u0560-\\u0588\\u05D0-\\u05EA\\u05EF-\\u05F2\\u0620-\\u064A\\u066E\\u066F\\u0671-\\u06D3\\u06D5\\u06E5\\u06E6\\u06EE\\u06EF\\u06FA-\\u06FC\\u06FF\\u0710\\u0712-\\u072F\\u074D-\\u07A5\\u07B1\\u07CA-\\u07EA\\u07F4\\u07F5\\u07FA\\u0800-\\u0815\\u081A\\u0824\\u0828\\u0840-\\u0858\\u0860-\\u086A\\u0870-\\u0887\\u0889-\\u088E\\u08A0-\\u08C9\\u0904-\\u0939\\u093D\\u0950\\u0958-\\u0961\\u0971-\\u0980\\u0985-\\u098C\\u098F\\u0990\\u0993-\\u09A8\\u09AA-\\u09B0\\u09B2\\u09B6-\\u09B9\\u09BD\\u09CE\\u09DC\\u09DD\\u09DF-\\u09E1\\u09F0\\u09F1\\u09FC\\u0A05-\\u0A0A\\u0A0F\\u0A10\\u0A13-\\u0A28\\u0A2A-\\u0A30\\u0A32\\u0A33\\u0A35\\u0A36\\u0A38\\u0A39\\u0A59-\\u0A5C\\u0A5E\\u0A72-\\u0A74\\u0A85-\\u0A8D\\u0A8F-\\u0A91\\u0A93-\\u0AA8\\u0AAA-\\u0AB0\\u0AB2\\u0AB3\\u0AB5-\\u0AB9\\u0ABD\\u0AD0\\u0AE0\\u0AE1\\u0AF9\\u0B05-\\u0B0C\\u0B0F\\u0B10\\u0B13-\\u0B28\\u0B2A-\\u0B30\\u0B32\\u0B33\\u0B35-\\u0B39\\u0B3D\\u0B5C\\u0B5D\\u0B5F-\\u0B61\\u0B71\\u0B83\\u0B85-\\u0B8A\\u0B8E-\\u0B90\\u0B92-\\u0B95\\u0B99\\u0B9A\\u0B9C\\u0B9E\\u0B9F\\u0BA3\\u0BA4\\u0BA8-\\u0BAA\\u0BAE-\\u0BB9\\u0BD0\\u0C05-\\u0C0C\\u0C0E-\\u0C10\\u0C12-\\u0C28\\u0C2A-\\u0C39\\u0C3D\\u0C58-\\u0C5A\\u0C5D\\u0C60\\u0C61\\u0C80\\u0C85-\\u0C8C\\u0C8E-\\u0C90\\u0C92-\\u0CA8\\u0CAA-\\u0CB3\\u0CB5-\\u0CB9\\u0CBD\\u0CDD\\u0CDE\\u0CE0\\u0CE1\\u0CF1\\u0CF2\\u0D04-\\u0D0C\\u0D0E-\\u0D10\\u0D12-\\u0D3A\\u0D3D\\u0D4E\\u0D54-\\u0D56\\u0D5F-\\u0D61\\u0D7A-\\u0D7F\\u0D85-\\u0D96\\u0D9A-\\u0DB1\\u0DB3-\\u0DBB\\u0DBD\\u0DC0-\\u0DC6\\u0E01-\\u0E30\\u0E32\\u0E33\\u0E40-\\u0E46\\u0E81\\u0E82\\u0E84\\u0E86-\\u0E8A\\u0E8C-\\u0EA3\\u0EA5\\u0EA7-\\u0EB0\\u0EB2\\u0EB3\\u0EBD\\u0EC0-\\u0EC4\\u0EC6\\u0EDC-\\u0EDF\\u0F00\\u0F40-\\u0F47\\u0F49-\\u0F6C\\u0F88-\\u0F8C\\u1000-\\u102A\\u103F\\u1050-\\u1055\\u105A-\\u105D\\u1061\\u1065\\u1066\\u106E-\\u1070\\u1075-\\u1081\\u108E\\u10A0-\\u10C5\\u10C7\\u10CD\\u10D0-\\u10FA\\u10FC-\\u1248\\u124A-\\u124D\\u1250-\\u1256\\u1258\\u125A-\\u125D\\u1260-\\u1288\\u128A-\\u128D\\u1290-\\u12B0\\u12B2-\\u12B5\\u12B8-\\u12BE\\u12C0\\u12C2-\\u12C5\\u12C8-\\u12D6\\u12D8-\\u1310\\u1312-\\u1315\\u1318-\\u135A\\u1380-\\u138F\\u13A0-\\u13F5\\u13F8-\\u13FD\\u1401-\\u166C\\u166F-\\u167F\\u1681-\\u169A\\u16A0-\\u16EA\\u16F1-\\u16F8\\u1700-\\u1711\\u171F-\\u1731\\u1740-\\u1751\\u1760-\\u176C\\u176E-\\u1770\\u1780-\\u17B3\\u17D7\\u17DC\\u1820-\\u1878\\u1880-\\u1884\\u1887-\\u18A8\\u18AA\\u18B0-\\u18F5\\u1900-\\u191E\\u1950-\\u196D\\u1970-\\u1974\\u1980-\\u19AB\\u19B0-\\u19C9\\u1A00-\\u1A16\\u1A20-\\u1A54\\u1AA7\\u1B05-\\u1B33\\u1B45-\\u1B4C\\u1B83-\\u1BA0\\u1BAE\\u1BAF\\u1BBA-\\u1BE5\\u1C00-\\u1C23\\u1C4D-\\u1C4F\\u1C5A-\\u1C7D\\u1C80-\\u1C88\\u1C90-\\u1CBA\\u1CBD-\\u1CBF\\u1CE9-\\u1CEC\\u1CEE-\\u1CF3\\u1CF5\\u1CF6\\u1CFA\\u1D00-\\u1DBF\\u1E00-\\u1F15\\u1F18-\\u1F1D\\u1F20-\\u1F45\\u1F48-\\u1F4D\\u1F50-\\u1F57\\u1F59\\u1F5B\\u1F5D\\u1F5F-\\u1F7D\\u1F80-\\u1FB4\\u1FB6-\\u1FBC\\u1FBE\\u1FC2-\\u1FC4\\u1FC6-\\u1FCC\\u1FD0-\\u1FD3\\u1FD6-\\u1FDB\\u1FE0-\\u1FEC\\u1FF2-\\u1FF4\\u1FF6-\\u1FFC\\u2071\\u207F\\u2090-\\u209C\\u2102\\u2107\\u210A-\\u2113\\u2115\\u2119-\\u211D\\u2124\\u2126\\u2128\\u212A-\\u212D\\u212F-\\u2139\\u213C-\\u213F\\u2145-\\u2149\\u214E\\u2183\\u2184\\u2C00-\\u2CE4\\u2CEB-\\u2CEE\\u2CF2\\u2CF3\\u2D00-\\u2D25\\u2D27\\u2D2D\\u2D30-\\u2D67\\u2D6F\\u2D80-\\u2D96\\u2DA0-\\u2DA6\\u2DA8-\\u2DAE\\u2DB0-\\u2DB6\\u2DB8-\\u2DBE\\u2DC0-\\u2DC6\\u2DC8-\\u2DCE\\u2DD0-\\u2DD6\\u2DD8-\\u2DDE\\u2E2F\\u3005\\u3006\\u3031-\\u3035\\u303B\\u303C\\u3041-\\u3096\\u309D-\\u309F\\u30A1-\\u30FA\\u30FC-\\u30FF\\u3105-\\u312F\\u3131-\\u318E\\u31A0-\\u31BF\\u31F0-\\u31FF\\u3400-\\u4DBF\\u4E00-\\uA48C\\uA4D0-\\uA4FD\\uA500-\\uA60C\\uA610-\\uA61F\\uA62A\\uA62B\\uA640-\\uA66E\\uA67F-\\uA69D\\uA6A0-\\uA6E5\\uA717-\\uA71F\\uA722-\\uA788\\uA78B-\\uA7CA\\uA7D0\\uA7D1\\uA7D3\\uA7D5-\\uA7D9\\uA7F2-\\uA801\\uA803-\\uA805\\uA807-\\uA80A\\uA80C-\\uA822\\uA840-\\uA873\\uA882-\\uA8B3\\uA8F2-\\uA8F7\\uA8FB\\uA8FD\\uA8FE\\uA90A-\\uA925\\uA930-\\uA946\\uA960-\\uA97C\\uA984-\\uA9B2\\uA9CF\\uA9E0-\\uA9E4\\uA9E6-\\uA9EF\\uA9FA-\\uA9FE\\uAA00-\\uAA28\\uAA40-\\uAA42\\uAA44-\\uAA4B\\uAA60-\\uAA76\\uAA7A\\uAA7E-\\uAAAF\\uAAB1\\uAAB5\\uAAB6\\uAAB9-\\uAABD\\uAAC0\\uAAC2\\uAADB-\\uAADD\\uAAE0-\\uAAEA\\uAAF2-\\uAAF4\\uAB01-\\uAB06\\uAB09-\\uAB0E\\uAB11-\\uAB16\\uAB20-\\uAB26\\uAB28-\\uAB2E\\uAB30-\\uAB5A\\uAB5C-\\uAB69\\uAB70-\\uABE2\\uAC00-\\uD7A3\\uD7B0-\\uD7C6\\uD7CB-\\uD7FB\\uF900-\\uFA6D\\uFA70-\\uFAD9\\uFB00-\\uFB06\\uFB13-\\uFB17\\uFB1D\\uFB1F-\\uFB28\\uFB2A-\\uFB36\\uFB38-\\uFB3C\\uFB3E\\uFB40\\uFB41\\uFB43\\uFB44\\uFB46-\\uFBB1\\uFBD3-\\uFD3D\\uFD50-\\uFD8F\\uFD92-\\uFDC7\\uFDF0-\\uFDFB\\uFE70-\\uFE74\\uFE76-\\uFEFC\\uFF21-\\uFF3A\\uFF41-\\uFF5A\\uFF66-\\uFFBE\\uFFC2-\\uFFC7\\uFFCA-\\uFFCF\\uFFD2-\\uFFD7\\uFFDA-\\uFFDC]|\\uD800[\\uDC00-\\uDC0B\\uDC0D-\\uDC26\\uDC28-\\uDC3A\\uDC3C\\uDC3D\\uDC3F-\\uDC4D\\uDC50-\\uDC5D\\uDC80-\\uDCFA\\uDE80-\\uDE9C\\uDEA0-\\uDED0\\uDF00-\\uDF1F\\uDF2D-\\uDF40\\uDF42-\\uDF49\\uDF50-\\uDF75\\uDF80-\\uDF9D\\uDFA0-\\uDFC3\\uDFC8-\\uDFCF]|\\uD801[\\uDC00-\\uDC9D\\uDCB0-\\uDCD3\\uDCD8-\\uDCFB\\uDD00-\\uDD27\\uDD30-\\uDD63\\uDD70-\\uDD7A\\uDD7C-\\uDD8A\\uDD8C-\\uDD92\\uDD94\\uDD95\\uDD97-\\uDDA1\\uDDA3-\\uDDB1\\uDDB3-\\uDDB9\\uDDBB\\uDDBC\\uDE00-\\uDF36\\uDF40-\\uDF55\\uDF60-\\uDF67\\uDF80-\\uDF85\\uDF87-\\uDFB0\\uDFB2-\\uDFBA]|\\uD802[\\uDC00-\\uDC05\\uDC08\\uDC0A-\\uDC35\\uDC37\\uDC38\\uDC3C\\uDC3F-\\uDC55\\uDC60-\\uDC76\\uDC80-\\uDC9E\\uDCE0-\\uDCF2\\uDCF4\\uDCF5\\uDD00-\\uDD15\\uDD20-\\uDD39\\uDD80-\\uDDB7\\uDDBE\\uDDBF\\uDE00\\uDE10-\\uDE13\\uDE15-\\uDE17\\uDE19-\\uDE35\\uDE60-\\uDE7C\\uDE80-\\uDE9C\\uDEC0-\\uDEC7\\uDEC9-\\uDEE4\\uDF00-\\uDF35\\uDF40-\\uDF55\\uDF60-\\uDF72\\uDF80-\\uDF91]|\\uD803[\\uDC00-\\uDC48\\uDC80-\\uDCB2\\uDCC0-\\uDCF2\\uDD00-\\uDD23\\uDE80-\\uDEA9\\uDEB0\\uDEB1\\uDF00-\\uDF1C\\uDF27\\uDF30-\\uDF45\\uDF70-\\uDF81\\uDFB0-\\uDFC4\\uDFE0-\\uDFF6]|\\uD804[\\uDC03-\\uDC37\\uDC71\\uDC72\\uDC75\\uDC83-\\uDCAF\\uDCD0-\\uDCE8\\uDD03-\\uDD26\\uDD44\\uDD47\\uDD50-\\uDD72\\uDD76\\uDD83-\\uDDB2\\uDDC1-\\uDDC4\\uDDDA\\uDDDC\\uDE00-\\uDE11\\uDE13-\\uDE2B\\uDE3F\\uDE40\\uDE80-\\uDE86\\uDE88\\uDE8A-\\uDE8D\\uDE8F-\\uDE9D\\uDE9F-\\uDEA8\\uDEB0-\\uDEDE\\uDF05-\\uDF0C\\uDF0F\\uDF10\\uDF13-\\uDF28\\uDF2A-\\uDF30\\uDF32\\uDF33\\uDF35-\\uDF39\\uDF3D\\uDF50\\uDF5D-\\uDF61]|\\uD805[\\uDC00-\\uDC34\\uDC47-\\uDC4A\\uDC5F-\\uDC61\\uDC80-\\uDCAF\\uDCC4\\uDCC5\\uDCC7\\uDD80-\\uDDAE\\uDDD8-\\uDDDB\\uDE00-\\uDE2F\\uDE44\\uDE80-\\uDEAA\\uDEB8\\uDF00-\\uDF1A\\uDF40-\\uDF46]|\\uD806[\\uDC00-\\uDC2B\\uDCA0-\\uDCDF\\uDCFF-\\uDD06\\uDD09\\uDD0C-\\uDD13\\uDD15\\uDD16\\uDD18-\\uDD2F\\uDD3F\\uDD41\\uDDA0-\\uDDA7\\uDDAA-\\uDDD0\\uDDE1\\uDDE3\\uDE00\\uDE0B-\\uDE32\\uDE3A\\uDE50\\uDE5C-\\uDE89\\uDE9D\\uDEB0-\\uDEF8]|\\uD807[\\uDC00-\\uDC08\\uDC0A-\\uDC2E\\uDC40\\uDC72-\\uDC8F\\uDD00-\\uDD06\\uDD08\\uDD09\\uDD0B-\\uDD30\\uDD46\\uDD60-\\uDD65\\uDD67\\uDD68\\uDD6A-\\uDD89\\uDD98\\uDEE0-\\uDEF2\\uDF02\\uDF04-\\uDF10\\uDF12-\\uDF33\\uDFB0]|\\uD808[\\uDC00-\\uDF99]|\\uD809[\\uDC80-\\uDD43]|\\uD80B[\\uDF90-\\uDFF0]|[\\uD80C\\uD81C-\\uD820\\uD822\\uD840-\\uD868\\uD86A-\\uD86C\\uD86F-\\uD872\\uD874-\\uD879\\uD880-\\uD883\\uD885-\\uD887][\\uDC00-\\uDFFF]|\\uD80D[\\uDC00-\\uDC2F\\uDC41-\\uDC46]|\\uD811[\\uDC00-\\uDE46]|\\uD81A[\\uDC00-\\uDE38\\uDE40-\\uDE5E\\uDE70-\\uDEBE\\uDED0-\\uDEED\\uDF00-\\uDF2F\\uDF40-\\uDF43\\uDF63-\\uDF77\\uDF7D-\\uDF8F]|\\uD81B[\\uDE40-\\uDE7F\\uDF00-\\uDF4A\\uDF50\\uDF93-\\uDF9F\\uDFE0\\uDFE1\\uDFE3]|\\uD821[\\uDC00-\\uDFF7]|\\uD823[\\uDC00-\\uDCD5\\uDD00-\\uDD08]|\\uD82B[\\uDFF0-\\uDFF3\\uDFF5-\\uDFFB\\uDFFD\\uDFFE]|\\uD82C[\\uDC00-\\uDD22\\uDD32\\uDD50-\\uDD52\\uDD55\\uDD64-\\uDD67\\uDD70-\\uDEFB]|\\uD82F[\\uDC00-\\uDC6A\\uDC70-\\uDC7C\\uDC80-\\uDC88\\uDC90-\\uDC99]|\\uD835[\\uDC00-\\uDC54\\uDC56-\\uDC9C\\uDC9E\\uDC9F\\uDCA2\\uDCA5\\uDCA6\\uDCA9-\\uDCAC\\uDCAE-\\uDCB9\\uDCBB\\uDCBD-\\uDCC3\\uDCC5-\\uDD05\\uDD07-\\uDD0A\\uDD0D-\\uDD14\\uDD16-\\uDD1C\\uDD1E-\\uDD39\\uDD3B-\\uDD3E\\uDD40-\\uDD44\\uDD46\\uDD4A-\\uDD50\\uDD52-\\uDEA5\\uDEA8-\\uDEC0\\uDEC2-\\uDEDA\\uDEDC-\\uDEFA\\uDEFC-\\uDF14\\uDF16-\\uDF34\\uDF36-\\uDF4E\\uDF50-\\uDF6E\\uDF70-\\uDF88\\uDF8A-\\uDFA8\\uDFAA-\\uDFC2\\uDFC4-\\uDFCB]|\\uD837[\\uDF00-\\uDF1E\\uDF25-\\uDF2A]|\\uD838[\\uDC30-\\uDC6D\\uDD00-\\uDD2C\\uDD37-\\uDD3D\\uDD4E\\uDE90-\\uDEAD\\uDEC0-\\uDEEB]|\\uD839[\\uDCD0-\\uDCEB\\uDFE0-\\uDFE6\\uDFE8-\\uDFEB\\uDFED\\uDFEE\\uDFF0-\\uDFFE]|\\uD83A[\\uDC00-\\uDCC4\\uDD00-\\uDD43\\uDD4B]|\\uD83B[\\uDE00-\\uDE03\\uDE05-\\uDE1F\\uDE21\\uDE22\\uDE24\\uDE27\\uDE29-\\uDE32\\uDE34-\\uDE37\\uDE39\\uDE3B\\uDE42\\uDE47\\uDE49\\uDE4B\\uDE4D-\\uDE4F\\uDE51\\uDE52\\uDE54\\uDE57\\uDE59\\uDE5B\\uDE5D\\uDE5F\\uDE61\\uDE62\\uDE64\\uDE67-\\uDE6A\\uDE6C-\\uDE72\\uDE74-\\uDE77\\uDE79-\\uDE7C\\uDE7E\\uDE80-\\uDE89\\uDE8B-\\uDE9B\\uDEA1-\\uDEA3\\uDEA5-\\uDEA9\\uDEAB-\\uDEBB]|\\uD869[\\uDC00-\\uDEDF\\uDF00-\\uDFFF]|\\uD86D[\\uDC00-\\uDF39\\uDF40-\\uDFFF]|\\uD86E[\\uDC00-\\uDC1D\\uDC20-\\uDFFF]|\\uD873[\\uDC00-\\uDEA1\\uDEB0-\\uDFFF]|\\uD87A[\\uDC00-\\uDFE0]|\\uD87E[\\uDC00-\\uDE1D]|\\uD884[\\uDC00-\\uDF4A\\uDF50-\\uDFFF]|\\uD888[\\uDC00-\\uDFAF])*$/.test(l)},{name:"string",test:St},{name:"Chain",test:bu},{name:"Array",test:Mr},{name:"Matrix",test:Qe},{name:"DenseMatrix",test:Xi},{name:"SparseMatrix",test:pa},{name:"Range",test:To},{name:"Index",test:Ai},{name:"boolean",test:cm},{name:"ResultSet",test:lm},{name:"Help",test:yu},{name:"function",test:mm},{name:"Date",test:pm},{name:"RegExp",test:dm},{name:"null",test:hm},{name:"undefined",test:vm},{name:"AccessorNode",test:qn},{name:"ArrayNode",test:jt},{name:"AssignmentNode",test:gm},{name:"BlockNode",test:xm},{name:"ConditionalNode",test:ym},{name:"ConstantNode",test:yr},{name:"FunctionNode",test:gn},{name:"FunctionAssignmentNode",test:_a},{name:"IndexNode",test:Qn},{name:"Node",test:Nr},{name:"ObjectNode",test:Ci},{name:"OperatorNode",test:ct},{name:"ParenthesisNode",test:en},{name:"RangeNode",test:bm},{name:"RelationalNode",test:wm},{name:"SymbolNode",test:at},{name:"Map",test:rw},{name:"Object",test:Mi}]),u.addConversions([{from:"number",to:"BigNumber",convert:function(c){if(t||tw(c),KA(c)>15)throw new TypeError("Cannot implicitly convert a number with >15 significant digits to BigNumber (value: "+c+"). Use function bignumber(x) to convert to BigNumber.");return new t(c)}},{from:"number",to:"Complex",convert:function(c){return n||Pm(c),new n(c,0)}},{from:"BigNumber",to:"Complex",convert:function(c){return n||Pm(c),new n(c.toNumber(),0)}},{from:"Fraction",to:"BigNumber",convert:function(c){throw new TypeError("Cannot implicitly convert a Fraction to BigNumber or vice versa. Use function bignumber(x) to convert to BigNumber or fraction(x) to convert to Fraction.")}},{from:"Fraction",to:"Complex",convert:function(c){return n||Pm(c),new n(c.valueOf(),0)}},{from:"number",to:"Fraction",convert:function(c){i||nw(c);var o=new i(c);if(o.valueOf()!==c)throw new TypeError("Cannot implicitly convert a number to a Fraction when there will be a loss of precision (value: "+c+"). Use function fraction(x) to convert to Fraction.");return o}},{from:"string",to:"number",convert:function(c){var o=Number(c);if(isNaN(o))throw new Error('Cannot convert "'+c+'" to a number');return o}},{from:"string",to:"BigNumber",convert:function(c){t||tw(c);try{return new t(c)}catch{throw new Error('Cannot convert "'+c+'" to BigNumber')}}},{from:"string",to:"Fraction",convert:function(c){i||nw(c);try{return new i(c)}catch{throw new Error('Cannot convert "'+c+'" to Fraction')}}},{from:"string",to:"Complex",convert:function(c){n||Pm(c);try{return new n(c)}catch{throw new Error('Cannot convert "'+c+'" to Complex')}}},{from:"boolean",to:"number",convert:function(c){return+c}},{from:"boolean",to:"BigNumber",convert:function(c){return t||tw(c),new t(+c)}},{from:"boolean",to:"Fraction",convert:function(c){return i||nw(c),new i(+c)}},{from:"boolean",to:"string",convert:function(c){return String(c)}},{from:"Array",to:"Matrix",convert:function(c){return a||sL(),new a(c)}},{from:"Matrix",to:"Array",convert:function(c){return c.valueOf()}}]),u.onMismatch=(l,c,o)=>{var s=u.createError(l,c,o);if(["wrongType","mismatch"].includes(s.data.category)&&c.length===1&&Nt(c[0])&&o.some(d=>!d.params.includes(","))){var m=new TypeError("Function '".concat(l,"' doesn't apply to matrices. To call it ")+"elementwise on a matrix 'M', try 'map(M, ".concat(l,")'."));throw m.data=s.data,m}throw s},u.onMismatch=(l,c,o)=>{var s=u.createError(l,c,o);if(["wrongType","mismatch"].includes(s.data.category)&&c.length===1&&Nt(c[0])&&o.some(d=>!d.params.includes(","))){var m=new TypeError("Function '".concat(l,"' doesn't apply to matrices. To call it ")+"elementwise on a matrix 'M', try 'map(M, ".concat(l,")'."));throw m.data=s.data,m}throw s},u});function tw(e){throw new Error("Cannot convert value ".concat(e," into a BigNumber: no class 'BigNumber' provided"))}function Pm(e){throw new Error("Cannot convert value ".concat(e," into a Complex number: no class 'Complex' provided"))}function sL(){throw new Error("Cannot convert array into a Matrix: no class 'DenseMatrix' provided")}function nw(e){throw new Error("Cannot convert value ".concat(e," into a Fraction, no class 'Fraction' provided."))}var uL="ResultSet",fL=[],Rm=F(uL,fL,()=>{function e(r){if(!(this instanceof e))throw new SyntaxError("Constructor must be called with the new operator");this.entries=r||[]}return e.prototype.type="ResultSet",e.prototype.isResultSet=!0,e.prototype.valueOf=function(){return this.entries},e.prototype.toString=function(){return"["+this.entries.join(", ")+"]"},e.prototype.toJSON=function(){return{mathjs:"ResultSet",entries:this.entries}},e.fromJSON=function(r){return new e(r.entries)},e},{isClass:!0});var Tu=9e15,Ro=1e9,iw="0123456789abcdef",qm="2.3025850929940456840179914546843642076011014886287729760333279009675726096773524802359972050895982983419677840422862486334095254650828067566662873690987816894829072083255546808437998948262331985283935053089653777326288461633662222876982198867465436674744042432743651550489343149393914796194044002221051017141748003688084012647080685567743216228355220114804663715659121373450747856947683463616792101806445070648000277502684916746550586856935673420670581136429224554405758925724208241314695689016758940256776311356919292033376587141660230105703089634572075440370847469940168269282808481184289314848524948644871927809676271275775397027668605952496716674183485704422507197965004714951050492214776567636938662976979522110718264549734772662425709429322582798502585509785265383207606726317164309505995087807523710333101197857547331541421808427543863591778117054309827482385045648019095610299291824318237525357709750539565187697510374970888692180205189339507238539205144634197265287286965110862571492198849978748873771345686209167058",Lm="3.1415926535897932384626433832795028841971693993751058209749445923078164062862089986280348253421170679821480865132823066470938446095505822317253594081284811174502841027019385211055596446229489549303819644288109756659334461284756482337867831652712019091456485669234603486104543266482133936072602491412737245870066063155881748815209209628292540917153643678925903600113305305488204665213841469519415116094330572703657595919530921861173819326117931051185480744623799627495673518857527248912279381830119491298336733624406566430860213949463952247371907021798609437027705392171762931767523846748184676694051320005681271452635608277857713427577896091736371787214684409012249534301465495853710507922796892589235420199561121290219608640344181598136297747713099605187072113499999983729780499510597317328160963185950244594553469083026425223082533446850352619311881710100031378387528865875332083814206171776691473035982534904287554687311595628638823537875937519577818577805321712268066130019278766111959092164201989380952572010654858632789",ow={precision:20,rounding:4,modulo:1,toExpNeg:-7,toExpPos:21,minE:-Tu,maxE:Tu,crypto:!1},AM,ji,Cr=!0,Um="[DecimalError] ",Io=Um+"Invalid argument: ",MM=Um+"Precision limit exceeded",CM=Um+"crypto unavailable",EM="[object Decimal]",Nn=Math.floor,nn=Math.pow,cL=/^0b([01]+(\\.[01]*)?|\\.[01]+)(p[+-]?\\d+)?$/i,lL=/^0x([0-9a-f]+(\\.[0-9a-f]*)?|\\.[0-9a-f]+)(p[+-]?\\d+)?$/i,mL=/^0o([0-7]+(\\.[0-7]*)?|\\.[0-7]+)(p[+-]?\\d+)?$/i,TM=/^(\\d+(\\.\\d*)?|\\.\\d+)(e[+-]?\\d+)?$/i,si=1e7,br=7,pL=9007199254740991,dL=qm.length-1,sw=Lm.length-1,Ue={toStringTag:EM};Ue.absoluteValue=Ue.abs=function(){var e=new this.constructor(this);return e.s<0&&(e.s=1),hr(e)};Ue.ceil=function(){return hr(new this.constructor(this),this.e+1,2)};Ue.clampedTo=Ue.clamp=function(e,r){var t,n=this,a=n.constructor;if(e=new a(e),r=new a(r),!e.s||!r.s)return new a(NaN);if(e.gt(r))throw Error(Io+r);return t=n.cmp(e),t<0?e:n.cmp(r)>0?r:new a(n)};Ue.comparedTo=Ue.cmp=function(e){var r,t,n,a,i=this,u=i.d,l=(e=new i.constructor(e)).d,c=i.s,o=e.s;if(!u||!l)return!c||!o?NaN:c!==o?c:u===l?0:!u^c<0?1:-1;if(!u[0]||!l[0])return u[0]?c:l[0]?-o:0;if(c!==o)return c;if(i.e!==e.e)return i.e>e.e^c<0?1:-1;for(n=u.length,a=l.length,r=0,t=nl[r]^c<0?1:-1;return n===a?0:n>a^c<0?1:-1};Ue.cosine=Ue.cos=function(){var e,r,t=this,n=t.constructor;return t.d?t.d[0]?(e=n.precision,r=n.rounding,n.precision=e+Math.max(t.e,t.sd())+br,n.rounding=1,t=hL(n,PM(n,t)),n.precision=e,n.rounding=r,hr(ji==2||ji==3?t.neg():t,e,r,!0)):new n(1):new n(NaN)};Ue.cubeRoot=Ue.cbrt=function(){var e,r,t,n,a,i,u,l,c,o,s=this,m=s.constructor;if(!s.isFinite()||s.isZero())return new m(s);for(Cr=!1,i=s.s*nn(s.s*s,1/3),!i||Math.abs(i)==1/0?(t=xn(s.d),e=s.e,(i=(e-t.length+1)%3)&&(t+=i==1||i==-2?"0":"00"),i=nn(t,1/3),e=Nn((e+1)/3)-(e%3==(e<0?-1:2)),i==1/0?t="5e"+e:(t=i.toExponential(),t=t.slice(0,t.indexOf("e")+1)+e),n=new m(t),n.s=s.s):n=new m(i.toString()),u=(e=m.precision)+3;;)if(l=n,c=l.times(l).times(l),o=c.plus(s),n=Dt(o.plus(s).times(l),o.plus(c),u+2,1),xn(l.d).slice(0,u)===(t=xn(n.d)).slice(0,u))if(t=t.slice(u-3,u+1),t=="9999"||!a&&t=="4999"){if(!a&&(hr(l,e+1,0),l.times(l).times(l).eq(s))){n=l;break}u+=4,a=1}else{(!+t||!+t.slice(1)&&t.charAt(0)=="5")&&(hr(n,e+1,1),r=!n.times(n).times(n).eq(s));break}return Cr=!0,hr(n,e,m.rounding,r)};Ue.decimalPlaces=Ue.dp=function(){var e,r=this.d,t=NaN;if(r){if(e=r.length-1,t=(e-Nn(this.e/br))*br,e=r[e],e)for(;e%10==0;e/=10)t--;t<0&&(t=0)}return t};Ue.dividedBy=Ue.div=function(e){return Dt(this,new this.constructor(e))};Ue.dividedToIntegerBy=Ue.divToInt=function(e){var r=this,t=r.constructor;return hr(Dt(r,new t(e),0,1,1),t.precision,t.rounding)};Ue.equals=Ue.eq=function(e){return this.cmp(e)===0};Ue.floor=function(){return hr(new this.constructor(this),this.e+1,3)};Ue.greaterThan=Ue.gt=function(e){return this.cmp(e)>0};Ue.greaterThanOrEqualTo=Ue.gte=function(e){var r=this.cmp(e);return r==1||r===0};Ue.hyperbolicCosine=Ue.cosh=function(){var e,r,t,n,a,i=this,u=i.constructor,l=new u(1);if(!i.isFinite())return new u(i.s?1/0:NaN);if(i.isZero())return l;t=u.precision,n=u.rounding,u.precision=t+Math.max(i.e,i.sd())+4,u.rounding=1,a=i.d.length,a<32?(e=Math.ceil(a/3),r=(1/Ym(4,e)).toString()):(e=16,r="2.3283064365386962890625e-10"),i=Fu(u,1,i.times(r),new u(1),!0);for(var c,o=e,s=new u(8);o--;)c=i.times(i),i=l.minus(c.times(s.minus(c.times(s))));return hr(i,u.precision=t,u.rounding=n,!0)};Ue.hyperbolicSine=Ue.sinh=function(){var e,r,t,n,a=this,i=a.constructor;if(!a.isFinite()||a.isZero())return new i(a);if(r=i.precision,t=i.rounding,i.precision=r+Math.max(a.e,a.sd())+4,i.rounding=1,n=a.d.length,n<3)a=Fu(i,2,a,a,!0);else{e=1.4*Math.sqrt(n),e=e>16?16:e|0,a=a.times(1/Ym(5,e)),a=Fu(i,2,a,a,!0);for(var u,l=new i(5),c=new i(16),o=new i(20);e--;)u=a.times(a),a=a.times(l.plus(u.times(c.times(u).plus(o))))}return i.precision=r,i.rounding=t,hr(a,r,t,!0)};Ue.hyperbolicTangent=Ue.tanh=function(){var e,r,t=this,n=t.constructor;return t.isFinite()?t.isZero()?new n(t):(e=n.precision,r=n.rounding,n.precision=e+7,n.rounding=1,Dt(t.sinh(),t.cosh(),n.precision=e,n.rounding=r)):new n(t.s)};Ue.inverseCosine=Ue.acos=function(){var e,r=this,t=r.constructor,n=r.abs().cmp(1),a=t.precision,i=t.rounding;return n!==-1?n===0?r.isNeg()?oi(t,a,i):new t(0):new t(NaN):r.isZero()?oi(t,a+4,i).times(.5):(t.precision=a+6,t.rounding=1,r=r.asin(),e=oi(t,a+4,i).times(.5),t.precision=a,t.rounding=i,e.minus(r))};Ue.inverseHyperbolicCosine=Ue.acosh=function(){var e,r,t=this,n=t.constructor;return t.lte(1)?new n(t.eq(1)?0:NaN):t.isFinite()?(e=n.precision,r=n.rounding,n.precision=e+Math.max(Math.abs(t.e),t.sd())+4,n.rounding=1,Cr=!1,t=t.times(t).minus(1).sqrt().plus(t),Cr=!0,n.precision=e,n.rounding=r,t.ln()):new n(t)};Ue.inverseHyperbolicSine=Ue.asinh=function(){var e,r,t=this,n=t.constructor;return!t.isFinite()||t.isZero()?new n(t):(e=n.precision,r=n.rounding,n.precision=e+2*Math.max(Math.abs(t.e),t.sd())+6,n.rounding=1,Cr=!1,t=t.times(t).plus(1).sqrt().plus(t),Cr=!0,n.precision=e,n.rounding=r,t.ln())};Ue.inverseHyperbolicTangent=Ue.atanh=function(){var e,r,t,n,a=this,i=a.constructor;return a.isFinite()?a.e>=0?new i(a.abs().eq(1)?a.s/0:a.isZero()?a:NaN):(e=i.precision,r=i.rounding,n=a.sd(),Math.max(n,e)<2*-a.e-1?hr(new i(a),e,r,!0):(i.precision=t=n-a.e,a=Dt(a.plus(1),new i(1).minus(a),t+e,1),i.precision=e+4,i.rounding=1,a=a.ln(),i.precision=e,i.rounding=r,a.times(.5))):new i(NaN)};Ue.inverseSine=Ue.asin=function(){var e,r,t,n,a=this,i=a.constructor;return a.isZero()?new i(a):(r=a.abs().cmp(1),t=i.precision,n=i.rounding,r!==-1?r===0?(e=oi(i,t+4,n).times(.5),e.s=a.s,e):new i(NaN):(i.precision=t+6,i.rounding=1,a=a.div(new i(1).minus(a.times(a)).sqrt().plus(1)).atan(),i.precision=t,i.rounding=n,a.times(2)))};Ue.inverseTangent=Ue.atan=function(){var e,r,t,n,a,i,u,l,c,o=this,s=o.constructor,m=s.precision,d=s.rounding;if(o.isFinite()){if(o.isZero())return new s(o);if(o.abs().eq(1)&&m+4<=sw)return u=oi(s,m+4,d).times(.25),u.s=o.s,u}else{if(!o.s)return new s(NaN);if(m+4<=sw)return u=oi(s,m+4,d).times(.5),u.s=o.s,u}for(s.precision=l=m+10,s.rounding=1,t=Math.min(28,l/br+2|0),e=t;e;--e)o=o.div(o.times(o).plus(1).sqrt().plus(1));for(Cr=!1,r=Math.ceil(l/br),n=1,c=o.times(o),u=new s(o),a=o;e!==-1;)if(a=a.times(c),i=u.minus(a.div(n+=2)),a=a.times(c),u=i.plus(a.div(n+=2)),u.d[r]!==void 0)for(e=r;u.d[e]===i.d[e]&&e--;);return t&&(u=u.times(2<this.d.length-2};Ue.isNaN=function(){return!this.s};Ue.isNegative=Ue.isNeg=function(){return this.s<0};Ue.isPositive=Ue.isPos=function(){return this.s>0};Ue.isZero=function(){return!!this.d&&this.d[0]===0};Ue.lessThan=Ue.lt=function(e){return this.cmp(e)<0};Ue.lessThanOrEqualTo=Ue.lte=function(e){return this.cmp(e)<1};Ue.logarithm=Ue.log=function(e){var r,t,n,a,i,u,l,c,o=this,s=o.constructor,m=s.precision,d=s.rounding,h=5;if(e==null)e=new s(10),r=!0;else{if(e=new s(e),t=e.d,e.s<0||!t||!t[0]||e.eq(1))return new s(NaN);r=e.eq(10)}if(t=o.d,o.s<0||!t||!t[0]||o.eq(1))return new s(t&&!t[0]?-1/0:o.s!=1?NaN:t?0:1/0);if(r)if(t.length>1)i=!0;else{for(a=t[0];a%10===0;)a/=10;i=a!==1}if(Cr=!1,l=m+h,u=Po(o,l),n=r?zm(s,l+10):Po(e,l),c=Dt(u,n,l,1),Tc(c.d,a=m,d))do if(l+=10,u=Po(o,l),n=r?zm(s,l+10):Po(e,l),c=Dt(u,n,l,1),!i){+xn(c.d).slice(a+1,a+15)+1==1e14&&(c=hr(c,m+1,0));break}while(Tc(c.d,a+=10,d));return Cr=!0,hr(c,m,d)};Ue.minus=Ue.sub=function(e){var r,t,n,a,i,u,l,c,o,s,m,d,h=this,x=h.constructor;if(e=new x(e),!h.d||!e.d)return!h.s||!e.s?e=new x(NaN):h.d?e.s=-e.s:e=new x(e.d||h.s!==e.s?h:NaN),e;if(h.s!=e.s)return e.s=-e.s,h.plus(e);if(o=h.d,d=e.d,l=x.precision,c=x.rounding,!o[0]||!d[0]){if(d[0])e.s=-e.s;else if(o[0])e=new x(h);else return new x(c===3?-0:0);return Cr?hr(e,l,c):e}if(t=Nn(e.e/br),s=Nn(h.e/br),o=o.slice(),i=s-t,i){for(m=i<0,m?(r=o,i=-i,u=d.length):(r=d,t=s,u=o.length),n=Math.max(Math.ceil(l/br),u)+2,i>n&&(i=n,r.length=1),r.reverse(),n=i;n--;)r.push(0);r.reverse()}else{for(n=o.length,u=d.length,m=n0;--n)o[u++]=0;for(n=d.length;n>i;){if(o[--n]u?i+1:u+1,a>u&&(a=u,t.length=1),t.reverse();a--;)t.push(0);t.reverse()}for(u=o.length,a=s.length,u-a<0&&(a=u,t=s,s=o,o=t),r=0;a;)r=(o[--a]=o[a]+s[a]+r)/si|0,o[a]%=si;for(r&&(o.unshift(r),++n),u=o.length;o[--u]==0;)o.pop();return e.d=o,e.e=Wm(o,n),Cr?hr(e,l,c):e};Ue.precision=Ue.sd=function(e){var r,t=this;if(e!==void 0&&e!==!!e&&e!==1&&e!==0)throw Error(Io+e);return t.d?(r=FM(t.d),e&&t.e+1>r&&(r=t.e+1)):r=NaN,r};Ue.round=function(){var e=this,r=e.constructor;return hr(new r(e),e.e+1,r.rounding)};Ue.sine=Ue.sin=function(){var e,r,t=this,n=t.constructor;return t.isFinite()?t.isZero()?new n(t):(e=n.precision,r=n.rounding,n.precision=e+Math.max(t.e,t.sd())+br,n.rounding=1,t=gL(n,PM(n,t)),n.precision=e,n.rounding=r,hr(ji>2?t.neg():t,e,r,!0)):new n(NaN)};Ue.squareRoot=Ue.sqrt=function(){var e,r,t,n,a,i,u=this,l=u.d,c=u.e,o=u.s,s=u.constructor;if(o!==1||!l||!l[0])return new s(!o||o<0&&(!l||l[0])?NaN:l?u:1/0);for(Cr=!1,o=Math.sqrt(+u),o==0||o==1/0?(r=xn(l),(r.length+c)%2==0&&(r+="0"),o=Math.sqrt(r),c=Nn((c+1)/2)-(c<0||c%2),o==1/0?r="5e"+c:(r=o.toExponential(),r=r.slice(0,r.indexOf("e")+1)+c),n=new s(r)):n=new s(o.toString()),t=(c=s.precision)+3;;)if(i=n,n=i.plus(Dt(u,i,t+2,1)).times(.5),xn(i.d).slice(0,t)===(r=xn(n.d)).slice(0,t))if(r=r.slice(t-3,t+1),r=="9999"||!a&&r=="4999"){if(!a&&(hr(i,c+1,0),i.times(i).eq(u))){n=i;break}t+=4,a=1}else{(!+r||!+r.slice(1)&&r.charAt(0)=="5")&&(hr(n,c+1,1),e=!n.times(n).eq(u));break}return Cr=!0,hr(n,c,s.rounding,e)};Ue.tangent=Ue.tan=function(){var e,r,t=this,n=t.constructor;return t.isFinite()?t.isZero()?new n(t):(e=n.precision,r=n.rounding,n.precision=e+10,n.rounding=1,t=t.sin(),t.s=1,t=Dt(t,new n(1).minus(t.times(t)).sqrt(),e+10,0),n.precision=e,n.rounding=r,hr(ji==2||ji==4?t.neg():t,e,r,!0)):new n(NaN)};Ue.times=Ue.mul=function(e){var r,t,n,a,i,u,l,c,o,s=this,m=s.constructor,d=s.d,h=(e=new m(e)).d;if(e.s*=s.s,!d||!d[0]||!h||!h[0])return new m(!e.s||d&&!d[0]&&!h||h&&!h[0]&&!d?NaN:!d||!h?e.s/0:e.s*0);for(t=Nn(s.e/br)+Nn(e.e/br),c=d.length,o=h.length,c=0;){for(r=0,a=c+n;a>n;)l=i[a]+h[n]*d[a-n-1]+r,i[a--]=l%si|0,r=l/si|0;i[a]=(i[a]+r)%si|0}for(;!i[--u];)i.pop();return r?++t:i.shift(),e.d=i,e.e=Wm(i,t),Cr?hr(e,m.precision,m.rounding):e};Ue.toBinary=function(e,r){return cw(this,2,e,r)};Ue.toDecimalPlaces=Ue.toDP=function(e,r){var t=this,n=t.constructor;return t=new n(t),e===void 0?t:(Jn(e,0,Ro),r===void 0?r=n.rounding:Jn(r,0,8),hr(t,e+t.e+1,r))};Ue.toExponential=function(e,r){var t,n=this,a=n.constructor;return e===void 0?t=Ti(n,!0):(Jn(e,0,Ro),r===void 0?r=a.rounding:Jn(r,0,8),n=hr(new a(n),e+1,r),t=Ti(n,!0,e+1)),n.isNeg()&&!n.isZero()?"-"+t:t};Ue.toFixed=function(e,r){var t,n,a=this,i=a.constructor;return e===void 0?t=Ti(a):(Jn(e,0,Ro),r===void 0?r=i.rounding:Jn(r,0,8),n=hr(new i(a),e+a.e+1,r),t=Ti(n,!1,e+n.e+1)),a.isNeg()&&!a.isZero()?"-"+t:t};Ue.toFraction=function(e){var r,t,n,a,i,u,l,c,o,s,m,d,h=this,x=h.d,v=h.constructor;if(!x)return new v(h);if(o=t=new v(1),n=c=new v(0),r=new v(n),i=r.e=FM(x)-h.e-1,u=i%br,r.d[0]=nn(10,u<0?br+u:u),e==null)e=i>0?r:o;else{if(l=new v(e),!l.isInt()||l.lt(o))throw Error(Io+l);e=l.gt(r)?i>0?r:o:l}for(Cr=!1,l=new v(xn(x)),s=v.precision,v.precision=i=x.length*br*2;m=Dt(l,r,0,1,1),a=t.plus(m.times(n)),a.cmp(e)!=1;)t=n,n=a,a=o,o=c.plus(m.times(a)),c=a,a=r,r=l.minus(m.times(a)),l=a;return a=Dt(e.minus(t),n,0,1,1),c=c.plus(a.times(o)),t=t.plus(a.times(n)),c.s=o.s=h.s,d=Dt(o,n,i,1).minus(h).abs().cmp(Dt(c,t,i,1).minus(h).abs())<1?[o,n]:[c,t],v.precision=s,Cr=!0,d};Ue.toHexadecimal=Ue.toHex=function(e,r){return cw(this,16,e,r)};Ue.toNearest=function(e,r){var t=this,n=t.constructor;if(t=new n(t),e==null){if(!t.d)return t;e=new n(1),r=n.rounding}else{if(e=new n(e),r===void 0?r=n.rounding:Jn(r,0,8),!t.d)return e.s?t:e;if(!e.d)return e.s&&(e.s=t.s),e}return e.d[0]?(Cr=!1,t=Dt(t,e,0,r,1).times(e),Cr=!0,hr(t)):(e.s=t.s,t=e),t};Ue.toNumber=function(){return+this};Ue.toOctal=function(e,r){return cw(this,8,e,r)};Ue.toPower=Ue.pow=function(e){var r,t,n,a,i,u,l=this,c=l.constructor,o=+(e=new c(e));if(!l.d||!e.d||!l.d[0]||!e.d[0])return new c(nn(+l,o));if(l=new c(l),l.eq(1))return l;if(n=c.precision,i=c.rounding,e.eq(1))return hr(l,n,i);if(r=Nn(e.e/br),r>=e.d.length-1&&(t=o<0?-o:o)<=pL)return a=_M(c,l,t,n),e.s<0?new c(1).div(a):hr(a,n,i);if(u=l.s,u<0){if(rc.maxE+1||r0?u/0:0):(Cr=!1,c.rounding=l.s=1,t=Math.min(12,(r+"").length),a=uw(e.times(Po(l,n+t)),n),a.d&&(a=hr(a,n+5,1),Tc(a.d,n,i)&&(r=n+10,a=hr(uw(e.times(Po(l,r+t)),r),r+5,1),+xn(a.d).slice(n+1,n+15)+1==1e14&&(a=hr(a,n+1,0)))),a.s=u,Cr=!0,c.rounding=i,hr(a,n,i))};Ue.toPrecision=function(e,r){var t,n=this,a=n.constructor;return e===void 0?t=Ti(n,n.e<=a.toExpNeg||n.e>=a.toExpPos):(Jn(e,1,Ro),r===void 0?r=a.rounding:Jn(r,0,8),n=hr(new a(n),e,r),t=Ti(n,e<=n.e||n.e<=a.toExpNeg,e)),n.isNeg()&&!n.isZero()?"-"+t:t};Ue.toSignificantDigits=Ue.toSD=function(e,r){var t=this,n=t.constructor;return e===void 0?(e=n.precision,r=n.rounding):(Jn(e,1,Ro),r===void 0?r=n.rounding:Jn(r,0,8)),hr(new n(t),e,r)};Ue.toString=function(){var e=this,r=e.constructor,t=Ti(e,e.e<=r.toExpNeg||e.e>=r.toExpPos);return e.isNeg()&&!e.isZero()?"-"+t:t};Ue.truncated=Ue.trunc=function(){return hr(new this.constructor(this),this.e+1,1)};Ue.valueOf=Ue.toJSON=function(){var e=this,r=e.constructor,t=Ti(e,e.e<=r.toExpNeg||e.e>=r.toExpPos);return e.isNeg()?"-"+t:t};function xn(e){var r,t,n,a=e.length-1,i="",u=e[0];if(a>0){for(i+=u,r=1;rt)throw Error(Io+e)}function Tc(e,r,t,n){var a,i,u,l;for(i=e[0];i>=10;i/=10)--r;return--r<0?(r+=br,a=0):(a=Math.ceil((r+1)/br),r%=br),i=nn(10,br-r),l=e[a]%i|0,n==null?r<3?(r==0?l=l/100|0:r==1&&(l=l/10|0),u=t<4&&l==99999||t>3&&l==49999||l==5e4||l==0):u=(t<4&&l+1==i||t>3&&l+1==i/2)&&(e[a+1]/i/100|0)==nn(10,r-2)-1||(l==i/2||l==0)&&(e[a+1]/i/100|0)==0:r<4?(r==0?l=l/1e3|0:r==1?l=l/100|0:r==2&&(l=l/10|0),u=(n||t<4)&&l==9999||!n&&t>3&&l==4999):u=((n||t<4)&&l+1==i||!n&&t>3&&l+1==i/2)&&(e[a+1]/i/1e3|0)==nn(10,r-3)-1,u}function km(e,r,t){for(var n,a=[0],i,u=0,l=e.length;ut-1&&(a[n+1]===void 0&&(a[n+1]=0),a[n+1]+=a[n]/t|0,a[n]%=t)}return a.reverse()}function hL(e,r){var t,n,a;if(r.isZero())return r;n=r.d.length,n<32?(t=Math.ceil(n/3),a=(1/Ym(4,t)).toString()):(t=16,a="2.3283064365386962890625e-10"),e.precision+=t,r=Fu(e,1,r.times(a),new e(1));for(var i=t;i--;){var u=r.times(r);r=u.times(u).minus(u).times(8).plus(1)}return e.precision-=t,r}var Dt=function(){function e(n,a,i){var u,l=0,c=n.length;for(n=n.slice();c--;)u=n[c]*a+l,n[c]=u%i|0,l=u/i|0;return l&&n.unshift(l),n}function r(n,a,i,u){var l,c;if(i!=u)c=i>u?1:-1;else for(l=c=0;la[l]?1:-1;break}return c}function t(n,a,i,u){for(var l=0;i--;)n[i]-=l,l=n[i]1;)n.shift()}return function(n,a,i,u,l,c){var o,s,m,d,h,x,v,y,w,C,b,M,A,S,O,_,E,T,R,q,W=n.constructor,G=n.s==a.s?1:-1,H=n.d,L=a.d;if(!H||!H[0]||!L||!L[0])return new W(!n.s||!a.s||(H?L&&H[0]==L[0]:!L)?NaN:H&&H[0]==0||!L?G*0:G/0);for(c?(h=1,s=n.e-a.e):(c=si,h=br,s=Nn(n.e/h)-Nn(a.e/h)),R=L.length,E=H.length,w=new W(G),C=w.d=[],m=0;L[m]==(H[m]||0);m++);if(L[m]>(H[m]||0)&&s--,i==null?(S=i=W.precision,u=W.rounding):l?S=i+(n.e-a.e)+1:S=i,S<0)C.push(1),x=!0;else{if(S=S/h+2|0,m=0,R==1){for(d=0,L=L[0],S++;(m1&&(L=e(L,d,c),H=e(H,d,c),R=L.length,E=H.length),_=R,b=H.slice(0,R),M=b.length;M=c/2&&++T;do d=0,o=r(L,b,R,M),o<0?(A=b[0],R!=M&&(A=A*c+(b[1]||0)),d=A/T|0,d>1?(d>=c&&(d=c-1),v=e(L,d,c),y=v.length,M=b.length,o=r(v,b,y,M),o==1&&(d--,t(v,R=10;d/=10)m++;w.e=m+s*h-1,hr(w,l?i+w.e+1:i,u,x)}return w}}();function hr(e,r,t,n){var a,i,u,l,c,o,s,m,d,h=e.constructor;e:if(r!=null){if(m=e.d,!m)return e;for(a=1,l=m[0];l>=10;l/=10)a++;if(i=r-a,i<0)i+=br,u=r,s=m[d=0],c=s/nn(10,a-u-1)%10|0;else if(d=Math.ceil((i+1)/br),l=m.length,d>=l)if(n){for(;l++<=d;)m.push(0);s=c=0,a=1,i%=br,u=i-br+1}else break e;else{for(s=l=m[d],a=1;l>=10;l/=10)a++;i%=br,u=i-br+a,c=u<0?0:s/nn(10,a-u-1)%10|0}if(n=n||r<0||m[d+1]!==void 0||(u<0?s:s%nn(10,a-u-1)),o=t<4?(c||n)&&(t==0||t==(e.s<0?3:2)):c>5||c==5&&(t==4||n||t==6&&(i>0?u>0?s/nn(10,a-u):0:m[d-1])%10&1||t==(e.s<0?8:7)),r<1||!m[0])return m.length=0,o?(r-=e.e+1,m[0]=nn(10,(br-r%br)%br),e.e=-r||0):m[0]=e.e=0,e;if(i==0?(m.length=d,l=1,d--):(m.length=d+1,l=nn(10,br-i),m[d]=u>0?(s/nn(10,a-u)%nn(10,u)|0)*l:0),o)for(;;)if(d==0){for(i=1,u=m[0];u>=10;u/=10)i++;for(u=m[0]+=l,l=1;u>=10;u/=10)l++;i!=l&&(e.e++,m[0]==si&&(m[0]=1));break}else{if(m[d]+=l,m[d]!=si)break;m[d--]=0,l=1}for(i=m.length;m[--i]===0;)m.pop()}return Cr&&(e.e>h.maxE?(e.d=null,e.e=NaN):e.e0?i=i.charAt(0)+"."+i.slice(1)+Bo(n):u>1&&(i=i.charAt(0)+"."+i.slice(1)),i=i+(e.e<0?"e":"e+")+e.e):a<0?(i="0."+Bo(-a-1)+i,t&&(n=t-u)>0&&(i+=Bo(n))):a>=u?(i+=Bo(a+1-u),t&&(n=t-a-1)>0&&(i=i+"."+Bo(n))):((n=a+1)0&&(a+1===u&&(i+="."),i+=Bo(n))),i}function Wm(e,r){var t=e[0];for(r*=br;t>=10;t/=10)r++;return r}function zm(e,r,t){if(r>dL)throw Cr=!0,t&&(e.precision=t),Error(MM);return hr(new e(qm),r,1,!0)}function oi(e,r,t){if(r>sw)throw Error(MM);return hr(new e(Lm),r,t,!0)}function FM(e){var r=e.length-1,t=r*br+1;if(r=e[r],r){for(;r%10==0;r/=10)t--;for(r=e[0];r>=10;r/=10)t++}return t}function Bo(e){for(var r="";e--;)r+="0";return r}function _M(e,r,t,n){var a,i=new e(1),u=Math.ceil(n/br+4);for(Cr=!1;;){if(t%2&&(i=i.times(r),SM(i.d,u)&&(a=!0)),t=Nn(t/2),t===0){t=i.d.length-1,a&&i.d[t]===0&&++i.d[t];break}r=r.times(r),SM(r.d,u)}return Cr=!0,i}function DM(e){return e.d[e.d.length-1]&1}function OM(e,r,t){for(var n,a=new e(r[0]),i=0;++i17)return new d(e.d?e.d[0]?e.s<0?0:1/0:1:e.s?e.s<0?0:e:0/0);for(r==null?(Cr=!1,c=x):c=r,l=new d(.03125);e.e>-2;)e=e.times(l),m+=5;for(n=Math.log(nn(2,m))/Math.LN10*2+5|0,c+=n,t=i=u=new d(1),d.precision=c;;){if(i=hr(i.times(e),c,1),t=t.times(++s),l=u.plus(Dt(i,t,c,1)),xn(l.d).slice(0,c)===xn(u.d).slice(0,c)){for(a=m;a--;)u=hr(u.times(u),c,1);if(r==null)if(o<3&&Tc(u.d,c-n,h,o))d.precision=c+=10,t=i=l=new d(1),s=0,o++;else return hr(u,d.precision=x,h,Cr=!0);else return d.precision=x,u}u=l}}function Po(e,r){var t,n,a,i,u,l,c,o,s,m,d,h=1,x=10,v=e,y=v.d,w=v.constructor,C=w.rounding,b=w.precision;if(v.s<0||!y||!y[0]||!v.e&&y[0]==1&&y.length==1)return new w(y&&!y[0]?-1/0:v.s!=1?NaN:y?0:v);if(r==null?(Cr=!1,s=b):s=r,w.precision=s+=x,t=xn(y),n=t.charAt(0),Math.abs(i=v.e)<15e14){for(;n<7&&n!=1||n==1&&t.charAt(1)>3;)v=v.times(e),t=xn(v.d),n=t.charAt(0),h++;i=v.e,n>1?(v=new w("0."+t),i++):v=new w(n+"."+t.slice(1))}else return o=zm(w,s+2,b).times(i+""),v=Po(new w(n+"."+t.slice(1)),s-x).plus(o),w.precision=b,r==null?hr(v,b,C,Cr=!0):v;for(m=v,c=u=v=Dt(v.minus(1),v.plus(1),s,1),d=hr(v.times(v),s,1),a=3;;){if(u=hr(u.times(d),s,1),o=c.plus(Dt(u,new w(a),s,1)),xn(o.d).slice(0,s)===xn(c.d).slice(0,s))if(c=c.times(2),i!==0&&(c=c.plus(zm(w,s+2,b).times(i+""))),c=Dt(c,new w(h),s,1),r==null)if(Tc(c.d,s-x,C,l))w.precision=s+=x,o=u=v=Dt(m.minus(1),m.plus(1),s,1),d=hr(v.times(v),s,1),a=l=1;else return hr(c,w.precision=b,C,Cr=!0);else return w.precision=b,c;c=o,a+=2}}function BM(e){return String(e.s*e.s/0)}function fw(e,r){var t,n,a;for((t=r.indexOf("."))>-1&&(r=r.replace(".","")),(n=r.search(/e/i))>0?(t<0&&(t=n),t+=+r.slice(n+1),r=r.substring(0,n)):t<0&&(t=r.length),n=0;r.charCodeAt(n)===48;n++);for(a=r.length;r.charCodeAt(a-1)===48;--a);if(r=r.slice(n,a),r){if(a-=n,e.e=t=t-n-1,e.d=[],n=(t+1)%br,t<0&&(n+=br),ne.constructor.maxE?(e.d=null,e.e=NaN):e.e-1){if(r=r.replace(/(\\d)_(?=\\d)/g,"$1"),TM.test(r))return fw(e,r)}else if(r==="Infinity"||r==="NaN")return+r||(e.s=NaN),e.e=NaN,e.d=null,e;if(lL.test(r))t=16,r=r.toLowerCase();else if(cL.test(r))t=2;else if(mL.test(r))t=8;else throw Error(Io+r);for(i=r.search(/p/i),i>0?(c=+r.slice(i+1),r=r.substring(2,i)):r=r.slice(2),i=r.indexOf("."),u=i>=0,n=e.constructor,u&&(r=r.replace(".",""),l=r.length,i=l-i,a=_M(n,new n(t),i,i*2)),o=km(r,t,si),s=o.length-1,i=s;o[i]===0;--i)o.pop();return i<0?new n(e.s*0):(e.e=Wm(o,s),e.d=o,Cr=!1,u&&(e=Dt(e,a,l*4)),c&&(e=e.times(Math.abs(c)<54?nn(2,c):Fc.pow(2,c))),Cr=!0,e)}function gL(e,r){var t,n=r.d.length;if(n<3)return r.isZero()?r:Fu(e,2,r,r);t=1.4*Math.sqrt(n),t=t>16?16:t|0,r=r.times(1/Ym(5,t)),r=Fu(e,2,r,r);for(var a,i=new e(5),u=new e(16),l=new e(20);t--;)a=r.times(r),r=r.times(i.plus(a.times(u.times(a).minus(l))));return r}function Fu(e,r,t,n,a){var i,u,l,c,o=1,s=e.precision,m=Math.ceil(s/br);for(Cr=!1,c=t.times(t),l=new e(n);;){if(u=Dt(l.times(c),new e(r++*r++),s,1),l=a?n.plus(u):n.minus(u),n=Dt(u.times(c),new e(r++*r++),s,1),u=l.plus(n),u.d[m]!==void 0){for(i=m;u.d[i]===l.d[i]&&i--;);if(i==-1)break}i=l,l=n,n=u,u=i,o++}return Cr=!0,u.d.length=m+1,u}function Ym(e,r){for(var t=e;--r;)t*=e;return t}function PM(e,r){var t,n=r.s<0,a=oi(e,e.precision,1),i=a.times(.5);if(r=r.abs(),r.lte(i))return ji=n?4:1,r;if(t=r.divToInt(a),t.isZero())ji=n?3:2;else{if(r=r.minus(t.times(a)),r.lte(i))return ji=DM(t)?n?2:3:n?4:1,r;ji=DM(t)?n?1:4:n?3:2}return r.minus(a).abs()}function cw(e,r,t,n){var a,i,u,l,c,o,s,m,d,h=e.constructor,x=t!==void 0;if(x?(Jn(t,1,Ro),n===void 0?n=h.rounding:Jn(n,0,8)):(t=h.precision,n=h.rounding),!e.isFinite())s=BM(e);else{for(s=Ti(e),u=s.indexOf("."),x?(a=2,r==16?t=t*4-3:r==8&&(t=t*3-2)):a=r,u>=0&&(s=s.replace(".",""),d=new h(1),d.e=s.length-u,d.d=km(Ti(d),10,a),d.e=d.d.length),m=km(s,10,a),i=c=m.length;m[--c]==0;)m.pop();if(!m[0])s=x?"0p+0":"0";else{if(u<0?i--:(e=new h(e),e.d=m,e.e=i,e=Dt(e,d,t,n,0,a),m=e.d,i=e.e,o=AM),u=m[t],l=a/2,o=o||m[t+1]!==void 0,o=n<4?(u!==void 0||o)&&(n===0||n===(e.s<0?3:2)):u>l||u===l&&(n===4||o||n===6&&m[t-1]&1||n===(e.s<0?8:7)),m.length=t,o)for(;++m[--t]>a-1;)m[t]=0,t||(++i,m.unshift(1));for(c=m.length;!m[c-1];--c);for(u=0,s="";u1)if(r==16||r==8){for(u=r==16?4:3,--c;c%u;c++)s+="0";for(m=km(s,a,r),c=m.length;!m[c-1];--c);for(u=1,s="1.";uc)for(i-=c;i--;)s+="0";else ir)return e.length=r,!0}function xL(e){return new this(e).abs()}function yL(e){return new this(e).acos()}function bL(e){return new this(e).acosh()}function wL(e,r){return new this(e).plus(r)}function DL(e){return new this(e).asin()}function SL(e){return new this(e).asinh()}function NL(e){return new this(e).atan()}function AL(e){return new this(e).atanh()}function ML(e,r){e=new this(e),r=new this(r);var t,n=this.precision,a=this.rounding,i=n+4;return!e.s||!r.s?t=new this(NaN):!e.d&&!r.d?(t=oi(this,i,1).times(r.s>0?.25:.75),t.s=e.s):!r.d||e.isZero()?(t=r.s<0?oi(this,n,a):new this(0),t.s=e.s):!e.d||r.isZero()?(t=oi(this,i,1).times(.5),t.s=e.s):r.s<0?(this.precision=i,this.rounding=1,t=this.atan(Dt(e,r,i,1)),r=oi(this,i,1),this.precision=n,this.rounding=a,t=e.s<0?t.minus(r):t.plus(r)):t=this.atan(Dt(e,r,i,1)),t}function CL(e){return new this(e).cbrt()}function EL(e){return hr(e=new this(e),e.e+1,2)}function TL(e,r,t){return new this(e).clamp(r,t)}function FL(e){if(!e||typeof e!="object")throw Error(Um+"Object expected");var r,t,n,a=e.defaults===!0,i=["precision",1,Ro,"rounding",0,8,"toExpNeg",-Tu,0,"toExpPos",0,Tu,"maxE",0,Tu,"minE",-Tu,0,"modulo",0,9];for(r=0;r=i[r+1]&&n<=i[r+2])this[t]=n;else throw Error(Io+t+": "+n);if(t="crypto",a&&(this[t]=ow[t]),(n=e[t])!==void 0)if(n===!0||n===!1||n===0||n===1)if(n)if(typeof crypto<"u"&&crypto&&(crypto.getRandomValues||crypto.randomBytes))this[t]=!0;else throw Error(CM);else this[t]=!1;else throw Error(Io+t+": "+n);return this}function _L(e){return new this(e).cos()}function OL(e){return new this(e).cosh()}function IM(e){var r,t,n;function a(i){var u,l,c,o=this;if(!(o instanceof a))return new a(i);if(o.constructor=a,NM(i)){o.s=i.s,Cr?!i.d||i.e>a.maxE?(o.e=NaN,o.d=null):i.e=10;l/=10)u++;Cr?u>a.maxE?(o.e=NaN,o.d=null):u=429e7?r[i]=crypto.getRandomValues(new Uint32Array(1))[0]:l[i++]=a%1e7;else if(crypto.randomBytes){for(r=crypto.randomBytes(n*=4);i=214e7?crypto.randomBytes(4).copy(r,i):(l.push(a%1e7),i+=4);i=n/4}else throw Error(CM);else for(;i=10;a/=10)n++;n{var{on:r,config:t}=e,n=Cs.clone({precision:t.precision,modulo:Cs.EUCLID});return n.prototype=Object.create(n.prototype),n.prototype.type="BigNumber",n.prototype.isBigNumber=!0,n.prototype.toJSON=function(){return{mathjs:"BigNumber",value:this.toString()}},n.fromJSON=function(a){return new n(a.value)},r&&r("config",function(a,i){a.precision!==i.precision&&n.config({precision:a.precision})}),n},{isClass:!0});var fn=ca(kM(),1);var iz="Complex",oz=[],$m=F(iz,oz,()=>(Object.defineProperty(fn.default,"name",{value:"Complex"}),fn.default.prototype.constructor=fn.default,fn.default.prototype.type="Complex",fn.default.prototype.isComplex=!0,fn.default.prototype.toJSON=function(){return{mathjs:"Complex",re:this.re,im:this.im}},fn.default.prototype.toPolar=function(){return{r:this.abs(),phi:this.arg()}},fn.default.prototype.format=function(e){var r="",t=this.im,n=this.re,a=ai(this.re,e),i=ai(this.im,e),u=sr(e)?e:e?e.precision:null;if(u!==null){var l=Math.pow(10,-u);Math.abs(n/t)r.re?1:e.rer.im?1:e.im(Object.defineProperty(Fi.default,"name",{value:"Fraction"}),Fi.default.prototype.constructor=Fi.default,Fi.default.prototype.type="Fraction",Fi.default.prototype.isFraction=!0,Fi.default.prototype.toJSON=function(){return{mathjs:"Fraction",n:this.s*this.n,d:this.d}},Fi.default.fromJSON=function(e){return new Fi.default(e)},Fi.default),{isClass:!0});var fz="Range",cz=[],Vm=F(fz,cz,()=>{function e(r,t,n){if(!(this instanceof e))throw new SyntaxError("Constructor must be called with the new operator");var a=r!=null,i=t!=null,u=n!=null;if(a){if(rr(r))r=r.toNumber();else if(typeof r!="number")throw new TypeError("Parameter start must be a number")}if(i){if(rr(t))t=t.toNumber();else if(typeof t!="number")throw new TypeError("Parameter end must be a number")}if(u){if(rr(n))n=n.toNumber();else if(typeof n!="number")throw new TypeError("Parameter step must be a number")}this.start=a?parseFloat(r):0,this.end=i?parseFloat(t):0,this.step=u?parseFloat(n):1}return e.prototype.type="Range",e.prototype.isRange=!0,e.parse=function(r){if(typeof r!="string")return null;var t=r.split(":"),n=t.map(function(i){return parseFloat(i)}),a=n.some(function(i){return isNaN(i)});if(a)return null;switch(n.length){case 2:return new e(n[0],n[1]);case 3:return new e(n[0],n[2],n[1]);default:return null}},e.prototype.clone=function(){return new e(this.start,this.end,this.step)},e.prototype.size=function(){var r=0,t=this.start,n=this.step,a=this.end,i=a-t;return Oa(n)===Oa(i)?r=Math.ceil(i/n):i===0&&(r=0),isNaN(r)&&(r=0),[r]},e.prototype.min=function(){var r=this.size()[0];if(r>0)return this.step>0?this.start:this.start+(r-1)*this.step},e.prototype.max=function(){var r=this.size()[0];if(r>0)return this.step>0?this.start+(r-1)*this.step:this.start},e.prototype.forEach=function(r){var t=this.start,n=this.step,a=this.end,i=0;if(n>0)for(;ta;)r(t,[i],this),t+=n,i++},e.prototype.map=function(r){var t=[];return this.forEach(function(n,a,i){t[a[0]]=r(n,a,i)}),t},e.prototype.toArray=function(){var r=[];return this.forEach(function(t,n){r[n[0]]=t}),r},e.prototype.valueOf=function(){return this.toArray()},e.prototype.format=function(r){var t=ai(this.start,r);return this.step!==1&&(t+=":"+ai(this.step,r)),t+=":"+ai(this.end,r),t},e.prototype.toString=function(){return this.format()},e.prototype.toJSON=function(){return{mathjs:"Range",start:this.start,end:this.end,step:this.step}},e.fromJSON=function(r){return new e(r.start,r.end,r.step)},e},{isClass:!0});var lz="Matrix",mz=[],Zm=F(lz,mz,()=>{function e(){if(!(this instanceof e))throw new SyntaxError("Constructor must be called with the new operator")}return e.prototype.type="Matrix",e.prototype.isMatrix=!0,e.prototype.storage=function(){throw new Error("Cannot invoke storage on a Matrix interface")},e.prototype.datatype=function(){throw new Error("Cannot invoke datatype on a Matrix interface")},e.prototype.create=function(r,t){throw new Error("Cannot invoke create on a Matrix interface")},e.prototype.subset=function(r,t,n){throw new Error("Cannot invoke subset on a Matrix interface")},e.prototype.get=function(r){throw new Error("Cannot invoke get on a Matrix interface")},e.prototype.set=function(r,t,n){throw new Error("Cannot invoke set on a Matrix interface")},e.prototype.resize=function(r,t){throw new Error("Cannot invoke resize on a Matrix interface")},e.prototype.reshape=function(r,t){throw new Error("Cannot invoke reshape on a Matrix interface")},e.prototype.clone=function(){throw new Error("Cannot invoke clone on a Matrix interface")},e.prototype.size=function(){throw new Error("Cannot invoke size on a Matrix interface")},e.prototype.map=function(r,t){throw new Error("Cannot invoke map on a Matrix interface")},e.prototype.forEach=function(r){throw new Error("Cannot invoke forEach on a Matrix interface")},e.prototype[Symbol.iterator]=function(){throw new Error("Cannot iterate a Matrix interface")},e.prototype.toArray=function(){throw new Error("Cannot invoke toArray on a Matrix interface")},e.prototype.valueOf=function(){throw new Error("Cannot invoke valueOf on a Matrix interface")},e.prototype.format=function(r){throw new Error("Cannot invoke format on a Matrix interface")},e.prototype.toString=function(){throw new Error("Cannot invoke toString on a Matrix interface")},e},{isClass:!0});function zM(e){var r=0,t=1,n=Object.create(null),a=Object.create(null),i=0,u=function(c){var o=a[c];if(!!o&&(delete n[o],delete a[c],--r,t===o)){if(!r){i=0,t=1;return}for(;!Object.prototype.hasOwnProperty.call(n,++t););}};return e=Math.abs(e),{hit:function(c){var o=a[c],s=++i;if(n[s]=c,a[c]=s,!o)return++r,r<=e?void 0:(c=n[t],u(c),c);if(delete n[o],t===o)for(;!Object.prototype.hasOwnProperty.call(n,++t););},delete:u,clear:function(){r=i=0,t=1,n=Object.create(null),a=Object.create(null)}}}function Es(e){var{hasher:r,limit:t}=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};return t=t??Number.POSITIVE_INFINITY,r=r??JSON.stringify,function n(){typeof n.cache!="object"&&(n.cache={values:new Map,lru:zM(t||Number.POSITIVE_INFINITY)});for(var a=[],i=0;i{var{Matrix:r}=e;function t(s,m){if(!(this instanceof t))throw new SyntaxError("Constructor must be called with the new operator");if(m&&!St(m))throw new Error("Invalid datatype: "+m);if(Qe(s))s.type==="DenseMatrix"?(this._data=ar(s._data),this._size=ar(s._size),this._datatype=m||s._datatype):(this._data=s.toArray(),this._size=s.size(),this._datatype=m||s._datatype);else if(s&&Mr(s.data)&&Mr(s.size))this._data=s.data,this._size=s.size,Qb(this._data,this._size),this._datatype=m||s.datatype;else if(Mr(s))this._data=o(s),this._size=ur(this._data),Qb(this._data,this._size),this._datatype=m;else{if(s)throw new TypeError("Unsupported type of data ("+Fr(s)+")");this._data=[],this._size=[0],this._datatype=m}}t.prototype=new r,t.prototype.createDenseMatrix=function(s,m){return new t(s,m)},Object.defineProperty(t,"name",{value:"DenseMatrix"}),t.prototype.constructor=t,t.prototype.type="DenseMatrix",t.prototype.isDenseMatrix=!0,t.prototype.getDataType=function(){return _o(this._data,Fr)},t.prototype.storage=function(){return"dense"},t.prototype.datatype=function(){return this._datatype},t.prototype.create=function(s,m){return new t(s,m)},t.prototype.subset=function(s,m,d){switch(arguments.length){case 1:return n(this,s);case 2:case 3:return i(this,s,m,d);default:throw new SyntaxError("Wrong number of arguments")}},t.prototype.get=function(s){if(!Mr(s))throw new TypeError("Array expected");if(s.length!==this._size.length)throw new pr(s.length,this._size.length);for(var m=0;m");var b=m.max().map(function(S){return S+1});c(s,b,h);var M=x.length,A=0;u(s._data,m,d,M,A)}return s}function u(s,m,d,h,x){var v=x===h-1,y=m.dimension(x);v?y.forEach(function(w,C){Kr(w),s[w]=d[C[0]]}):y.forEach(function(w,C){Kr(w),u(s[w],m,d[C[0]],h,x+1)})}t.prototype.resize=function(s,m,d){if(!Nt(s))throw new TypeError("Array or Matrix expected");var h=s.valueOf().map(v=>Array.isArray(v)&&v.length===1?v[0]:v),x=d?this.clone():this;return l(x,h,m)};function l(s,m,d){if(m.length===0){for(var h=s._data;Mr(h);)h=h[0];return h}return s._size=m.slice(0),s._data=ii(s._data,s._size,d),s}t.prototype.reshape=function(s,m){var d=m?this.clone():this;d._data=Mc(d._data,s);var h=d._size.reduce((x,v)=>x*v);return d._size=Cc(s,h),d};function c(s,m,d){for(var h=s._size.slice(0),x=!1;h.lengthh[v]&&(h[v]=m[v],x=!0);x&&l(s,h,d)}t.prototype.clone=function(){var s=new t({data:ar(this._data),size:ar(this._size),datatype:this._datatype});return s},t.prototype.size=function(){return this._size.slice(0)},t.prototype.map=function(s){var m=this,d=Qm(s),h=function y(w,C){return Mr(w)?w.map(function(b,M){return y(b,C.concat(M))}):d===1?s(w):d===2?s(w,C):s(w,C,m)},x=h(this._data,[]),v=this._datatype!==void 0?_o(x,Fr):void 0;return new t(x,v)},t.prototype.forEach=function(s){var m=this,d=function h(x,v){Mr(x)?x.forEach(function(y,w){h(y,v.concat(w))}):s(x,v,m)};d(this._data,[])},t.prototype[Symbol.iterator]=function*(){var s=function*m(d,h){if(Mr(d))for(var x=0;x[b[w]]);m.push(new t(C,s._datatype))},v=0;v0?s:0,d=s<0?-s:0,h=this._size[0],x=this._size[1],v=Math.min(h-d,x-m),y=[],w=0;w0?d:0,v=d<0?-d:0,y=s[0],w=s[1],C=Math.min(y-v,w-x),b;if(Mr(m)){if(m.length!==C)throw new Error("Invalid value array length");b=function(_){return m[_]}}else if(Qe(m)){var M=m.size();if(M.length!==1||M[0]!==C)throw new Error("Invalid matrix length");b=function(_){return m.get([_])}}else b=function(){return m};h||(h=rr(b(0))?b(0).mul(0):0);var A=[];if(s.length>0){A=ii(A,s,h);for(var S=0;S{var{typed:r}=e;return r(UM,{any:ar})});function Km(e){var r=e.length,t=e[0].length,n,a,i=[];for(a=0;a=n.length)throw new tn(r,n.length);return Qe(e)?e.create(jm(e.valueOf(),r,t)):jm(e,r,t)}function jm(e,r,t){var n,a,i,u;if(r<=0)if(Array.isArray(e[0])){for(u=Km(e),a=[],n=0;n{var{typed:r}=e;return r(WM,{number:Ze,BigNumber:function(n){return n.isInt()},Fraction:function(n){return n.d===1&&isFinite(n.n)},"Array | Matrix":r.referToSelf(t=>n=>je(n,t))})});var Kn="number",eo="number, number";function dw(e){return Math.abs(e)}dw.signature=Kn;function hw(e,r){return e+r}hw.signature=eo;function vw(e,r){return e-r}vw.signature=eo;function gw(e,r){return e*r}gw.signature=eo;function gz(e,r){return e/r}gz.signature=eo;function xw(e){return-e}xw.signature=Kn;function yw(e){return e}yw.signature=Kn;function _u(e){return QA(e)}_u.signature=Kn;function bw(e){return e*e*e}bw.signature=Kn;function ww(e){return Math.exp(e)}ww.signature=Kn;function Dw(e){return XA(e)}Dw.signature=Kn;function xz(e,r){if(!Ze(e)||!Ze(r))throw new Error("Parameters in function gcd must be integer numbers");for(var t;r!==0;)t=e%r,e=r,r=t;return e<0?-e:e}xz.signature=eo;function Sw(e,r){if(!Ze(e)||!Ze(r))throw new Error("Parameters in function lcm must be integer numbers");if(e===0||r===0)return 0;for(var t,n=e*r;r!==0;)t=r,r=e%t,e=t;return Math.abs(n/e)}Sw.signature=eo;function YM(e,r){return r?Math.log(e)/Math.log(r):Math.log(e)}function Nw(e){return ZA(e)}Nw.signature=Kn;function Aw(e){return VA(e)}Aw.signature=Kn;function yz(e){return Mm(e)}yz.signature=Kn;function bz(e,r){return r===0?e:e-r*Math.floor(e/r)}bz.signature=eo;function Mw(e){var r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:2,t=r<0;if(t&&(r=-r),r===0)throw new Error("Root must be non-zero");if(e<0&&Math.abs(r)%2!==1)throw new Error("Root must be odd when a is negative.");if(e===0)return t?1/0:0;if(!isFinite(e))return t?0:e;var n=Math.pow(Math.abs(e),1/r);return n=e<0?-n:n,t?1/n:n}function rp(e){return Oa(e)}rp.signature=Kn;function wz(e){return Math.sqrt(e)}wz.signature=Kn;function Cw(e){return e*e}Cw.signature=Kn;function Ew(e,r){var t,n,a,i=0,u=1,l=1,c=0;if(!Ze(e)||!Ze(r))throw new Error("Parameters in function xgcd must be integer numbers");for(;r;)n=Math.floor(e/r),a=e-n*r,t=i,i=u-n*i,u=t,t=l,l=c-n*l,c=t,e=r,r=a;var o;return e<0?o=[-e,-u,-c]:o=[e,e?u:0,c],o}Ew.signature=eo;function Tw(e,r){return e*e<1&&r===1/0||e*e>1&&r===-1/0?0:Math.pow(e,r)}Tw.signature=eo;function Ou(e){var r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:0;if(!Ze(r)||r<0||r>15)throw new Error("Number of decimals in function round must be an integer from 0 to 15 inclusive");return parseFloat(Gb(e,r))}function Dz(e){return Math.abs(e)}Dz.signature=Kn;var Sz="number",Bu="number, number";function Fw(e,r){if(!Ze(e)||!Ze(r))throw new Error("Integers expected in function bitAnd");return e&r}Fw.signature=Bu;function _w(e){if(!Ze(e))throw new Error("Integer expected in function bitNot");return~e}_w.signature=Sz;function Ow(e,r){if(!Ze(e)||!Ze(r))throw new Error("Integers expected in function bitOr");return e|r}Ow.signature=Bu;function Bw(e,r){if(!Ze(e)||!Ze(r))throw new Error("Integers expected in function bitXor");return e^r}Bw.signature=Bu;function Pw(e,r){if(!Ze(e)||!Ze(r))throw new Error("Integers expected in function leftShift");return e<>r}Iw.signature=Bu;function Rw(e,r){if(!Ze(e)||!Ze(r))throw new Error("Integers expected in function rightLogShift");return e>>>r}Rw.signature=Bu;function da(e,r){if(r>1;return da(e,t)*da(t+1,r)}function kw(e,r){if(!Ze(e)||e<0)throw new TypeError("Positive integer value expected in function combinations");if(!Ze(r)||r<0)throw new TypeError("Positive integer value expected in function combinations");if(r>e)throw new TypeError("k must be less than or equal to n");for(var t=e-r,n=1,a=r171?1/0:da(1,e-1);if(e<.5)return Math.PI/(Math.sin(Math.PI*e)*_c(1-e));if(e>=171.35)return 1/0;if(e>85){var t=e*e,n=t*e,a=n*e,i=a*e;return Math.sqrt(2*Math.PI/e)*Math.pow(e/Math.E,e)*(1+1/(12*e)+1/(288*t)-139/(51840*n)-571/(2488320*a)+163879/(209018880*i)+5246819/(75246796800*i*e))}--e,r=Ts[0];for(var u=1;u=1;n--)t+=ZM[n]/(e+n);return Hw+(e+.5)*Math.log(r)-r+Math.log(t)}Oc.signature="number";var Ct="number",Cz="number, number";function Ez(e){return Math.acos(e)}Ez.signature=Ct;function $w(e){return jA(e)}$w.signature=Ct;function Gw(e){return Math.atan(1/e)}Gw.signature=Ct;function Vw(e){return isFinite(e)?(Math.log((e+1)/e)+Math.log(e/(e-1)))/2:0}Vw.signature=Ct;function Zw(e){return Math.asin(1/e)}Zw.signature=Ct;function Qw(e){var r=1/e;return Math.log(r+Math.sqrt(r*r+1))}Qw.signature=Ct;function Xw(e){return Math.acos(1/e)}Xw.signature=Ct;function Jw(e){var r=1/e,t=Math.sqrt(r*r-1);return Math.log(t+r)}Jw.signature=Ct;function Tz(e){return Math.asin(e)}Tz.signature=Ct;function Kw(e){return eM(e)}Kw.signature=Ct;function Fz(e){return Math.atan(e)}Fz.signature=Ct;function _z(e,r){return Math.atan2(e,r)}_z.signature=Cz;function jw(e){return rM(e)}jw.signature=Ct;function Oz(e){return Math.cos(e)}Oz.signature=Ct;function Bz(e){return Em(e)}Bz.signature=Ct;function eD(e){return 1/Math.tan(e)}eD.signature=Ct;function rD(e){var r=Math.exp(2*e);return(r+1)/(r-1)}rD.signature=Ct;function tD(e){return 1/Math.sin(e)}tD.signature=Ct;function nD(e){return e===0?Number.POSITIVE_INFINITY:Math.abs(2/(Math.exp(e)-Math.exp(-e)))*Oa(e)}nD.signature=Ct;function aD(e){return 1/Math.cos(e)}aD.signature=Ct;function iD(e){return 2/(Math.exp(e)+Math.exp(-e))}iD.signature=Ct;function Pz(e){return Math.sin(e)}Pz.signature=Ct;function oD(e){return tM(e)}oD.signature=Ct;function Iz(e){return Math.tan(e)}Iz.signature=Ct;function Rz(e){return Tm(e)}Rz.signature=Ct;var Bc="number";function kz(e){return Ze(e)}kz.signature=Bc;function sD(e){return e<0}sD.signature=Bc;function uD(e){return e>0}uD.signature=Bc;function fD(e){return e===0}fD.signature=Bc;function cD(e){return Number.isNaN(e)}cD.signature=Bc;var QM="isNegative",qz=["typed"],tp=F(QM,qz,e=>{var{typed:r}=e;return r(QM,{number:sD,BigNumber:function(n){return n.isNeg()&&!n.isZero()&&!n.isNaN()},Fraction:function(n){return n.s<0},Unit:r.referToSelf(t=>n=>r.find(t,n.valueType())(n.value)),"Array | Matrix":r.referToSelf(t=>n=>je(n,t))})});var XM="isNumeric",Lz=["typed"],np=F(XM,Lz,e=>{var{typed:r}=e;return r(XM,{"number | BigNumber | Fraction | boolean":()=>!0,"Complex | Unit | string | null | undefined | Node":()=>!1,"Array | Matrix":r.referToSelf(t=>n=>je(n,t))})});var JM="hasNumericValue",zz=["typed","isNumeric"],ap=F(JM,zz,e=>{var{typed:r,isNumeric:t}=e;return r(JM,{boolean:()=>!0,string:function(a){return a.trim().length>0&&!isNaN(Number(a))},any:function(a){return t(a)}})});var KM="isPositive",Uz=["typed"],ip=F(KM,Uz,e=>{var{typed:r}=e;return r(KM,{number:uD,BigNumber:function(n){return!n.isNeg()&&!n.isZero()&&!n.isNaN()},Fraction:function(n){return n.s>0&&n.n>0},Unit:r.referToSelf(t=>n=>r.find(t,n.valueType())(n.value)),"Array | Matrix":r.referToSelf(t=>n=>je(n,t))})});var jM="isZero",Wz=["typed"],op=F(jM,Wz,e=>{var{typed:r}=e;return r(jM,{number:fD,BigNumber:function(n){return n.isZero()},Complex:function(n){return n.re===0&&n.im===0},Fraction:function(n){return n.d===1&&n.n===0},Unit:r.referToSelf(t=>n=>r.find(t,n.valueType())(n.value)),"Array | Matrix":r.referToSelf(t=>n=>je(n,t))})});var e2="isNaN",Yz=["typed"],sp=F(e2,Yz,e=>{var{typed:r}=e;return r(e2,{number:cD,BigNumber:function(n){return n.isNaN()},Fraction:function(n){return!1},Complex:function(n){return n.isNaN()},Unit:function(n){return Number.isNaN(n.value)},"Array | Matrix":function(n){return je(n,Number.isNaN)}})});var r2="typeOf",Hz=["typed"],up=F(r2,Hz,e=>{var{typed:r}=e;return r(r2,{any:Fr})});function $t(e,r,t){if(t==null)return e.eq(r);if(e.eq(r))return!0;if(e.isNaN()||r.isNaN())return!1;if(e.isFinite()&&r.isFinite()){var n=e.minus(r).abs();if(n.isZero())return!0;var a=e.constructor.max(e.abs(),r.abs());return n.lte(a.times(t))}return!1}function t2(e,r,t){return At(e.re,r.re,t)&&At(e.im,r.im,t)}var Pa=F("compareUnits",["typed"],e=>{var{typed:r}=e;return{"Unit, Unit":r.referToSelf(t=>(n,a)=>{if(!n.equalBase(a))throw new Error("Cannot compare units with different base");return r.find(t,[n.valueType(),a.valueType()])(n.value,a.value)})}});var fp="equalScalar",$z=["typed","config"],cp=F(fp,$z,e=>{var{typed:r,config:t}=e,n=Pa({typed:r});return r(fp,{"boolean, boolean":function(i,u){return i===u},"number, number":function(i,u){return At(i,u,t.epsilon)},"BigNumber, BigNumber":function(i,u){return i.eq(u)||$t(i,u,t.epsilon)},"Fraction, Fraction":function(i,u){return i.equals(u)},"Complex, Complex":function(i,u){return t2(i,u,t.epsilon)}},n)}),fee=F(fp,["typed","config"],e=>{var{typed:r,config:t}=e;return r(fp,{"number, number":function(a,i){return At(a,i,t.epsilon)}})});var Gz="SparseMatrix",Vz=["typed","equalScalar","Matrix"],lp=F(Gz,Vz,e=>{var{typed:r,equalScalar:t,Matrix:n}=e;function a(v,y){if(!(this instanceof a))throw new SyntaxError("Constructor must be called with the new operator");if(y&&!St(y))throw new Error("Invalid datatype: "+y);if(Qe(v))i(this,v,y);else if(v&&Mr(v.index)&&Mr(v.ptr)&&Mr(v.size))this._values=v.values,this._index=v.index,this._ptr=v.ptr,this._size=v.size,this._datatype=y||v.datatype;else if(Mr(v))u(this,v,y);else{if(v)throw new TypeError("Unsupported type of data ("+Fr(v)+")");this._values=[],this._index=[],this._ptr=[0],this._size=[0,0],this._datatype=y}}function i(v,y,w){y.type==="SparseMatrix"?(v._values=y._values?ar(y._values):void 0,v._index=ar(y._index),v._ptr=ar(y._ptr),v._size=ar(y._size),v._datatype=w||y._datatype):u(v,y.valueOf(),w||y._datatype)}function u(v,y,w){v._values=[],v._index=[],v._ptr=[],v._datatype=w;var C=y.length,b=0,M=t,A=0;if(St(w)&&(M=r.find(t,[w,w])||t,A=r.convert(0,w)),C>0){var S=0;do{v._ptr.push(v._index.length);for(var O=0;O");if(b.length===1){var _=y.dimension(0);_.forEach(function(R,q){Kr(R),v.set([R,0],w[q[0]],C)})}else{var E=y.dimension(0),T=y.dimension(1);E.forEach(function(R,q){Kr(R),T.forEach(function(W,G){Kr(W),v.set([R,W],w[q[0]][G[0]],C)})})}}return v}a.prototype.get=function(v){if(!Mr(v))throw new TypeError("Array expected");if(v.length!==this._size.length)throw new pr(v.length,this._size.length);if(!this._values)throw new Error("Cannot invoke get on a Pattern only matrix");var y=v[0],w=v[1];Kr(y,this._size[0]),Kr(w,this._size[1]);var C=o(y,this._ptr[w],this._ptr[w+1],this._index);return CM-1||b>A-1)&&(d(this,Math.max(C+1,M),Math.max(b+1,A),w),M=this._size[0],A=this._size[1]),Kr(C,M),Kr(b,A);var _=o(C,this._ptr[b],this._ptr[b+1],this._index);return _Array.isArray(M)&&M.length===1?M[0]:M);if(C.length!==2)throw new Error("Only two dimensions matrix are supported");C.forEach(function(M){if(!sr(M)||!Ze(M)||M<0)throw new TypeError("Invalid size, must contain positive integers (size: "+lr(C)+")")});var b=w?this.clone():this;return d(b,C[0],C[1],y)};function d(v,y,w,C){var b=C||0,M=t,A=0;St(v._datatype)&&(M=r.find(t,[v._datatype,v._datatype])||t,A=r.convert(0,v._datatype),b=r.convert(b,v._datatype));var S=!M(b,A),O=v._size[0],_=v._size[1],E,T,R;if(w>_){for(T=_;TO){if(S){var q=0;for(T=0;T<_;T++){v._ptr[T]=v._ptr[T]+q,R=v._ptr[T+1]+q;var W=0;for(E=O;Ey-1&&(v._values.splice(R,1),v._index.splice(R,1),G++)}v._ptr[T]=v._values.length}return v._size[0]=y,v._size[1]=w,v}a.prototype.reshape=function(v,y){if(!Mr(v))throw new TypeError("Array expected");if(v.length!==2)throw new Error("Sparse matrices can only be reshaped in two dimensions");v.forEach(function(z){if(!sr(z)||!Ze(z)||z<=-2||z===0)throw new TypeError("Invalid size, must contain positive integers or -1 (size: "+lr(v)+")")});var w=this._size[0]*this._size[1];v=Cc(v,w);var C=v[0]*v[1];if(w!==C)throw new Error("Reshaping sparse matrix will result in the wrong number of elements");var b=y?this.clone():this;if(this._size[0]===v[0]&&this._size[1]===v[1])return b;for(var M=[],A=0;A=y&&L<=w&&R(v._values[H],L-y,q-C)}else{for(var k={},K=W;K "+(this._values?lr(this._values[O],v):"X")}return b},a.prototype.toString=function(){return lr(this.toArray())},a.prototype.toJSON=function(){return{mathjs:"SparseMatrix",values:this._values,index:this._index,ptr:this._ptr,size:this._size,datatype:this._datatype}},a.prototype.diagonal=function(v){if(v){if(rr(v)&&(v=v.toNumber()),!sr(v)||!Ze(v))throw new TypeError("The parameter k must be an integer number")}else v=0;var y=v>0?v:0,w=v<0?-v:0,C=this._size[0],b=this._size[1],M=Math.min(C-w,b-y),A=[],S=[],O=[];O[0]=0;for(var _=y;_0?w:0,O=w<0?-w:0,_=v[0],E=v[1],T=Math.min(_-O,E-S),R;if(Mr(y)){if(y.length!==T)throw new Error("Invalid value array length");R=function(oe){return y[oe]}}else if(Qe(y)){var q=y.size();if(q.length!==1||q[0]!==T)throw new Error("Invalid matrix length");R=function(oe){return y.get([oe])}}else R=function(){return y};for(var W=[],G=[],H=[],L=0;L=0&&k=O||b[E]!==y)){var R=C?C[_]:void 0;b.splice(E,0,y),C&&C.splice(E,0,R),b.splice(E<=_?_+1:_,1),C&&C.splice(E<=_?_+1:_,1);continue}if(E=O||b[_]!==v)){var q=C?C[E]:void 0;b.splice(_,0,v),C&&C.splice(_,0,q),b.splice(_<=E?E+1:E,1),C&&C.splice(_<=E?E+1:E,1)}}},a},{isClass:!0});var Zz="number",Qz=["typed"];function Xz(e){var r=e.match(/(0[box])([0-9a-fA-F]*)\\.([0-9a-fA-F]*)/);if(r){var t={"0b":2,"0o":8,"0x":16}[r[1]],n=r[2],a=r[3];return{input:e,radix:t,integerPart:n,fractionalPart:a}}else return null}function Jz(e){for(var r=parseInt(e.integerPart,e.radix),t=0,n=0;n{var{typed:r}=e,t=r("number",{"":function(){return 0},number:function(a){return a},string:function(a){if(a==="NaN")return NaN;var i=Xz(a);if(i)return Jz(i);var u=0,l=a.match(/(0[box][0-9a-fA-F]*)i([0-9]*)/);l&&(u=Number(l[2]),a=l[1]);var c=Number(a);if(isNaN(c))throw new SyntaxError('String "'+a+'" is not a valid number');if(l){if(c>2**u-1)throw new SyntaxError('String "'.concat(a,'" is out of range'));c>=2**(u-1)&&(c=c-2**u)}return c},BigNumber:function(a){return a.toNumber()},Fraction:function(a){return a.valueOf()},Unit:r.referToSelf(n=>a=>{var i=a.clone();return i.value=n(a.value),i}),null:function(a){return 0},"Unit, string | Unit":function(a,i){return a.toNumber(i)},"Array | Matrix":r.referToSelf(n=>a=>je(a,n))});return t.fromJSON=function(n){return parseFloat(n.value)},t});var n2="string",Kz=["typed"],pp=F(n2,Kz,e=>{var{typed:r}=e;return r(n2,{"":function(){return""},number:ai,null:function(n){return"null"},boolean:function(n){return n+""},string:function(n){return n},"Array | Matrix":r.referToSelf(t=>n=>je(n,t)),any:function(n){return String(n)}})});var a2="boolean",jz=["typed"],dp=F(a2,jz,e=>{var{typed:r}=e;return r(a2,{"":function(){return!1},boolean:function(n){return n},number:function(n){return!!n},null:function(n){return!1},BigNumber:function(n){return!n.isZero()},string:function(n){var a=n.toLowerCase();if(a==="true")return!0;if(a==="false")return!1;var i=Number(n);if(n!==""&&!isNaN(i))return!!i;throw new Error('Cannot convert "'+n+'" to a boolean')},"Array | Matrix":r.referToSelf(t=>n=>je(n,t))})});var eU="bignumber",rU=["typed","BigNumber"],hp=F(eU,rU,e=>{var{typed:r,BigNumber:t}=e;return r("bignumber",{"":function(){return new t(0)},number:function(a){return new t(a+"")},string:function(a){var i=a.match(/(0[box][0-9a-fA-F]*)i([0-9]*)/);if(i){var u=i[2],l=t(i[1]),c=new t(2).pow(Number(u));if(l.gt(c.sub(1)))throw new SyntaxError('String "'.concat(a,'" is out of range'));var o=new t(2).pow(Number(u)-1);return l.gte(o)?l.sub(c):l}return new t(a)},BigNumber:function(a){return a},Unit:r.referToSelf(n=>a=>{var i=a.clone();return i.value=n(a.value),i}),Fraction:function(a){return new t(a.n).div(a.d).times(a.s)},null:function(a){return new t(0)},"Array | Matrix":r.referToSelf(n=>a=>je(a,n))})});var tU="complex",nU=["typed","Complex"],vp=F(tU,nU,e=>{var{typed:r,Complex:t}=e;return r("complex",{"":function(){return t.ZERO},number:function(a){return new t(a,0)},"number, number":function(a,i){return new t(a,i)},"BigNumber, BigNumber":function(a,i){return new t(a.toNumber(),i.toNumber())},Fraction:function(a){return new t(a.valueOf(),0)},Complex:function(a){return a.clone()},string:function(a){return t(a)},null:function(a){return t(0)},Object:function(a){if("re"in a&&"im"in a)return new t(a.re,a.im);if("r"in a&&"phi"in a||"abs"in a&&"arg"in a)return new t(a);throw new Error("Expected object with properties (re and im) or (r and phi) or (abs and arg)")},"Array | Matrix":r.referToSelf(n=>a=>je(a,n))})});var aU="fraction",iU=["typed","Fraction"],gp=F(aU,iU,e=>{var{typed:r,Fraction:t}=e;return r("fraction",{number:function(a){if(!isFinite(a)||isNaN(a))throw new Error(a+" cannot be represented as a fraction");return new t(a)},string:function(a){return new t(a)},"number, number":function(a,i){return new t(a,i)},null:function(a){return new t(0)},BigNumber:function(a){return new t(a.toString())},Fraction:function(a){return a},Unit:r.referToSelf(n=>a=>{var i=a.clone();return i.value=n(a.value),i}),Object:function(a){return new t(a)},"Array | Matrix":r.referToSelf(n=>a=>je(a,n))})});var i2="matrix",oU=["typed","Matrix","DenseMatrix","SparseMatrix"],xp=F(i2,oU,e=>{var{typed:r,Matrix:t,DenseMatrix:n,SparseMatrix:a}=e;return r(i2,{"":function(){return i([])},string:function(l){return i([],l)},"string, string":function(l,c){return i([],l,c)},Array:function(l){return i(l)},Matrix:function(l){return i(l,l.storage())},"Array | Matrix, string":i,"Array | Matrix, string, string":i});function i(u,l,c){if(l==="dense"||l==="default"||l===void 0)return new n(u,c);if(l==="sparse")return new a(u,c);throw new TypeError("Unknown matrix type "+JSON.stringify(l)+".")}});var o2="matrixFromFunction",sU=["typed","matrix","isZero"],yp=F(o2,sU,e=>{var{typed:r,matrix:t,isZero:n}=e;return r(o2,{"Array | Matrix, function, string, string":function(u,l,c,o){return a(u,l,c,o)},"Array | Matrix, function, string":function(u,l,c){return a(u,l,c)},"Matrix, function":function(u,l){return a(u,l,"dense")},"Array, function":function(u,l){return a(u,l,"dense").toArray()},"Array | Matrix, string, function":function(u,l,c){return a(u,c,l)},"Array | Matrix, string, string, function":function(u,l,c,o){return a(u,o,l,c)}});function a(i,u,l,c){var o;return c!==void 0?o=t(l,c):o=t(l),o.resize(i),o.forEach(function(s,m){var d=u(m);n(d)||o.set(m,d)}),o}});var s2="matrixFromRows",uU=["typed","matrix","flatten","size"],bp=F(s2,uU,e=>{var{typed:r,matrix:t,flatten:n,size:a}=e;return r(s2,{"...Array":function(c){return i(c)},"...Matrix":function(c){return t(i(c.map(o=>o.toArray())))}});function i(l){if(l.length===0)throw new TypeError("At least one row is needed to construct a matrix.");var c=u(l[0]),o=[];for(var s of l){var m=u(s);if(m!==c)throw new TypeError("The vectors had different length: "+(c|0)+" \\u2260 "+(m|0));o.push(n(s))}return o}function u(l){var c=a(l);if(c.length===1)return c[0];if(c.length===2){if(c[0]===1)return c[1];if(c[1]===1)return c[0];throw new TypeError("At least one of the arguments is not a vector.")}else throw new TypeError("Only one- or two-dimensional vectors are supported.")}});var u2="matrixFromColumns",fU=["typed","matrix","flatten","size"],wp=F(u2,fU,e=>{var{typed:r,matrix:t,flatten:n,size:a}=e;return r(u2,{"...Array":function(c){return i(c)},"...Matrix":function(c){return t(i(c.map(o=>o.toArray())))}});function i(l){if(l.length===0)throw new TypeError("At least one column is needed to construct a matrix.");for(var c=u(l[0]),o=[],s=0;s{var{typed:r}=e;return r(f2,{"Unit, Array":function(n,a){return n.splitUnit(a)}})});var c2="unaryMinus",lU=["typed"],Sp=F(c2,lU,e=>{var{typed:r}=e;return r(c2,{number:xw,"Complex | BigNumber | Fraction":t=>t.neg(),Unit:r.referToSelf(t=>n=>{var a=n.clone();return a.value=r.find(t,a.valueType())(n.value),a}),"Array | Matrix":r.referToSelf(t=>n=>je(n,t,!0))})});var l2="unaryPlus",mU=["typed","config","BigNumber"],Np=F(l2,mU,e=>{var{typed:r,config:t,BigNumber:n}=e;return r(l2,{number:yw,Complex:function(i){return i},BigNumber:function(i){return i},Fraction:function(i){return i},Unit:function(i){return i.clone()},"Array | Matrix":r.referToSelf(a=>i=>je(i,a,!0)),"boolean | string":function(i){return t.number==="BigNumber"?new n(+i):+i}})});var m2="abs",pU=["typed"],Ap=F(m2,pU,e=>{var{typed:r}=e;return r(m2,{number:dw,"Complex | BigNumber | Fraction | Unit":t=>t.abs(),"Array | Matrix":r.referToSelf(t=>n=>je(n,t,!0))})});var p2="apply",dU=["typed","isInteger"],qo=F(p2,dU,e=>{var{typed:r,isInteger:t}=e;return r(p2,{"Array | Matrix, number | BigNumber, function":function(a,i,u){if(!t(i))throw new TypeError("Integer number expected for dimension");var l=Array.isArray(a)?ur(a):a.size();if(i<0||i>=l.length)throw new tn(i,l.length);return Qe(a)?a.create(Mp(a.valueOf(),i,u)):Mp(a,i,u)}})});function Mp(e,r,t){var n,a,i;if(r<=0)if(Array.isArray(e[0])){for(i=hU(e),a=[],n=0;n{var{typed:r}=e;return r(d2,{"number, number":hw,"Complex, Complex":function(n,a){return n.add(a)},"BigNumber, BigNumber":function(n,a){return n.plus(a)},"Fraction, Fraction":function(n,a){return n.add(a)},"Unit, Unit":r.referToSelf(t=>(n,a)=>{if(n.value===null||n.value===void 0)throw new Error("Parameter x contains a unit with undefined value");if(a.value===null||a.value===void 0)throw new Error("Parameter y contains a unit with undefined value");if(!n.equalBase(a))throw new Error("Units do not match");var i=n.clone();return i.value=r.find(t,[i.valueType(),a.valueType()])(i.value,a.value),i.fixPrefix=!1,i})})});var h2="subtractScalar",gU=["typed"],Ep=F(h2,gU,e=>{var{typed:r}=e;return r(h2,{"number, number":vw,"Complex, Complex":function(n,a){return n.sub(a)},"BigNumber, BigNumber":function(n,a){return n.minus(a)},"Fraction, Fraction":function(n,a){return n.sub(a)},"Unit, Unit":r.referToSelf(t=>(n,a)=>{if(n.value===null||n.value===void 0)throw new Error("Parameter x contains a unit with undefined value");if(a.value===null||a.value===void 0)throw new Error("Parameter y contains a unit with undefined value");if(!n.equalBase(a))throw new Error("Units do not match");var i=n.clone();return i.value=r.find(t,[i.valueType(),a.valueType()])(i.value,a.value),i.fixPrefix=!1,i})})});var v2="cbrt",xU=["config","typed","isNegative","unaryMinus","matrix","Complex","BigNumber","Fraction"],Tp=F(v2,xU,e=>{var{config:r,typed:t,isNegative:n,unaryMinus:a,matrix:i,Complex:u,BigNumber:l,Fraction:c}=e;return t(v2,{number:_u,Complex:o,"Complex, boolean":o,BigNumber:function(d){return d.cbrt()},Unit:s});function o(m,d){var h=m.arg()/3,x=m.abs(),v=new u(_u(x),0).mul(new u(0,h).exp());if(d){var y=[v,new u(_u(x),0).mul(new u(0,h+Math.PI*2/3).exp()),new u(_u(x),0).mul(new u(0,h-Math.PI*2/3).exp())];return r.matrix==="Array"?y:i(y)}else return v}function s(m){if(m.value&&Kt(m.value)){var d=m.clone();return d.value=1,d=d.pow(1/3),d.value=o(m.value),d}else{var h=n(m.value);h&&(m.value=a(m.value));var x;rr(m.value)?x=new l(1).div(3):ma(m.value)?x=new c(1,3):x=1/3;var v=m.pow(x);return h&&(v.value=a(v.value)),v}}});var yU="matAlgo11xS0s",bU=["typed","equalScalar"],jr=F(yU,bU,e=>{var{typed:r,equalScalar:t}=e;return function(a,i,u,l){var c=a._values,o=a._index,s=a._ptr,m=a._size,d=a._datatype;if(!c)throw new Error("Cannot perform operation on Pattern Sparse Matrix and Scalar value");var h=m[0],x=m[1],v,y=t,w=0,C=u;typeof d=="string"&&(v=d,y=r.find(t,[v,v]),w=r.convert(0,v),i=r.convert(i,v),C=r.find(u,[v,v]));for(var b=[],M=[],A=[],S=0;S{var{typed:r,DenseMatrix:t}=e;return function(a,i,u,l){var c=a._values,o=a._index,s=a._ptr,m=a._size,d=a._datatype;if(!c)throw new Error("Cannot perform operation on Pattern Sparse Matrix and Scalar value");var h=m[0],x=m[1],v,y=u;typeof d=="string"&&(v=d,i=r.convert(i,v),y=r.find(u,[v,v]));for(var w=[],C=[],b=[],M=0;M{var{typed:r}=e;return function(a,i,u,l){var c=a._data,o=a._size,s=a._datatype,m,d=u;typeof s=="string"&&(m=s,i=r.convert(i,m),d=r.find(u,[m,m]));var h=o.length>0?t(d,0,o,o[0],c,i,l):[];return a.createDenseMatrix({data:h,size:ar(o),datatype:m})};function t(n,a,i,u,l,c,o){var s=[];if(a===i.length-1)for(var m=0;m{var{typed:r,config:t,round:n}=e;return r(lD,{number:function(i){return At(i,n(i),t.epsilon)?n(i):Math.ceil(i)},"number, number":function(i,u){if(At(i,n(i,u),t.epsilon))return n(i,u);var[l,c]="".concat(i,"e").split("e"),o=Math.ceil(Number("".concat(l,"e").concat(Number(c)+u)));return[l,c]="".concat(o,"e").split("e"),Number("".concat(l,"e").concat(Number(c)-u))}})}),Fp=F(lD,AU,e=>{var{typed:r,config:t,round:n,matrix:a,equalScalar:i,zeros:u,DenseMatrix:l}=e,c=jr({typed:r,equalScalar:i}),o=Wr({typed:r,DenseMatrix:l}),s=qt({typed:r}),m=MU({typed:r,config:t,round:n});return r("ceil",{number:m.signatures.number,"number,number":m.signatures["number,number"],Complex:function(h){return h.ceil()},"Complex, number":function(h,x){return h.ceil(x)},"Complex, BigNumber":function(h,x){return h.ceil(x.toNumber())},BigNumber:function(h){return $t(h,n(h),t.epsilon)?n(h):h.ceil()},"BigNumber, BigNumber":function(h,x){return $t(h,n(h,x),t.epsilon)?n(h,x):h.toDecimalPlaces(x.toNumber(),Cs.ROUND_CEIL)},Fraction:function(h){return h.ceil()},"Fraction, number":function(h,x){return h.ceil(x)},"Fraction, BigNumber":function(h,x){return h.ceil(x.toNumber())},"Array | Matrix":r.referToSelf(d=>h=>je(h,d,!0)),"Array, number | BigNumber":r.referToSelf(d=>(h,x)=>je(h,v=>d(v,x),!0)),"SparseMatrix, number | BigNumber":r.referToSelf(d=>(h,x)=>c(h,x,d,!1)),"DenseMatrix, number | BigNumber":r.referToSelf(d=>(h,x)=>s(h,x,d,!1)),"number | Complex | Fraction | BigNumber, Array":r.referToSelf(d=>(h,x)=>s(a(x),h,d,!0).valueOf()),"number | Complex | Fraction | BigNumber, Matrix":r.referToSelf(d=>(h,x)=>i(h,0)?u(x.size(),x.storage()):x.storage()==="dense"?s(x,h,d,!0):o(x,h,d,!0))})});var g2="cube",CU=["typed"],_p=F(g2,CU,e=>{var{typed:r}=e;return r(g2,{number:bw,Complex:function(n){return n.mul(n).mul(n)},BigNumber:function(n){return n.times(n).times(n)},Fraction:function(n){return n.pow(3)},Unit:function(n){return n.pow(3)}})});var x2="exp",EU=["typed"],Op=F(x2,EU,e=>{var{typed:r}=e;return r(x2,{number:ww,Complex:function(n){return n.exp()},BigNumber:function(n){return n.exp()}})});var y2="expm1",TU=["typed","Complex"],Bp=F(y2,TU,e=>{var{typed:r,Complex:t}=e;return r(y2,{number:Dw,Complex:function(a){var i=Math.exp(a.re);return new t(i*Math.cos(a.im)-1,i*Math.sin(a.im))},BigNumber:function(a){return a.exp().minus(1)}})});var mD="fix",FU=["typed","Complex","matrix","ceil","floor","equalScalar","zeros","DenseMatrix"],_U=F(mD,["typed","ceil","floor"],e=>{var{typed:r,ceil:t,floor:n}=e;return r(mD,{number:function(i){return i>0?n(i):t(i)},"number, number":function(i,u){return i>0?n(i,u):t(i,u)}})}),Pp=F(mD,FU,e=>{var{typed:r,Complex:t,matrix:n,ceil:a,floor:i,equalScalar:u,zeros:l,DenseMatrix:c}=e,o=Wr({typed:r,DenseMatrix:c}),s=qt({typed:r}),m=_U({typed:r,ceil:a,floor:i});return r("fix",{number:m.signatures.number,"number, number | BigNumber":m.signatures["number,number"],Complex:function(h){return new t(h.re>0?Math.floor(h.re):Math.ceil(h.re),h.im>0?Math.floor(h.im):Math.ceil(h.im))},"Complex, number":function(h,x){return new t(h.re>0?i(h.re,x):a(h.re,x),h.im>0?i(h.im,x):a(h.im,x))},"Complex, BigNumber":function(h,x){var v=x.toNumber();return new t(h.re>0?i(h.re,v):a(h.re,v),h.im>0?i(h.im,v):a(h.im,v))},BigNumber:function(h){return h.isNegative()?a(h):i(h)},"BigNumber, number | BigNumber":function(h,x){return h.isNegative()?a(h,x):i(h,x)},Fraction:function(h){return h.s<0?h.ceil():h.floor()},"Fraction, number | BigNumber":function(h,x){return h.s<0?a(h,x):i(h,x)},"Array | Matrix":r.referToSelf(d=>h=>je(h,d,!0)),"Array | Matrix, number | BigNumber":r.referToSelf(d=>(h,x)=>je(h,v=>d(v,x),!0)),"number | Complex | Fraction | BigNumber, Array":r.referToSelf(d=>(h,x)=>s(n(x),h,d,!0).valueOf()),"number | Complex | Fraction | BigNumber, Matrix":r.referToSelf(d=>(h,x)=>u(h,0)?l(x.size(),x.storage()):x.storage()==="dense"?s(x,h,d,!0):o(x,h,d,!0))})});var pD="floor",OU=["typed","config","round","matrix","equalScalar","zeros","DenseMatrix"],BU=F(pD,["typed","config","round"],e=>{var{typed:r,config:t,round:n}=e;return r(pD,{number:function(i){return At(i,n(i),t.epsilon)?n(i):Math.floor(i)},"number, number":function(i,u){if(At(i,n(i,u),t.epsilon))return n(i,u);var[l,c]="".concat(i,"e").split("e"),o=Math.floor(Number("".concat(l,"e").concat(Number(c)+u)));return[l,c]="".concat(o,"e").split("e"),Number("".concat(l,"e").concat(Number(c)-u))}})}),Pu=F(pD,OU,e=>{var{typed:r,config:t,round:n,matrix:a,equalScalar:i,zeros:u,DenseMatrix:l}=e,c=jr({typed:r,equalScalar:i}),o=Wr({typed:r,DenseMatrix:l}),s=qt({typed:r}),m=BU({typed:r,config:t,round:n});return r("floor",{number:m.signatures.number,"number,number":m.signatures["number,number"],Complex:function(h){return h.floor()},"Complex, number":function(h,x){return h.floor(x)},"Complex, BigNumber":function(h,x){return h.floor(x.toNumber())},BigNumber:function(h){return $t(h,n(h),t.epsilon)?n(h):h.floor()},"BigNumber, BigNumber":function(h,x){return $t(h,n(h,x),t.epsilon)?n(h,x):h.toDecimalPlaces(x.toNumber(),Cs.ROUND_FLOOR)},Fraction:function(h){return h.floor()},"Fraction, number":function(h,x){return h.floor(x)},"Fraction, BigNumber":function(h,x){return h.floor(x.toNumber())},"Array | Matrix":r.referToSelf(d=>h=>je(h,d,!0)),"Array, number | BigNumber":r.referToSelf(d=>(h,x)=>je(h,v=>d(v,x),!0)),"SparseMatrix, number | BigNumber":r.referToSelf(d=>(h,x)=>c(h,x,d,!1)),"DenseMatrix, number | BigNumber":r.referToSelf(d=>(h,x)=>s(h,x,d,!1)),"number | Complex | Fraction | BigNumber, Array":r.referToSelf(d=>(h,x)=>s(a(x),h,d,!0).valueOf()),"number | Complex | Fraction | BigNumber, Matrix":r.referToSelf(d=>(h,x)=>i(h,0)?u(x.size(),x.storage()):x.storage()==="dense"?s(x,h,d,!0):o(x,h,d,!0))})});var PU="matAlgo02xDS0",IU=["typed","equalScalar"],Lt=F(PU,IU,e=>{var{typed:r,equalScalar:t}=e;return function(a,i,u,l){var c=a._data,o=a._size,s=a._datatype||a.getDataType(),m=i._values,d=i._index,h=i._ptr,x=i._size,v=i._datatype||i._data===void 0?i._datatype:i.getDataType();if(o.length!==x.length)throw new pr(o.length,x.length);if(o[0]!==x[0]||o[1]!==x[1])throw new RangeError("Dimension mismatch. Matrix A ("+o+") must match Matrix B ("+x+")");if(!m)throw new Error("Cannot perform operation on Dense Matrix and Pattern Sparse Matrix");var y=o[0],w=o[1],C,b=t,M=0,A=u;typeof s=="string"&&s===v&&s!=="mixed"&&(C=s,b=r.find(t,[C,C]),M=r.convert(0,C),A=r.find(u,[C,C]));for(var S=[],O=[],_=[],E=0;E{var{typed:r}=e;return function(n,a,i,u){var l=n._data,c=n._size,o=n._datatype||n.getDataType(),s=a._values,m=a._index,d=a._ptr,h=a._size,x=a._datatype||a._data===void 0?a._datatype:a.getDataType();if(c.length!==h.length)throw new pr(c.length,h.length);if(c[0]!==h[0]||c[1]!==h[1])throw new RangeError("Dimension mismatch. Matrix A ("+c+") must match Matrix B ("+h+")");if(!s)throw new Error("Cannot perform operation on Dense Matrix and Pattern Sparse Matrix");var v=c[0],y=c[1],w,C=0,b=i;typeof o=="string"&&o===x&&o!=="mixed"&&(w=o,C=r.convert(0,w),b=r.find(i,[w,w]));for(var M=[],A=0;A{var{typed:r,equalScalar:t}=e;return function(a,i,u){var l=a._values,c=a._index,o=a._ptr,s=a._size,m=a._datatype||a._data===void 0?a._datatype:a.getDataType(),d=i._values,h=i._index,x=i._ptr,v=i._size,y=i._datatype||i._data===void 0?i._datatype:i.getDataType();if(s.length!==v.length)throw new pr(s.length,v.length);if(s[0]!==v[0]||s[1]!==v[1])throw new RangeError("Dimension mismatch. Matrix A ("+s+") must match Matrix B ("+v+")");var w=s[0],C=s[1],b,M=t,A=0,S=u;typeof m=="string"&&m===y&&m!=="mixed"&&(b=m,M=r.find(t,[b,b]),A=r.convert(0,b),S=r.find(u,[b,b]));var O=l&&d?[]:void 0,_=[],E=[],T=O?[]:void 0,R=O?[]:void 0,q=[],W=[],G,H,L,k;for(H=0;H{var{typed:r}=e;return function(a,i,u){var l=a._data,c=a._size,o=a._datatype,s=i._data,m=i._size,d=i._datatype,h=[];if(c.length!==m.length)throw new pr(c.length,m.length);for(var x=0;x0?t(y,0,h,h[0],l,s):[];return a.createDenseMatrix({data:w,size:h,datatype:v})};function t(n,a,i,u,l,c){var o=[];if(a===i.length-1)for(var s=0;s{var{concat:r}=e;return function(a,i){var u=Math.max(a._size.length,i._size.length);if(a._size.length===i._size.length&&a._size.every((x,v)=>x===i._size[v]))return[a,i];for(var l=t(a._size,u,0),c=t(i._size,u,0),o=[],s=0;s{var{typed:r,matrix:t,concat:n}=e,a=b2({typed:r}),i=qt({typed:r}),u=w2({concat:n});return function(c){var o=c.elop,s=c.SD||c.DS,m;o?(m={"DenseMatrix, DenseMatrix":(v,y)=>a(...u(v,y),o),"Array, Array":(v,y)=>a(...u(t(v),t(y)),o).valueOf(),"Array, DenseMatrix":(v,y)=>a(...u(t(v),y),o),"DenseMatrix, Array":(v,y)=>a(...u(v,t(y)),o)},c.SS&&(m["SparseMatrix, SparseMatrix"]=(v,y)=>c.SS(...u(v,y),o,!1)),c.DS&&(m["DenseMatrix, SparseMatrix"]=(v,y)=>c.DS(...u(v,y),o,!1),m["Array, SparseMatrix"]=(v,y)=>c.DS(...u(t(v),y),o,!1)),s&&(m["SparseMatrix, DenseMatrix"]=(v,y)=>s(...u(y,v),o,!0),m["SparseMatrix, Array"]=(v,y)=>s(...u(t(y),v),o,!0))):(m={"DenseMatrix, DenseMatrix":r.referToSelf(v=>(y,w)=>a(...u(y,w),v)),"Array, Array":r.referToSelf(v=>(y,w)=>a(...u(t(y),t(w)),v).valueOf()),"Array, DenseMatrix":r.referToSelf(v=>(y,w)=>a(...u(t(y),w),v)),"DenseMatrix, Array":r.referToSelf(v=>(y,w)=>a(...u(y,t(w)),v))},c.SS&&(m["SparseMatrix, SparseMatrix"]=r.referToSelf(v=>(y,w)=>c.SS(...u(y,w),v,!1))),c.DS&&(m["DenseMatrix, SparseMatrix"]=r.referToSelf(v=>(y,w)=>c.DS(...u(y,w),v,!1)),m["Array, SparseMatrix"]=r.referToSelf(v=>(y,w)=>c.DS(...u(t(y),w),v,!1))),s&&(m["SparseMatrix, DenseMatrix"]=r.referToSelf(v=>(y,w)=>s(...u(w,y),v,!0)),m["SparseMatrix, Array"]=r.referToSelf(v=>(y,w)=>s(...u(t(w),y),v,!0))));var d=c.scalar||"any",h=c.Ds||c.Ss;h&&(o?(m["DenseMatrix,"+d]=(v,y)=>i(v,y,o,!1),m[d+", DenseMatrix"]=(v,y)=>i(y,v,o,!0),m["Array,"+d]=(v,y)=>i(t(v),y,o,!1).valueOf(),m[d+", Array"]=(v,y)=>i(t(y),v,o,!0).valueOf()):(m["DenseMatrix,"+d]=r.referToSelf(v=>(y,w)=>i(y,w,v,!1)),m[d+", DenseMatrix"]=r.referToSelf(v=>(y,w)=>i(w,y,v,!0)),m["Array,"+d]=r.referToSelf(v=>(y,w)=>i(t(y),w,v,!1).valueOf()),m[d+", Array"]=r.referToSelf(v=>(y,w)=>i(t(w),y,v,!0).valueOf())));var x=c.sS!==void 0?c.sS:c.Ss;return o?(c.Ss&&(m["SparseMatrix,"+d]=(v,y)=>c.Ss(v,y,o,!1)),x&&(m[d+", SparseMatrix"]=(v,y)=>x(y,v,o,!0))):(c.Ss&&(m["SparseMatrix,"+d]=r.referToSelf(v=>(y,w)=>c.Ss(y,w,v,!1))),x&&(m[d+", SparseMatrix"]=r.referToSelf(v=>(y,w)=>x(w,y,v,!0)))),o&&o.signatures&&Dm(m,o.signatures),m}});var D2="mod",GU=["typed","config","round","matrix","equalScalar","zeros","DenseMatrix","concat"],Iu=F(D2,GU,e=>{var{typed:r,config:t,round:n,matrix:a,equalScalar:i,zeros:u,DenseMatrix:l,concat:c}=e,o=Pu({typed:r,config:t,round:n,matrix:a,equalScalar:i,zeros:u,DenseMatrix:l}),s=Lt({typed:r,equalScalar:i}),m=lt({typed:r}),d=Lo({typed:r,equalScalar:i}),h=jr({typed:r,equalScalar:i}),x=Wr({typed:r,DenseMatrix:l}),v=vr({typed:r,matrix:a,concat:c});return r(D2,{"number, number":y,"BigNumber, BigNumber":function(C,b){return b.isZero()?C:C.sub(b.mul(o(C.div(b))))},"Fraction, Fraction":function(C,b){return b.equals(0)?C:C.sub(b.mul(o(C.div(b))))}},v({SS:d,DS:m,SD:s,Ss:h,sS:x}));function y(w,C){return C===0?w:w-C*o(w/C)}});var VU="matAlgo01xDSid",ZU=["typed"],Mn=F(VU,ZU,e=>{var{typed:r}=e;return function(n,a,i,u){var l=n._data,c=n._size,o=n._datatype||n.getDataType(),s=a._values,m=a._index,d=a._ptr,h=a._size,x=a._datatype||a._data===void 0?a._datatype:a.getDataType();if(c.length!==h.length)throw new pr(c.length,h.length);if(c[0]!==h[0]||c[1]!==h[1])throw new RangeError("Dimension mismatch. Matrix A ("+c+") must match Matrix B ("+h+")");if(!s)throw new Error("Cannot perform operation on Dense Matrix and Pattern Sparse Matrix");var v=c[0],y=c[1],w=typeof o=="string"&&o!=="mixed"&&o===x?o:void 0,C=w?r.find(i,[w,w]):i,b,M,A=[];for(b=0;b{var{typed:r,equalScalar:t}=e;return function(a,i,u){var l=a._values,c=a._index,o=a._ptr,s=a._size,m=a._datatype||a._data===void 0?a._datatype:a.getDataType(),d=i._values,h=i._index,x=i._ptr,v=i._size,y=i._datatype||i._data===void 0?i._datatype:i.getDataType();if(s.length!==v.length)throw new pr(s.length,v.length);if(s[0]!==v[0]||s[1]!==v[1])throw new RangeError("Dimension mismatch. Matrix A ("+s+") must match Matrix B ("+v+")");var w=s[0],C=s[1],b,M=t,A=0,S=u;typeof m=="string"&&m===y&&m!=="mixed"&&(b=m,M=r.find(t,[b,b]),A=r.convert(0,b),S=r.find(u,[b,b]));var O=l&&d?[]:void 0,_=[],E=[],T=l&&d?[]:void 0,R=l&&d?[]:void 0,q=[],W=[],G,H,L,k,K;for(H=0;H{var{typed:r,DenseMatrix:t}=e;return function(a,i,u,l){var c=a._values,o=a._index,s=a._ptr,m=a._size,d=a._datatype;if(!c)throw new Error("Cannot perform operation on Pattern Sparse Matrix and Scalar value");var h=m[0],x=m[1],v,y=u;typeof d=="string"&&(v=d,i=r.convert(i,v),y=r.find(u,[v,v]));for(var w=[],C=[],b=[],M=0;MArray.isArray(r))}var Ip=F(S2,jU,e=>{var{typed:r,matrix:t,config:n,round:a,equalScalar:i,zeros:u,BigNumber:l,DenseMatrix:c,concat:o}=e,s=Iu({typed:r,config:n,round:a,matrix:t,equalScalar:i,zeros:u,DenseMatrix:c,concat:o}),m=Mn({typed:r}),d=Ru({typed:r,equalScalar:i}),h=jn({typed:r,DenseMatrix:c}),x=vr({typed:r,matrix:t,concat:o});return r(S2,{"number, number":v,"BigNumber, BigNumber":y,"Fraction, Fraction":(w,C)=>w.gcd(C)},x({SS:d,DS:m,Ss:h}),{[eW]:r.referToSelf(w=>(C,b,M)=>{for(var A=w(C,b),S=0;SC=>{if(C.length===1&&Array.isArray(C[0])&&N2(C[0]))return w(...C[0]);if(N2(C))return w(...C);throw new ha("gcd() supports only 1d matrices!")}),Matrix:r.referToSelf(w=>C=>w(C.toArray()))});function v(w,C){if(!Ze(w)||!Ze(C))throw new Error("Parameters in function gcd must be integer numbers");for(var b;C!==0;)b=s(w,C),w=C,C=b;return w<0?-w:w}function y(w,C){if(!w.isInt()||!C.isInt())throw new Error("Parameters in function gcd must be integer numbers");for(var b=new l(0);!C.isZero();){var M=s(w,C);w=C,C=M}return w.lt(b)?w.neg():w}});var rW="matAlgo06xS0S0",tW=["typed","equalScalar"],zo=F(rW,tW,e=>{var{typed:r,equalScalar:t}=e;return function(a,i,u){var l=a._values,c=a._size,o=a._datatype||a._data===void 0?a._datatype:a.getDataType(),s=i._values,m=i._size,d=i._datatype||i._data===void 0?i._datatype:i.getDataType();if(c.length!==m.length)throw new pr(c.length,m.length);if(c[0]!==m[0]||c[1]!==m[1])throw new RangeError("Dimension mismatch. Matrix A ("+c+") must match Matrix B ("+m+")");var h=c[0],x=c[1],v,y=t,w=0,C=u;typeof o=="string"&&o===d&&o!=="mixed"&&(v=o,y=r.find(t,[v,v]),w=r.convert(0,v),C=r.find(u,[v,v]));for(var b=l&&s?[]:void 0,M=[],A=[],S=b?[]:void 0,O=[],_=[],E=0;E{var{typed:r,matrix:t,equalScalar:n,concat:a}=e,i=Lt({typed:r,equalScalar:n}),u=zo({typed:r,equalScalar:n}),l=jr({typed:r,equalScalar:n}),c=vr({typed:r,matrix:t,concat:a}),o="number | BigNumber | Fraction | Matrix | Array",s={};return s["".concat(o,", ").concat(o,", ...").concat(o)]=r.referToSelf(d=>(h,x,v)=>{for(var y=d(h,x),w=0;wd.lcm(h)},c({SS:u,DS:i,Ss:l}),s);function m(d,h){if(!d.isInt()||!h.isInt())throw new Error("Parameters in function lcm must be integer numbers");if(d.isZero())return d;if(h.isZero())return h;for(var x=d.times(h);!h.isZero();){var v=h;h=d.mod(v),d=v}return x.div(d).abs()}});var M2="log10",aW=["typed","config","Complex"],kp=F(M2,aW,e=>{var{typed:r,config:t,Complex:n}=e;return r(M2,{number:function(i){return i>=0||t.predictable?Nw(i):new n(i,0).log().div(Math.LN10)},Complex:function(i){return new n(i).log().div(Math.LN10)},BigNumber:function(i){return!i.isNegative()||t.predictable?i.log():new n(i.toNumber(),0).log().div(Math.LN10)},"Array | Matrix":r.referToSelf(a=>i=>je(i,a))})});var C2="log2",iW=["typed","config","Complex"],qp=F(C2,iW,e=>{var{typed:r,config:t,Complex:n}=e;return r(C2,{number:function(u){return u>=0||t.predictable?Aw(u):a(new n(u,0))},Complex:a,BigNumber:function(u){return!u.isNegative()||t.predictable?u.log(2):a(new n(u.toNumber(),0))},"Array | Matrix":r.referToSelf(i=>u=>je(u,i))});function a(i){var u=Math.sqrt(i.re*i.re+i.im*i.im);return new n(Math.log2?Math.log2(u):Math.log(u)/Math.LN2,Math.atan2(i.im,i.re)/Math.LN2)}});var oW="multiplyScalar",sW=["typed"],Lp=F(oW,sW,e=>{var{typed:r}=e;return r("multiplyScalar",{"number, number":gw,"Complex, Complex":function(n,a){return n.mul(a)},"BigNumber, BigNumber":function(n,a){return n.times(a)},"Fraction, Fraction":function(n,a){return n.mul(a)},"number | Fraction | BigNumber | Complex, Unit":(t,n)=>n.multiply(t),"Unit, number | Fraction | BigNumber | Complex | Unit":(t,n)=>t.multiply(n)})});var E2="multiply",uW=["typed","matrix","addScalar","multiplyScalar","equalScalar","dot"],zp=F(E2,uW,e=>{var{typed:r,matrix:t,addScalar:n,multiplyScalar:a,equalScalar:i,dot:u}=e,l=jr({typed:r,equalScalar:i}),c=qt({typed:r});function o(A,S){switch(A.length){case 1:switch(S.length){case 1:if(A[0]!==S[0])throw new RangeError("Dimension mismatch in multiplication. Vectors must have the same length");break;case 2:if(A[0]!==S[0])throw new RangeError("Dimension mismatch in multiplication. Vector length ("+A[0]+") must match Matrix rows ("+S[0]+")");break;default:throw new Error("Can only multiply a 1 or 2 dimensional matrix (Matrix B has "+S.length+" dimensions)")}break;case 2:switch(S.length){case 1:if(A[1]!==S[0])throw new RangeError("Dimension mismatch in multiplication. Matrix columns ("+A[1]+") must match Vector length ("+S[0]+")");break;case 2:if(A[1]!==S[0])throw new RangeError("Dimension mismatch in multiplication. Matrix A columns ("+A[1]+") must match Matrix B rows ("+S[0]+")");break;default:throw new Error("Can only multiply a 1 or 2 dimensional matrix (Matrix B has "+S.length+" dimensions)")}break;default:throw new Error("Can only multiply a 1 or 2 dimensional matrix (Matrix A has "+A.length+" dimensions)")}}function s(A,S,O){if(O===0)throw new Error("Cannot multiply two empty vectors");return u(A,S)}function m(A,S){if(S.storage()!=="dense")throw new Error("Support for SparseMatrix not implemented");return d(A,S)}function d(A,S){var O=A._data,_=A._size,E=A._datatype||A.getDataType(),T=S._data,R=S._size,q=S._datatype||S.getDataType(),W=_[0],G=R[1],H,L=n,k=a;E&&q&&E===q&&typeof E=="string"&&E!=="mixed"&&(H=E,L=r.find(n,[H,H]),k=r.find(a,[H,H]));for(var K=[],z=0;zge)for(var xe=0,be=0;be(S,O)=>{o(ur(S),ur(O));var _=A(t(S),t(O));return Qe(_)?_.valueOf():_}),"Matrix, Matrix":function(S,O){var _=S.size(),E=O.size();return o(_,E),_.length===1?E.length===1?s(S,O,_[0]):m(S,O):E.length===1?h(S,O):x(S,O)},"Matrix, Array":r.referTo("Matrix,Matrix",A=>(S,O)=>A(S,t(O))),"Array, Matrix":r.referToSelf(A=>(S,O)=>A(t(S,O.storage()),O)),"SparseMatrix, any":function(S,O){return l(S,O,a,!1)},"DenseMatrix, any":function(S,O){return c(S,O,a,!1)},"any, SparseMatrix":function(S,O){return l(O,S,a,!0)},"any, DenseMatrix":function(S,O){return c(O,S,a,!0)},"Array, any":function(S,O){return c(t(S),O,a,!1).valueOf()},"any, Array":function(S,O){return c(t(O),S,a,!0).valueOf()},"any, any":a,"any, any, ...any":r.referToSelf(A=>(S,O,_)=>{for(var E=A(S,O),T=0;T<_.length;T++)E=A(E,_[T]);return E})})});var T2="nthRoot",fW=["typed","matrix","equalScalar","BigNumber","concat"],Up=F(T2,fW,e=>{var{typed:r,matrix:t,equalScalar:n,BigNumber:a,concat:i}=e,u=Mn({typed:r}),l=Lt({typed:r,equalScalar:n}),c=zo({typed:r,equalScalar:n}),o=jr({typed:r,equalScalar:n}),s=vr({typed:r,matrix:t,concat:i});function m(){throw new Error("Complex number not supported in function nthRoot. Use nthRoots instead.")}return r(T2,{number:Mw,"number, number":Mw,BigNumber:h=>d(h,new a(2)),"BigNumber, BigNumber":d,Complex:m,"Complex, number":m,Array:r.referTo("DenseMatrix,number",h=>x=>h(t(x),2).valueOf()),DenseMatrix:r.referTo("DenseMatrix,number",h=>x=>h(x,2)),SparseMatrix:r.referTo("SparseMatrix,number",h=>x=>h(x,2)),"SparseMatrix, SparseMatrix":r.referToSelf(h=>(x,v)=>{if(v.density()===1)return c(x,v,h);throw new Error("Root must be non-zero")}),"DenseMatrix, SparseMatrix":r.referToSelf(h=>(x,v)=>{if(v.density()===1)return u(x,v,h,!1);throw new Error("Root must be non-zero")}),"Array, SparseMatrix":r.referTo("DenseMatrix,SparseMatrix",h=>(x,v)=>h(t(x),v)),"number | BigNumber, SparseMatrix":r.referToSelf(h=>(x,v)=>{if(v.density()===1)return o(v,x,h,!0);throw new Error("Root must be non-zero")})},s({scalar:"number | BigNumber",SD:l,Ss:o,sS:!1}));function d(h,x){var v=a.precision,y=a.clone({precision:v+2}),w=new a(0),C=new y(1),b=x.isNegative();if(b&&(x=x.neg()),x.isZero())throw new Error("Root must be non-zero");if(h.isNegative()&&!x.abs().mod(2).equals(1))throw new Error("Root must be odd when a is negative.");if(h.isZero())return b?new y(1/0):0;if(!h.isFinite())return b?w:h;var M=h.abs().pow(C.div(x));return M=h.isNeg()?M.neg():M,new a((b?C.div(M):M).toPrecision(v))}});var F2="sign",cW=["typed","BigNumber","Fraction","complex"],Wp=F(F2,cW,e=>{var{typed:r,BigNumber:t,complex:n,Fraction:a}=e;return r(F2,{number:rp,Complex:function(u){return u.im===0?n(rp(u.re)):u.sign()},BigNumber:function(u){return new t(u.cmp(0))},Fraction:function(u){return new a(u.s,1)},"Array | Matrix":r.referToSelf(i=>u=>je(u,i,!0)),Unit:r.referToSelf(i=>u=>{if(!u._isDerived()&&u.units[0].unit.offset!==0)throw new TypeError("sign is ambiguous for units with offset");return r.find(i,u.valueType())(u.value)})})});var lW="sqrt",mW=["config","typed","Complex"],Yp=F(lW,mW,e=>{var{config:r,typed:t,Complex:n}=e;return t("sqrt",{number:a,Complex:function(u){return u.sqrt()},BigNumber:function(u){return!u.isNegative()||r.predictable?u.sqrt():a(u.toNumber())},Unit:function(u){return u.pow(.5)}});function a(i){return isNaN(i)?NaN:i>=0||r.predictable?Math.sqrt(i):new n(i,0).sqrt()}});var _2="square",pW=["typed"],Hp=F(_2,pW,e=>{var{typed:r}=e;return r(_2,{number:Cw,Complex:function(n){return n.mul(n)},BigNumber:function(n){return n.times(n)},Fraction:function(n){return n.mul(n)},Unit:function(n){return n.pow(2)}})});var O2="subtract",dW=["typed","matrix","equalScalar","subtractScalar","unaryMinus","DenseMatrix","concat"],$p=F(O2,dW,e=>{var{typed:r,matrix:t,equalScalar:n,subtractScalar:a,unaryMinus:i,DenseMatrix:u,concat:l}=e,c=Mn({typed:r}),o=lt({typed:r}),s=Lo({typed:r,equalScalar:n}),m=jn({typed:r,DenseMatrix:u}),d=Wr({typed:r,DenseMatrix:u}),h=vr({typed:r,matrix:t,concat:l});return r(O2,{"any, any":a},h({elop:a,SS:s,DS:c,SD:o,Ss:d,sS:m}))});var B2="xgcd",hW=["typed","config","matrix","BigNumber"],Gp=F(B2,hW,e=>{var{typed:r,config:t,matrix:n,BigNumber:a}=e;return r(B2,{"number, number":function(l,c){var o=Ew(l,c);return t.matrix==="Array"?o:n(o)},"BigNumber, BigNumber":i});function i(u,l){var c,o,s,m=new a(0),d=new a(1),h=m,x=d,v=d,y=m;if(!u.isInt()||!l.isInt())throw new Error("Parameters in function xgcd must be integer numbers");for(;!l.isZero();)o=u.div(l).floor(),s=u.mod(l),c=h,h=x.minus(o.times(h)),x=c,c=v,v=y.minus(o.times(v)),y=c,u=l,l=s;var w;return u.lt(m)?w=[u.neg(),x.neg(),y.neg()]:w=[u,u.isZero()?0:x,y],t.matrix==="Array"?w:n(w)}});var P2="invmod",vW=["typed","config","BigNumber","xgcd","equal","smaller","mod","add","isInteger"],Vp=F(P2,vW,e=>{var{typed:r,config:t,BigNumber:n,xgcd:a,equal:i,smaller:u,mod:l,add:c,isInteger:o}=e;return r(P2,{"number, number":s,"BigNumber, BigNumber":s});function s(m,d){if(!o(m)||!o(d))throw new Error("Parameters in function invmod must be integer numbers");if(m=l(m,d),i(d,0))throw new Error("Divisor must be non zero");var h=a(m,d);h=h.valueOf();var[x,v]=h;return i(x,n(1))?(v=l(v,d),u(v,n(0))&&(v=c(v,d)),v):NaN}});var gW="matAlgo09xS0Sf",xW=["typed","equalScalar"],Zp=F(gW,xW,e=>{var{typed:r,equalScalar:t}=e;return function(a,i,u){var l=a._values,c=a._index,o=a._ptr,s=a._size,m=a._datatype||a._data===void 0?a._datatype:a.getDataType(),d=i._values,h=i._index,x=i._ptr,v=i._size,y=i._datatype||i._data===void 0?i._datatype:i.getDataType();if(s.length!==v.length)throw new pr(s.length,v.length);if(s[0]!==v[0]||s[1]!==v[1])throw new RangeError("Dimension mismatch. Matrix A ("+s+") must match Matrix B ("+v+")");var w=s[0],C=s[1],b,M=t,A=0,S=u;typeof m=="string"&&m===y&&m!=="mixed"&&(b=m,M=r.find(t,[b,b]),A=r.convert(0,b),S=r.find(u,[b,b]));var O=l&&d?[]:void 0,_=[],E=[],T=O?[]:void 0,R=[],q,W,G,H,L;for(W=0;W{var{typed:r,matrix:t,equalScalar:n,multiplyScalar:a,concat:i}=e,u=Lt({typed:r,equalScalar:n}),l=Zp({typed:r,equalScalar:n}),c=jr({typed:r,equalScalar:n}),o=vr({typed:r,matrix:t,concat:i});return r(I2,o({elop:a,SS:l,DS:u,Ss:c}))});function R2(e,r){if(e.isFinite()&&!e.isInteger()||r.isFinite()&&!r.isInteger())throw new Error("Integers expected in function bitAnd");var t=e.constructor;if(e.isNaN()||r.isNaN())return new t(NaN);if(e.isZero()||r.eq(-1)||e.eq(r))return e;if(r.isZero()||e.eq(-1))return r;if(!e.isFinite()||!r.isFinite()){if(!e.isFinite()&&!r.isFinite())return e.isNegative()===r.isNegative()?e:new t(0);if(!e.isFinite())return r.isNegative()?e:e.isNegative()?new t(0):r;if(!r.isFinite())return e.isNegative()?r:r.isNegative()?new t(0):e}return hD(e,r,function(n,a){return n&a})}function ku(e){if(e.isFinite()&&!e.isInteger())throw new Error("Integer expected in function bitNot");var r=e.constructor,t=r.precision;r.config({precision:1e9});var n=e.plus(new r(1));return n.s=-n.s||null,r.config({precision:t}),n}function k2(e,r){if(e.isFinite()&&!e.isInteger()||r.isFinite()&&!r.isInteger())throw new Error("Integers expected in function bitOr");var t=e.constructor;if(e.isNaN()||r.isNaN())return new t(NaN);var n=new t(-1);return e.isZero()||r.eq(n)||e.eq(r)?r:r.isZero()||e.eq(n)?e:!e.isFinite()||!r.isFinite()?!e.isFinite()&&!e.isNegative()&&r.isNegative()||e.isNegative()&&!r.isNegative()&&!r.isFinite()?n:e.isNegative()&&r.isNegative()?e.isFinite()?e:r:e.isFinite()?r:e:hD(e,r,function(a,i){return a|i})}function hD(e,r,t){var n=e.constructor,a,i,u=+(e.s<0),l=+(r.s<0);if(u){a=Xp(ku(e));for(var c=0;c0;)t(s[--h],m[--x])===v&&(y=y.plus(w)),w=w.times(C);for(;x>0;)t(d,m[--x])===v&&(y=y.plus(w)),w=w.times(C);return n.config({precision:b}),v===0&&(y.s=-y.s),y}function Xp(e){for(var r=e.d,t=r[0]+"",n=1;n0)if(++l>o)for(l-=o;l--;)c+="0";else l1&&((s[h+1]===null||s[h+1]===void 0)&&(s[h+1]=0),s[h+1]+=s[h]>>1,s[h]&=1)}return s.reverse()}function q2(e,r){if(e.isFinite()&&!e.isInteger()||r.isFinite()&&!r.isInteger())throw new Error("Integers expected in function bitXor");var t=e.constructor;if(e.isNaN()||r.isNaN())return new t(NaN);if(e.isZero())return r;if(r.isZero())return e;if(e.eq(r))return new t(0);var n=new t(-1);return e.eq(n)?ku(r):r.eq(n)?ku(e):!e.isFinite()||!r.isFinite()?!e.isFinite()&&!r.isFinite()?n:new t(e.isNegative()===r.isNegative()?1/0:-1/0):hD(e,r,function(a,i){return a^i})}function L2(e,r){if(e.isFinite()&&!e.isInteger()||r.isFinite()&&!r.isInteger())throw new Error("Integers expected in function leftShift");var t=e.constructor;return e.isNaN()||r.isNaN()||r.isNegative()&&!r.isZero()?new t(NaN):e.isZero()||r.isZero()?e:!e.isFinite()&&!r.isFinite()?new t(NaN):r.lt(55)?e.times(Math.pow(2,r.toNumber())+""):e.times(new t(2).pow(r))}function z2(e,r){if(e.isFinite()&&!e.isInteger()||r.isFinite()&&!r.isInteger())throw new Error("Integers expected in function rightArithShift");var t=e.constructor;return e.isNaN()||r.isNaN()||r.isNegative()&&!r.isZero()?new t(NaN):e.isZero()||r.isZero()?e:r.isFinite()?r.lt(55)?e.div(Math.pow(2,r.toNumber())+"").floor():e.div(new t(2).pow(r)).floor():e.isNegative()?new t(-1):e.isFinite()?new t(0):new t(NaN)}var U2="bitAnd",bW=["typed","matrix","equalScalar","concat"],qu=F(U2,bW,e=>{var{typed:r,matrix:t,equalScalar:n,concat:a}=e,i=Lt({typed:r,equalScalar:n}),u=zo({typed:r,equalScalar:n}),l=jr({typed:r,equalScalar:n}),c=vr({typed:r,matrix:t,concat:a});return r(U2,{"number, number":Fw,"BigNumber, BigNumber":R2},c({SS:u,DS:i,Ss:l}))});var W2="bitNot",wW=["typed"],Jp=F(W2,wW,e=>{var{typed:r}=e;return r(W2,{number:_w,BigNumber:ku,"Array | Matrix":r.referToSelf(t=>n=>je(n,t))})});var Y2="bitOr",DW=["typed","matrix","equalScalar","DenseMatrix","concat"],Lu=F(Y2,DW,e=>{var{typed:r,matrix:t,equalScalar:n,DenseMatrix:a,concat:i}=e,u=Mn({typed:r}),l=Ru({typed:r,equalScalar:n}),c=jn({typed:r,DenseMatrix:a}),o=vr({typed:r,matrix:t,concat:i});return r(Y2,{"number, number":Ow,"BigNumber, BigNumber":k2},o({SS:l,DS:u,Ss:c}))});var SW="matAlgo07xSSf",NW=["typed","DenseMatrix"],Zt=F(SW,NW,e=>{var{typed:r,DenseMatrix:t}=e;return function(i,u,l){var c=i._size,o=i._datatype||i._data===void 0?i._datatype:i.getDataType(),s=u._size,m=u._datatype||u._data===void 0?u._datatype:u.getDataType();if(c.length!==s.length)throw new pr(c.length,s.length);if(c[0]!==s[0]||c[1]!==s[1])throw new RangeError("Dimension mismatch. Matrix A ("+c+") must match Matrix B ("+s+")");var d=c[0],h=c[1],x,v=0,y=l;typeof o=="string"&&o===m&&o!=="mixed"&&(x=o,v=r.convert(0,x),y=r.find(l,[x,x]));var w,C,b=[];for(w=0;w{var{typed:r,matrix:t,DenseMatrix:n,concat:a}=e,i=lt({typed:r}),u=Zt({typed:r,DenseMatrix:n}),l=Wr({typed:r,DenseMatrix:n}),c=vr({typed:r,matrix:t,concat:a});return r(H2,{"number, number":Bw,"BigNumber, BigNumber":q2},c({SS:u,DS:i,Ss:l}))});var $2="arg",MW=["typed"],jp=F($2,MW,e=>{var{typed:r}=e;return r($2,{number:function(n){return Math.atan2(0,n)},BigNumber:function(n){return n.constructor.atan2(0,n)},Complex:function(n){return n.arg()},"Array | Matrix":r.referToSelf(t=>n=>je(n,t))})});var G2="conj",CW=["typed"],ed=F(G2,CW,e=>{var{typed:r}=e;return r(G2,{"number | BigNumber | Fraction":t=>t,Complex:t=>t.conjugate(),"Array | Matrix":r.referToSelf(t=>n=>je(n,t))})});var V2="im",EW=["typed"],rd=F(V2,EW,e=>{var{typed:r}=e;return r(V2,{number:()=>0,"BigNumber | Fraction":t=>t.mul(0),Complex:t=>t.im,"Array | Matrix":r.referToSelf(t=>n=>je(n,t))})});var Z2="re",TW=["typed"],td=F(Z2,TW,e=>{var{typed:r}=e;return r(Z2,{"number | BigNumber | Fraction":t=>t,Complex:t=>t.re,"Array | Matrix":r.referToSelf(t=>n=>je(n,t))})});var Q2="not",FW=["typed"],nd=F(Q2,FW,e=>{var{typed:r}=e;return r(Q2,{"null | undefined":()=>!0,number:Lw,Complex:function(n){return n.re===0&&n.im===0},BigNumber:function(n){return n.isZero()||n.isNaN()},Unit:r.referToSelf(t=>n=>r.find(t,n.valueType())(n.value)),"Array | Matrix":r.referToSelf(t=>n=>je(n,t))})});var X2="or",_W=["typed","matrix","equalScalar","DenseMatrix","concat"],zu=F(X2,_W,e=>{var{typed:r,matrix:t,equalScalar:n,DenseMatrix:a,concat:i}=e,u=lt({typed:r}),l=Lo({typed:r,equalScalar:n}),c=Wr({typed:r,DenseMatrix:a}),o=vr({typed:r,matrix:t,concat:i});return r(X2,{"number, number":zw,"Complex, Complex":function(m,d){return m.re!==0||m.im!==0||d.re!==0||d.im!==0},"BigNumber, BigNumber":function(m,d){return!m.isZero()&&!m.isNaN()||!d.isZero()&&!d.isNaN()},"Unit, Unit":r.referToSelf(s=>(m,d)=>s(m.value||0,d.value||0))},o({SS:l,DS:u,Ss:c}))});var J2="xor",OW=["typed","matrix","DenseMatrix","concat"],ad=F(J2,OW,e=>{var{typed:r,matrix:t,DenseMatrix:n,concat:a}=e,i=lt({typed:r}),u=Zt({typed:r,DenseMatrix:n}),l=Wr({typed:r,DenseMatrix:n}),c=vr({typed:r,matrix:t,concat:a});return r(J2,{"number, number":Uw,"Complex, Complex":function(s,m){return(s.re!==0||s.im!==0)!=(m.re!==0||m.im!==0)},"BigNumber, BigNumber":function(s,m){return(!s.isZero()&&!s.isNaN())!=(!m.isZero()&&!m.isNaN())},"Unit, Unit":r.referToSelf(o=>(s,m)=>o(s.value||0,m.value||0))},c({SS:u,DS:i,Ss:l}))});var K2="concat",BW=["typed","matrix","isInteger"],Uu=F(K2,BW,e=>{var{typed:r,matrix:t,isInteger:n}=e;return r(K2,{"...Array | Matrix | number | BigNumber":function(i){var u,l=i.length,c=-1,o,s=!1,m=[];for(u=0;u0&&c>o)throw new tn(c,o+1)}else{var h=ar(d).valueOf(),x=ur(h);if(m[u]=h,o=c,c=x.length-1,u>0&&c!==o)throw new pr(o+1,c+1)}}if(m.length===0)throw new SyntaxError("At least one matrix expected");for(var v=m.shift();m.length;)v=Kb(v,m.shift(),c);return s?t(v):v},"...string":function(i){return i.join("")}})});var j2="column",PW=["typed","Index","matrix","range"],Wu=F(j2,PW,e=>{var{typed:r,Index:t,matrix:n,range:a}=e;return r(j2,{"Matrix, number":i,"Array, number":function(l,c){return i(n(ar(l)),c).valueOf()}});function i(u,l){if(u.size().length!==2)throw new Error("Only two dimensional matrix is supported");Kr(l,u.size()[1]);var c=a(0,u.size()[0]),o=new t(c,l),s=u.subset(o);return Qe(s)?s:n([[s]])}});var eC="count",IW=["typed","size","prod"],id=F(eC,IW,e=>{var{typed:r,size:t,prod:n}=e;return r(eC,{string:function(i){return i.length},"Matrix | Array":function(i){return n(t(i))}})});var rC="cross",RW=["typed","matrix","subtract","multiply"],od=F(rC,RW,e=>{var{typed:r,matrix:t,subtract:n,multiply:a}=e;return r(rC,{"Matrix, Matrix":function(l,c){return t(i(l.toArray(),c.toArray()))},"Matrix, Array":function(l,c){return t(i(l.toArray(),c))},"Array, Matrix":function(l,c){return t(i(l,c.toArray()))},"Array, Array":i});function i(u,l){var c=Math.max(ur(u).length,ur(l).length);u=Au(u),l=Au(l);var o=ur(u),s=ur(l);if(o.length!==1||s.length!==1||o[0]!==3||s[0]!==3)throw new RangeError("Vectors with length 3 expected (Size A = ["+o.join(", ")+"], B = ["+s.join(", ")+"])");var m=[n(a(u[1],l[2]),a(u[2],l[1])),n(a(u[2],l[0]),a(u[0],l[2])),n(a(u[0],l[1]),a(u[1],l[0]))];return c>1?[m]:m}});var tC="diag",kW=["typed","matrix","DenseMatrix","SparseMatrix"],sd=F(tC,kW,e=>{var{typed:r,matrix:t,DenseMatrix:n,SparseMatrix:a}=e;return r(tC,{Array:function(o){return i(o,0,ur(o),null)},"Array, number":function(o,s){return i(o,s,ur(o),null)},"Array, BigNumber":function(o,s){return i(o,s.toNumber(),ur(o),null)},"Array, string":function(o,s){return i(o,0,ur(o),s)},"Array, number, string":function(o,s,m){return i(o,s,ur(o),m)},"Array, BigNumber, string":function(o,s,m){return i(o,s.toNumber(),ur(o),m)},Matrix:function(o){return i(o,0,o.size(),o.storage())},"Matrix, number":function(o,s){return i(o,s,o.size(),o.storage())},"Matrix, BigNumber":function(o,s){return i(o,s.toNumber(),o.size(),o.storage())},"Matrix, string":function(o,s){return i(o,0,o.size(),s)},"Matrix, number, string":function(o,s,m){return i(o,s,o.size(),m)},"Matrix, BigNumber, string":function(o,s,m){return i(o,s.toNumber(),o.size(),m)}});function i(c,o,s,m){if(!Ze(o))throw new TypeError("Second parameter in function diag must be an integer");var d=o>0?o:0,h=o<0?-o:0;switch(s.length){case 1:return u(c,o,m,s[0],h,d);case 2:return l(c,o,m,s,h,d)}throw new RangeError("Matrix for function diag must be 2 dimensional")}function u(c,o,s,m,d,h){var x=[m+d,m+h];if(s&&s!=="sparse"&&s!=="dense")throw new TypeError("Unknown matrix type ".concat(s,'"'));var v=s==="sparse"?a.diagonal(x,c,o):n.diagonal(x,c,o);return s!==null?v:v.valueOf()}function l(c,o,s,m,d,h){if(Qe(c)){var x=c.diagonal(o);return s!==null?s!==x.storage()?t(x,s):x:x.valueOf()}for(var v=Math.min(m[0]-d,m[1]-h),y=[],w=0;w=2&&v.push("index: ".concat(Fr(t))),h.length>=3&&v.push("array: ".concat(Fr(n))),new TypeError("Function ".concat(a," cannot apply callback arguments ")+"".concat(e.name,"(").concat(v.join(", "),") at index ").concat(JSON.stringify(t)))}else throw new TypeError("Function ".concat(a," cannot apply callback arguments ")+"to function ".concat(e.name,": ").concat(y.message))}}}var qW="filter",LW=["typed"],ud=F(qW,LW,e=>{var{typed:r}=e;return r("filter",{"Array, function":nC,"Matrix, function":function(n,a){return n.create(nC(n.toArray(),a))},"Array, RegExp":Mu,"Matrix, RegExp":function(n,a){return n.create(Mu(n.toArray(),a))}})});function nC(e,r){return Om(e,function(t,n,a){return Ia(r,t,[n],a,"filter")})}var aC="flatten",zW=["typed","matrix"],fd=F(aC,zW,e=>{var{typed:r,matrix:t}=e;return r(aC,{Array:function(a){return gr(a)},Matrix:function(a){var i=gr(a.toArray());return t(i)}})});var iC="forEach",UW=["typed"],cd=F(iC,UW,e=>{var{typed:r}=e;return r(iC,{"Array, function":WW,"Matrix, function":function(n,a){n.forEach(a)}})});function WW(e,r){var t=function n(a,i){if(Array.isArray(a))Fo(a,function(u,l){n(u,i.concat(l))});else return Ia(r,a,i,e,"forEach")};t(e,[])}var oC="getMatrixDataType",YW=["typed"],ld=F(oC,YW,e=>{var{typed:r}=e;return r(oC,{Array:function(n){return _o(n,Fr)},Matrix:function(n){return n.getDataType()}})});var sC="identity",HW=["typed","config","matrix","BigNumber","DenseMatrix","SparseMatrix"],md=F(sC,HW,e=>{var{typed:r,config:t,matrix:n,BigNumber:a,DenseMatrix:i,SparseMatrix:u}=e;return r(sC,{"":function(){return t.matrix==="Matrix"?n([]):[]},string:function(s){return n(s)},"number | BigNumber":function(s){return c(s,s,t.matrix==="Matrix"?"dense":void 0)},"number | BigNumber, string":function(s,m){return c(s,s,m)},"number | BigNumber, number | BigNumber":function(s,m){return c(s,m,t.matrix==="Matrix"?"dense":void 0)},"number | BigNumber, number | BigNumber, string":function(s,m,d){return c(s,m,d)},Array:function(s){return l(s)},"Array, string":function(s,m){return l(s,m)},Matrix:function(s){return l(s.valueOf(),s.storage())},"Matrix, string":function(s,m){return l(s.valueOf(),m)}});function l(o,s){switch(o.length){case 0:return s?n(s):[];case 1:return c(o[0],o[0],s);case 2:return c(o[0],o[1],s);default:throw new Error("Vector containing two values expected")}}function c(o,s,m){var d=rr(o)||rr(s)?a:null;if(rr(o)&&(o=o.toNumber()),rr(s)&&(s=s.toNumber()),!Ze(o)||o<1)throw new Error("Parameters in function identity must be positive integers");if(!Ze(s)||s<1)throw new Error("Parameters in function identity must be positive integers");var h=d?new a(1):1,x=d?new d(0):0,v=[o,s];if(m){if(m==="sparse")return u.diagonal(v,h,0,x);if(m==="dense")return i.diagonal(v,h,0,x);throw new TypeError('Unknown matrix type "'.concat(m,'"'))}for(var y=ii([],v,x),w=o{var{typed:r,matrix:t,multiplyScalar:n}=e;return r(uC,{"Matrix, Matrix":function(u,l){return t(a(u.toArray(),l.toArray()))},"Matrix, Array":function(u,l){return t(a(u.toArray(),l))},"Array, Matrix":function(u,l){return t(a(u,l.toArray()))},"Array, Array":a});function a(i,u){if(ur(i).length===1&&(i=[i]),ur(u).length===1&&(u=[u]),ur(i).length>2||ur(u).length>2)throw new RangeError("Vectors with dimensions greater then 2 are not supported expected (Size x = "+JSON.stringify(i.length)+", y = "+JSON.stringify(u.length)+")");var l=[],c=[];return i.map(function(o){return u.map(function(s){return c=[],l.push(c),o.map(function(m){return s.map(function(d){return c.push(n(m,d))})})})})&&l}});var fC="map",GW=["typed"],dd=F(fC,GW,e=>{var{typed:r}=e;return r(fC,{"Array, function":VW,"Matrix, function":function(n,a){return n.map(a)}})});function VW(e,r){var t=function n(a,i){return Array.isArray(a)?a.map(function(u,l){return n(u,i.concat(l))}):Ia(r,a,i,e,"map")};return t(e,[])}var cC="diff",ZW=["typed","matrix","subtract","number"],Yu=F(cC,ZW,e=>{var{typed:r,matrix:t,subtract:n,number:a}=e;return r(cC,{"Array | Matrix":function(s){return Qe(s)?t(u(s.toArray())):u(s)},"Array | Matrix, number":function(s,m){if(!Ze(m))throw new RangeError("Dimension must be a whole number");return Qe(s)?t(i(s.toArray(),m)):i(s,m)},"Array, BigNumber":r.referTo("Array,number",o=>(s,m)=>o(s,a(m))),"Matrix, BigNumber":r.referTo("Matrix,number",o=>(s,m)=>o(s,a(m)))});function i(o,s){if(Qe(o)&&(o=o.toArray()),!Array.isArray(o))throw RangeError("Array/Matrix does not have that many dimensions");if(s>0){var m=[];return o.forEach(d=>{m.push(i(d,s-1))}),m}else{if(s===0)return u(o);throw RangeError("Cannot have negative dimension")}}function u(o){for(var s=[],m=o.length,d=1;d{var{typed:r,config:t,matrix:n,BigNumber:a}=e;return r("ones",{"":function(){return t.matrix==="Array"?i([]):i([],"default")},"...number | BigNumber | string":function(o){var s=o[o.length-1];if(typeof s=="string"){var m=o.pop();return i(o,m)}else return t.matrix==="Array"?i(o):i(o,"default")},Array:i,Matrix:function(o){var s=o.storage();return i(o.valueOf(),s)},"Array | Matrix, string":function(o,s){return i(o.valueOf(),s)}});function i(c,o){var s=u(c),m=s?new a(1):1;if(l(c),o){var d=n(o);return c.length>0?d.resize(c,m):d}else{var h=[];return c.length>0?ii(h,c,m):h}}function u(c){var o=!1;return c.forEach(function(s,m,d){rr(s)&&(o=!0,d[m]=s.toNumber())}),o}function l(c){c.forEach(function(o){if(typeof o!="number"||!Ze(o)||o<0)throw new Error("Parameters in function ones must be positive integers")})}});function Hu(){throw new Error('No "bignumber" implementation available')}function vd(){throw new Error('No "fraction" implementation available')}function gd(){throw new Error('No "matrix" implementation available')}var lC="range",JW=["typed","config","?matrix","?bignumber","smaller","smallerEq","larger","largerEq","add","isPositive"],$u=F(lC,JW,e=>{var{typed:r,config:t,matrix:n,bignumber:a,smaller:i,smallerEq:u,larger:l,largerEq:c,add:o,isPositive:s}=e;return r(lC,{string:d,"string, boolean":d,"number, number":function(y,w){return m(h(y,w,1,!1))},"number, number, number":function(y,w,C){return m(h(y,w,C,!1))},"number, number, boolean":function(y,w,C){return m(h(y,w,1,C))},"number, number, number, boolean":function(y,w,C,b){return m(h(y,w,C,b))},"BigNumber, BigNumber":function(y,w){var C=y.constructor;return m(h(y,w,new C(1),!1))},"BigNumber, BigNumber, BigNumber":function(y,w,C){return m(h(y,w,C,!1))},"BigNumber, BigNumber, boolean":function(y,w,C){var b=y.constructor;return m(h(y,w,new b(1),C))},"BigNumber, BigNumber, BigNumber, boolean":function(y,w,C,b){return m(h(y,w,C,b))},"Unit, Unit, Unit":function(y,w,C){return m(h(y,w,C,!1))},"Unit, Unit, Unit, boolean":function(y,w,C,b){return m(h(y,w,C,b))}});function m(v){return t.matrix==="Matrix"?n?n(v):gd():v}function d(v,y){var w=x(v);if(!w)throw new SyntaxError('String "'+v+'" is no valid range');return t.number==="BigNumber"?(a===void 0&&Hu(),m(h(a(w.start),a(w.end),a(w.step)),y)):m(h(w.start,w.end,w.step,y))}function h(v,y,w,C){for(var b=[],M=s(w)?C?u:i:C?c:l,A=v;M(A,y);)b.push(A),A=o(A,w);return b}function x(v){var y=v.split(":"),w=y.map(function(b){return Number(b)}),C=w.some(function(b){return isNaN(b)});if(C)return null;switch(w.length){case 2:return{start:w[0],end:w[1],step:1};case 3:return{start:w[0],end:w[2],step:w[1]};default:return null}}});var mC="reshape",KW=["typed","isInteger","matrix"],xd=F(mC,KW,e=>{var{typed:r,isInteger:t}=e;return r(mC,{"Matrix, Array":function(a,i){return a.reshape(i,!0)},"Array, Array":function(a,i){return i.forEach(function(u){if(!t(u))throw new TypeError("Invalid size for dimension: "+u)}),Mc(a,i)}})});var jW="resize",eY=["config","matrix"],yd=F(jW,eY,e=>{var{config:r,matrix:t}=e;return function(i,u,l){if(arguments.length!==2&&arguments.length!==3)throw new ha("resize",arguments.length,2,3);if(Qe(u)&&(u=u.valueOf()),rr(u[0])&&(u=u.map(function(s){return rr(s)?s.toNumber():s})),Qe(i))return i.resize(u,l,!0);if(typeof i=="string")return n(i,u,l);var c=Array.isArray(i)?!1:r.matrix!=="Array";if(u.length===0){for(;Array.isArray(i);)i=i[0];return ar(i)}else{Array.isArray(i)||(i=[i]),i=ar(i);var o=ii(i,u,l);return c?t(o):o}};function n(a,i,u){if(u!==void 0){if(typeof u!="string"||u.length!==1)throw new TypeError("Single character expected as defaultValue")}else u=" ";if(i.length!==1)throw new pr(i.length,1);var l=i[0];if(typeof l!="number"||!Ze(l))throw new TypeError("Invalid size, must contain positive integers (size: "+lr(i)+")");if(a.length>l)return a.substring(0,l);if(a.length{var{typed:r,multiply:t,rotationMatrix:n}=e;return r(pC,{"Array , number | BigNumber | Complex | Unit":function(u,l){a(u,2);var c=t(n(l),u);return c.toArray()},"Matrix , number | BigNumber | Complex | Unit":function(u,l){return a(u,2),t(n(l),u)},"Array, number | BigNumber | Complex | Unit, Array | Matrix":function(u,l,c){a(u,3);var o=t(n(l,c),u);return o},"Matrix, number | BigNumber | Complex | Unit, Array | Matrix":function(u,l,c){return a(u,3),t(n(l,c),u)}});function a(i,u){var l=Array.isArray(i)?ur(i):i.size();if(l.length>2)throw new RangeError("Vector must be of dimensions 1x".concat(u));if(l.length===2&&l[1]!==1)throw new RangeError("Vector must be of dimensions 1x".concat(u));if(l[0]!==u)throw new RangeError("Vector must be of dimensions 1x".concat(u))}});var dC="rotationMatrix",tY=["typed","config","multiplyScalar","addScalar","unaryMinus","norm","matrix","BigNumber","DenseMatrix","SparseMatrix","cos","sin"],wd=F(dC,tY,e=>{var{typed:r,config:t,multiplyScalar:n,addScalar:a,unaryMinus:i,norm:u,BigNumber:l,matrix:c,DenseMatrix:o,SparseMatrix:s,cos:m,sin:d}=e;return r(dC,{"":function(){return t.matrix==="Matrix"?c([]):[]},string:function(b){return c(b)},"number | BigNumber | Complex | Unit":function(b){return h(b,t.matrix==="Matrix"?"dense":void 0)},"number | BigNumber | Complex | Unit, string":function(b,M){return h(b,M)},"number | BigNumber | Complex | Unit, Array":function(b,M){var A=c(M);return x(A),w(b,A,void 0)},"number | BigNumber | Complex | Unit, Matrix":function(b,M){x(M);var A=M.storage()||(t.matrix==="Matrix"?"dense":void 0);return w(b,M,A)},"number | BigNumber | Complex | Unit, Array, string":function(b,M,A){var S=c(M);return x(S),w(b,S,A)},"number | BigNumber | Complex | Unit, Matrix, string":function(b,M,A){return x(M),w(b,M,A)}});function h(C,b){var M=rr(C),A=M?new l(-1):-1,S=m(C),O=d(C),_=[[S,n(A,O)],[O,S]];return y(_,b)}function x(C){var b=C.size();if(b.length<1||b[0]!==3)throw new RangeError("Vector must be of dimensions 1x3")}function v(C){return C.reduce((b,M)=>n(b,M))}function y(C,b){if(b){if(b==="sparse")return new s(C);if(b==="dense")return new o(C);throw new TypeError('Unknown matrix type "'.concat(b,'"'))}return C}function w(C,b,M){var A=u(b);if(A===0)throw new RangeError("Rotation around zero vector");var S=rr(C)?l:null,O=S?new S(1):1,_=S?new S(-1):-1,E=S?new S(b.get([0])/A):b.get([0])/A,T=S?new S(b.get([1])/A):b.get([1])/A,R=S?new S(b.get([2])/A):b.get([2])/A,q=m(C),W=a(O,i(q)),G=d(C),H=a(q,v([E,E,W])),L=a(v([E,T,W]),v([_,R,G])),k=a(v([E,R,W]),v([T,G])),K=a(v([E,T,W]),v([R,G])),z=a(q,v([T,T,W])),oe=a(v([T,R,W]),v([_,E,G])),pe=a(v([E,R,W]),v([_,T,G])),ae=a(v([T,R,W]),v([E,G])),$=a(q,v([R,R,W])),le=[[H,L,k],[K,z,oe],[pe,ae,$]];return y(le,M)}});var hC="row",nY=["typed","Index","matrix","range"],Gu=F(hC,nY,e=>{var{typed:r,Index:t,matrix:n,range:a}=e;return r(hC,{"Matrix, number":i,"Array, number":function(l,c){return i(n(ar(l)),c).valueOf()}});function i(u,l){if(u.size().length!==2)throw new Error("Only two dimensional matrix is supported");Kr(l,u.size()[0]);var c=a(0,u.size()[1]),o=new t(l,c),s=u.subset(o);return Qe(s)?s:n([[s]])}});var vC="size",aY=["typed","config","?matrix"],Dd=F(vC,aY,e=>{var{typed:r,config:t,matrix:n}=e;return r(vC,{Matrix:function(i){return i.create(i.size())},Array:ur,string:function(i){return t.matrix==="Array"?[i.length]:n([i.length])},"number | Complex | BigNumber | Unit | boolean | null":function(i){return t.matrix==="Array"?[]:n?n([]):gd()}})});var gC="squeeze",iY=["typed","matrix"],Sd=F(gC,iY,e=>{var{typed:r,matrix:t}=e;return r(gC,{Array:function(a){return Au(ar(a))},Matrix:function(a){var i=Au(a.toArray());return Array.isArray(i)?t(i):i},any:function(a){return ar(a)}})});var xC="subset",oY=["typed","matrix","zeros","add"],Vu=F(xC,oY,e=>{var{typed:r,matrix:t,zeros:n,add:a}=e;return r(xC,{"Matrix, Index":function(l,c){return Ns(c)?t():(Ac(l,c),l.subset(c))},"Array, Index":r.referTo("Matrix, Index",function(u){return function(l,c){var o=u(t(l),c);return c.isScalar()?o:o.valueOf()}}),"Object, Index":uY,"string, Index":sY,"Matrix, Index, any, any":function(l,c,o,s){return Ns(c)?l:(Ac(l,c),l.clone().subset(c,i(o,c),s))},"Array, Index, any, any":r.referTo("Matrix, Index, any, any",function(u){return function(l,c,o,s){var m=u(t(l),c,o,s);return m.isMatrix?m.valueOf():m}}),"Array, Index, any":r.referTo("Matrix, Index, any, any",function(u){return function(l,c,o){return u(t(l),c,o,void 0).valueOf()}}),"Matrix, Index, any":r.referTo("Matrix, Index, any, any",function(u){return function(l,c,o){return u(l,c,o,void 0)}}),"string, Index, string":yC,"string, Index, string, string":yC,"Object, Index, any":fY});function i(u,l){if(typeof u=="string")throw new Error("can't boradcast a string");if(l._isScalar)return u;var c=l.size();if(c.every(o=>o>0))try{return a(u,n(c))}catch{return u}else return u}});function sY(e,r){if(!Ai(r))throw new TypeError("Index expected");if(Ns(r))return"";if(Ac(Array.from(e),r),r.size().length!==1)throw new pr(r.size().length,1);var t=e.length;Kr(r.min()[0],t),Kr(r.max()[0],t);var n=r.dimension(0),a="";return n.forEach(function(i){a+=e.charAt(i)}),a}function yC(e,r,t,n){if(!r||r.isIndex!==!0)throw new TypeError("Index expected");if(Ns(r))return e;if(Ac(Array.from(e),r),r.size().length!==1)throw new pr(r.size().length,1);if(n!==void 0){if(typeof n!="string"||n.length!==1)throw new TypeError("Single character expected as defaultValue")}else n=" ";var a=r.dimension(0),i=a.size()[0];if(i!==t.length)throw new pr(a.size()[0],t.length);var u=e.length;Kr(r.min()[0]),Kr(r.max()[0]);for(var l=[],c=0;cu)for(var o=u-1,s=l.length;o{var{typed:r,matrix:t}=e;return r(bC,{Array:u=>n(t(u)).valueOf(),Matrix:n,any:ar});function n(u){var l=u.size(),c;switch(l.length){case 1:c=u.clone();break;case 2:{var o=l[0],s=l[1];if(s===0)throw new RangeError("Cannot transpose a 2D matrix with no columns (size: "+lr(l)+")");switch(u.storage()){case"dense":c=a(u,o,s);break;case"sparse":c=i(u,o,s);break}}break;default:throw new RangeError("Matrix must be a vector or two dimensional (size: "+lr(l)+")")}return c}function a(u,l,c){for(var o=u._data,s=[],m,d=0;d{var{typed:r,transpose:t,conj:n}=e;return r(wC,{any:function(i){return n(t(i))}})});var DC="zeros",mY=["typed","config","matrix","BigNumber"],Md=F(DC,mY,e=>{var{typed:r,config:t,matrix:n,BigNumber:a}=e;return r(DC,{"":function(){return t.matrix==="Array"?i([]):i([],"default")},"...number | BigNumber | string":function(o){var s=o[o.length-1];if(typeof s=="string"){var m=o.pop();return i(o,m)}else return t.matrix==="Array"?i(o):i(o,"default")},Array:i,Matrix:function(o){var s=o.storage();return i(o.valueOf(),s)},"Array | Matrix, string":function(o,s){return i(o.valueOf(),s)}});function i(c,o){var s=u(c),m=s?new a(0):0;if(l(c),o){var d=n(o);return c.length>0?d.resize(c,m):d}else{var h=[];return c.length>0?ii(h,c,m):h}}function u(c){var o=!1;return c.forEach(function(s,m,d){rr(s)&&(o=!0,d[m]=s.toNumber())}),o}function l(c){c.forEach(function(o){if(typeof o!="number"||!Ze(o)||o<0)throw new Error("Parameters in function zeros must be positive integers")})}});var SC="fft",pY=["typed","matrix","addScalar","multiplyScalar","divideScalar","exp","tau","i","dotDivide","conj","pow","ceil","log2"],Cd=F(SC,pY,e=>{var{typed:r,matrix:t,addScalar:n,multiplyScalar:a,divideScalar:i,exp:u,tau:l,i:c,dotDivide:o,conj:s,pow:m,ceil:d,log2:h}=e;return r(SC,{Array:x,Matrix:function(b){return b.create(x(b.toArray()))}});function x(C){var b=ur(C);return b.length===1?w(C,b[0]):v(C.map(M=>x(M,b.slice(1))),0)}function v(C,b){var M=ur(C);if(b!==0)return new Array(M[0]).fill(0).map((S,O)=>v(C[O],b-1));if(M.length===1)return w(C);function A(S){var O=ur(S);return new Array(O[1]).fill(0).map((_,E)=>new Array(O[0]).fill(0).map((T,R)=>S[R][E]))}return A(v(A(C),1))}function y(C){for(var b=C.length,M=u(i(a(-1,a(c,l)),b)),A=[],S=1-b;Sa(C[k],A[b-1+k])),...new Array(O-b).fill(0)],E=[...new Array(b+b-1).fill(0).map((L,k)=>i(1,A[k])),...new Array(O-(b+b-1)).fill(0)],T=w(_),R=w(E),q=new Array(O).fill(0).map((L,k)=>a(T[k],R[k])),W=o(s(x(s(q))),O),G=[],H=b-1;HE%2===0),b/2),...w(C.filter((_,E)=>E%2===1),b/2)],A=0;A{var{typed:r,fft:t,dotDivide:n,conj:a}=e;return r(NC,{"Array | Matrix":function(u){var l=Qe(u)?u.size():ur(u);return n(a(t(a(u))),l.reduce((c,o)=>c*o,1))}})});function AC(e,r){var t=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);r&&(n=n.filter(function(a){return Object.getOwnPropertyDescriptor(e,a).enumerable})),t.push.apply(t,n)}return t}function hY(e){for(var r=1;r{var{typed:r,add:t,subtract:n,multiply:a,divide:i,max:u,map:l,abs:c,isPositive:o,isNegative:s,larger:m,smaller:d,matrix:h,bignumber:x,unaryMinus:v}=e;function y(_){return function(E,T,R,q){var W=!(T.length===2&&(T.every(S)||T.every(Ht)));if(W)throw new Error('"tspan" must be an Array of two numeric values or two units [tStart, tEnd]');var G=T[0],H=T[1],L=m(H,G),k=q.firstStep;if(k!==void 0&&!o(k))throw new Error('"firstStep" must be positive');var K=q.maxStep;if(K!==void 0&&!o(K))throw new Error('"maxStep" must be positive');var z=q.minStep;if(z&&s(z))throw new Error('"minStep" must be positive or zero');var oe=[G,H,k,z,K].filter(Le=>Le!==void 0);if(!(oe.every(S)||oe.every(Ht)))throw new Error('Inconsistent type of "t" dependant variables');for(var pe=1,ae=q.tol?q.tol:1e-4,$=q.minDelta?q.minDelta:.2,le=q.maxDelta?q.maxDelta:5,Ee=q.maxIter?q.maxIter:1e4,me=[G,H,...R,K,z].some(rr),[ge,Se,xe,be]=me?[x(_.a),x(_.c),x(_.b),x(_.bp)]:[_.a,_.c,_.b,_.bp],De=k?L?k:v(k):i(n(H,G),pe),Ae=[G],We=[R],Je=n(xe,be),J=0,re=0,ye=M(L),j=A(L);ye(Ae[J],H);){var ne=[];De=j(Ae[J],H,De),ne.push(E(Ae[J],We[J]));for(var ue=1;ueHt(Le)?Le.value:Le)));Me1/4&&(Ae.push(t(Ae[J],De)),We.push(t(We[J],a(De,xe,ne))),J++);var Ce=.84*(ae/Me)**(1/5);if(d(Ce,$)?Ce=$:m(Ce,le)&&(Ce=le),Ce=me?x(Ce):Ce,De=a(De,Ce),K&&m(c(De),K)?De=L?K:v(K):z&&d(c(De),z)&&(De=L?z:v(z)),re++,re>Ee)throw new Error("Maximum number of iterations reached, try changing options")}return{t:Ae,y:We}}}function w(_,E,T,R){var q=[[],[.5],[0,.75],[.2222222222222222,.3333333333333333,.4444444444444444]],W=[null,1/2,3/4,1],G=[2/9,1/3,4/9,0],H=[7/24,1/4,1/3,1/8],L={a:q,c:W,b:G,bp:H};return y(L)(_,E,T,R)}function C(_,E,T,R){var q=[[],[.2],[.075,.225],[.9777777777777777,-3.7333333333333334,3.5555555555555554],[2.9525986892242035,-11.595793324188385,9.822892851699436,-.2908093278463649],[2.8462752525252526,-10.757575757575758,8.906422717743473,.2784090909090909,-.2735313036020583],[.09114583333333333,0,.44923629829290207,.6510416666666666,-.322376179245283,.13095238095238096]],W=[null,1/5,3/10,4/5,8/9,1,1],G=[35/384,0,500/1113,125/192,-2187/6784,11/84,0],H=[5179/57600,0,7571/16695,393/640,-92097/339200,187/2100,1/40],L={a:q,c:W,b:G,bp:H};return y(L)(_,E,T,R)}function b(_,E,T,R){var q=R.method?R.method:"RK45",W={RK23:w,RK45:C};if(q.toUpperCase()in W){var G=hY({},R);return delete G.method,W[q.toUpperCase()](_,E,T,G)}else{var H=Object.keys(W).map(k=>'"'.concat(k,'"')),L="".concat(H.slice(0,-1).join(", ")," and ").concat(H.slice(-1));throw new Error('Unavailable method "'.concat(q,'". Available methods are ').concat(L))}}function M(_){return _?d:m}function A(_){var E=_?m:d;return function(T,R,q){var W=t(T,q);return E(W,R)?n(R,T):q}}function S(_){return rr(_)||sr(_)}function O(_,E,T,R){var q=b(_,E.toArray(),T.toArray(),R);return{t:h(q.t),y:h(q.y)}}return r("solveODE",{"function, Array, Array, Object":b,"function, Matrix, Matrix, Object":O,"function, Array, Array":(_,E,T)=>b(_,E,T,{}),"function, Matrix, Matrix":(_,E,T)=>O(_,E,T,{}),"function, Array, number | BigNumber | Unit":(_,E,T)=>{var R=b(_,E,[T],{});return{t:R.t,y:R.y.map(q=>q[0])}},"function, Matrix, number | BigNumber | Unit":(_,E,T)=>{var R=b(_,E.toArray(),[T],{});return{t:h(R.t),y:h(R.y.map(q=>q[0]))}},"function, Array, number | BigNumber | Unit, Object":(_,E,T,R)=>{var q=b(_,E,[T],R);return{t:q.t,y:q.y.map(W=>W[0])}},"function, Matrix, number | BigNumber | Unit, Object":(_,E,T,R)=>{var q=b(_,E.toArray(),[T],R);return{t:h(q.t),y:h(q.y.map(W=>W[0]))}}})});var xY="erf",yY=["typed"],Fd=F(xY,yY,e=>{var{typed:r}=e;return r("name",{number:function(u){var l=Math.abs(u);return l>=DY?Oa(u):l<=bY?Oa(u)*t(l):l<=4?Oa(u)*(1-n(l)):Oa(u)*(1-a(l))},"Array | Matrix":r.referToSelf(i=>u=>je(u,i))});function t(i){var u=i*i,l=ro[0][4]*u,c=u,o;for(o=0;o<3;o+=1)l=(l+ro[0][o])*u,c=(c+Zu[0][o])*u;return i*(l+ro[0][3])/(c+Zu[0][3])}function n(i){var u=ro[1][8]*i,l=i,c;for(c=0;c<7;c+=1)u=(u+ro[1][c])*i,l=(l+Zu[1][c])*i;var o=(u+ro[1][7])/(l+Zu[1][7]),s=parseInt(i*16)/16,m=(i-s)*(i+s);return Math.exp(-s*s)*Math.exp(-m)*o}function a(i){var u=1/(i*i),l=ro[2][5]*u,c=u,o;for(o=0;o<4;o+=1)l=(l+ro[2][o])*u,c=(c+Zu[2][o])*u;var s=u*(l+ro[2][4])/(c+Zu[2][4]);s=(wY-s)/i,u=parseInt(i*16)/16;var m=(i-u)*(i+u);return Math.exp(-u*u)*Math.exp(-m)*s}}),bY=.46875,wY=.5641895835477563,ro=[[3.1611237438705655,113.86415415105016,377.485237685302,3209.3775891384694,.18577770618460315],[.5641884969886701,8.883149794388377,66.11919063714163,298.6351381974001,881.952221241769,1712.0476126340707,2051.0783778260716,1230.3393547979972,21531153547440383e-24],[.30532663496123236,.36034489994980445,.12578172611122926,.016083785148742275,.0006587491615298378,.016315387137302097]],Zu=[[23.601290952344122,244.02463793444417,1282.6165260773723,2844.236833439171],[15.744926110709835,117.6939508913125,537.1811018620099,1621.3895745666903,3290.7992357334597,4362.619090143247,3439.3676741437216,1230.3393548037495],[2.568520192289822,1.8729528499234604,.5279051029514285,.06051834131244132,.0023352049762686918]],DY=Math.pow(2,53);var MC="zeta",SY=["typed","config","multiply","pow","divide","factorial","equal","smallerEq","isNegative","gamma","sin","subtract","add","?Complex","?BigNumber","pi"],_d=F(MC,SY,e=>{var{typed:r,config:t,multiply:n,pow:a,divide:i,factorial:u,equal:l,smallerEq:c,isNegative:o,gamma:s,sin:m,subtract:d,add:h,Complex:x,BigNumber:v,pi:y}=e;return r(MC,{number:S=>w(S,O=>O,()=>20),BigNumber:S=>w(S,O=>new v(O),()=>Math.abs(Math.log10(t.epsilon))),Complex:C});function w(S,O,_){return l(S,0)?O(-.5):l(S,1)?O(NaN):isFinite(S)?b(S,O,_,E=>E):o(S)?O(NaN):O(1)}function C(S){return S.re===0&&S.im===0?new x(-.5):S.re===1?new x(NaN,NaN):S.re===1/0&&S.im===0?new x(1):S.im===1/0||S.re===-1/0?new x(NaN,NaN):b(S,O=>O,O=>Math.round(1.3*15+.9*Math.abs(O.im)),O=>O.re)}function b(S,O,_,E){var T=_(S);if(E(S)>-(T-1)/2)return A(S,O(T),O);var R=n(a(2,S),a(O(y),d(S,1)));return R=n(R,m(n(i(O(y),2),S))),R=n(R,s(d(1,S))),n(R,b(d(1,S),O,_,E))}function M(S,O){for(var _=S,E=S;c(E,O);E=h(E,1)){var T=i(n(u(h(O,d(E,1))),a(4,E)),n(u(d(O,E)),u(n(2,E))));_=h(_,T)}return n(O,_)}function A(S,O,_){for(var E=i(1,n(M(_(0),O),d(1,a(2,d(1,S))))),T=_(0),R=_(1);c(R,O);R=h(R,1))T=h(T,i(n((-1)**(R-1),M(R,O)),a(R,S)));return n(E,T)}});var CC="mode",NY=["typed","isNaN","isNumeric"],Od=F(CC,NY,e=>{var{typed:r,isNaN:t,isNumeric:n}=e;return r(CC,{"Array | Matrix":a,"...":function(u){return a(u)}});function a(i){i=gr(i.valueOf());var u=i.length;if(u===0)throw new Error("Cannot calculate mode of an empty array");for(var l={},c=[],o=0,s=0;so&&(o=l[m],c=[m])}return c}});function Et(e,r,t){var n;return String(e).indexOf("Unexpected type")!==-1?(n=arguments.length>2?" (type: "+Fr(t)+", value: "+JSON.stringify(t)+")":" (type: "+e.data.actual+")",new TypeError("Cannot calculate "+r+", unexpected type of argument"+n)):String(e).indexOf("complex numbers")!==-1?(n=arguments.length>2?" (type: "+Fr(t)+", value: "+JSON.stringify(t)+")":"",new TypeError("Cannot calculate "+r+", no ordering relation is defined for complex numbers"+n)):e}var EC="prod",AY=["typed","config","multiplyScalar","numeric"],Bd=F(EC,AY,e=>{var{typed:r,config:t,multiplyScalar:n,numeric:a}=e;return r(EC,{"Array | Matrix":i,"Array | Matrix, number | BigNumber":function(l,c){throw new Error("prod(A, dim) is not yet supported")},"...":function(l){return i(l)}});function i(u){var l;if(An(u,function(c){try{l=l===void 0?c:n(l,c)}catch(o){throw Et(o,"prod",c)}}),typeof l=="string"&&(l=a(l,t.number)),l===void 0)throw new Error("Cannot calculate prod of an empty array");return l}});var TC="format",MY=["typed"],Pd=F(TC,MY,e=>{var{typed:r}=e;return r(TC,{any:lr,"any, Object | function | number | BigNumber":lr})});var FC="bin",CY=["typed","format"],Id=F(FC,CY,e=>{var{typed:r,format:t}=e;return r(FC,{"number | BigNumber":function(a){return t(a,{notation:"bin"})},"number | BigNumber, number | BigNumber":function(a,i){return t(a,{notation:"bin",wordSize:i})}})});var _C="oct",EY=["typed","format"],Rd=F(_C,EY,e=>{var{typed:r,format:t}=e;return r(_C,{"number | BigNumber":function(a){return t(a,{notation:"oct"})},"number | BigNumber, number | BigNumber":function(a,i){return t(a,{notation:"oct",wordSize:i})}})});var OC="hex",TY=["typed","format"],kd=F(OC,TY,e=>{var{typed:r,format:t}=e;return r(OC,{"number | BigNumber":function(a){return t(a,{notation:"hex"})},"number | BigNumber, number | BigNumber":function(a,i){return t(a,{notation:"hex",wordSize:i})}})});var qd=/\\$([\\w.]+)/g;var BC="print",FY=["typed"],Qu=F(BC,FY,e=>{var{typed:r}=e;return r(BC,{"string, Object | Array":PC,"string, Object | Array, number | Object":PC})});function PC(e,r,t){return e.replace(qd,function(n,a){var i=a.split("."),u=r[i.shift()];for(u!==void 0&&u.isMatrix&&(u=u.toArray());i.length&&u!==void 0;){var l=i.shift();u=l?u[l]:u+"."}return u!==void 0?St(u)?u:lr(u,t):n})}var IC="to",_Y=["typed","matrix","concat"],Ld=F(IC,_Y,e=>{var{typed:r,matrix:t,concat:n}=e,a=vr({typed:r,matrix:t,concat:n});return r(IC,{"Unit, Unit | string":(i,u)=>i.to(u)},a({Ds:!0}))});var RC="isPrime",OY=["typed"],zd=F(RC,OY,e=>{var{typed:r}=e;return r(RC,{number:function(n){if(n*0!==0)return!1;if(n<=3)return n>1;if(n%2===0||n%3===0)return!1;for(var a=5;a*a<=n;a+=6)if(n%a===0||n%(a+2)===0)return!1;return!0},BigNumber:function(n){if(n.toNumber()*0!==0)return!1;if(n.lte(3))return n.gt(1);if(n.mod(2).eq(0)||n.mod(3).eq(0))return!1;if(n.lt(Math.pow(2,32))){for(var a=n.toNumber(),i=5;i*i<=a;i+=6)if(a%i===0||a%(i+2)===0)return!1;return!0}function u(C,b,M){for(var A=1;!b.eq(0);)b.mod(2).eq(0)?(b=b.div(2),C=C.mul(C).mod(M)):(b=b.sub(1),A=C.mul(A).mod(M));return A}var l=n.constructor.clone({precision:n.toFixed(0).length*2});n=new l(n);for(var c=0,o=n.sub(1);o.mod(2).eq(0);)o=o.div(2),c+=1;var s=null;if(n.lt("3317044064679887385961981"))s=[2,3,5,7,11,13,17,19,23,29,31,37,41].filter(C=>Cn=>je(n,t))})});var BY="numeric",PY=["number","?bignumber","?fraction"],Ud=F(BY,PY,e=>{var{number:r,bignumber:t,fraction:n}=e,a={string:!0,number:!0,BigNumber:!0,Fraction:!0},i={number:u=>r(u),BigNumber:t?u=>t(u):Hu,Fraction:n?u=>n(u):vd};return function(l){var c=arguments.length>1&&arguments[1]!==void 0?arguments[1]:"number",o=arguments.length>2?arguments[2]:void 0;if(o!==void 0)throw new SyntaxError("numeric() takes one or two arguments");var s=Fr(l);if(!(s in a))throw new TypeError("Cannot convert "+l+' of type "'+s+'"; valid input types are '+Object.keys(a).join(", "));if(!(c in i))throw new TypeError("Cannot convert "+l+' to type "'+c+'"; valid output types are '+Object.keys(i).join(", "));return c===s?l:i[c](l)}});var kC="divideScalar",IY=["typed","numeric"],Wd=F(kC,IY,e=>{var{typed:r,numeric:t}=e;return r(kC,{"number, number":function(a,i){return a/i},"Complex, Complex":function(a,i){return a.div(i)},"BigNumber, BigNumber":function(a,i){return a.div(i)},"Fraction, Fraction":function(a,i){return a.div(i)},"Unit, number | Complex | Fraction | BigNumber | Unit":(n,a)=>n.divide(a),"number | Fraction | Complex | BigNumber, Unit":(n,a)=>a.divideInto(n)})});var qC="pow",RY=["typed","config","identity","multiply","matrix","inv","fraction","number","Complex"],Yd=F(qC,RY,e=>{var{typed:r,config:t,identity:n,multiply:a,matrix:i,inv:u,number:l,fraction:c,Complex:o}=e;return r(qC,{"number, number":s,"Complex, Complex":function(x,v){return x.pow(v)},"BigNumber, BigNumber":function(x,v){return v.isInteger()||x>=0||t.predictable?x.pow(v):new o(x.toNumber(),0).pow(v.toNumber(),0)},"Fraction, Fraction":function(x,v){var y=x.pow(v);if(y!=null)return y;if(t.predictable)throw new Error("Result of pow is non-rational and cannot be expressed as a fraction");return s(x.valueOf(),v.valueOf())},"Array, number":m,"Array, BigNumber":function(x,v){return m(x,v.toNumber())},"Matrix, number":d,"Matrix, BigNumber":function(x,v){return d(x,v.toNumber())},"Unit, number | BigNumber":function(x,v){return x.pow(v)}});function s(h,x){if(t.predictable&&!Ze(x)&&h<0)try{var v=c(x),y=l(v);if((x===y||Math.abs((x-y)/x)<1e-14)&&v.d%2===1)return(v.n%2===0?1:-1)*Math.pow(-h,x)}catch{}return t.predictable&&(h<-1&&x===1/0||h>-1&&h<0&&x===-1/0)?NaN:Ze(x)||h>=0||t.predictable?Tw(h,x):h*h<1&&x===1/0||h*h>1&&x===-1/0?0:new o(h,0).pow(x,0)}function m(h,x){if(!Ze(x))throw new TypeError("For A^b, b must be an integer (value is "+x+")");var v=ur(h);if(v.length!==2)throw new Error("For A^b, A must be 2 dimensional (A has "+v.length+" dimensions)");if(v[0]!==v[1])throw new Error("For A^b, A must be square (size is "+v[0]+"x"+v[1]+")");if(x<0)try{return m(u(h),-x)}catch(C){throw C.message==="Cannot calculate inverse, determinant is zero"?new TypeError("For A^b, when A is not invertible, b must be a positive integer (value is "+x+")"):C}for(var y=n(v[0]).valueOf(),w=h;x>=1;)(x&1)===1&&(y=a(w,y)),x>>=1,w=a(w,w);return y}function d(h,x){return i(m(h.valueOf(),x))}});var Xu="Number of decimals in function round must be an integer",LC="round",kY=["typed","config","matrix","equalScalar","zeros","BigNumber","DenseMatrix"],Hd=F(LC,kY,e=>{var{typed:r,config:t,matrix:n,equalScalar:a,zeros:i,BigNumber:u,DenseMatrix:l}=e,c=jr({typed:r,equalScalar:a}),o=Wr({typed:r,DenseMatrix:l}),s=qt({typed:r});function m(d){return Math.abs(Nu(d).exponent)}return r(LC,{number:function(h){var x=Ou(h,m(t.epsilon)),v=At(h,x,t.epsilon)?x:h;return Ou(v)},"number, number":function(h,x){var v=m(t.epsilon);if(x>=v)return Ou(h,x);var y=Ou(h,v),w=At(h,y,t.epsilon)?y:h;return Ou(w,x)},"number, BigNumber":function(h,x){if(!x.isInteger())throw new TypeError(Xu);return new u(h).toDecimalPlaces(x.toNumber())},Complex:function(h){return h.round()},"Complex, number":function(h,x){if(x%1)throw new TypeError(Xu);return h.round(x)},"Complex, BigNumber":function(h,x){if(!x.isInteger())throw new TypeError(Xu);var v=x.toNumber();return h.round(v)},BigNumber:function(h){var x=new u(h).toDecimalPlaces(m(t.epsilon)),v=$t(h,x,t.epsilon)?x:h;return v.toDecimalPlaces(0)},"BigNumber, BigNumber":function(h,x){if(!x.isInteger())throw new TypeError(Xu);var v=m(t.epsilon);if(x>=v)return h.toDecimalPlaces(x.toNumber());var y=h.toDecimalPlaces(v),w=$t(h,y,t.epsilon)?y:h;return w.toDecimalPlaces(x.toNumber())},Fraction:function(h){return h.round()},"Fraction, number":function(h,x){if(x%1)throw new TypeError(Xu);return h.round(x)},"Fraction, BigNumber":function(h,x){if(!x.isInteger())throw new TypeError(Xu);return h.round(x.toNumber())},"Unit, number, Unit":r.referToSelf(d=>function(h,x,v){var y=h.toNumeric(v);return v.multiply(d(y,x))}),"Unit, BigNumber, Unit":r.referToSelf(d=>(h,x,v)=>d(h,x.toNumber(),v)),"Unit, Unit":r.referToSelf(d=>(h,x)=>d(h,0,x)),"Array | Matrix, number, Unit":r.referToSelf(d=>(h,x,v)=>je(h,y=>d(y,x,v),!0)),"Array | Matrix, BigNumber, Unit":r.referToSelf(d=>(h,x,v)=>d(h,x.toNumber(),v)),"Array | Matrix, Unit":r.referToSelf(d=>(h,x)=>d(h,0,x)),"Array | Matrix":r.referToSelf(d=>h=>je(h,d,!0)),"SparseMatrix, number | BigNumber":r.referToSelf(d=>(h,x)=>c(h,x,d,!1)),"DenseMatrix, number | BigNumber":r.referToSelf(d=>(h,x)=>s(h,x,d,!1)),"Array, number | BigNumber":r.referToSelf(d=>(h,x)=>s(n(h),x,d,!1).valueOf()),"number | Complex | BigNumber | Fraction, SparseMatrix":r.referToSelf(d=>(h,x)=>a(h,0)?i(x.size(),x.storage()):o(x,h,d,!0)),"number | Complex | BigNumber | Fraction, DenseMatrix":r.referToSelf(d=>(h,x)=>a(h,0)?i(x.size(),x.storage()):s(x,h,d,!0)),"number | Complex | BigNumber | Fraction, Array":r.referToSelf(d=>(h,x)=>s(n(x),h,d,!0).valueOf())})});var zC="log",qY=["config","typed","divideScalar","Complex"],$d=F(zC,qY,e=>{var{typed:r,config:t,divideScalar:n,Complex:a}=e;return r(zC,{number:function(u){return u>=0||t.predictable?YM(u):new a(u,0).log()},Complex:function(u){return u.log()},BigNumber:function(u){return!u.isNegative()||t.predictable?u.ln():new a(u.toNumber(),0).log()},"any, any":r.referToSelf(i=>(u,l)=>n(i(u),i(l)))})});var UC="log1p",LY=["typed","config","divideScalar","log","Complex"],Gd=F(UC,LY,e=>{var{typed:r,config:t,divideScalar:n,log:a,Complex:i}=e;return r(UC,{number:function(c){return c>=-1||t.predictable?Mm(c):u(new i(c,0))},Complex:u,BigNumber:function(c){var o=c.plus(1);return!o.isNegative()||t.predictable?o.ln():u(new i(c.toNumber(),0))},"Array | Matrix":r.referToSelf(l=>c=>je(c,l)),"any, any":r.referToSelf(l=>(c,o)=>n(l(c),a(o)))});function u(l){var c=l.re+1;return new i(Math.log(Math.sqrt(c*c+l.im*l.im)),Math.atan2(l.im,c))}});var WC="nthRoots",zY=["config","typed","divideScalar","Complex"],Vd=F(WC,zY,e=>{var{typed:r,config:t,divideScalar:n,Complex:a}=e,i=[function(c){return new a(c,0)},function(c){return new a(0,c)},function(c){return new a(-c,0)},function(c){return new a(0,-c)}];function u(l,c){if(c<0)throw new Error("Root must be greater than zero");if(c===0)throw new Error("Root must be non-zero");if(c%1!==0)throw new Error("Root must be an integer");if(l===0||l.abs()===0)return[new a(0,0)];var o=typeof l=="number",s;(o||l.re===0||l.im===0)&&(o?s=2*+(l<0):l.im===0?s=2*+(l.re<0):s=2*+(l.im<0)+1);for(var m=l.arg(),d=l.abs(),h=[],x=Math.pow(d,1/c),v=0;v{var{typed:r,equalScalar:t,matrix:n,pow:a,DenseMatrix:i,concat:u}=e,l=lt({typed:r}),c=Zt({typed:r,DenseMatrix:i}),o=jr({typed:r,equalScalar:t}),s=Wr({typed:r,DenseMatrix:i}),m=vr({typed:r,matrix:n,concat:u}),d={};for(var h in a.signatures)Object.prototype.hasOwnProperty.call(a.signatures,h)&&!h.includes("Matrix")&&!h.includes("Array")&&(d[h]=a.signatures[h]);var x=r(d);return r(YC,m({elop:x,SS:c,DS:l,Ss:o,sS:s}))});var HC="dotDivide",WY=["typed","matrix","equalScalar","divideScalar","DenseMatrix","concat"],Qd=F(HC,WY,e=>{var{typed:r,matrix:t,equalScalar:n,divideScalar:a,DenseMatrix:i,concat:u}=e,l=Lt({typed:r,equalScalar:n}),c=lt({typed:r}),o=Zt({typed:r,DenseMatrix:i}),s=jr({typed:r,equalScalar:n}),m=Wr({typed:r,DenseMatrix:i}),d=vr({typed:r,matrix:t,concat:u});return r(HC,d({elop:a,SS:o,DS:c,SD:l,Ss:s,sS:m}))});function _i(e){var{DenseMatrix:r}=e;return function(n,a,i){var u=n.size();if(u.length!==2)throw new RangeError("Matrix must be two dimensional (size: "+lr(u)+")");var l=u[0],c=u[1];if(l!==c)throw new RangeError("Matrix must be square (size: "+lr(u)+")");var o=[];if(Qe(a)){var s=a.size(),m=a._data;if(s.length===1){if(s[0]!==l)throw new RangeError("Dimension mismatch. Matrix columns must match vector length.");for(var d=0;d{var{typed:r,matrix:t,divideScalar:n,multiplyScalar:a,subtractScalar:i,equalScalar:u,DenseMatrix:l}=e,c=_i({DenseMatrix:l});return r($C,{"SparseMatrix, Array | Matrix":function(d,h){return s(d,h)},"DenseMatrix, Array | Matrix":function(d,h){return o(d,h)},"Array, Array | Matrix":function(d,h){var x=t(d),v=o(x,h);return v.valueOf()}});function o(m,d){d=c(m,d,!0);for(var h=d._data,x=m._size[0],v=m._size[1],y=[],w=m._data,C=0;CM&&(O.push(y[R]),_.push(q))}if(u(S,0))throw new Error("Linear system cannot be solved since matrix is singular");for(var W=n(A,S),G=0,H=_.length;G{var{typed:r,matrix:t,divideScalar:n,multiplyScalar:a,subtractScalar:i,equalScalar:u,DenseMatrix:l}=e,c=_i({DenseMatrix:l});return r(GC,{"SparseMatrix, Array | Matrix":function(d,h){return s(d,h)},"DenseMatrix, Array | Matrix":function(d,h){return o(d,h)},"Array, Array | Matrix":function(d,h){var x=t(d),v=o(x,h);return v.valueOf()}});function o(m,d){d=c(m,d,!0);for(var h=d._data,x=m._size[0],v=m._size[1],y=[],w=m._data,C=v-1;C>=0;C--){var b=h[C][0]||0,M=void 0;if(u(b,0))M=0;else{var A=w[C][C];if(u(A,0))throw new Error("Linear system cannot be solved since matrix is singular");M=n(b,A);for(var S=C-1;S>=0;S--)h[S]=[i(h[S][0]||0,a(M,w[S][C]))]}y[C]=[M]}return new l({data:y,size:[x,1]})}function s(m,d){d=c(m,d,!0);for(var h=d._data,x=m._size[0],v=m._size[1],y=m._values,w=m._index,C=m._ptr,b=[],M=v-1;M>=0;M--){var A=h[M][0]||0;if(u(A,0))b[M]=[0];else{for(var S=0,O=[],_=[],E=C[M],T=C[M+1],R=T-1;R>=E;R--){var q=w[R];q===M?S=y[R]:q{var{typed:r,matrix:t,divideScalar:n,multiplyScalar:a,subtractScalar:i,equalScalar:u,DenseMatrix:l}=e,c=_i({DenseMatrix:l});return r(VC,{"SparseMatrix, Array | Matrix":function(d,h){return s(d,h)},"DenseMatrix, Array | Matrix":function(d,h){return o(d,h)},"Array, Array | Matrix":function(d,h){var x=t(d),v=o(x,h);return v.map(y=>y.valueOf())}});function o(m,d){for(var h=[c(m,d,!0)._data.map(_=>_[0])],x=m._data,v=m._size[0],y=m._size[1],w=0;wnew l({data:_.map(E=>[E]),size:[v,1]}))}function s(m,d){for(var h=[c(m,d,!0)._data.map(pe=>pe[0])],x=m._size[0],v=m._size[1],y=m._values,w=m._index,C=m._ptr,b=0;bb&&(O.push(y[q]),_.push(W))}if(u(R,0))if(u(S[b],0)){if(A===0){var k=[...S];k[b]=1;for(var K=0,z=_.length;Knew l({data:pe.map(ae=>[ae]),size:[x,1]}))}});var ZC="usolveAll",GY=["typed","matrix","divideScalar","multiplyScalar","subtractScalar","equalScalar","DenseMatrix"],jd=F(ZC,GY,e=>{var{typed:r,matrix:t,divideScalar:n,multiplyScalar:a,subtractScalar:i,equalScalar:u,DenseMatrix:l}=e,c=_i({DenseMatrix:l});return r(ZC,{"SparseMatrix, Array | Matrix":function(d,h){return s(d,h)},"DenseMatrix, Array | Matrix":function(d,h){return o(d,h)},"Array, Array | Matrix":function(d,h){var x=t(d),v=o(x,h);return v.map(y=>y.valueOf())}});function o(m,d){for(var h=[c(m,d,!0)._data.map(_=>_[0])],x=m._data,v=m._size[0],y=m._size[1],w=y-1;w>=0;w--)for(var C=h.length,b=0;b=0;O--)S[O]=i(S[O],x[O][w]);h.push(S)}}else{if(b===0)return[];h.splice(b,1),b-=1,C-=1}else{M[w]=n(M[w],x[w][w]);for(var A=w-1;A>=0;A--)M[A]=i(M[A],a(M[w],x[A][w]))}}return h.map(_=>new l({data:_.map(E=>[E]),size:[v,1]}))}function s(m,d){for(var h=[c(m,d,!0)._data.map(pe=>pe[0])],x=m._size[0],v=m._size[1],y=m._values,w=m._index,C=m._ptr,b=v-1;b>=0;b--)for(var M=h.length,A=0;A=E;q--){var W=w[q];W===b?R=y[q]:Wnew l({data:pe.map(ae=>[ae]),size:[x,1]}))}});var VY="matAlgo08xS0Sid",ZY=["typed","equalScalar"],Ju=F(VY,ZY,e=>{var{typed:r,equalScalar:t}=e;return function(a,i,u){var l=a._values,c=a._index,o=a._ptr,s=a._size,m=a._datatype||a._data===void 0?a._datatype:a.getDataType(),d=i._values,h=i._index,x=i._ptr,v=i._size,y=i._datatype||i._data===void 0?i._datatype:i.getDataType();if(s.length!==v.length)throw new pr(s.length,v.length);if(s[0]!==v[0]||s[1]!==v[1])throw new RangeError("Dimension mismatch. Matrix A ("+s+") must match Matrix B ("+v+")");if(!l||!d)throw new Error("Cannot perform operation on Pattern Sparse Matrices");var w=s[0],C=s[1],b,M=t,A=0,S=u;typeof m=="string"&&m===y&&m!=="mixed"&&(b=m,M=r.find(t,[b,b]),A=r.convert(0,b),S=r.find(u,[b,b]));for(var O=[],_=[],E=[],T=[],R=[],q,W,G,H,L=0;L{var{typed:r,matrix:t}=e;return{"Array, number":r.referTo("DenseMatrix, number",n=>(a,i)=>n(t(a),i).valueOf()),"Array, BigNumber":r.referTo("DenseMatrix, BigNumber",n=>(a,i)=>n(t(a),i).valueOf()),"number, Array":r.referTo("number, DenseMatrix",n=>(a,i)=>n(a,t(i)).valueOf()),"BigNumber, Array":r.referTo("BigNumber, DenseMatrix",n=>(a,i)=>n(a,t(i)).valueOf())}});var QC="leftShift",QY=["typed","matrix","equalScalar","zeros","DenseMatrix","concat"],eh=F(QC,QY,e=>{var{typed:r,matrix:t,equalScalar:n,zeros:a,DenseMatrix:i,concat:u}=e,l=Mn({typed:r}),c=Lt({typed:r,equalScalar:n}),o=Ju({typed:r,equalScalar:n}),s=jn({typed:r,DenseMatrix:i}),m=jr({typed:r,equalScalar:n}),d=qt({typed:r}),h=vr({typed:r,matrix:t,concat:u}),x=Ku({typed:r,matrix:t});return r(QC,{"number, number":Pw,"BigNumber, BigNumber":L2,"SparseMatrix, number | BigNumber":r.referToSelf(v=>(y,w)=>n(w,0)?y.clone():m(y,w,v,!1)),"DenseMatrix, number | BigNumber":r.referToSelf(v=>(y,w)=>n(w,0)?y.clone():d(y,w,v,!1)),"number | BigNumber, SparseMatrix":r.referToSelf(v=>(y,w)=>n(y,0)?a(w.size(),w.storage()):s(w,y,v,!0)),"number | BigNumber, DenseMatrix":r.referToSelf(v=>(y,w)=>n(y,0)?a(w.size(),w.storage()):d(w,y,v,!0))},x,h({SS:o,DS:l,SD:c}))});var XC="rightArithShift",XY=["typed","matrix","equalScalar","zeros","DenseMatrix","concat"],rh=F(XC,XY,e=>{var{typed:r,matrix:t,equalScalar:n,zeros:a,DenseMatrix:i,concat:u}=e,l=Mn({typed:r}),c=Lt({typed:r,equalScalar:n}),o=Ju({typed:r,equalScalar:n}),s=jn({typed:r,DenseMatrix:i}),m=jr({typed:r,equalScalar:n}),d=qt({typed:r}),h=vr({typed:r,matrix:t,concat:u}),x=Ku({typed:r,matrix:t});return r(XC,{"number, number":Iw,"BigNumber, BigNumber":z2,"SparseMatrix, number | BigNumber":r.referToSelf(v=>(y,w)=>n(w,0)?y.clone():m(y,w,v,!1)),"DenseMatrix, number | BigNumber":r.referToSelf(v=>(y,w)=>n(w,0)?y.clone():d(y,w,v,!1)),"number | BigNumber, SparseMatrix":r.referToSelf(v=>(y,w)=>n(y,0)?a(w.size(),w.storage()):s(w,y,v,!0)),"number | BigNumber, DenseMatrix":r.referToSelf(v=>(y,w)=>n(y,0)?a(w.size(),w.storage()):d(w,y,v,!0))},x,h({SS:o,DS:l,SD:c}))});var JC="rightLogShift",JY=["typed","matrix","equalScalar","zeros","DenseMatrix","concat"],th=F(JC,JY,e=>{var{typed:r,matrix:t,equalScalar:n,zeros:a,DenseMatrix:i,concat:u}=e,l=Mn({typed:r}),c=Lt({typed:r,equalScalar:n}),o=Ju({typed:r,equalScalar:n}),s=jn({typed:r,DenseMatrix:i}),m=jr({typed:r,equalScalar:n}),d=qt({typed:r}),h=vr({typed:r,matrix:t,concat:u}),x=Ku({typed:r,matrix:t});return r(JC,{"number, number":Rw,"SparseMatrix, number | BigNumber":r.referToSelf(v=>(y,w)=>n(w,0)?y.clone():m(y,w,v,!1)),"DenseMatrix, number | BigNumber":r.referToSelf(v=>(y,w)=>n(w,0)?y.clone():d(y,w,v,!1)),"number | BigNumber, SparseMatrix":r.referToSelf(v=>(y,w)=>n(y,0)?a(w.size(),w.storage()):s(w,y,v,!0)),"number | BigNumber, DenseMatrix":r.referToSelf(v=>(y,w)=>n(y,0)?a(w.size(),w.storage()):d(w,y,v,!0))},x,h({SS:o,DS:l,SD:c}))});var KC="and",KY=["typed","matrix","equalScalar","zeros","not","concat"],ju=F(KC,KY,e=>{var{typed:r,matrix:t,equalScalar:n,zeros:a,not:i,concat:u}=e,l=Lt({typed:r,equalScalar:n}),c=zo({typed:r,equalScalar:n}),o=jr({typed:r,equalScalar:n}),s=qt({typed:r}),m=vr({typed:r,matrix:t,concat:u});return r(KC,{"number, number":Ww,"Complex, Complex":function(h,x){return(h.re!==0||h.im!==0)&&(x.re!==0||x.im!==0)},"BigNumber, BigNumber":function(h,x){return!h.isZero()&&!x.isZero()&&!h.isNaN()&&!x.isNaN()},"Unit, Unit":r.referToSelf(d=>(h,x)=>d(h.value||0,x.value||0)),"SparseMatrix, any":r.referToSelf(d=>(h,x)=>i(x)?a(h.size(),h.storage()):o(h,x,d,!1)),"DenseMatrix, any":r.referToSelf(d=>(h,x)=>i(x)?a(h.size(),h.storage()):s(h,x,d,!1)),"any, SparseMatrix":r.referToSelf(d=>(h,x)=>i(h)?a(h.size(),h.storage()):o(x,h,d,!0)),"any, DenseMatrix":r.referToSelf(d=>(h,x)=>i(h)?a(h.size(),h.storage()):s(x,h,d,!0)),"Array, any":r.referToSelf(d=>(h,x)=>d(t(h),x).valueOf()),"any, Array":r.referToSelf(d=>(h,x)=>d(h,t(x)).valueOf())},m({SS:c,DS:l}))});var nh="compare",jY=["typed","config","matrix","equalScalar","BigNumber","Fraction","DenseMatrix","concat"],ah=F(nh,jY,e=>{var{typed:r,config:t,equalScalar:n,matrix:a,BigNumber:i,Fraction:u,DenseMatrix:l,concat:c}=e,o=lt({typed:r}),s=Lo({typed:r,equalScalar:n}),m=Wr({typed:r,DenseMatrix:l}),d=vr({typed:r,matrix:a,concat:c}),h=Pa({typed:r});return r(nh,eH({typed:r,config:t}),{"boolean, boolean":function(v,y){return v===y?0:v>y?1:-1},"BigNumber, BigNumber":function(v,y){return $t(v,y,t.epsilon)?new i(0):new i(v.cmp(y))},"Fraction, Fraction":function(v,y){return new u(v.compare(y))},"Complex, Complex":function(){throw new TypeError("No ordering relation is defined for complex numbers")}},h,d({SS:s,DS:o,Ss:m}))}),eH=F(nh,["typed","config"],e=>{var{typed:r,config:t}=e;return r(nh,{"number, number":function(a,i){return At(a,i,t.epsilon)?0:a>i?1:-1}})});var Fs=ca(eE(),1);var rE="compareNatural",rH=["typed","compare"],ih=F(rE,rH,e=>{var{typed:r,compare:t}=e,n=t.signatures["boolean,boolean"];return r(rE,{"any, any":a});function a(c,o){var s=Fr(c),m=Fr(o),d;if((s==="number"||s==="BigNumber"||s==="Fraction")&&(m==="number"||m==="BigNumber"||m==="Fraction"))return d=t(c,o),d.toString()!=="0"?d>0?1:-1:(0,Fs.default)(s,m);var h=["Array","DenseMatrix","SparseMatrix"];if(h.includes(s)||h.includes(m))return d=i(a,c,o),d!==0?d:(0,Fs.default)(s,m);if(s!==m)return(0,Fs.default)(s,m);if(s==="Complex")return tH(c,o);if(s==="Unit")return c.equalBase(o)?a(c.value,o.value):u(a,c.formatUnits(),o.formatUnits());if(s==="boolean")return n(c,o);if(s==="string")return(0,Fs.default)(c,o);if(s==="Object")return l(a,c,o);if(s==="null"||s==="undefined")return 0;throw new TypeError('Unsupported type of value "'+s+'"')}function i(c,o,s){return pa(o)&&pa(s)?u(c,o.toJSON().values,s.toJSON().values):pa(o)?i(c,o.toArray(),s):pa(s)?i(c,o,s.toArray()):Xi(o)?i(c,o.toJSON().data,s):Xi(s)?i(c,o,s.toJSON().data):Array.isArray(o)?Array.isArray(s)?u(c,o,s):i(c,o,[s]):i(c,[o],s)}function u(c,o,s){for(var m=0,d=Math.min(o.length,s.length);ms.length?1:o.lengthr.re?1:e.rer.im?1:e.im{var{typed:r,matrix:t,concat:n}=e,a=vr({typed:r,matrix:t,concat:n});return r(tE,Fm,a({elop:Fm,Ds:!0}))});var sh="equal",aH=["typed","matrix","equalScalar","DenseMatrix","concat"],uh=F(sh,aH,e=>{var{typed:r,matrix:t,equalScalar:n,DenseMatrix:a,concat:i}=e,u=lt({typed:r}),l=Zt({typed:r,DenseMatrix:a}),c=Wr({typed:r,DenseMatrix:a}),o=vr({typed:r,matrix:t,concat:i});return r(sh,iH({typed:r,equalScalar:n}),o({elop:n,SS:l,DS:u,Ss:c}))}),iH=F(sh,["typed","equalScalar"],e=>{var{typed:r,equalScalar:t}=e;return r(sh,{"any, any":function(a,i){return a===null?i===null:i===null?a===null:a===void 0?i===void 0:i===void 0?a===void 0:t(a,i)}})});var nE="equalText",oH=["typed","compareText","isZero"],fh=F(nE,oH,e=>{var{typed:r,compareText:t,isZero:n}=e;return r(nE,{"any, any":function(i,u){return n(t(i,u))}})});var ch="smaller",sH=["typed","config","matrix","DenseMatrix","concat"],lh=F(ch,sH,e=>{var{typed:r,config:t,matrix:n,DenseMatrix:a,concat:i}=e,u=lt({typed:r}),l=Zt({typed:r,DenseMatrix:a}),c=Wr({typed:r,DenseMatrix:a}),o=vr({typed:r,matrix:n,concat:i}),s=Pa({typed:r});return r(ch,uH({typed:r,config:t}),{"boolean, boolean":(m,d)=>mm.compare(d)===-1,"Complex, Complex":function(d,h){throw new TypeError("No ordering relation is defined for complex numbers")}},s,o({SS:l,DS:u,Ss:c}))}),uH=F(ch,["typed","config"],e=>{var{typed:r,config:t}=e;return r(ch,{"number, number":function(a,i){return a{var{typed:r,config:t,matrix:n,DenseMatrix:a,concat:i}=e,u=lt({typed:r}),l=Zt({typed:r,DenseMatrix:a}),c=Wr({typed:r,DenseMatrix:a}),o=vr({typed:r,matrix:n,concat:i}),s=Pa({typed:r});return r(mh,cH({typed:r,config:t}),{"boolean, boolean":(m,d)=>m<=d,"BigNumber, BigNumber":function(d,h){return d.lte(h)||$t(d,h,t.epsilon)},"Fraction, Fraction":(m,d)=>m.compare(d)!==1,"Complex, Complex":function(){throw new TypeError("No ordering relation is defined for complex numbers")}},s,o({SS:l,DS:u,Ss:c}))}),cH=F(mh,["typed","config"],e=>{var{typed:r,config:t}=e;return r(mh,{"number, number":function(a,i){return a<=i||At(a,i,t.epsilon)}})});var dh="larger",lH=["typed","config","matrix","DenseMatrix","concat"],hh=F(dh,lH,e=>{var{typed:r,config:t,matrix:n,DenseMatrix:a,concat:i}=e,u=lt({typed:r}),l=Zt({typed:r,DenseMatrix:a}),c=Wr({typed:r,DenseMatrix:a}),o=vr({typed:r,matrix:n,concat:i}),s=Pa({typed:r});return r(dh,mH({typed:r,config:t}),{"boolean, boolean":(m,d)=>m>d,"BigNumber, BigNumber":function(d,h){return d.gt(h)&&!$t(d,h,t.epsilon)},"Fraction, Fraction":(m,d)=>m.compare(d)===1,"Complex, Complex":function(){throw new TypeError("No ordering relation is defined for complex numbers")}},s,o({SS:l,DS:u,Ss:c}))}),mH=F(dh,["typed","config"],e=>{var{typed:r,config:t}=e;return r(dh,{"number, number":function(a,i){return a>i&&!At(a,i,t.epsilon)}})});var vh="largerEq",pH=["typed","config","matrix","DenseMatrix","concat"],gh=F(vh,pH,e=>{var{typed:r,config:t,matrix:n,DenseMatrix:a,concat:i}=e,u=lt({typed:r}),l=Zt({typed:r,DenseMatrix:a}),c=Wr({typed:r,DenseMatrix:a}),o=vr({typed:r,matrix:n,concat:i}),s=Pa({typed:r});return r(vh,dH({typed:r,config:t}),{"boolean, boolean":(m,d)=>m>=d,"BigNumber, BigNumber":function(d,h){return d.gte(h)||$t(d,h,t.epsilon)},"Fraction, Fraction":(m,d)=>m.compare(d)!==-1,"Complex, Complex":function(){throw new TypeError("No ordering relation is defined for complex numbers")}},s,o({SS:l,DS:u,Ss:c}))}),dH=F(vh,["typed","config"],e=>{var{typed:r,config:t}=e;return r(vh,{"number, number":function(a,i){return a>=i||At(a,i,t.epsilon)}})});var aE="deepEqual",hH=["typed","equal"],xh=F(aE,hH,e=>{var{typed:r,equal:t}=e;return r(aE,{"any, any":function(i,u){return n(i.valueOf(),u.valueOf())}});function n(a,i){if(Array.isArray(a))if(Array.isArray(i)){var u=a.length;if(u!==i.length)return!1;for(var l=0;l{var{typed:r,config:t,equalScalar:n,matrix:a,DenseMatrix:i,concat:u}=e,l=lt({typed:r}),c=Zt({typed:r,DenseMatrix:i}),o=Wr({typed:r,DenseMatrix:i}),s=vr({typed:r,matrix:a,concat:u});return r(yh,gH({typed:r,equalScalar:n}),s({elop:m,SS:c,DS:l,Ss:o}));function m(d,h){return!n(d,h)}}),gH=F(yh,["typed","equalScalar"],e=>{var{typed:r,equalScalar:t}=e;return r(yh,{"any, any":function(a,i){return a===null?i!==null:i===null?a!==null:a===void 0?i!==void 0:i===void 0?a!==void 0:!t(a,i)}})});var iE="partitionSelect",xH=["typed","isNumeric","isNaN","compare"],wh=F(iE,xH,e=>{var{typed:r,isNumeric:t,isNaN:n,compare:a}=e,i=a,u=(o,s)=>-a(o,s);return r(iE,{"Array | Matrix, number":function(s,m){return l(s,m,i)},"Array | Matrix, number, string":function(s,m,d){if(d==="asc")return l(s,m,i);if(d==="desc")return l(s,m,u);throw new Error('Compare string must be "asc" or "desc"')},"Array | Matrix, number, function":l});function l(o,s,m){if(!Ze(s)||s<0)throw new Error("k must be a non-negative integer");if(Qe(o)){var d=o.size();if(d.length>1)throw new Error("Only one dimensional matrices supported");return c(o.valueOf(),s,m)}if(Array.isArray(o))return c(o,s,m)}function c(o,s,m){if(s>=o.length)throw new Error("k out of bounds");for(var d=0;d=0){var C=o[y];o[y]=o[v],o[v]=C,--y}else++v;m(o[v],w)>0&&--v,s<=v?x=v:h=v+1}return o[s]}});var oE="sort",yH=["typed","matrix","compare","compareNatural"],Dh=F(oE,yH,e=>{var{typed:r,matrix:t,compare:n,compareNatural:a}=e,i=n,u=(s,m)=>-n(s,m);return r(oE,{Array:function(m){return c(m),m.sort(i)},Matrix:function(m){return o(m),t(m.toArray().sort(i),m.storage())},"Array, function":function(m,d){return c(m),m.sort(d)},"Matrix, function":function(m,d){return o(m),t(m.toArray().sort(d),m.storage())},"Array, string":function(m,d){return c(m),m.sort(l(d))},"Matrix, string":function(m,d){return o(m),t(m.toArray().sort(l(d)),m.storage())}});function l(s){if(s==="asc")return i;if(s==="desc")return u;if(s==="natural")return a;throw new Error('String "asc", "desc", or "natural" expected')}function c(s){if(ur(s).length!==1)throw new Error("One dimensional array expected")}function o(s){if(s.size().length!==1)throw new Error("One dimensional matrix expected")}});var sE="max",bH=["typed","config","numeric","larger"],ef=F(sE,bH,e=>{var{typed:r,config:t,numeric:n,larger:a}=e;return r(sE,{"Array | Matrix":u,"Array | Matrix, number | BigNumber":function(c,o){return ko(c,o.valueOf(),i)},"...":function(c){if(Ba(c))throw new TypeError("Scalar values expected in function max");return u(c)}});function i(l,c){try{return a(l,c)?l:c}catch(o){throw Et(o,"max",c)}}function u(l){var c;if(An(l,function(o){try{isNaN(o)&&typeof o=="number"?c=NaN:(c===void 0||a(o,c))&&(c=o)}catch(s){throw Et(s,"max",o)}}),c===void 0)throw new Error("Cannot calculate max of an empty array");return typeof c=="string"&&(c=n(c,t.number)),c}});var uE="min",wH=["typed","config","numeric","smaller"],rf=F(uE,wH,e=>{var{typed:r,config:t,numeric:n,smaller:a}=e;return r(uE,{"Array | Matrix":u,"Array | Matrix, number | BigNumber":function(c,o){return ko(c,o.valueOf(),i)},"...":function(c){if(Ba(c))throw new TypeError("Scalar values expected in function min");return u(c)}});function i(l,c){try{return a(l,c)?l:c}catch(o){throw Et(o,"min",c)}}function u(l){var c;if(An(l,function(o){try{isNaN(o)&&typeof o=="number"?c=NaN:(c===void 0||a(o,c))&&(c=o)}catch(s){throw Et(s,"min",o)}}),c===void 0)throw new Error("Cannot calculate min of an empty array");return typeof c=="string"&&(c=n(c,t.number)),c}});var DH="ImmutableDenseMatrix",SH=["smaller","DenseMatrix"],Sh=F(DH,SH,e=>{var{smaller:r,DenseMatrix:t}=e;function n(a,i){if(!(this instanceof n))throw new SyntaxError("Constructor must be called with the new operator");if(i&&!St(i))throw new Error("Invalid datatype: "+i);if(Qe(a)||Mr(a)){var u=new t(a,i);this._data=u._data,this._size=u._size,this._datatype=u._datatype,this._min=null,this._max=null}else if(a&&Mr(a.data)&&Mr(a.size))this._data=a.data,this._size=a.size,this._datatype=a.datatype,this._min=typeof a.min<"u"?a.min:null,this._max=typeof a.max<"u"?a.max:null;else{if(a)throw new TypeError("Unsupported type of data ("+Fr(a)+")");this._data=[],this._size=[0],this._datatype=i,this._min=null,this._max=null}}return n.prototype=new t,n.prototype.type="ImmutableDenseMatrix",n.prototype.isImmutableDenseMatrix=!0,n.prototype.subset=function(a){switch(arguments.length){case 1:{var i=t.prototype.subset.call(this,a);return Qe(i)?new n({data:i._data,size:i._size,datatype:i._datatype}):i}case 2:case 3:throw new Error("Cannot invoke set subset on an Immutable Matrix instance");default:throw new SyntaxError("Wrong number of arguments")}},n.prototype.set=function(){throw new Error("Cannot invoke set on an Immutable Matrix instance")},n.prototype.resize=function(){throw new Error("Cannot invoke resize on an Immutable Matrix instance")},n.prototype.reshape=function(){throw new Error("Cannot invoke reshape on an Immutable Matrix instance")},n.prototype.clone=function(){return new n({data:ar(this._data),size:ar(this._size),datatype:this._datatype})},n.prototype.toJSON=function(){return{mathjs:"ImmutableDenseMatrix",data:this._data,size:this._size,datatype:this._datatype}},n.fromJSON=function(a){return new n(a)},n.prototype.swapRows=function(){throw new Error("Cannot invoke swapRows on an Immutable Matrix instance")},n.prototype.min=function(){if(this._min===null){var a=null;this.forEach(function(i){(a===null||r(i,a))&&(a=i)}),this._min=a!==null?a:void 0}return this._min},n.prototype.max=function(){if(this._max===null){var a=null;this.forEach(function(i){(a===null||r(a,i))&&(a=i)}),this._max=a!==null?a:void 0}return this._max},n},{isClass:!0});var NH="Index",AH=["ImmutableDenseMatrix","getMatrixDataType"],Nh=F(NH,AH,e=>{var{ImmutableDenseMatrix:r,getMatrixDataType:t}=e;function n(i){if(!(this instanceof n))throw new SyntaxError("Constructor must be called with the new operator");this._dimensions=[],this._sourceSize=[],this._isScalar=!0;for(var u=0,l=arguments.length;u{t&&r.push(n)}),r}var MH="FibonacciHeap",CH=["smaller","larger"],Ah=F(MH,CH,e=>{var{smaller:r,larger:t}=e,n=1/Math.log((1+Math.sqrt(5))/2);function a(){if(!(this instanceof a))throw new SyntaxError("Constructor must be called with the new operator");this._minimum=null,this._size=0}a.prototype.type="FibonacciHeap",a.prototype.isFibonacciHeap=!0,a.prototype.insert=function(s,m){var d={key:s,value:m,degree:0};if(this._minimum){var h=this._minimum;d.left=h,d.right=h.right,h.right=d,d.right.left=d,r(s,h.key)&&(this._minimum=d)}else d.left=d,d.right=d,this._minimum=d;return this._size++,d},a.prototype.size=function(){return this._size},a.prototype.clear=function(){this._minimum=null,this._size=0},a.prototype.isEmpty=function(){return this._size===0},a.prototype.extractMinimum=function(){var s=this._minimum;if(s===null)return s;for(var m=this._minimum,d=s.degree,h=s.child;d>0;){var x=h.right;h.left.right=h.right,h.right.left=h.left,h.left=m,h.right=m.right,m.right=h,h.right.left=h,h.parent=null,h=x,d--}return s.left.right=s.right,s.right.left=s.left,s===s.right?m=null:(m=s.right,m=o(m,this._size)),this._size--,this._minimum=m,s},a.prototype.remove=function(s){this._minimum=i(this._minimum,s,-1),this.extractMinimum()};function i(s,m,d){m.key=d;var h=m.parent;return h&&r(m.key,h.key)&&(u(s,m,h),l(s,h)),r(m.key,s.key)&&(s=m),s}function u(s,m,d){m.left.right=m.right,m.right.left=m.left,d.degree--,d.child===m&&(d.child=m.right),d.degree===0&&(d.child=null),m.left=s,m.right=s.right,s.right=m,m.right.left=m,m.parent=null,m.mark=!1}function l(s,m){var d=m.parent;!d||(m.mark?(u(s,m,d),l(d)):m.mark=!0)}var c=function(m,d){m.left.right=m.right,m.right.left=m.left,m.parent=d,d.child?(m.left=d.child,m.right=d.child.right,d.child.right=m,m.right.left=m):(d.child=m,m.right=m,m.left=m),d.degree++,m.mark=!1};function o(s,m){var d=Math.floor(Math.log(m)*n)+1,h=new Array(d),x=0,v=s;if(v)for(x++,v=v.right;v!==s;)x++,v=v.right;for(var y;x>0;){for(var w=v.degree,C=v.right;y=h[w],!!y;){if(t(v.key,y.key)){var b=y;y=v,v=b}c(y,v),h[w]=null,w++}h[w]=v,v=C,x--}s=null;for(var M=0;M{var{addScalar:r,equalScalar:t,FibonacciHeap:n}=e;function a(){if(!(this instanceof a))throw new SyntaxError("Constructor must be called with the new operator");this._values=[],this._heap=new n}return a.prototype.type="Spa",a.prototype.isSpa=!0,a.prototype.set=function(i,u){if(this._values[i])this._values[i].value=u;else{var l=this._heap.insert(i,u);this._values[i]=l}},a.prototype.get=function(i){var u=this._values[i];return u?u.value:0},a.prototype.accumulate=function(i,u){var l=this._values[i];l?l.value=r(l.value,u):(l=this._heap.insert(i,u),this._values[i]=l)},a.prototype.forEach=function(i,u,l){var c=this._heap,o=this._values,s=[],m=c.extractMinimum();for(m&&s.push(m);m&&m.key<=u;)m.key>=i&&(t(m.value,0)||l(m.key,m.value,this)),m=c.extractMinimum(),m&&s.push(m);for(var d=0;d{var{on:r,config:t,addScalar:n,subtractScalar:a,multiplyScalar:i,divideScalar:u,pow:l,abs:c,fix:o,round:s,equal:m,isNumeric:d,format:h,number:x,Complex:v,BigNumber:y,Fraction:w}=e,C=x;function b(J,re){if(!(this instanceof b))throw new Error("Constructor must be called with the new operator");if(!(J==null||d(J)||Kt(J)))throw new TypeError("First parameter in Unit constructor must be number, BigNumber, Fraction, Complex, or undefined");if(this.fixPrefix=!1,this.skipAutomaticSimplification=!0,re===void 0)this.units=[],this.dimensions=K.map(j=>0);else if(typeof re=="string"){var ye=b.parse(re);this.units=ye.units,this.dimensions=ye.dimensions}else if(Ht(re)&&re.value===null)this.fixPrefix=re.fixPrefix,this.skipAutomaticSimplification=re.skipAutomaticSimplification,this.dimensions=re.dimensions.slice(0),this.units=re.units.map(j=>ht({},j));else throw new TypeError("Second parameter in Unit constructor must be a string or valueless Unit");this.value=this._normalize(J)}Object.defineProperty(b,"name",{value:"Unit"}),b.prototype.constructor=b,b.prototype.type="Unit",b.prototype.isUnit=!0;var M,A,S;function O(){for(;S===" "||S===" ";)T()}function _(J){return J>="0"&&J<="9"||J==="."}function E(J){return J>="0"&&J<="9"}function T(){A++,S=M.charAt(A)}function R(J){A=J,S=M.charAt(A)}function q(){var J="",re=A;if(S==="+"?T():S==="-"&&(J+=S,T()),!_(S))return R(re),null;if(S==="."){if(J+=S,T(),!E(S))return R(re),null}else{for(;E(S);)J+=S,T();S==="."&&(J+=S,T())}for(;E(S);)J+=S,T();if(S==="E"||S==="e"){var ye="",j=A;if(ye+=S,T(),(S==="+"||S==="-")&&(ye+=S,T()),!E(S))return R(j),J;for(J=J+ye;E(S);)J+=S,T()}return J}function W(){for(var J="";E(S)||b.isValidAlpha(S);)J+=S,T();var re=J.charAt(0);return b.isValidAlpha(re)?J:null}function G(J){return S===J?(T(),J):null}b.parse=function(J,re){if(re=re||{},M=J,A=-1,S="",typeof M!="string")throw new TypeError("Invalid argument in Unit.parse, string expected");var ye=new b;ye.units=[];var j=1,ne=!1;T(),O();var ue=q(),Me=null;if(ue){if(t.number==="BigNumber")Me=new y(ue);else if(t.number==="Fraction")try{Me=new w(ue)}catch{Me=parseFloat(ue)}else Me=parseFloat(ue);O(),G("*")?(j=1,ne=!0):G("/")&&(j=-1,ne=!0)}for(var Ce=[],Le=1;;){for(O();S==="(";)Ce.push(j),Le*=j,j=1,T(),O();var Ie=void 0;if(S){var fr=S;if(Ie=W(),Ie===null)throw new SyntaxError('Unexpected "'+fr+'" in "'+M+'" at index '+A.toString())}else break;var or=H(Ie);if(or===null)throw new SyntaxError('Unit "'+Ie+'" not found.');var Ke=j*Le;if(O(),G("^")){O();var Pr=q();if(Pr===null)throw new SyntaxError('In "'+J+'", "^" must be followed by a floating-point number');Ke*=Pr}ye.units.push({unit:or.unit,prefix:or.prefix,power:Ke});for(var ee=0;ee1||Math.abs(this.units[0].power-1)>1e-15},b.prototype._normalize=function(J){if(J==null||this.units.length===0)return J;for(var re=J,ye=b._getNumberConverter(Fr(J)),j=0;j{if(Xe($,J)){var re=$[J],ye=re.prefixes[""];return{unit:re,prefix:ye}}for(var j in $)if(Xe($,j)&&uM(J,j)){var ne=$[j],ue=J.length-j.length,Me=J.substring(0,ue),Ce=Xe(ne.prefixes,Me)?ne.prefixes[Me]:void 0;if(Ce!==void 0)return{unit:ne,prefix:Ce}}return null},{hasher:J=>J[0],limit:100});b.isValuelessUnit=function(J){return H(J)!==null},b.prototype.hasBase=function(J){if(typeof J=="string"&&(J=z[J]),!J)return!1;for(var re=0;re1e-12)return!1;return!0},b.prototype.equalBase=function(J){for(var re=0;re1e-12)return!1;return!0},b.prototype.equals=function(J){return this.equalBase(J)&&m(this.value,J.value)},b.prototype.multiply=function(J){for(var re=this.clone(),ye=Ht(J)?J:new b(J),j=0;j1e-12&&(Xe(ge,Ce)?re.push({unit:ge[Ce].unit,prefix:ge[Ce].prefix,power:J.dimensions[Me]||0}):ue=!0)}re.length1e-12)if(Xe(me.si,j))re.push({unit:me.si[j].unit,prefix:me.si[j].prefix,power:J.dimensions[ye]||0});else throw new Error("Cannot express custom unit "+j+" in SI units")}return J.units=re,J.fixPrefix=!0,J.skipAutomaticSimplification=!0,this.value!==null?(J.value=null,this.to(J)):J},b.prototype.formatUnits=function(){for(var J="",re="",ye=0,j=0,ne=0;ne0?(ye++,J+=" "+this.units[ne].prefix.name+this.units[ne].unit.name,Math.abs(this.units[ne].power-1)>1e-15&&(J+="^"+this.units[ne].power)):this.units[ne].power<0&&j++;if(j>0)for(var ue=0;ue0?(re+=" "+this.units[ue].prefix.name+this.units[ue].unit.name,Math.abs(this.units[ue].power+1)>1e-15&&(re+="^"+-this.units[ue].power)):(re+=" "+this.units[ue].prefix.name+this.units[ue].unit.name,re+="^"+this.units[ue].power));J=J.substr(1),re=re.substr(1),ye>1&&j>0&&(J="("+J+")"),j>1&&ye>0&&(re="("+re+")");var Me=J;return ye>0&&j>0&&(Me+=" / "),Me+=re,Me},b.prototype.format=function(J){var re=this.skipAutomaticSimplification||this.value===null?this.clone():this.simplify(),ye=!1;typeof re.value<"u"&&re.value!==null&&Kt(re.value)&&(ye=Math.abs(re.value.re)<1e-14);for(var j in re.units)Xe(re.units,j)&&re.units[j].unit&&(re.units[j].unit.name==="VA"&&ye?re.units[j].unit=$.VAR:re.units[j].unit.name==="VAR"&&!ye&&(re.units[j].unit=$.VA));re.units.length===1&&!re.fixPrefix&&Math.abs(re.units[0].power-Math.round(re.units[0].power))<1e-14&&(re.units[0].prefix=re._bestPrefix());var ne=re._denormalize(re.value),ue=re.value!==null?h(ne,J||{}):"",Me=re.formatUnits();return re.value&&Kt(re.value)&&(ue="("+ue+")"),Me.length>0&&ue.length>0&&(ue+=" "),ue+=Me,ue},b.prototype._bestPrefix=function(){if(this.units.length!==1)throw new Error("Can only compute the best prefix for single units with integer powers, like kg, s^2, N^-1, and so forth!");if(Math.abs(this.units[0].power-Math.round(this.units[0].power))>=1e-14)throw new Error("Can only compute the best prefix for single units with integer powers, like kg, s^2, N^-1, and so forth!");var J=this.value!==null?c(this.value):0,re=c(this.units[0].unit.value),ye=this.units[0].prefix;if(J===0)return ye;var j=this.units[0].power,ne=Math.log(J/Math.pow(ye.value*re,j))/Math.LN10-1.2;if(ne>-2.200001&&ne<1.800001)return ye;ne=Math.abs(ne);var ue=this.units[0].unit.prefixes;for(var Me in ue)if(Xe(ue,Me)){var Ce=ue[Me];if(Ce.scientific){var Le=Math.abs(Math.log(J/Math.pow(Ce.value*re,j))/Math.LN10-1.2);(Le0)},$={meter:{name:"meter",base:z.LENGTH,prefixes:k.LONG,value:1,offset:0},inch:{name:"inch",base:z.LENGTH,prefixes:k.NONE,value:.0254,offset:0},foot:{name:"foot",base:z.LENGTH,prefixes:k.NONE,value:.3048,offset:0},yard:{name:"yard",base:z.LENGTH,prefixes:k.NONE,value:.9144,offset:0},mile:{name:"mile",base:z.LENGTH,prefixes:k.NONE,value:1609.344,offset:0},link:{name:"link",base:z.LENGTH,prefixes:k.NONE,value:.201168,offset:0},rod:{name:"rod",base:z.LENGTH,prefixes:k.NONE,value:5.0292,offset:0},chain:{name:"chain",base:z.LENGTH,prefixes:k.NONE,value:20.1168,offset:0},angstrom:{name:"angstrom",base:z.LENGTH,prefixes:k.NONE,value:1e-10,offset:0},m:{name:"m",base:z.LENGTH,prefixes:k.SHORT,value:1,offset:0},in:{name:"in",base:z.LENGTH,prefixes:k.NONE,value:.0254,offset:0},ft:{name:"ft",base:z.LENGTH,prefixes:k.NONE,value:.3048,offset:0},yd:{name:"yd",base:z.LENGTH,prefixes:k.NONE,value:.9144,offset:0},mi:{name:"mi",base:z.LENGTH,prefixes:k.NONE,value:1609.344,offset:0},li:{name:"li",base:z.LENGTH,prefixes:k.NONE,value:.201168,offset:0},rd:{name:"rd",base:z.LENGTH,prefixes:k.NONE,value:5.02921,offset:0},ch:{name:"ch",base:z.LENGTH,prefixes:k.NONE,value:20.1168,offset:0},mil:{name:"mil",base:z.LENGTH,prefixes:k.NONE,value:254e-7,offset:0},m2:{name:"m2",base:z.SURFACE,prefixes:k.SQUARED,value:1,offset:0},sqin:{name:"sqin",base:z.SURFACE,prefixes:k.NONE,value:64516e-8,offset:0},sqft:{name:"sqft",base:z.SURFACE,prefixes:k.NONE,value:.09290304,offset:0},sqyd:{name:"sqyd",base:z.SURFACE,prefixes:k.NONE,value:.83612736,offset:0},sqmi:{name:"sqmi",base:z.SURFACE,prefixes:k.NONE,value:2589988110336e-6,offset:0},sqrd:{name:"sqrd",base:z.SURFACE,prefixes:k.NONE,value:25.29295,offset:0},sqch:{name:"sqch",base:z.SURFACE,prefixes:k.NONE,value:404.6873,offset:0},sqmil:{name:"sqmil",base:z.SURFACE,prefixes:k.NONE,value:64516e-14,offset:0},acre:{name:"acre",base:z.SURFACE,prefixes:k.NONE,value:4046.86,offset:0},hectare:{name:"hectare",base:z.SURFACE,prefixes:k.NONE,value:1e4,offset:0},m3:{name:"m3",base:z.VOLUME,prefixes:k.CUBIC,value:1,offset:0},L:{name:"L",base:z.VOLUME,prefixes:k.SHORT,value:.001,offset:0},l:{name:"l",base:z.VOLUME,prefixes:k.SHORT,value:.001,offset:0},litre:{name:"litre",base:z.VOLUME,prefixes:k.LONG,value:.001,offset:0},cuin:{name:"cuin",base:z.VOLUME,prefixes:k.NONE,value:16387064e-12,offset:0},cuft:{name:"cuft",base:z.VOLUME,prefixes:k.NONE,value:.028316846592,offset:0},cuyd:{name:"cuyd",base:z.VOLUME,prefixes:k.NONE,value:.764554857984,offset:0},teaspoon:{name:"teaspoon",base:z.VOLUME,prefixes:k.NONE,value:5e-6,offset:0},tablespoon:{name:"tablespoon",base:z.VOLUME,prefixes:k.NONE,value:15e-6,offset:0},drop:{name:"drop",base:z.VOLUME,prefixes:k.NONE,value:5e-8,offset:0},gtt:{name:"gtt",base:z.VOLUME,prefixes:k.NONE,value:5e-8,offset:0},minim:{name:"minim",base:z.VOLUME,prefixes:k.NONE,value:6161152e-14,offset:0},fluiddram:{name:"fluiddram",base:z.VOLUME,prefixes:k.NONE,value:36966911e-13,offset:0},fluidounce:{name:"fluidounce",base:z.VOLUME,prefixes:k.NONE,value:2957353e-11,offset:0},gill:{name:"gill",base:z.VOLUME,prefixes:k.NONE,value:.0001182941,offset:0},cc:{name:"cc",base:z.VOLUME,prefixes:k.NONE,value:1e-6,offset:0},cup:{name:"cup",base:z.VOLUME,prefixes:k.NONE,value:.0002365882,offset:0},pint:{name:"pint",base:z.VOLUME,prefixes:k.NONE,value:.0004731765,offset:0},quart:{name:"quart",base:z.VOLUME,prefixes:k.NONE,value:.0009463529,offset:0},gallon:{name:"gallon",base:z.VOLUME,prefixes:k.NONE,value:.003785412,offset:0},beerbarrel:{name:"beerbarrel",base:z.VOLUME,prefixes:k.NONE,value:.1173478,offset:0},oilbarrel:{name:"oilbarrel",base:z.VOLUME,prefixes:k.NONE,value:.1589873,offset:0},hogshead:{name:"hogshead",base:z.VOLUME,prefixes:k.NONE,value:.238481,offset:0},fldr:{name:"fldr",base:z.VOLUME,prefixes:k.NONE,value:36966911e-13,offset:0},floz:{name:"floz",base:z.VOLUME,prefixes:k.NONE,value:2957353e-11,offset:0},gi:{name:"gi",base:z.VOLUME,prefixes:k.NONE,value:.0001182941,offset:0},cp:{name:"cp",base:z.VOLUME,prefixes:k.NONE,value:.0002365882,offset:0},pt:{name:"pt",base:z.VOLUME,prefixes:k.NONE,value:.0004731765,offset:0},qt:{name:"qt",base:z.VOLUME,prefixes:k.NONE,value:.0009463529,offset:0},gal:{name:"gal",base:z.VOLUME,prefixes:k.NONE,value:.003785412,offset:0},bbl:{name:"bbl",base:z.VOLUME,prefixes:k.NONE,value:.1173478,offset:0},obl:{name:"obl",base:z.VOLUME,prefixes:k.NONE,value:.1589873,offset:0},g:{name:"g",base:z.MASS,prefixes:k.SHORT,value:.001,offset:0},gram:{name:"gram",base:z.MASS,prefixes:k.LONG,value:.001,offset:0},ton:{name:"ton",base:z.MASS,prefixes:k.SHORT,value:907.18474,offset:0},t:{name:"t",base:z.MASS,prefixes:k.SHORT,value:1e3,offset:0},tonne:{name:"tonne",base:z.MASS,prefixes:k.LONG,value:1e3,offset:0},grain:{name:"grain",base:z.MASS,prefixes:k.NONE,value:6479891e-11,offset:0},dram:{name:"dram",base:z.MASS,prefixes:k.NONE,value:.0017718451953125,offset:0},ounce:{name:"ounce",base:z.MASS,prefixes:k.NONE,value:.028349523125,offset:0},poundmass:{name:"poundmass",base:z.MASS,prefixes:k.NONE,value:.45359237,offset:0},hundredweight:{name:"hundredweight",base:z.MASS,prefixes:k.NONE,value:45.359237,offset:0},stick:{name:"stick",base:z.MASS,prefixes:k.NONE,value:.115,offset:0},stone:{name:"stone",base:z.MASS,prefixes:k.NONE,value:6.35029318,offset:0},gr:{name:"gr",base:z.MASS,prefixes:k.NONE,value:6479891e-11,offset:0},dr:{name:"dr",base:z.MASS,prefixes:k.NONE,value:.0017718451953125,offset:0},oz:{name:"oz",base:z.MASS,prefixes:k.NONE,value:.028349523125,offset:0},lbm:{name:"lbm",base:z.MASS,prefixes:k.NONE,value:.45359237,offset:0},cwt:{name:"cwt",base:z.MASS,prefixes:k.NONE,value:45.359237,offset:0},s:{name:"s",base:z.TIME,prefixes:k.SHORT,value:1,offset:0},min:{name:"min",base:z.TIME,prefixes:k.NONE,value:60,offset:0},h:{name:"h",base:z.TIME,prefixes:k.NONE,value:3600,offset:0},second:{name:"second",base:z.TIME,prefixes:k.LONG,value:1,offset:0},sec:{name:"sec",base:z.TIME,prefixes:k.LONG,value:1,offset:0},minute:{name:"minute",base:z.TIME,prefixes:k.NONE,value:60,offset:0},hour:{name:"hour",base:z.TIME,prefixes:k.NONE,value:3600,offset:0},day:{name:"day",base:z.TIME,prefixes:k.NONE,value:86400,offset:0},week:{name:"week",base:z.TIME,prefixes:k.NONE,value:7*86400,offset:0},month:{name:"month",base:z.TIME,prefixes:k.NONE,value:2629800,offset:0},year:{name:"year",base:z.TIME,prefixes:k.NONE,value:31557600,offset:0},decade:{name:"decade",base:z.TIME,prefixes:k.NONE,value:315576e3,offset:0},century:{name:"century",base:z.TIME,prefixes:k.NONE,value:315576e4,offset:0},millennium:{name:"millennium",base:z.TIME,prefixes:k.NONE,value:315576e5,offset:0},hertz:{name:"Hertz",base:z.FREQUENCY,prefixes:k.LONG,value:1,offset:0,reciprocal:!0},Hz:{name:"Hz",base:z.FREQUENCY,prefixes:k.SHORT,value:1,offset:0,reciprocal:!0},rad:{name:"rad",base:z.ANGLE,prefixes:k.SHORT,value:1,offset:0},radian:{name:"radian",base:z.ANGLE,prefixes:k.LONG,value:1,offset:0},deg:{name:"deg",base:z.ANGLE,prefixes:k.SHORT,value:null,offset:0},degree:{name:"degree",base:z.ANGLE,prefixes:k.LONG,value:null,offset:0},grad:{name:"grad",base:z.ANGLE,prefixes:k.SHORT,value:null,offset:0},gradian:{name:"gradian",base:z.ANGLE,prefixes:k.LONG,value:null,offset:0},cycle:{name:"cycle",base:z.ANGLE,prefixes:k.NONE,value:null,offset:0},arcsec:{name:"arcsec",base:z.ANGLE,prefixes:k.NONE,value:null,offset:0},arcmin:{name:"arcmin",base:z.ANGLE,prefixes:k.NONE,value:null,offset:0},A:{name:"A",base:z.CURRENT,prefixes:k.SHORT,value:1,offset:0},ampere:{name:"ampere",base:z.CURRENT,prefixes:k.LONG,value:1,offset:0},K:{name:"K",base:z.TEMPERATURE,prefixes:k.SHORT,value:1,offset:0},degC:{name:"degC",base:z.TEMPERATURE,prefixes:k.SHORT,value:1,offset:273.15},degF:{name:"degF",base:z.TEMPERATURE,prefixes:k.SHORT,value:new w(5,9),offset:459.67},degR:{name:"degR",base:z.TEMPERATURE,prefixes:k.SHORT,value:new w(5,9),offset:0},kelvin:{name:"kelvin",base:z.TEMPERATURE,prefixes:k.LONG,value:1,offset:0},celsius:{name:"celsius",base:z.TEMPERATURE,prefixes:k.LONG,value:1,offset:273.15},fahrenheit:{name:"fahrenheit",base:z.TEMPERATURE,prefixes:k.LONG,value:new w(5,9),offset:459.67},rankine:{name:"rankine",base:z.TEMPERATURE,prefixes:k.LONG,value:new w(5,9),offset:0},mol:{name:"mol",base:z.AMOUNT_OF_SUBSTANCE,prefixes:k.SHORT,value:1,offset:0},mole:{name:"mole",base:z.AMOUNT_OF_SUBSTANCE,prefixes:k.LONG,value:1,offset:0},cd:{name:"cd",base:z.LUMINOUS_INTENSITY,prefixes:k.SHORT,value:1,offset:0},candela:{name:"candela",base:z.LUMINOUS_INTENSITY,prefixes:k.LONG,value:1,offset:0},N:{name:"N",base:z.FORCE,prefixes:k.SHORT,value:1,offset:0},newton:{name:"newton",base:z.FORCE,prefixes:k.LONG,value:1,offset:0},dyn:{name:"dyn",base:z.FORCE,prefixes:k.SHORT,value:1e-5,offset:0},dyne:{name:"dyne",base:z.FORCE,prefixes:k.LONG,value:1e-5,offset:0},lbf:{name:"lbf",base:z.FORCE,prefixes:k.NONE,value:4.4482216152605,offset:0},poundforce:{name:"poundforce",base:z.FORCE,prefixes:k.NONE,value:4.4482216152605,offset:0},kip:{name:"kip",base:z.FORCE,prefixes:k.LONG,value:4448.2216,offset:0},kilogramforce:{name:"kilogramforce",base:z.FORCE,prefixes:k.NONE,value:9.80665,offset:0},J:{name:"J",base:z.ENERGY,prefixes:k.SHORT,value:1,offset:0},joule:{name:"joule",base:z.ENERGY,prefixes:k.LONG,value:1,offset:0},erg:{name:"erg",base:z.ENERGY,prefixes:k.SHORTLONG,value:1e-7,offset:0},Wh:{name:"Wh",base:z.ENERGY,prefixes:k.SHORT,value:3600,offset:0},BTU:{name:"BTU",base:z.ENERGY,prefixes:k.BTU,value:1055.05585262,offset:0},eV:{name:"eV",base:z.ENERGY,prefixes:k.SHORT,value:1602176565e-28,offset:0},electronvolt:{name:"electronvolt",base:z.ENERGY,prefixes:k.LONG,value:1602176565e-28,offset:0},W:{name:"W",base:z.POWER,prefixes:k.SHORT,value:1,offset:0},watt:{name:"watt",base:z.POWER,prefixes:k.LONG,value:1,offset:0},hp:{name:"hp",base:z.POWER,prefixes:k.NONE,value:745.6998715386,offset:0},VAR:{name:"VAR",base:z.POWER,prefixes:k.SHORT,value:v.I,offset:0},VA:{name:"VA",base:z.POWER,prefixes:k.SHORT,value:1,offset:0},Pa:{name:"Pa",base:z.PRESSURE,prefixes:k.SHORT,value:1,offset:0},psi:{name:"psi",base:z.PRESSURE,prefixes:k.NONE,value:6894.75729276459,offset:0},atm:{name:"atm",base:z.PRESSURE,prefixes:k.NONE,value:101325,offset:0},bar:{name:"bar",base:z.PRESSURE,prefixes:k.SHORTLONG,value:1e5,offset:0},torr:{name:"torr",base:z.PRESSURE,prefixes:k.NONE,value:133.322,offset:0},mmHg:{name:"mmHg",base:z.PRESSURE,prefixes:k.NONE,value:133.322,offset:0},mmH2O:{name:"mmH2O",base:z.PRESSURE,prefixes:k.NONE,value:9.80665,offset:0},cmH2O:{name:"cmH2O",base:z.PRESSURE,prefixes:k.NONE,value:98.0665,offset:0},coulomb:{name:"coulomb",base:z.ELECTRIC_CHARGE,prefixes:k.LONG,value:1,offset:0},C:{name:"C",base:z.ELECTRIC_CHARGE,prefixes:k.SHORT,value:1,offset:0},farad:{name:"farad",base:z.ELECTRIC_CAPACITANCE,prefixes:k.LONG,value:1,offset:0},F:{name:"F",base:z.ELECTRIC_CAPACITANCE,prefixes:k.SHORT,value:1,offset:0},volt:{name:"volt",base:z.ELECTRIC_POTENTIAL,prefixes:k.LONG,value:1,offset:0},V:{name:"V",base:z.ELECTRIC_POTENTIAL,prefixes:k.SHORT,value:1,offset:0},ohm:{name:"ohm",base:z.ELECTRIC_RESISTANCE,prefixes:k.SHORTLONG,value:1,offset:0},henry:{name:"henry",base:z.ELECTRIC_INDUCTANCE,prefixes:k.LONG,value:1,offset:0},H:{name:"H",base:z.ELECTRIC_INDUCTANCE,prefixes:k.SHORT,value:1,offset:0},siemens:{name:"siemens",base:z.ELECTRIC_CONDUCTANCE,prefixes:k.LONG,value:1,offset:0},S:{name:"S",base:z.ELECTRIC_CONDUCTANCE,prefixes:k.SHORT,value:1,offset:0},weber:{name:"weber",base:z.MAGNETIC_FLUX,prefixes:k.LONG,value:1,offset:0},Wb:{name:"Wb",base:z.MAGNETIC_FLUX,prefixes:k.SHORT,value:1,offset:0},tesla:{name:"tesla",base:z.MAGNETIC_FLUX_DENSITY,prefixes:k.LONG,value:1,offset:0},T:{name:"T",base:z.MAGNETIC_FLUX_DENSITY,prefixes:k.SHORT,value:1,offset:0},b:{name:"b",base:z.BIT,prefixes:k.BINARY_SHORT,value:1,offset:0},bits:{name:"bits",base:z.BIT,prefixes:k.BINARY_LONG,value:1,offset:0},B:{name:"B",base:z.BIT,prefixes:k.BINARY_SHORT,value:8,offset:0},bytes:{name:"bytes",base:z.BIT,prefixes:k.BINARY_LONG,value:8,offset:0}},le={meters:"meter",inches:"inch",feet:"foot",yards:"yard",miles:"mile",links:"link",rods:"rod",chains:"chain",angstroms:"angstrom",lt:"l",litres:"litre",liter:"litre",liters:"litre",teaspoons:"teaspoon",tablespoons:"tablespoon",minims:"minim",fluiddrams:"fluiddram",fluidounces:"fluidounce",gills:"gill",cups:"cup",pints:"pint",quarts:"quart",gallons:"gallon",beerbarrels:"beerbarrel",oilbarrels:"oilbarrel",hogsheads:"hogshead",gtts:"gtt",grams:"gram",tons:"ton",tonnes:"tonne",grains:"grain",drams:"dram",ounces:"ounce",poundmasses:"poundmass",hundredweights:"hundredweight",sticks:"stick",lb:"lbm",lbs:"lbm",kips:"kip",kgf:"kilogramforce",acres:"acre",hectares:"hectare",sqfeet:"sqft",sqyard:"sqyd",sqmile:"sqmi",sqmiles:"sqmi",mmhg:"mmHg",mmh2o:"mmH2O",cmh2o:"cmH2O",seconds:"second",secs:"second",minutes:"minute",mins:"minute",hours:"hour",hr:"hour",hrs:"hour",days:"day",weeks:"week",months:"month",years:"year",decades:"decade",centuries:"century",millennia:"millennium",hertz:"hertz",radians:"radian",degrees:"degree",gradians:"gradian",cycles:"cycle",arcsecond:"arcsec",arcseconds:"arcsec",arcminute:"arcmin",arcminutes:"arcmin",BTUs:"BTU",watts:"watt",joules:"joule",amperes:"ampere",amps:"ampere",amp:"ampere",coulombs:"coulomb",volts:"volt",ohms:"ohm",farads:"farad",webers:"weber",teslas:"tesla",electronvolts:"electronvolt",moles:"mole",bit:"bits",byte:"bytes"};function Ee(J){if(J.number==="BigNumber"){var re=Ic(y);$.rad.value=new y(1),$.deg.value=re.div(180),$.grad.value=re.div(200),$.cycle.value=re.times(2),$.arcsec.value=re.div(648e3),$.arcmin.value=re.div(10800)}else $.rad.value=1,$.deg.value=Math.PI/180,$.grad.value=Math.PI/200,$.cycle.value=Math.PI*2,$.arcsec.value=Math.PI/648e3,$.arcmin.value=Math.PI/10800;$.radian.value=$.rad.value,$.degree.value=$.deg.value,$.gradian.value=$.grad.value}Ee(t),r&&r("config",function(J,re){J.number!==re.number&&Ee(J)});var me={si:{NONE:{unit:ae,prefix:k.NONE[""]},LENGTH:{unit:$.m,prefix:k.SHORT[""]},MASS:{unit:$.g,prefix:k.SHORT.k},TIME:{unit:$.s,prefix:k.SHORT[""]},CURRENT:{unit:$.A,prefix:k.SHORT[""]},TEMPERATURE:{unit:$.K,prefix:k.SHORT[""]},LUMINOUS_INTENSITY:{unit:$.cd,prefix:k.SHORT[""]},AMOUNT_OF_SUBSTANCE:{unit:$.mol,prefix:k.SHORT[""]},ANGLE:{unit:$.rad,prefix:k.SHORT[""]},BIT:{unit:$.bits,prefix:k.SHORT[""]},FORCE:{unit:$.N,prefix:k.SHORT[""]},ENERGY:{unit:$.J,prefix:k.SHORT[""]},POWER:{unit:$.W,prefix:k.SHORT[""]},PRESSURE:{unit:$.Pa,prefix:k.SHORT[""]},ELECTRIC_CHARGE:{unit:$.C,prefix:k.SHORT[""]},ELECTRIC_CAPACITANCE:{unit:$.F,prefix:k.SHORT[""]},ELECTRIC_POTENTIAL:{unit:$.V,prefix:k.SHORT[""]},ELECTRIC_RESISTANCE:{unit:$.ohm,prefix:k.SHORT[""]},ELECTRIC_INDUCTANCE:{unit:$.H,prefix:k.SHORT[""]},ELECTRIC_CONDUCTANCE:{unit:$.S,prefix:k.SHORT[""]},MAGNETIC_FLUX:{unit:$.Wb,prefix:k.SHORT[""]},MAGNETIC_FLUX_DENSITY:{unit:$.T,prefix:k.SHORT[""]},FREQUENCY:{unit:$.Hz,prefix:k.SHORT[""]}}};me.cgs=JSON.parse(JSON.stringify(me.si)),me.cgs.LENGTH={unit:$.m,prefix:k.SHORT.c},me.cgs.MASS={unit:$.g,prefix:k.SHORT[""]},me.cgs.FORCE={unit:$.dyn,prefix:k.SHORT[""]},me.cgs.ENERGY={unit:$.erg,prefix:k.NONE[""]},me.us=JSON.parse(JSON.stringify(me.si)),me.us.LENGTH={unit:$.ft,prefix:k.NONE[""]},me.us.MASS={unit:$.lbm,prefix:k.NONE[""]},me.us.TEMPERATURE={unit:$.degF,prefix:k.NONE[""]},me.us.FORCE={unit:$.lbf,prefix:k.NONE[""]},me.us.ENERGY={unit:$.BTU,prefix:k.BTU[""]},me.us.POWER={unit:$.hp,prefix:k.NONE[""]},me.us.PRESSURE={unit:$.psi,prefix:k.NONE[""]},me.auto=JSON.parse(JSON.stringify(me.si));var ge=me.auto;b.setUnitSystem=function(J){if(Xe(me,J))ge=me[J];else throw new Error("Unit system "+J+" does not exist. Choices are: "+Object.keys(me).join(", "))},b.getUnitSystem=function(){for(var J in me)if(Xe(me,J)&&me[J]===ge)return J},b.typeConverters={BigNumber:function(re){return re!=null&&re.isFraction?new y(re.n).div(re.d).times(re.s):new y(re+"")},Fraction:function(re){return new w(re)},Complex:function(re){return re},number:function(re){return re!=null&&re.isFraction?x(re):re}},b.prototype._numberConverter=function(){var J=b.typeConverters[this.valueType()];if(J)return J;throw new TypeError('Unsupported Unit value type "'+this.valueType()+'"')},b._getNumberConverter=function(J){if(!b.typeConverters[J])throw new TypeError('Unsupported type "'+J+'"');return b.typeConverters[J]};for(var Se in $)if(Xe($,Se)){var xe=$[Se];xe.dimensions=xe.base.dimensions}for(var be in le)if(Xe(le,be)){var De=$[le[be]],Ae={};for(var We in De)Xe(De,We)&&(Ae[We]=De[We]);Ae.name=be,$[be]=Ae}b.isValidAlpha=function(re){return/^[a-zA-Z]$/.test(re)};function Je(J){for(var re=0;re0&&!(b.isValidAlpha(S)||E(S)))throw new Error('Invalid unit name (only alphanumeric characters are allowed): "'+J+'"')}}return b.createUnit=function(J,re){if(typeof J!="object")throw new TypeError("createUnit expects first parameter to be of type 'Object'");if(re&&re.override){for(var ye in J)if(Xe(J,ye)&&b.deleteUnit(ye),J[ye].aliases)for(var j=0;j"u"||re===null)&&(re={}),typeof J!="string")throw new TypeError("createUnitSingle expects first parameter to be of type 'string'");if(Xe($,J))throw new Error('Cannot create unit "'+J+'": a unit with that name already exists');Je(J);var ye=null,j=[],ne=0,ue,Me,Ce;if(re&&re.type==="Unit")ye=re.clone();else if(typeof re=="string")re!==""&&(ue=re);else if(typeof re=="object")ue=re.definition,Me=re.prefixes,ne=re.offset,Ce=re.baseName,re.aliases&&(j=re.aliases.valueOf());else throw new TypeError('Cannot create unit "'+J+'" from "'+re.toString()+'": expecting "string" or "Unit" or "Object"');if(j){for(var Le=0;Le1e-12){ce=!1;break}if(ce){Pr=!0,Ie.base=z[ee];break}}if(!Pr){Ce=Ce||J+"_STUFF";var Be={dimensions:ye.dimensions.slice(0)};Be.key=Ce,z[Ce]=Be,ge[Ce]={unit:Ie,prefix:k.NONE[""]},Ie.base=z[Ce]}}else{if(Ce=Ce||J+"_STUFF",K.indexOf(Ce)>=0)throw new Error('Cannot create new base unit "'+J+'": a base unit with that name already exists (and cannot be overridden)');K.push(Ce);for(var fr in z)Xe(z,fr)&&(z[fr].dimensions[K.length-1]=0);for(var or={dimensions:[]},Ke=0;Ke{var{typed:r,Unit:t}=e;return r(dE,{Unit:function(a){return a.clone()},string:function(a){return t.isValuelessUnit(a)?new t(null,a):t.parse(a,{allowNoUnits:!0})},"number | BigNumber | Fraction | Complex, string | Unit":function(a,i){return new t(a,i)},"number | BigNumber | Fraction":function(a){return new t(a)},"Array | Matrix":r.referToSelf(n=>a=>je(a,n))})});var hE="sparse",BH=["typed","SparseMatrix"],Fh=F(hE,BH,e=>{var{typed:r,SparseMatrix:t}=e;return r(hE,{"":function(){return new t([])},string:function(a){return new t([],a)},"Array | Matrix":function(a){return new t(a)},"Array | Matrix, string":function(a,i){return new t(a,i)}})});var vE="createUnit",PH=["typed","Unit"],_h=F(vE,PH,e=>{var{typed:r,Unit:t}=e;return r(vE,{"Object, Object":function(a,i){return t.createUnit(a,i)},Object:function(a){return t.createUnit(a,{})},"string, Unit | string | Object, Object":function(a,i,u){var l={};return l[a]=i,t.createUnit(l,u)},"string, Unit | string | Object":function(a,i){var u={};return u[a]=i,t.createUnit(u,{})},string:function(a){var i={};return i[a]={},t.createUnit(i,{})}})});var gE="acos",IH=["typed","config","Complex"],Oh=F(gE,IH,e=>{var{typed:r,config:t,Complex:n}=e;return r(gE,{number:function(i){return i>=-1&&i<=1||t.predictable?Math.acos(i):new n(i,0).acos()},Complex:function(i){return i.acos()},BigNumber:function(i){return i.acos()}})});var xE="acosh",RH=["typed","config","Complex"],Bh=F(xE,RH,e=>{var{typed:r,config:t,Complex:n}=e;return r(xE,{number:function(i){return i>=1||t.predictable?$w(i):i<=-1?new n(Math.log(Math.sqrt(i*i-1)-i),Math.PI):new n(i,0).acosh()},Complex:function(i){return i.acosh()},BigNumber:function(i){return i.acosh()}})});var yE="acot",kH=["typed","BigNumber"],Ph=F(yE,kH,e=>{var{typed:r,BigNumber:t}=e;return r(yE,{number:Gw,Complex:function(a){return a.acot()},BigNumber:function(a){return new t(1).div(a).atan()}})});var bE="acoth",qH=["typed","config","Complex","BigNumber"],Ih=F(bE,qH,e=>{var{typed:r,config:t,Complex:n,BigNumber:a}=e;return r(bE,{number:function(u){return u>=1||u<=-1||t.predictable?Vw(u):new n(u,0).acoth()},Complex:function(u){return u.acoth()},BigNumber:function(u){return new a(1).div(u).atanh()}})});var wE="acsc",LH=["typed","config","Complex","BigNumber"],Rh=F(wE,LH,e=>{var{typed:r,config:t,Complex:n,BigNumber:a}=e;return r(wE,{number:function(u){return u<=-1||u>=1||t.predictable?Zw(u):new n(u,0).acsc()},Complex:function(u){return u.acsc()},BigNumber:function(u){return new a(1).div(u).asin()}})});var DE="acsch",zH=["typed","BigNumber"],kh=F(DE,zH,e=>{var{typed:r,BigNumber:t}=e;return r(DE,{number:Qw,Complex:function(a){return a.acsch()},BigNumber:function(a){return new t(1).div(a).asinh()}})});var SE="asec",UH=["typed","config","Complex","BigNumber"],qh=F(SE,UH,e=>{var{typed:r,config:t,Complex:n,BigNumber:a}=e;return r(SE,{number:function(u){return u<=-1||u>=1||t.predictable?Xw(u):new n(u,0).asec()},Complex:function(u){return u.asec()},BigNumber:function(u){return new a(1).div(u).acos()}})});var NE="asech",WH=["typed","config","Complex","BigNumber"],Lh=F(NE,WH,e=>{var{typed:r,config:t,Complex:n,BigNumber:a}=e;return r(NE,{number:function(u){if(u<=1&&u>=-1||t.predictable){var l=1/u;if(l>0||t.predictable)return Jw(u);var c=Math.sqrt(l*l-1);return new n(Math.log(c-l),Math.PI)}return new n(u,0).asech()},Complex:function(u){return u.asech()},BigNumber:function(u){return new a(1).div(u).acosh()}})});var AE="asin",YH=["typed","config","Complex"],zh=F(AE,YH,e=>{var{typed:r,config:t,Complex:n}=e;return r(AE,{number:function(i){return i>=-1&&i<=1||t.predictable?Math.asin(i):new n(i,0).asin()},Complex:function(i){return i.asin()},BigNumber:function(i){return i.asin()}})});var HH="asinh",$H=["typed"],Uh=F(HH,$H,e=>{var{typed:r}=e;return r("asinh",{number:Kw,Complex:function(n){return n.asinh()},BigNumber:function(n){return n.asinh()}})});var GH="atan",VH=["typed"],Wh=F(GH,VH,e=>{var{typed:r}=e;return r("atan",{number:function(n){return Math.atan(n)},Complex:function(n){return n.atan()},BigNumber:function(n){return n.atan()}})});var ME="atan2",ZH=["typed","matrix","equalScalar","BigNumber","DenseMatrix","concat"],Yh=F(ME,ZH,e=>{var{typed:r,matrix:t,equalScalar:n,BigNumber:a,DenseMatrix:i,concat:u}=e,l=Lt({typed:r,equalScalar:n}),c=lt({typed:r}),o=Zp({typed:r,equalScalar:n}),s=jr({typed:r,equalScalar:n}),m=Wr({typed:r,DenseMatrix:i}),d=vr({typed:r,matrix:t,concat:u});return r(ME,{"number, number":Math.atan2,"BigNumber, BigNumber":(h,x)=>a.atan2(h,x)},d({scalar:"number | BigNumber",SS:o,DS:c,SD:l,Ss:s,sS:m}))});var CE="atanh",QH=["typed","config","Complex"],Hh=F(CE,QH,e=>{var{typed:r,config:t,Complex:n}=e;return r(CE,{number:function(i){return i<=1&&i>=-1||t.predictable?jw(i):new n(i,0).atanh()},Complex:function(i){return i.atanh()},BigNumber:function(i){return i.atanh()}})});var Ra=F("trigUnit",["typed"],e=>{var{typed:r}=e;return{Unit:r.referToSelf(t=>n=>{if(!n.hasBase(n.constructor.BASE_UNITS.ANGLE))throw new TypeError("Unit in function cot is no angle");return r.find(t,n.valueType())(n.value)})}});var EE="cos",XH=["typed"],$h=F(EE,XH,e=>{var{typed:r}=e,t=Ra({typed:r});return r(EE,{number:Math.cos,"Complex | BigNumber":n=>n.cos()},t)});var TE="cosh",JH=["typed"],Gh=F(TE,JH,e=>{var{typed:r}=e;return r(TE,{number:Em,"Complex | BigNumber":t=>t.cosh()})});var FE="cot",KH=["typed","BigNumber"],Vh=F(FE,KH,e=>{var{typed:r,BigNumber:t}=e,n=Ra({typed:r});return r(FE,{number:eD,Complex:a=>a.cot(),BigNumber:a=>new t(1).div(a.tan())},n)});var _E="coth",jH=["typed","BigNumber"],Zh=F(_E,jH,e=>{var{typed:r,BigNumber:t}=e;return r(_E,{number:rD,Complex:n=>n.coth(),BigNumber:n=>new t(1).div(n.tanh())})});var OE="csc",e$=["typed","BigNumber"],Qh=F(OE,e$,e=>{var{typed:r,BigNumber:t}=e,n=Ra({typed:r});return r(OE,{number:tD,Complex:a=>a.csc(),BigNumber:a=>new t(1).div(a.sin())},n)});var BE="csch",r$=["typed","BigNumber"],Xh=F(BE,r$,e=>{var{typed:r,BigNumber:t}=e;return r(BE,{number:nD,Complex:n=>n.csch(),BigNumber:n=>new t(1).div(n.sinh())})});var PE="sec",t$=["typed","BigNumber"],Jh=F(PE,t$,e=>{var{typed:r,BigNumber:t}=e,n=Ra({typed:r});return r(PE,{number:aD,Complex:a=>a.sec(),BigNumber:a=>new t(1).div(a.cos())},n)});var IE="sech",n$=["typed","BigNumber"],Kh=F(IE,n$,e=>{var{typed:r,BigNumber:t}=e;return r(IE,{number:iD,Complex:n=>n.sech(),BigNumber:n=>new t(1).div(n.cosh())})});var RE="sin",a$=["typed"],jh=F(RE,a$,e=>{var{typed:r}=e,t=Ra({typed:r});return r(RE,{number:Math.sin,"Complex | BigNumber":n=>n.sin()},t)});var kE="sinh",i$=["typed"],ev=F(kE,i$,e=>{var{typed:r}=e;return r(kE,{number:oD,"Complex | BigNumber":t=>t.sinh()})});var qE="tan",o$=["typed"],rv=F(qE,o$,e=>{var{typed:r}=e,t=Ra({typed:r});return r(qE,{number:Math.tan,"Complex | BigNumber":n=>n.tan()},t)});var s$="tanh",u$=["typed"],tv=F(s$,u$,e=>{var{typed:r}=e;return r("tanh",{number:Tm,"Complex | BigNumber":t=>t.tanh()})});var LE="setCartesian",f$=["typed","size","subset","compareNatural","Index","DenseMatrix"],nv=F(LE,f$,e=>{var{typed:r,size:t,subset:n,compareNatural:a,Index:i,DenseMatrix:u}=e;return r(LE,{"Array | Matrix, Array | Matrix":function(c,o){var s=[];if(n(t(c),new i(0))!==0&&n(t(o),new i(0))!==0){var m=gr(Array.isArray(c)?c:c.toArray()).sort(a),d=gr(Array.isArray(o)?o:o.toArray()).sort(a);s=[];for(var h=0;h{var{typed:r,size:t,subset:n,compareNatural:a,Index:i,DenseMatrix:u}=e;return r(zE,{"Array | Matrix, Array | Matrix":function(c,o){var s;if(n(t(c),new i(0))===0)s=[];else{if(n(t(o),new i(0))===0)return gr(c.toArray());var m=Ji(gr(Array.isArray(c)?c:c.toArray()).sort(a)),d=Ji(gr(Array.isArray(o)?o:o.toArray()).sort(a));s=[];for(var h,x=0;x{var{typed:r,size:t,subset:n,compareNatural:a,Index:i,DenseMatrix:u}=e;return r(UE,{"Array | Matrix":function(c){var o;if(n(t(c),new i(0))===0)o=[];else{var s=gr(Array.isArray(c)?c:c.toArray()).sort(a);o=[],o.push(s[0]);for(var m=1;m{var{typed:r,size:t,subset:n,compareNatural:a,Index:i,DenseMatrix:u}=e;return r(WE,{"Array | Matrix, Array | Matrix":function(c,o){var s;if(n(t(c),new i(0))===0||n(t(o),new i(0))===0)s=[];else{var m=Ji(gr(Array.isArray(c)?c:c.toArray()).sort(a)),d=Ji(gr(Array.isArray(o)?o:o.toArray()).sort(a));s=[];for(var h=0;h{var{typed:r,size:t,subset:n,compareNatural:a,Index:i}=e;return r(YE,{"Array | Matrix, Array | Matrix":function(l,c){if(n(t(l),new i(0))===0)return!0;if(n(t(c),new i(0))===0)return!1;for(var o=Ji(gr(Array.isArray(l)?l:l.toArray()).sort(a)),s=Ji(gr(Array.isArray(c)?c:c.toArray()).sort(a)),m,d=0;d{var{typed:r,size:t,subset:n,compareNatural:a,Index:i}=e;return r(HE,{"number | BigNumber | Fraction | Complex, Array | Matrix":function(l,c){if(n(t(c),new i(0))===0)return 0;for(var o=gr(Array.isArray(c)?c:c.toArray()),s=0,m=0;m{var{typed:r,size:t,subset:n,compareNatural:a,Index:i}=e;return r($E,{"Array | Matrix":function(o){if(n(t(o),new i(0))===0)return[];for(var s=gr(Array.isArray(o)?o:o.toArray()).sort(a),m=[],d=0;d.toString(2).length<=s.length;)m.push(u(s,d.toString(2).split("").reverse())),d++;return l(m)}});function u(c,o){for(var s=[],m=0;m0;s--)for(var m=0;mc[m+1].length&&(o=c[m],c[m]=c[m+1],c[m+1]=o);return c}});var GE="setSize",v$=["typed","compareNatural"],cv=F(GE,v$,e=>{var{typed:r,compareNatural:t}=e;return r(GE,{"Array | Matrix":function(a){return Array.isArray(a)?gr(a).length:gr(a.toArray()).length},"Array | Matrix, boolean":function(a,i){if(i===!1||a.length===0)return Array.isArray(a)?gr(a).length:gr(a.toArray()).length;for(var u=gr(Array.isArray(a)?a:a.toArray()).sort(t),l=1,c=1;c{var{typed:r,size:t,concat:n,subset:a,setDifference:i,Index:u}=e;return r(VE,{"Array | Matrix, Array | Matrix":function(c,o){if(a(t(c),new u(0))===0)return gr(o);if(a(t(o),new u(0))===0)return gr(c);var s=gr(c),m=gr(o);return n(i(s,m),i(m,s))}})});var ZE="setUnion",x$=["typed","size","concat","subset","setIntersect","setSymDifference","Index"],mv=F(ZE,x$,e=>{var{typed:r,size:t,concat:n,subset:a,setIntersect:i,setSymDifference:u,Index:l}=e;return r(ZE,{"Array | Matrix, Array | Matrix":function(o,s){if(a(t(o),new l(0))===0)return gr(s);if(a(t(s),new l(0))===0)return gr(o);var m=gr(o),d=gr(s);return n(u(m,d),i(m,d))}})});var QE="add",y$=["typed","matrix","addScalar","equalScalar","DenseMatrix","SparseMatrix","concat"],pv=F(QE,y$,e=>{var{typed:r,matrix:t,addScalar:n,equalScalar:a,DenseMatrix:i,SparseMatrix:u,concat:l}=e,c=Mn({typed:r}),o=Ru({typed:r,equalScalar:a}),s=jn({typed:r,DenseMatrix:i}),m=vr({typed:r,matrix:t,concat:l});return r(QE,{"any, any":n,"any, any, ...any":r.referToSelf(d=>(h,x,v)=>{for(var y=d(h,x),w=0;w{var{typed:r,abs:t,addScalar:n,divideScalar:a,multiplyScalar:i,sqrt:u,smaller:l,isPositive:c}=e;return r(XE,{"... number | BigNumber":o,Array:o,Matrix:s=>o(gr(s.toArray()))});function o(s){for(var m=0,d=0,h=0;h{var{typed:r,abs:t,add:n,pow:a,conj:i,sqrt:u,multiply:l,equalScalar:c,larger:o,smaller:s,matrix:m,ctranspose:d,eigs:h}=e;return r(JE,{number:Math.abs,Complex:function(_){return _.abs()},BigNumber:function(_){return _.abs()},boolean:function(_){return Math.abs(_)},Array:function(_){return S(m(_),2)},Matrix:function(_){return S(_,2)},"Array, number | BigNumber | string":function(_,E){return S(m(_),E)},"Matrix, number | BigNumber | string":function(_,E){return S(_,E)}});function x(O){var _=0;return O.forEach(function(E){var T=t(E);o(T,_)&&(_=T)},!0),_}function v(O){var _;return O.forEach(function(E){var T=t(E);(!_||s(T,_))&&(_=T)},!0),_||0}function y(O,_){if(_===Number.POSITIVE_INFINITY||_==="inf")return x(O);if(_===Number.NEGATIVE_INFINITY||_==="-inf")return v(O);if(_==="fro")return S(O,2);if(typeof _=="number"&&!isNaN(_)){if(!c(_,0)){var E=0;return O.forEach(function(T){E=n(a(t(T),_),E)},!0),a(E,1/_)}return Number.POSITIVE_INFINITY}throw new Error("Unsupported parameter value")}function w(O){var _=0;return O.forEach(function(E,T){_=n(_,l(E,i(E)))}),t(u(_))}function C(O){var _=[],E=0;return O.forEach(function(T,R){var q=R[1],W=n(_[q]||0,t(T));o(W,E)&&(E=W),_[q]=W},!0),E}function b(O){var _=O.size();if(_[0]!==_[1])throw new RangeError("Invalid matrix dimensions");var E=d(O),T=l(E,O),R=h(T).values.toArray(),q=R[R.length-1];return t(u(q))}function M(O){var _=[],E=0;return O.forEach(function(T,R){var q=R[0],W=n(_[q]||0,t(T));o(W,E)&&(E=W),_[q]=W},!0),E}function A(O,_){if(_===1)return C(O);if(_===Number.POSITIVE_INFINITY||_==="inf")return M(O);if(_==="fro")return w(O);if(_===2)return b(O);throw new Error("Unsupported parameter value "+_)}function S(O,_){var E=O.size();if(E.length===1)return y(O,_);if(E.length===2){if(E[0]&&E[1])return A(O,_);throw new RangeError("Invalid matrix dimensions")}}});var KE="dot",D$=["typed","addScalar","multiplyScalar","conj","size"],vv=F(KE,D$,e=>{var{typed:r,addScalar:t,multiplyScalar:n,conj:a,size:i}=e;return r(KE,{"Array | DenseMatrix, Array | DenseMatrix":l,"SparseMatrix, SparseMatrix":c});function u(s,m){var d=o(s),h=o(m),x,v;if(d.length===1)x=d[0];else if(d.length===2&&d[1]===1)x=d[0];else throw new RangeError("Expected a column vector, instead got a matrix of size ("+d.join(", ")+")");if(h.length===1)v=h[0];else if(h.length===2&&h[1]===1)v=h[0];else throw new RangeError("Expected a column vector, instead got a matrix of size ("+h.join(", ")+")");if(x!==v)throw new RangeError("Vectors must have equal length ("+x+" != "+v+")");if(x===0)throw new RangeError("Cannot calculate the dot product of empty vectors");return x}function l(s,m){var d=u(s,m),h=Qe(s)?s._data:s,x=Qe(s)?s._datatype||s.getDataType():void 0,v=Qe(m)?m._data:m,y=Qe(m)?m._datatype||m.getDataType():void 0,w=o(s).length===2,C=o(m).length===2,b=t,M=n;if(x&&y&&x===y&&typeof x=="string"&&x!=="mixed"){var A=x;b=r.find(t,[A,A]),M=r.find(n,[A,A])}if(!w&&!C){for(var S=M(a(h[0]),v[0]),O=1;OS){M++;continue}A===S&&(y=w(y,C(h[b],v[M])),b++,M++)}return y}function o(s){return Qe(s)?s.size():i(s)}});var S$="trace",N$=["typed","matrix","add"],gv=F(S$,N$,e=>{var{typed:r,matrix:t,add:n}=e;return r("trace",{Array:function(l){return a(t(l))},SparseMatrix:i,DenseMatrix:a,any:ar});function a(u){var l=u._size,c=u._data;switch(l.length){case 1:if(l[0]===1)return ar(c[0]);throw new RangeError("Matrix must be square (size: "+lr(l)+")");case 2:{var o=l[0],s=l[1];if(o===s){for(var m=0,d=0;d0)for(var x=0;xx)break}return h}throw new RangeError("Matrix must be square (size: "+lr(s)+")")}});var jE="index",A$=["typed","Index"],xv=F(jE,A$,e=>{var{typed:r,Index:t}=e;return r(jE,{"...number | string | BigNumber | Range | Array | Matrix":function(a){var i=a.map(function(l){return rr(l)?l.toNumber():Mr(l)||Qe(l)?l.map(function(c){return rr(c)?c.toNumber():c}):l}),u=new t;return t.apply(u,i),u}})});var yv=new Set(["end"]);var M$="Node",C$=["mathWithTransform"],bv=F(M$,C$,e=>{var{mathWithTransform:r}=e;function t(a){for(var i of[...yv])if(a.has(i))throw new Error('Scope contains an illegal symbol, "'+i+'" is a reserved keyword')}class n{get type(){return"Node"}get isNode(){return!0}evaluate(i){return this.compile().evaluate(i)}compile(){var i=this._compile(r,{}),u={},l=null;function c(o){var s=Ki(o);return t(s),i(s,u,l)}return{evaluate:c}}_compile(i,u){throw new Error("Method _compile must be implemented by type "+this.type)}forEach(i){throw new Error("Cannot run forEach on a Node interface")}map(i){throw new Error("Cannot run map on a Node interface")}_ifNode(i){if(!Nr(i))throw new TypeError("Callback function must return a Node");return i}traverse(i){i(this,null,null);function u(l,c){l.forEach(function(o,s,m){c(o,s,m),u(o,c)})}u(this,i)}transform(i){function u(l,c,o){var s=i(l,c,o);return s!==l?s:l.map(u)}return u(this,null,null)}filter(i){var u=[];return this.traverse(function(l,c,o){i(l,c,o)&&u.push(l)}),u}clone(){throw new Error("Cannot clone a Node interface")}cloneDeep(){return this.map(function(i){return i.cloneDeep()})}equals(i){return i?this.type===i.type&&ni(this,i):!1}toString(i){var u=this._getCustomString(i);return typeof u<"u"?u:this._toString(i)}_toString(){throw new Error("_toString not implemented for "+this.type)}toJSON(){throw new Error("Cannot serialize object: toJSON not implemented by "+this.type)}toHTML(i){var u=this._getCustomString(i);return typeof u<"u"?u:this._toHTML(i)}_toHTML(){throw new Error("_toHTML not implemented for "+this.type)}toTex(i){var u=this._getCustomString(i);return typeof u<"u"?u:this._toTex(i)}_toTex(i){throw new Error("_toTex not implemented for "+this.type)}_getCustomString(i){if(i&&typeof i=="object")switch(typeof i.handler){case"object":case"undefined":return;case"function":return i.handler(this,i);default:throw new TypeError("Object or function expected as callback")}}getIdentifier(){return this.type}getContent(){return this}}return n},{isClass:!0,isNode:!0});function mt(e){return e&&e.isIndexError?new tn(e.index+1,e.min+1,e.max!==void 0?e.max+1:void 0):e}function wv(e){var{subset:r}=e;return function(n,a){try{if(Array.isArray(n))return r(n,a);if(n&&typeof n.subset=="function")return n.subset(a);if(typeof n=="string")return r(n,a);if(typeof n=="object"){if(!a.isObjectProperty())throw new TypeError("Cannot apply a numeric index as object property");return wt(n,a.getObjectProperty())}else throw new TypeError("Cannot apply index: unsupported type of object")}catch(i){throw mt(i)}}}var Dv="AccessorNode",E$=["subset","Node"],Sv=F(Dv,E$,e=>{var{subset:r,Node:t}=e,n=wv({subset:r});function a(u){return!(qn(u)||jt(u)||yr(u)||gn(u)||Ci(u)||en(u)||at(u))}class i extends t{constructor(l,c){if(super(),!Nr(l))throw new TypeError('Node expected for parameter "object"');if(!Qn(c))throw new TypeError('IndexNode expected for parameter "index"');this.object=l,this.index=c}get name(){return this.index?this.index.isObjectProperty()?this.index.getObjectProperty():"":this.object.name||""}get type(){return Dv}get isAccessorNode(){return!0}_compile(l,c){var o=this.object._compile(l,c),s=this.index._compile(l,c);if(this.index.isObjectProperty()){var m=this.index.getObjectProperty();return function(h,x,v){return wt(o(h,x,v),m)}}else return function(h,x,v){var y=o(h,x,v),w=s(h,x,y);return n(y,w)}}forEach(l){l(this.object,"object",this),l(this.index,"index",this)}map(l){return new i(this._ifNode(l(this.object,"object",this)),this._ifNode(l(this.index,"index",this)))}clone(){return new i(this.object,this.index)}_toString(l){var c=this.object.toString(l);return a(this.object)&&(c="("+c+")"),c+this.index.toString(l)}_toHTML(l){var c=this.object.toHTML(l);return a(this.object)&&(c='('+c+')'),c+this.index.toHTML(l)}_toTex(l){var c=this.object.toTex(l);return a(this.object)&&(c="\\\\left(' + object + '\\\\right)"),c+this.index.toTex(l)}toJSON(){return{mathjs:Dv,object:this.object,index:this.index}}static fromJSON(l){return new i(l.object,l.index)}}return Hr(i,"name",Dv),i},{isClass:!0,isNode:!0});var Nv="ArrayNode",T$=["Node"],Av=F(Nv,T$,e=>{var{Node:r}=e;class t extends r{constructor(a){if(super(),this.items=a||[],!Array.isArray(this.items)||!this.items.every(Nr))throw new TypeError("Array containing Nodes expected")}get type(){return Nv}get isArrayNode(){return!0}_compile(a,i){var u=Xn(this.items,function(o){return o._compile(a,i)}),l=a.config.matrix!=="Array";if(l){var c=a.matrix;return function(s,m,d){return c(Xn(u,function(h){return h(s,m,d)}))}}else return function(s,m,d){return Xn(u,function(h){return h(s,m,d)})}}forEach(a){for(var i=0;i['+i.join(',')+']'}_toTex(a){function i(u,l){var c=u.some(jt)&&!u.every(jt),o=l||c,s=o?"&":"\\\\\\\\",m=u.map(function(d){return d.items?i(d.items,!l):d.toTex(a)}).join(s);return c||!o||o&&!l?"\\\\begin{bmatrix}"+m+"\\\\end{bmatrix}":m}return i(this.items,!1)}}return Hr(t,"name",Nv),t},{isClass:!0,isNode:!0});function eT(e){var{subset:r,matrix:t}=e;return function(a,i,u){try{if(Array.isArray(a)){var l=t(a).subset(i,u).valueOf();return l.forEach((c,o)=>{a[o]=c}),a}else{if(a&&typeof a.subset=="function")return a.subset(i,u);if(typeof a=="string")return r(a,i,u);if(typeof a=="object"){if(!i.isObjectProperty())throw TypeError("Cannot apply a numeric index as object property");return Ei(a,i.getObjectProperty(),u),a}else throw new TypeError("Cannot apply index: unsupported type of object")}}catch(c){throw mt(c)}}}var ka=[{AssignmentNode:{},FunctionAssignmentNode:{}},{ConditionalNode:{latexLeftParens:!1,latexRightParens:!1,latexParens:!1}},{"OperatorNode:or":{op:"or",associativity:"left",associativeWith:[]}},{"OperatorNode:xor":{op:"xor",associativity:"left",associativeWith:[]}},{"OperatorNode:and":{op:"and",associativity:"left",associativeWith:[]}},{"OperatorNode:bitOr":{op:"|",associativity:"left",associativeWith:[]}},{"OperatorNode:bitXor":{op:"^|",associativity:"left",associativeWith:[]}},{"OperatorNode:bitAnd":{op:"&",associativity:"left",associativeWith:[]}},{"OperatorNode:equal":{op:"==",associativity:"left",associativeWith:[]},"OperatorNode:unequal":{op:"!=",associativity:"left",associativeWith:[]},"OperatorNode:smaller":{op:"<",associativity:"left",associativeWith:[]},"OperatorNode:larger":{op:">",associativity:"left",associativeWith:[]},"OperatorNode:smallerEq":{op:"<=",associativity:"left",associativeWith:[]},"OperatorNode:largerEq":{op:">=",associativity:"left",associativeWith:[]},RelationalNode:{associativity:"left",associativeWith:[]}},{"OperatorNode:leftShift":{op:"<<",associativity:"left",associativeWith:[]},"OperatorNode:rightArithShift":{op:">>",associativity:"left",associativeWith:[]},"OperatorNode:rightLogShift":{op:">>>",associativity:"left",associativeWith:[]}},{"OperatorNode:to":{op:"to",associativity:"left",associativeWith:[]}},{RangeNode:{}},{"OperatorNode:add":{op:"+",associativity:"left",associativeWith:["OperatorNode:add","OperatorNode:subtract"]},"OperatorNode:subtract":{op:"-",associativity:"left",associativeWith:[]}},{"OperatorNode:multiply":{op:"*",associativity:"left",associativeWith:["OperatorNode:multiply","OperatorNode:divide","Operator:dotMultiply","Operator:dotDivide"]},"OperatorNode:divide":{op:"/",associativity:"left",associativeWith:[],latexLeftParens:!1,latexRightParens:!1,latexParens:!1},"OperatorNode:dotMultiply":{op:".*",associativity:"left",associativeWith:["OperatorNode:multiply","OperatorNode:divide","OperatorNode:dotMultiply","OperatorNode:doDivide"]},"OperatorNode:dotDivide":{op:"./",associativity:"left",associativeWith:[]},"OperatorNode:mod":{op:"mod",associativity:"left",associativeWith:[]}},{"OperatorNode:multiply":{associativity:"left",associativeWith:["OperatorNode:multiply","OperatorNode:divide","Operator:dotMultiply","Operator:dotDivide"]}},{"OperatorNode:unaryPlus":{op:"+",associativity:"right"},"OperatorNode:unaryMinus":{op:"-",associativity:"right"},"OperatorNode:bitNot":{op:"~",associativity:"right"},"OperatorNode:not":{op:"not",associativity:"right"}},{"OperatorNode:pow":{op:"^",associativity:"right",associativeWith:[],latexRightParens:!1},"OperatorNode:dotPow":{op:".^",associativity:"right",associativeWith:[]}},{"OperatorNode:factorial":{op:"!",associativity:"left"}},{"OperatorNode:ctranspose":{op:"'",associativity:"left"}}];function Mv(e,r){if(!r||r!=="auto")return e;for(var t=e;en(t);)t=t.content;return t}function Qr(e,r,t,n){var a=e;r!=="keep"&&(a=e.getContent());for(var i=a.getIdentifier(),u=null,l=0;l{var{subset:r,matrix:t,Node:n}=e,a=wv({subset:r}),i=eT({subset:r,matrix:t});function u(c,o,s){o||(o="keep");var m=Qr(c,o,s),d=Qr(c.value,o,s);return o==="all"||d!==null&&d<=m}class l extends n{constructor(o,s,m){if(super(),this.object=o,this.index=m?s:null,this.value=m||s,!at(o)&&!qn(o))throw new TypeError('SymbolNode or AccessorNode expected as "object"');if(at(o)&&o.name==="end")throw new Error('Cannot assign to symbol "end"');if(this.index&&!Qn(this.index))throw new TypeError('IndexNode expected as "index"');if(!Nr(this.value))throw new TypeError('Node expected as "value"')}get name(){return this.index?this.index.isObjectProperty()?this.index.getObjectProperty():"":this.object.name||""}get type(){return Ev}get isAssignmentNode(){return!0}_compile(o,s){var m=this.object._compile(o,s),d=this.index?this.index._compile(o,s):null,h=this.value._compile(o,s),x=this.object.name;if(this.index)if(this.index.isObjectProperty()){var v=this.index.getObjectProperty();return function(M,A,S){var O=m(M,A,S),_=h(M,A,S);return Ei(O,v,_),_}}else{if(at(this.object))return function(M,A,S){var O=m(M,A,S),_=h(M,A,S),E=d(M,A,O);return M.set(x,i(O,E,_)),_};var y=this.object.object._compile(o,s);if(this.object.index.isObjectProperty()){var w=this.object.index.getObjectProperty();return function(M,A,S){var O=y(M,A,S),_=wt(O,w),E=d(M,A,_),T=h(M,A,S);return Ei(O,w,i(_,E,T)),T}}else{var C=this.object.index._compile(o,s);return function(M,A,S){var O=y(M,A,S),_=C(M,A,O),E=a(O,_),T=d(M,A,E),R=h(M,A,S);return i(O,_,i(E,T,R)),R}}}else{if(!at(this.object))throw new TypeError("SymbolNode expected as object");return function(M,A,S){var O=h(M,A,S);return M.set(x,O),O}}}forEach(o){o(this.object,"object",this),this.index&&o(this.index,"index",this),o(this.value,"value",this)}map(o){var s=this._ifNode(o(this.object,"object",this)),m=this.index?this._ifNode(o(this.index,"index",this)):null,d=this._ifNode(o(this.value,"value",this));return new l(s,m,d)}clone(){return new l(this.object,this.index,this.value)}_toString(o){var s=this.object.toString(o),m=this.index?this.index.toString(o):"",d=this.value.toString(o);return u(this,o&&o.parenthesis,o&&o.implicit)&&(d="("+d+")"),s+m+" = "+d}toJSON(){return{mathjs:Ev,object:this.object,index:this.index,value:this.value}}static fromJSON(o){return new l(o.object,o.index,o.value)}_toHTML(o){var s=this.object.toHTML(o),m=this.index?this.index.toHTML(o):"",d=this.value.toHTML(o);return u(this,o&&o.parenthesis,o&&o.implicit)&&(d='('+d+')'),s+m+'='+d}_toTex(o){var s=this.object.toTex(o),m=this.index?this.index.toTex(o):"",d=this.value.toTex(o);return u(this,o&&o.parenthesis,o&&o.implicit)&&(d="\\\\left(".concat(d,"\\\\right)")),s+m+"="+d}}return Hr(l,"name",Ev),l},{isClass:!0,isNode:!0});var Fv="BlockNode",_$=["ResultSet","Node"],_v=F(Fv,_$,e=>{var{ResultSet:r,Node:t}=e;class n extends t{constructor(i){if(super(),!Array.isArray(i))throw new Error("Array expected");this.blocks=i.map(function(u){var l=u&&u.node,c=u&&u.visible!==void 0?u.visible:!0;if(!Nr(l))throw new TypeError('Property "node" must be a Node');if(typeof c!="boolean")throw new TypeError('Property "visible" must be a boolean');return{node:l,visible:c}})}get type(){return Fv}get isBlockNode(){return!0}_compile(i,u){var l=Xn(this.blocks,function(c){return{evaluate:c.node._compile(i,u),visible:c.visible}});return function(o,s,m){var d=[];return Fo(l,function(x){var v=x.evaluate(o,s,m);x.visible&&d.push(v)}),new r(d)}}forEach(i){for(var u=0;u;')}).join('
')}_toTex(i){return this.blocks.map(function(u){return u.node.toTex(i)+(u.visible?"":";")}).join(\`\\\\;\\\\; +\`)}}return Hr(n,"name",Fv),n},{isClass:!0,isNode:!0});var Ov="ConditionalNode",O$=["Node"],Bv=F(Ov,O$,e=>{var{Node:r}=e;function t(a){if(typeof a=="number"||typeof a=="boolean"||typeof a=="string")return!!a;if(a){if(rr(a))return!a.isZero();if(Kt(a))return!!(a.re||a.im);if(Ht(a))return!!a.value}if(a==null)return!1;throw new TypeError('Unsupported type of condition "'+Fr(a)+'"')}class n extends r{constructor(i,u,l){if(super(),!Nr(i))throw new TypeError("Parameter condition must be a Node");if(!Nr(u))throw new TypeError("Parameter trueExpr must be a Node");if(!Nr(l))throw new TypeError("Parameter falseExpr must be a Node");this.condition=i,this.trueExpr=u,this.falseExpr=l}get type(){return Ov}get isConditionalNode(){return!0}_compile(i,u){var l=this.condition._compile(i,u),c=this.trueExpr._compile(i,u),o=this.falseExpr._compile(i,u);return function(m,d,h){return t(l(m,d,h))?c(m,d,h):o(m,d,h)}}forEach(i){i(this.condition,"condition",this),i(this.trueExpr,"trueExpr",this),i(this.falseExpr,"falseExpr",this)}map(i){return new n(this._ifNode(i(this.condition,"condition",this)),this._ifNode(i(this.trueExpr,"trueExpr",this)),this._ifNode(i(this.falseExpr,"falseExpr",this)))}clone(){return new n(this.condition,this.trueExpr,this.falseExpr)}_toString(i){var u=i&&i.parenthesis?i.parenthesis:"keep",l=Qr(this,u,i&&i.implicit),c=this.condition.toString(i),o=Qr(this.condition,u,i&&i.implicit);(u==="all"||this.condition.type==="OperatorNode"||o!==null&&o<=l)&&(c="("+c+")");var s=this.trueExpr.toString(i),m=Qr(this.trueExpr,u,i&&i.implicit);(u==="all"||this.trueExpr.type==="OperatorNode"||m!==null&&m<=l)&&(s="("+s+")");var d=this.falseExpr.toString(i),h=Qr(this.falseExpr,u,i&&i.implicit);return(u==="all"||this.falseExpr.type==="OperatorNode"||h!==null&&h<=l)&&(d="("+d+")"),c+" ? "+s+" : "+d}toJSON(){return{mathjs:Ov,condition:this.condition,trueExpr:this.trueExpr,falseExpr:this.falseExpr}}static fromJSON(i){return new n(i.condition,i.trueExpr,i.falseExpr)}_toHTML(i){var u=i&&i.parenthesis?i.parenthesis:"keep",l=Qr(this,u,i&&i.implicit),c=this.condition.toHTML(i),o=Qr(this.condition,u,i&&i.implicit);(u==="all"||this.condition.type==="OperatorNode"||o!==null&&o<=l)&&(c='('+c+')');var s=this.trueExpr.toHTML(i),m=Qr(this.trueExpr,u,i&&i.implicit);(u==="all"||this.trueExpr.type==="OperatorNode"||m!==null&&m<=l)&&(s='('+s+')');var d=this.falseExpr.toHTML(i),h=Qr(this.falseExpr,u,i&&i.implicit);return(u==="all"||this.falseExpr.type==="OperatorNode"||h!==null&&h<=l)&&(d='('+d+')'),c+'?'+s+':'+d}_toTex(i){return"\\\\begin{cases} {"+this.trueExpr.toTex(i)+"}, &\\\\quad{\\\\text{if }\\\\;"+this.condition.toTex(i)+"}\\\\\\\\{"+this.falseExpr.toTex(i)+"}, &\\\\quad{\\\\text{otherwise}}\\\\end{cases}"}}return Hr(n,"name",Ov),n},{isClass:!0,isNode:!0});var iT=ca(nT(),1);var xD={Alpha:"A",alpha:"\\\\alpha",Beta:"B",beta:"\\\\beta",Gamma:"\\\\Gamma",gamma:"\\\\gamma",Delta:"\\\\Delta",delta:"\\\\delta",Epsilon:"E",epsilon:"\\\\epsilon",varepsilon:"\\\\varepsilon",Zeta:"Z",zeta:"\\\\zeta",Eta:"H",eta:"\\\\eta",Theta:"\\\\Theta",theta:"\\\\theta",vartheta:"\\\\vartheta",Iota:"I",iota:"\\\\iota",Kappa:"K",kappa:"\\\\kappa",varkappa:"\\\\varkappa",Lambda:"\\\\Lambda",lambda:"\\\\lambda",Mu:"M",mu:"\\\\mu",Nu:"N",nu:"\\\\nu",Xi:"\\\\Xi",xi:"\\\\xi",Omicron:"O",omicron:"o",Pi:"\\\\Pi",pi:"\\\\pi",varpi:"\\\\varpi",Rho:"P",rho:"\\\\rho",varrho:"\\\\varrho",Sigma:"\\\\Sigma",sigma:"\\\\sigma",varsigma:"\\\\varsigma",Tau:"T",tau:"\\\\tau",Upsilon:"\\\\Upsilon",upsilon:"\\\\upsilon",Phi:"\\\\Phi",phi:"\\\\phi",varphi:"\\\\varphi",Chi:"X",chi:"\\\\chi",Psi:"\\\\Psi",psi:"\\\\psi",Omega:"\\\\Omega",omega:"\\\\omega",true:"\\\\mathrm{True}",false:"\\\\mathrm{False}",i:"i",inf:"\\\\infty",Inf:"\\\\infty",infinity:"\\\\infty",Infinity:"\\\\infty",oo:"\\\\infty",lim:"\\\\lim",undefined:"\\\\mathbf{?}"},$r={transpose:"^\\\\top",ctranspose:"^H",factorial:"!",pow:"^",dotPow:".^\\\\wedge",unaryPlus:"+",unaryMinus:"-",bitNot:"\\\\~",not:"\\\\neg",multiply:"\\\\cdot",divide:"\\\\frac",dotMultiply:".\\\\cdot",dotDivide:".:",mod:"\\\\mod",add:"+",subtract:"-",to:"\\\\rightarrow",leftShift:"<<",rightArithShift:">>",rightLogShift:">>>",equal:"=",unequal:"\\\\neq",smaller:"<",larger:">",smallerEq:"\\\\leq",largerEq:"\\\\geq",bitAnd:"\\\\&",bitXor:"\\\\underline{|}",bitOr:"|",and:"\\\\wedge",xor:"\\\\veebar",or:"\\\\vee"},yD={abs:{1:"\\\\left|\${args[0]}\\\\right|"},add:{2:"\\\\left(\${args[0]}".concat($r.add,"\${args[1]}\\\\right)")},cbrt:{1:"\\\\sqrt[3]{\${args[0]}}"},ceil:{1:"\\\\left\\\\lceil\${args[0]}\\\\right\\\\rceil"},cube:{1:"\\\\left(\${args[0]}\\\\right)^3"},divide:{2:"\\\\frac{\${args[0]}}{\${args[1]}}"},dotDivide:{2:"\\\\left(\${args[0]}".concat($r.dotDivide,"\${args[1]}\\\\right)")},dotMultiply:{2:"\\\\left(\${args[0]}".concat($r.dotMultiply,"\${args[1]}\\\\right)")},dotPow:{2:"\\\\left(\${args[0]}".concat($r.dotPow,"\${args[1]}\\\\right)")},exp:{1:"\\\\exp\\\\left(\${args[0]}\\\\right)"},expm1:"\\\\left(e".concat($r.pow,"{\${args[0]}}-1\\\\right)"),fix:{1:"\\\\mathrm{\${name}}\\\\left(\${args[0]}\\\\right)"},floor:{1:"\\\\left\\\\lfloor\${args[0]}\\\\right\\\\rfloor"},gcd:"\\\\gcd\\\\left(\${args}\\\\right)",hypot:"\\\\hypot\\\\left(\${args}\\\\right)",log:{1:"\\\\ln\\\\left(\${args[0]}\\\\right)",2:"\\\\log_{\${args[1]}}\\\\left(\${args[0]}\\\\right)"},log10:{1:"\\\\log_{10}\\\\left(\${args[0]}\\\\right)"},log1p:{1:"\\\\ln\\\\left(\${args[0]}+1\\\\right)",2:"\\\\log_{\${args[1]}}\\\\left(\${args[0]}+1\\\\right)"},log2:"\\\\log_{2}\\\\left(\${args[0]}\\\\right)",mod:{2:"\\\\left(\${args[0]}".concat($r.mod,"\${args[1]}\\\\right)")},multiply:{2:"\\\\left(\${args[0]}".concat($r.multiply,"\${args[1]}\\\\right)")},norm:{1:"\\\\left\\\\|\${args[0]}\\\\right\\\\|",2:void 0},nthRoot:{2:"\\\\sqrt[\${args[1]}]{\${args[0]}}"},nthRoots:{2:"\\\\{y : $y^{args[1]} = {\${args[0]}}\\\\}"},pow:{2:"\\\\left(\${args[0]}\\\\right)".concat($r.pow,"{\${args[1]}}")},round:{1:"\\\\left\\\\lfloor\${args[0]}\\\\right\\\\rceil",2:void 0},sign:{1:"\\\\mathrm{\${name}}\\\\left(\${args[0]}\\\\right)"},sqrt:{1:"\\\\sqrt{\${args[0]}}"},square:{1:"\\\\left(\${args[0]}\\\\right)^2"},subtract:{2:"\\\\left(\${args[0]}".concat($r.subtract,"\${args[1]}\\\\right)")},unaryMinus:{1:"".concat($r.unaryMinus,"\\\\left(\${args[0]}\\\\right)")},unaryPlus:{1:"".concat($r.unaryPlus,"\\\\left(\${args[0]}\\\\right)")},bitAnd:{2:"\\\\left(\${args[0]}".concat($r.bitAnd,"\${args[1]}\\\\right)")},bitNot:{1:$r.bitNot+"\\\\left(\${args[0]}\\\\right)"},bitOr:{2:"\\\\left(\${args[0]}".concat($r.bitOr,"\${args[1]}\\\\right)")},bitXor:{2:"\\\\left(\${args[0]}".concat($r.bitXor,"\${args[1]}\\\\right)")},leftShift:{2:"\\\\left(\${args[0]}".concat($r.leftShift,"\${args[1]}\\\\right)")},rightArithShift:{2:"\\\\left(\${args[0]}".concat($r.rightArithShift,"\${args[1]}\\\\right)")},rightLogShift:{2:"\\\\left(\${args[0]}".concat($r.rightLogShift,"\${args[1]}\\\\right)")},bellNumbers:{1:"\\\\mathrm{B}_{\${args[0]}}"},catalan:{1:"\\\\mathrm{C}_{\${args[0]}}"},stirlingS2:{2:"\\\\mathrm{S}\\\\left(\${args}\\\\right)"},arg:{1:"\\\\arg\\\\left(\${args[0]}\\\\right)"},conj:{1:"\\\\left(\${args[0]}\\\\right)^*"},im:{1:"\\\\Im\\\\left\\\\lbrace\${args[0]}\\\\right\\\\rbrace"},re:{1:"\\\\Re\\\\left\\\\lbrace\${args[0]}\\\\right\\\\rbrace"},and:{2:"\\\\left(\${args[0]}".concat($r.and,"\${args[1]}\\\\right)")},not:{1:$r.not+"\\\\left(\${args[0]}\\\\right)"},or:{2:"\\\\left(\${args[0]}".concat($r.or,"\${args[1]}\\\\right)")},xor:{2:"\\\\left(\${args[0]}".concat($r.xor,"\${args[1]}\\\\right)")},cross:{2:"\\\\left(\${args[0]}\\\\right)\\\\times\\\\left(\${args[1]}\\\\right)"},ctranspose:{1:"\\\\left(\${args[0]}\\\\right)".concat($r.ctranspose)},det:{1:"\\\\det\\\\left(\${args[0]}\\\\right)"},dot:{2:"\\\\left(\${args[0]}\\\\cdot\${args[1]}\\\\right)"},expm:{1:"\\\\exp\\\\left(\${args[0]}\\\\right)"},inv:{1:"\\\\left(\${args[0]}\\\\right)^{-1}"},pinv:{1:"\\\\left(\${args[0]}\\\\right)^{+}"},sqrtm:{1:"{\${args[0]}}".concat($r.pow,"{\\\\frac{1}{2}}")},trace:{1:"\\\\mathrm{tr}\\\\left(\${args[0]}\\\\right)"},transpose:{1:"\\\\left(\${args[0]}\\\\right)".concat($r.transpose)},combinations:{2:"\\\\binom{\${args[0]}}{\${args[1]}}"},combinationsWithRep:{2:"\\\\left(\\\\!\\\\!{\\\\binom{\${args[0]}}{\${args[1]}}}\\\\!\\\\!\\\\right)"},factorial:{1:"\\\\left(\${args[0]}\\\\right)".concat($r.factorial)},gamma:{1:"\\\\Gamma\\\\left(\${args[0]}\\\\right)"},lgamma:{1:"\\\\ln\\\\Gamma\\\\left(\${args[0]}\\\\right)"},equal:{2:"\\\\left(\${args[0]}".concat($r.equal,"\${args[1]}\\\\right)")},larger:{2:"\\\\left(\${args[0]}".concat($r.larger,"\${args[1]}\\\\right)")},largerEq:{2:"\\\\left(\${args[0]}".concat($r.largerEq,"\${args[1]}\\\\right)")},smaller:{2:"\\\\left(\${args[0]}".concat($r.smaller,"\${args[1]}\\\\right)")},smallerEq:{2:"\\\\left(\${args[0]}".concat($r.smallerEq,"\${args[1]}\\\\right)")},unequal:{2:"\\\\left(\${args[0]}".concat($r.unequal,"\${args[1]}\\\\right)")},erf:{1:"erf\\\\left(\${args[0]}\\\\right)"},max:"\\\\max\\\\left(\${args}\\\\right)",min:"\\\\min\\\\left(\${args}\\\\right)",variance:"\\\\mathrm{Var}\\\\left(\${args}\\\\right)",acos:{1:"\\\\cos^{-1}\\\\left(\${args[0]}\\\\right)"},acosh:{1:"\\\\cosh^{-1}\\\\left(\${args[0]}\\\\right)"},acot:{1:"\\\\cot^{-1}\\\\left(\${args[0]}\\\\right)"},acoth:{1:"\\\\coth^{-1}\\\\left(\${args[0]}\\\\right)"},acsc:{1:"\\\\csc^{-1}\\\\left(\${args[0]}\\\\right)"},acsch:{1:"\\\\mathrm{csch}^{-1}\\\\left(\${args[0]}\\\\right)"},asec:{1:"\\\\sec^{-1}\\\\left(\${args[0]}\\\\right)"},asech:{1:"\\\\mathrm{sech}^{-1}\\\\left(\${args[0]}\\\\right)"},asin:{1:"\\\\sin^{-1}\\\\left(\${args[0]}\\\\right)"},asinh:{1:"\\\\sinh^{-1}\\\\left(\${args[0]}\\\\right)"},atan:{1:"\\\\tan^{-1}\\\\left(\${args[0]}\\\\right)"},atan2:{2:"\\\\mathrm{atan2}\\\\left(\${args}\\\\right)"},atanh:{1:"\\\\tanh^{-1}\\\\left(\${args[0]}\\\\right)"},cos:{1:"\\\\cos\\\\left(\${args[0]}\\\\right)"},cosh:{1:"\\\\cosh\\\\left(\${args[0]}\\\\right)"},cot:{1:"\\\\cot\\\\left(\${args[0]}\\\\right)"},coth:{1:"\\\\coth\\\\left(\${args[0]}\\\\right)"},csc:{1:"\\\\csc\\\\left(\${args[0]}\\\\right)"},csch:{1:"\\\\mathrm{csch}\\\\left(\${args[0]}\\\\right)"},sec:{1:"\\\\sec\\\\left(\${args[0]}\\\\right)"},sech:{1:"\\\\mathrm{sech}\\\\left(\${args[0]}\\\\right)"},sin:{1:"\\\\sin\\\\left(\${args[0]}\\\\right)"},sinh:{1:"\\\\sinh\\\\left(\${args[0]}\\\\right)"},tan:{1:"\\\\tan\\\\left(\${args[0]}\\\\right)"},tanh:{1:"\\\\tanh\\\\left(\${args[0]}\\\\right)"},to:{2:"\\\\left(\${args[0]}".concat($r.to,"\${args[1]}\\\\right)")},numeric:function(r,t){return r.args[0].toTex()},number:{0:"0",1:"\\\\left(\${args[0]}\\\\right)",2:"\\\\left(\\\\left(\${args[0]}\\\\right)\${args[1]}\\\\right)"},string:{0:'\\\\mathtt{""}',1:"\\\\mathrm{string}\\\\left(\${args[0]}\\\\right)"},bignumber:{0:"0",1:"\\\\left(\${args[0]}\\\\right)"},complex:{0:"0",1:"\\\\left(\${args[0]}\\\\right)",2:"\\\\left(\\\\left(\${args[0]}\\\\right)+".concat(xD.i,"\\\\cdot\\\\left(\${args[1]}\\\\right)\\\\right)")},matrix:{0:"\\\\begin{bmatrix}\\\\end{bmatrix}",1:"\\\\left(\${args[0]}\\\\right)",2:"\\\\left(\${args[0]}\\\\right)"},sparse:{0:"\\\\begin{bsparse}\\\\end{bsparse}",1:"\\\\left(\${args[0]}\\\\right)"},unit:{1:"\\\\left(\${args[0]}\\\\right)",2:"\\\\left(\\\\left(\${args[0]}\\\\right)\${args[1]}\\\\right)"}},oT="\\\\mathrm{\${name}}\\\\left(\${args}\\\\right)",aT={deg:"^\\\\circ"};function Pv(e){return(0,iT.default)(e,{preserveFormatting:!0})}function Iv(e,r){return r=typeof r>"u"?!1:r,r?Xe(aT,e)?aT[e]:"\\\\mathrm{"+Pv(e)+"}":Xe(xD,e)?xD[e]:Pv(e)}var Rv="ConstantNode",R$=["Node"],kv=F(Rv,R$,e=>{var{Node:r}=e;class t extends r{constructor(a){super(),this.value=a}get type(){return Rv}get isConstantNode(){return!0}_compile(a,i){var u=this.value;return function(){return u}}forEach(a){}map(a){return this.clone()}clone(){return new t(this.value)}_toString(a){return lr(this.value,a)}_toHTML(a){var i=this._toString(a);switch(Fr(this.value)){case"number":case"BigNumber":case"Fraction":return''+i+"";case"string":return''+i+"";case"boolean":return''+i+"";case"null":return''+i+"";case"undefined":return''+i+"";default:return''+i+""}}toJSON(){return{mathjs:Rv,value:this.value}}static fromJSON(a){return new t(a.value)}_toTex(a){var i=this._toString(a),u=Fr(this.value);switch(u){case"string":return"\\\\mathtt{"+Pv(i)+"}";case"number":case"BigNumber":{var l=u==="BigNumber"?this.value.isFinite():isFinite(this.value);if(!l)return this.value.valueOf()<0?"-\\\\infty":"\\\\infty";var c=i.toLowerCase().indexOf("e");return c!==-1?i.substring(0,c)+"\\\\cdot10^{"+i.substring(c+1)+"}":i}case"Fraction":return this.value.toLatex();default:return i}}}return Hr(t,"name",Rv),t},{isClass:!0,isNode:!0});var qv="FunctionAssignmentNode",k$=["typed","Node"],Lv=F(qv,k$,e=>{var{typed:r,Node:t}=e;function n(i,u,l){var c=Qr(i,u,l),o=Qr(i.expr,u,l);return u==="all"||o!==null&&o<=c}class a extends t{constructor(u,l,c){if(super(),typeof u!="string")throw new TypeError('String expected for parameter "name"');if(!Array.isArray(l))throw new TypeError('Array containing strings or objects expected for parameter "params"');if(!Nr(c))throw new TypeError('Node expected for parameter "expr"');if(yv.has(u))throw new Error('Illegal function name, "'+u+'" is a reserved keyword');var o=new Set;for(var s of l){var m=typeof s=="string"?s:s.name;if(o.has(m))throw new Error('Duplicate parameter name "'.concat(m,'"'));o.add(m)}this.name=u,this.params=l.map(function(d){return d&&d.name||d}),this.types=l.map(function(d){return d&&d.type||"any"}),this.expr=c}get type(){return qv}get isFunctionAssignmentNode(){return!0}_compile(u,l){var c=Object.create(l);Fo(this.params,function(x){c[x]=!0});var o=this.expr._compile(u,c),s=this.name,m=this.params,d=Xb(this.types,","),h=s+"("+Xb(this.params,", ")+")";return function(v,y,w){var C={};C[d]=function(){for(var M=Object.create(y),A=0;A'+rn(this.params[o])+"");var s=this.expr.toHTML(u);return n(this,l,u&&u.implicit)&&(s='('+s+')'),''+rn(this.name)+'('+c.join(',')+')='+s}_toTex(u){var l=u&&u.parenthesis?u.parenthesis:"keep",c=this.expr.toTex(u);return n(this,l,u&&u.implicit)&&(c="\\\\left(".concat(c,"\\\\right)")),"\\\\mathrm{"+this.name+"}\\\\left("+this.params.map(Iv).join(",")+"\\\\right)="+c}}return Hr(a,"name",qv),a},{isClass:!0,isNode:!0});var zv="IndexNode",q$=["Node","size"],Uv=F(zv,q$,e=>{var{Node:r,size:t}=e;class n extends r{constructor(i,u){if(super(),this.dimensions=i,this.dotNotation=u||!1,!Array.isArray(i)||!i.every(Nr))throw new TypeError('Array containing Nodes expected for parameter "dimensions"');if(this.dotNotation&&!this.isObjectProperty())throw new Error("dotNotation only applicable for object properties")}get type(){return zv}get isIndexNode(){return!0}_compile(i,u){var l=Xn(this.dimensions,function(o,s){var m=o.filter(x=>x.isSymbolNode&&x.name==="end").length>0;if(m){var d=Object.create(u);d.end=!0;var h=o._compile(i,d);return function(v,y,w){if(!Qe(w)&&!Mr(w)&&!St(w))throw new TypeError('Cannot resolve "end": context must be a Matrix, Array, or string but is '+Fr(w));var C=t(w).valueOf(),b=Object.create(y);return b.end=C[s],h(v,b,w)}}else return o._compile(i,u)}),c=wt(i,"index");return function(s,m,d){var h=Xn(l,function(x){return x(s,m,d)});return c(...h)}}forEach(i){for(var u=0;u.'+rn(this.getObjectProperty())+"":'['+u.join(',')+']'}_toTex(i){var u=this.dimensions.map(function(l){return l.toTex(i)});return this.dotNotation?"."+this.getObjectProperty():"_{"+u.join(",")+"}"}}return Hr(n,"name",zv),n},{isClass:!0,isNode:!0});var Wv="ObjectNode",L$=["Node"],Yv=F(Wv,L$,e=>{var{Node:r}=e;class t extends r{constructor(a){if(super(),this.properties=a||{},a&&(typeof a!="object"||!Object.keys(a).every(function(i){return Nr(a[i])})))throw new TypeError("Object containing Nodes expected")}get type(){return Wv}get isObjectNode(){return!0}_compile(a,i){var u={};for(var l in this.properties)if(Xe(this.properties,l)){var c=Ss(l),o=JSON.parse(c),s=wt(this.properties,l);u[o]=s._compile(a,i)}return function(d,h,x){var v={};for(var y in u)Xe(u,y)&&(v[y]=u[y](d,h,x));return v}}forEach(a){for(var i in this.properties)Xe(this.properties,i)&&a(this.properties[i],"properties["+Ss(i)+"]",this)}map(a){var i={};for(var u in this.properties)Xe(this.properties,u)&&(i[u]=this._ifNode(a(this.properties[u],"properties["+Ss(u)+"]",this)));return new t(i)}clone(){var a={};for(var i in this.properties)Xe(this.properties,i)&&(a[i]=this.properties[i]);return new t(a)}_toString(a){var i=[];for(var u in this.properties)Xe(this.properties,u)&&i.push(Ss(u)+": "+this.properties[u].toString(a));return"{"+i.join(", ")+"}"}toJSON(){return{mathjs:Wv,properties:this.properties}}static fromJSON(a){return new t(a.properties)}_toHTML(a){var i=[];for(var u in this.properties)Xe(this.properties,u)&&i.push(''+rn(u)+':'+this.properties[u].toHTML(a));return'{'+i.join(',')+'}'}_toTex(a){var i=[];for(var u in this.properties)Xe(this.properties,u)&&i.push("\\\\mathbf{"+u+":} & "+this.properties[u].toTex(a)+"\\\\\\\\");var l="\\\\left\\\\{\\\\begin{array}{ll}"+i.join(\` +\`)+"\\\\end{array}\\\\right\\\\}";return l}}return Hr(t,"name",Wv),t},{isClass:!0,isNode:!0});function _s(e,r){return new Eu(e,new Ms(r),new Set(Object.keys(r)))}var Hv="OperatorNode",z$=["Node"],$v=F(Hv,z$,e=>{var{Node:r}=e;function t(i,u){var l=i;if(u==="auto")for(;en(l);)l=l.content;return yr(l)?!0:ct(l)?t(l.args[0],u):!1}function n(i,u,l,c,o){var s=Qr(i,u,l),m=tf(i,u);if(u==="all"||c.length>2&&i.getIdentifier()!=="OperatorNode:add"&&i.getIdentifier()!=="OperatorNode:multiply")return c.map(function(T){switch(T.getContent().type){case"ArrayNode":case"ConstantNode":case"SymbolNode":case"ParenthesisNode":return!1;default:return!0}});var d;switch(c.length){case 0:d=[];break;case 1:{var h=Qr(c[0],u,l,i);if(o&&h!==null){var x,v;if(u==="keep"?(x=c[0].getIdentifier(),v=i.getIdentifier()):(x=c[0].getContent().getIdentifier(),v=i.getContent().getIdentifier()),ka[s][v].latexLeftParens===!1){d=[!1];break}if(ka[h][x].latexParens===!1){d=[!1];break}}if(h===null){d=[!1];break}if(h<=s){d=[!0];break}d=[!1]}break;case 2:{var y,w=Qr(c[0],u,l,i),C=Cv(i,c[0],u);w===null?y=!1:w===s&&m==="right"&&!C||w=2&&i.getIdentifier()==="OperatorNode:multiply"&&i.implicit&&u!=="all"&&l==="hide")for(var E=1;E2&&(this.getIdentifier()==="OperatorNode:add"||this.getIdentifier()==="OperatorNode:multiply")){var y=o.map(function(w,C){return w=w.toString(u),s[C]&&(w="("+w+")"),w});return this.implicit&&this.getIdentifier()==="OperatorNode:multiply"&&c==="hide"?y.join(" "):y.join(" "+this.op+" ")}else return this.fn+"("+this.args.join(", ")+")"}toJSON(){return{mathjs:Hv,op:this.op,fn:this.fn,args:this.args,implicit:this.implicit,isPercentage:this.isPercentage}}static fromJSON(u){return new a(u.op,u.fn,u.args,u.implicit,u.isPercentage)}_toHTML(u){var l=u&&u.parenthesis?u.parenthesis:"keep",c=u&&u.implicit?u.implicit:"hide",o=this.args,s=n(this,l,c,o,!1);if(o.length===1){var m=tf(this,l),d=o[0].toHTML(u);return s[0]&&(d='('+d+')'),m==="right"?''+rn(this.op)+""+d:d+''+rn(this.op)+""}else if(o.length===2){var h=o[0].toHTML(u),x=o[1].toHTML(u);return s[0]&&(h='('+h+')'),s[1]&&(x='('+x+')'),this.implicit&&this.getIdentifier()==="OperatorNode:multiply"&&c==="hide"?h+''+x:h+''+rn(this.op)+""+x}else{var v=o.map(function(y,w){return y=y.toHTML(u),s[w]&&(y='('+y+')'),y});return o.length>2&&(this.getIdentifier()==="OperatorNode:add"||this.getIdentifier()==="OperatorNode:multiply")?this.implicit&&this.getIdentifier()==="OperatorNode:multiply"&&c==="hide"?v.join(''):v.join(''+rn(this.op)+""):''+rn(this.fn)+'('+v.join(',')+')'}}_toTex(u){var l=u&&u.parenthesis?u.parenthesis:"keep",c=u&&u.implicit?u.implicit:"hide",o=this.args,s=n(this,l,c,o,!0),m=$r[this.fn];if(m=typeof m>"u"?this.op:m,o.length===1){var d=tf(this,l),h=o[0].toTex(u);return s[0]&&(h="\\\\left(".concat(h,"\\\\right)")),d==="right"?m+h:h+m}else if(o.length===2){var x=o[0],v=x.toTex(u);s[0]&&(v="\\\\left(".concat(v,"\\\\right)"));var y=o[1],w=y.toTex(u);s[1]&&(w="\\\\left(".concat(w,"\\\\right)"));var C;switch(l==="keep"?C=x.getIdentifier():C=x.getContent().getIdentifier(),this.getIdentifier()){case"OperatorNode:divide":return m+"{"+v+"}{"+w+"}";case"OperatorNode:pow":switch(v="{"+v+"}",w="{"+w+"}",C){case"ConditionalNode":case"OperatorNode:divide":v="\\\\left(".concat(v,"\\\\right)")}break;case"OperatorNode:multiply":if(this.implicit&&c==="hide")return v+"~"+w}return v+m+w}else if(o.length>2&&(this.getIdentifier()==="OperatorNode:add"||this.getIdentifier()==="OperatorNode:multiply")){var b=o.map(function(M,A){return M=M.toTex(u),s[A]&&(M="\\\\left(".concat(M,"\\\\right)")),M});return this.getIdentifier()==="OperatorNode:multiply"&&this.implicit&&c==="hide"?b.join("~"):b.join(m)}else return"\\\\mathrm{"+this.fn+"}\\\\left("+o.map(function(M){return M.toTex(u)}).join(",")+"\\\\right)"}getIdentifier(){return this.type+":"+this.fn}}return Hr(a,"name",Hv),a},{isClass:!0,isNode:!0});var Gv="ParenthesisNode",U$=["Node"],Vv=F(Gv,U$,e=>{var{Node:r}=e;class t extends r{constructor(a){if(super(),!Nr(a))throw new TypeError('Node expected for parameter "content"');this.content=a}get type(){return Gv}get isParenthesisNode(){return!0}_compile(a,i){return this.content._compile(a,i)}getContent(){return this.content.getContent()}forEach(a){a(this.content,"content",this)}map(a){var i=a(this.content,"content",this);return new t(i)}clone(){return new t(this.content)}_toString(a){return!a||a&&!a.parenthesis||a&&a.parenthesis==="keep"?"("+this.content.toString(a)+")":this.content.toString(a)}toJSON(){return{mathjs:Gv,content:this.content}}static fromJSON(a){return new t(a.content)}_toHTML(a){return!a||a&&!a.parenthesis||a&&a.parenthesis==="keep"?'('+this.content.toHTML(a)+')':this.content.toHTML(a)}_toTex(a){return!a||a&&!a.parenthesis||a&&a.parenthesis==="keep"?"\\\\left(".concat(this.content.toTex(a),"\\\\right)"):this.content.toTex(a)}}return Hr(t,"name",Gv),t},{isClass:!0,isNode:!0});var Zv="RangeNode",W$=["Node"],Qv=F(Zv,W$,e=>{var{Node:r}=e;function t(a,i,u){var l=Qr(a,i,u),c={},o=Qr(a.start,i,u);if(c.start=o!==null&&o<=l||i==="all",a.step){var s=Qr(a.step,i,u);c.step=s!==null&&s<=l||i==="all"}var m=Qr(a.end,i,u);return c.end=m!==null&&m<=l||i==="all",c}class n extends r{constructor(i,u,l){if(super(),!Nr(i))throw new TypeError("Node expected");if(!Nr(u))throw new TypeError("Node expected");if(l&&!Nr(l))throw new TypeError("Node expected");if(arguments.length>3)throw new Error("Too many arguments");this.start=i,this.end=u,this.step=l||null}get type(){return Zv}get isRangeNode(){return!0}needsEnd(){var i=this.filter(function(u){return at(u)&&u.name==="end"});return i.length>0}_compile(i,u){var l=i.range,c=this.start._compile(i,u),o=this.end._compile(i,u);if(this.step){var s=this.step._compile(i,u);return function(d,h,x){return l(c(d,h,x),o(d,h,x),s(d,h,x))}}else return function(d,h,x){return l(c(d,h,x),o(d,h,x))}}forEach(i){i(this.start,"start",this),i(this.end,"end",this),this.step&&i(this.step,"step",this)}map(i){return new n(this._ifNode(i(this.start,"start",this)),this._ifNode(i(this.end,"end",this)),this.step&&this._ifNode(i(this.step,"step",this)))}clone(){return new n(this.start,this.end,this.step&&this.step)}_toString(i){var u=i&&i.parenthesis?i.parenthesis:"keep",l=t(this,u,i&&i.implicit),c,o=this.start.toString(i);if(l.start&&(o="("+o+")"),c=o,this.step){var s=this.step.toString(i);l.step&&(s="("+s+")"),c+=":"+s}var m=this.end.toString(i);return l.end&&(m="("+m+")"),c+=":"+m,c}toJSON(){return{mathjs:Zv,start:this.start,end:this.end,step:this.step}}static fromJSON(i){return new n(i.start,i.end,i.step)}_toHTML(i){var u=i&&i.parenthesis?i.parenthesis:"keep",l=t(this,u,i&&i.implicit),c,o=this.start.toHTML(i);if(l.start&&(o='('+o+')'),c=o,this.step){var s=this.step.toHTML(i);l.step&&(s='('+s+')'),c+=':'+s}var m=this.end.toHTML(i);return l.end&&(m='('+m+')'),c+=':'+m,c}_toTex(i){var u=i&&i.parenthesis?i.parenthesis:"keep",l=t(this,u,i&&i.implicit),c=this.start.toTex(i);if(l.start&&(c="\\\\left(".concat(c,"\\\\right)")),this.step){var o=this.step.toTex(i);l.step&&(o="\\\\left(".concat(o,"\\\\right)")),c+=":"+o}var s=this.end.toTex(i);return l.end&&(s="\\\\left(".concat(s,"\\\\right)")),c+=":"+s,c}}return Hr(n,"name",Zv),n},{isClass:!0,isNode:!0});var Xv="RelationalNode",Y$=["Node"],Jv=F(Xv,Y$,e=>{var{Node:r}=e,t={equal:"==",unequal:"!=",smaller:"<",larger:">",smallerEq:"<=",largerEq:">="};class n extends r{constructor(i,u){if(super(),!Array.isArray(i))throw new TypeError("Parameter conditionals must be an array");if(!Array.isArray(u))throw new TypeError("Parameter params must be an array");if(i.length!==u.length-1)throw new TypeError("Parameter params must contain exactly one more element than parameter conditionals");this.conditionals=i,this.params=u}get type(){return Xv}get isRelationalNode(){return!0}_compile(i,u){var l=this,c=this.params.map(o=>o._compile(i,u));return function(s,m,d){for(var h,x=c[0](s,m,d),v=0;vi(u,"params["+l+"]",this),this)}map(i){return new n(this.conditionals.slice(),this.params.map((u,l)=>this._ifNode(i(u,"params["+l+"]",this)),this))}clone(){return new n(this.conditionals,this.params)}_toString(i){for(var u=i&&i.parenthesis?i.parenthesis:"keep",l=Qr(this,u,i&&i.implicit),c=this.params.map(function(m,d){var h=Qr(m,u,i&&i.implicit);return u==="all"||h!==null&&h<=l?"("+m.toString(i)+")":m.toString(i)}),o=c[0],s=0;s('+m.toHTML(i)+')':m.toHTML(i)}),o=c[0],s=0;s'+rn(t[this.conditionals[s]])+""+c[s+1];return o}_toTex(i){for(var u=i&&i.parenthesis?i.parenthesis:"keep",l=Qr(this,u,i&&i.implicit),c=this.params.map(function(m,d){var h=Qr(m,u,i&&i.implicit);return u==="all"||h!==null&&h<=l?"\\\\left("+m.toTex(i)+"\\right)":m.toTex(i)}),o=c[0],s=0;s{var{math:r,Unit:t,Node:n}=e;function a(u){return t?t.isValuelessUnit(u):!1}class i extends n{constructor(l){if(super(),typeof l!="string")throw new TypeError('String expected for parameter "name"');this.name=l}get type(){return"SymbolNode"}get isSymbolNode(){return!0}_compile(l,c){var o=this.name;if(c[o]===!0)return function(m,d,h){return wt(d,o)};if(o in l)return function(m,d,h){return m.has(o)?m.get(o):wt(l,o)};var s=a(o);return function(m,d,h){return m.has(o)?m.get(o):s?new t(null,o):i.onUndefinedSymbol(o)}}forEach(l){}map(l){return this.clone()}static onUndefinedSymbol(l){throw new Error("Undefined symbol "+l)}clone(){return new i(this.name)}_toString(l){return this.name}_toHTML(l){var c=rn(this.name);return c==="true"||c==="false"?''+c+"":c==="i"?''+c+"":c==="Infinity"?''+c+"":c==="NaN"?''+c+"":c==="null"?''+c+"":c==="undefined"?''+c+"":''+c+""}toJSON(){return{mathjs:"SymbolNode",name:this.name}}static fromJSON(l){return new i(l.name)}_toTex(l){var c=!1;typeof r[this.name]>"u"&&a(this.name)&&(c=!0);var o=Iv(this.name,c);return o[0]==="\\\\"?o:" "+o}}return i},{isClass:!0,isNode:!0});var jv="FunctionNode",G$=["math","Node","SymbolNode"],eg=F(jv,G$,e=>{var r,{math:t,Node:n,SymbolNode:a}=e,i=c=>lr(c,{truncate:78});function u(c,o,s){for(var m="",d=/\\$(?:\\{([a-z_][a-z_0-9]*)(?:\\[([0-9]+)\\])?\\}|\\$)/gi,h=0,x;(x=d.exec(c))!==null;)if(m+=c.substring(h,x.index),h=x.index,x[0]==="$$")m+="$",h++;else{h+=x[0].length;var v=o[x[1]];if(!v)throw new ReferenceError("Template: Property "+x[1]+" does not exist.");if(x[2]===void 0)switch(typeof v){case"string":m+=v;break;case"object":if(Nr(v))m+=v.toTex(s);else if(Array.isArray(v))m+=v.map(function(y,w){if(Nr(y))return y.toTex(s);throw new TypeError("Template: "+x[1]+"["+w+"] is not a Node.")}).join(",");else throw new TypeError("Template: "+x[1]+" has to be a Node, String or array of Nodes");break;default:throw new TypeError("Template: "+x[1]+" has to be a Node, String or array of Nodes")}else if(Nr(v[x[2]]&&v[x[2]]))m+=v[x[2]].toTex(s);else throw new TypeError("Template: "+x[1]+"["+x[2]+"] is not a Node.")}return m+=c.slice(h),m}class l extends n{constructor(o,s){if(super(),typeof o=="string"&&(o=new a(o)),!Nr(o))throw new TypeError('Node expected as parameter "fn"');if(!Array.isArray(s)||!s.every(Nr))throw new TypeError('Array containing Nodes expected for parameter "args"');this.fn=o,this.args=s||[]}get name(){return this.fn.name||""}get type(){return jv}get isFunctionNode(){return!0}_compile(o,s){var m=this.args.map(_=>_._compile(o,s));if(at(this.fn)){var d=this.fn.name;if(s[d]){var w=this.args;return function(E,T,R){var q=wt(T,d);if(typeof q!="function")throw new TypeError("Argument '".concat(d,"' was not a function; received: ").concat(i(q)));if(q.rawArgs)return q(w,o,_s(E,T));var W=m.map(G=>G(E,T,R));return q.apply(q,W)}}else{var h=d in o?wt(o,d):void 0,x=typeof h=="function"&&h.rawArgs===!0,v=_=>{var E;if(_.has(d))E=_.get(d);else if(d in o)E=wt(o,d);else return l.onUndefinedFunction(d);if(typeof E=="function")return E;throw new TypeError("'".concat(d,\`' is not a function; its value is: + \`).concat(i(E)))};if(x){var y=this.args;return function(E,T,R){var q=v(E);return q(y,o,_s(E,T))}}else switch(m.length){case 0:return function(E,T,R){var q=v(E);return q()};case 1:return function(E,T,R){var q=v(E),W=m[0];return q(W(E,T,R))};case 2:return function(E,T,R){var q=v(E),W=m[0],G=m[1];return q(W(E,T,R),G(E,T,R))};default:return function(E,T,R){var q=v(E),W=m.map(G=>G(E,T,R));return q(...W)}}}}else if(qn(this.fn)&&Qn(this.fn.index)&&this.fn.index.isObjectProperty()){var C=this.fn.object._compile(o,s),b=this.fn.index.getObjectProperty(),M=this.args;return function(E,T,R){var q=C(E,T,R),W=gM(q,b);if(W!=null&&W.rawArgs)return W(M,o,_s(E,T));var G=m.map(H=>H(E,T,R));return W.apply(q,G)}}else{var A=this.fn.toString(),S=this.fn._compile(o,s),O=this.args;return function(E,T,R){var q=S(E,T,R);if(typeof q!="function")throw new TypeError("Expression '".concat(A,"' did not evaluate to a function; value is:")+\` + \`.concat(i(q)));if(q.rawArgs)return q(O,o,_s(E,T));var W=m.map(G=>G(E,T,R));return q.apply(q,W)}}}forEach(o){o(this.fn,"fn",this);for(var s=0;s'+rn(this.fn)+'('+s.join(',')+')'}toTex(o){var s;return o&&typeof o.handler=="object"&&Xe(o.handler,this.name)&&(s=o.handler[this.name](this,o)),typeof s<"u"?s:super.toTex(o)}_toTex(o){var s=this.args.map(function(h){return h.toTex(o)}),m;yD[this.name]&&(m=yD[this.name]),t[this.name]&&(typeof t[this.name].toTex=="function"||typeof t[this.name].toTex=="object"||typeof t[this.name].toTex=="string")&&(m=t[this.name].toTex);var d;switch(typeof m){case"function":d=m(this,o);break;case"string":d=u(m,this,o);break;case"object":switch(typeof m[s.length]){case"function":d=m[s.length](this,o);break;case"string":d=u(m[s.length],this,o);break}}return typeof d<"u"?d:u(oT,this,o)}getIdentifier(){return this.type+":"+this.name}}return r=l,Hr(l,"name",jv),Hr(l,"onUndefinedFunction",function(c){throw new Error("Undefined function "+c)}),Hr(l,"fromJSON",function(c){return new r(c.fn,c.args)}),l},{isClass:!0,isNode:!0});var sT="parse",V$=["typed","numeric","config","AccessorNode","ArrayNode","AssignmentNode","BlockNode","ConditionalNode","ConstantNode","FunctionAssignmentNode","FunctionNode","IndexNode","ObjectNode","OperatorNode","ParenthesisNode","RangeNode","RelationalNode","SymbolNode"],rg=F(sT,V$,e=>{var{typed:r,numeric:t,config:n,AccessorNode:a,ArrayNode:i,AssignmentNode:u,BlockNode:l,ConditionalNode:c,ConstantNode:o,FunctionAssignmentNode:s,FunctionNode:m,IndexNode:d,ObjectNode:h,OperatorNode:x,ParenthesisNode:v,RangeNode:y,RelationalNode:w,SymbolNode:C}=e,b=r(sT,{string:function(Q){return pe(Q,{})},"Array | Matrix":function(Q){return M(Q,{})},"string, Object":function(Q,ve){var Pe=ve.nodes!==void 0?ve.nodes:{};return pe(Q,Pe)},"Array | Matrix, Object":M});function M(B){var Q=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},ve=Q.nodes!==void 0?Q.nodes:{};return je(B,function(Pe){if(typeof Pe!="string")throw new TypeError("String expected");return pe(Pe,ve)})}var A={NULL:0,DELIMITER:1,NUMBER:2,SYMBOL:3,UNKNOWN:4},S={",":!0,"(":!0,")":!0,"[":!0,"]":!0,"{":!0,"}":!0,'"':!0,"'":!0,";":!0,"+":!0,"-":!0,"*":!0,".*":!0,"/":!0,"./":!0,"%":!0,"^":!0,".^":!0,"~":!0,"!":!0,"&":!0,"|":!0,"^|":!0,"=":!0,":":!0,"?":!0,"==":!0,"!=":!0,"<":!0,">":!0,"<=":!0,">=":!0,"<<":!0,">>":!0,">>>":!0},O={mod:!0,to:!0,in:!0,and:!0,xor:!0,or:!0,not:!0},_={true:!0,false:!1,null:null,undefined:void 0},E=["NaN","Infinity"],T={'"':'"',"'":"'","\\\\":"\\\\","/":"/",b:"\\b",f:"\\f",n:\` +\`,r:"\\r",t:" "};function R(){return{extraNodes:{},expression:"",comment:"",index:0,token:"",tokenType:A.NULL,nestingLevel:0,conditionalLevel:null}}function q(B,Q){return B.expression.substr(B.index,Q)}function W(B){return q(B,1)}function G(B){B.index++}function H(B){return B.expression.charAt(B.index-1)}function L(B){return B.expression.charAt(B.index+1)}function k(B){for(B.tokenType=A.NULL,B.token="",B.comment="";;){if(W(B)==="#")for(;W(B)!==\` +\`&&W(B)!=="";)B.comment+=W(B),G(B);if(b.isWhitespace(W(B),B.nestingLevel))G(B);else break}if(W(B)===""){B.tokenType=A.DELIMITER;return}if(W(B)===\` +\`&&!B.nestingLevel){B.tokenType=A.DELIMITER,B.token=W(B),G(B);return}var Q=W(B),ve=q(B,2),Pe=q(B,3);if(Pe.length===3&&S[Pe]){B.tokenType=A.DELIMITER,B.token=Pe,G(B),G(B),G(B);return}if(ve.length===2&&S[ve]){B.tokenType=A.DELIMITER,B.token=ve,G(B),G(B);return}if(S[Q]){B.tokenType=A.DELIMITER,B.token=Q,G(B);return}if(b.isDigitDot(Q)){B.tokenType=A.NUMBER;var tr=q(B,2);if(tr==="0b"||tr==="0o"||tr==="0x"){for(B.token+=W(B),G(B),B.token+=W(B),G(B);b.isHexDigit(W(B));)B.token+=W(B),G(B);if(W(B)===".")for(B.token+=".",G(B);b.isHexDigit(W(B));)B.token+=W(B),G(B);else if(W(B)==="i")for(B.token+="i",G(B);b.isDigit(W(B));)B.token+=W(B),G(B);return}if(W(B)==="."){if(B.token+=W(B),G(B),!b.isDigit(W(B))){B.tokenType=A.DELIMITER;return}}else{for(;b.isDigit(W(B));)B.token+=W(B),G(B);b.isDecimalMark(W(B),L(B))&&(B.token+=W(B),G(B))}for(;b.isDigit(W(B));)B.token+=W(B),G(B);if(W(B)==="E"||W(B)==="e"){if(b.isDigit(L(B))||L(B)==="-"||L(B)==="+"){if(B.token+=W(B),G(B),(W(B)==="+"||W(B)==="-")&&(B.token+=W(B),G(B)),!b.isDigit(W(B)))throw Re(B,'Digit expected, got "'+W(B)+'"');for(;b.isDigit(W(B));)B.token+=W(B),G(B);if(b.isDecimalMark(W(B),L(B)))throw Re(B,'Digit expected, got "'+W(B)+'"')}else if(L(B)===".")throw G(B),Re(B,'Digit expected, got "'+W(B)+'"')}return}if(b.isAlpha(W(B),H(B),L(B))){for(;b.isAlpha(W(B),H(B),L(B))||b.isDigit(W(B));)B.token+=W(B),G(B);Xe(O,B.token)?B.tokenType=A.DELIMITER:B.tokenType=A.SYMBOL;return}for(B.tokenType=A.UNKNOWN;W(B)!=="";)B.token+=W(B),G(B);throw Re(B,'Syntax error in part "'+B.token+'"')}function K(B){do k(B);while(B.token===\` +\`)}function z(B){B.nestingLevel++}function oe(B){B.nestingLevel--}b.isAlpha=function(Q,ve,Pe){return b.isValidLatinOrGreek(Q)||b.isValidMathSymbol(Q,Pe)||b.isValidMathSymbol(ve,Q)},b.isValidLatinOrGreek=function(Q){return/^[a-zA-Z_$\\u00C0-\\u02AF\\u0370-\\u03FF\\u2100-\\u214F]$/.test(Q)},b.isValidMathSymbol=function(Q,ve){return/^[\\uD835]$/.test(Q)&&/^[\\uDC00-\\uDFFF]$/.test(ve)&&/^[^\\uDC55\\uDC9D\\uDCA0\\uDCA1\\uDCA3\\uDCA4\\uDCA7\\uDCA8\\uDCAD\\uDCBA\\uDCBC\\uDCC4\\uDD06\\uDD0B\\uDD0C\\uDD15\\uDD1D\\uDD3A\\uDD3F\\uDD45\\uDD47-\\uDD49\\uDD51\\uDEA6\\uDEA7\\uDFCC\\uDFCD]$/.test(ve)},b.isWhitespace=function(Q,ve){return Q===" "||Q===" "||Q===\` +\`&&ve>0},b.isDecimalMark=function(Q,ve){return Q==="."&&ve!=="/"&&ve!=="*"&&ve!=="^"},b.isDigitDot=function(Q){return Q>="0"&&Q<="9"||Q==="."},b.isDigit=function(Q){return Q>="0"&&Q<="9"},b.isHexDigit=function(Q){return Q>="0"&&Q<="9"||Q>="a"&&Q<="f"||Q>="A"&&Q<="F"};function pe(B,Q){var ve=R();ht(ve,{expression:B,extraNodes:Q}),k(ve);var Pe=ae(ve);if(ve.token!=="")throw ve.tokenType===A.DELIMITER?Ye(ve,"Unexpected operator "+ve.token):Re(ve,'Unexpected part "'+ve.token+'"');return Pe}function ae(B){var Q,ve=[],Pe;for(B.token!==""&&B.token!==\` +\`&&B.token!==";"&&(Q=$(B),B.comment&&(Q.comment=B.comment));B.token===\` +\`||B.token===";";)ve.length===0&&Q&&(Pe=B.token!==";",ve.push({node:Q,visible:Pe})),k(B),B.token!==\` +\`&&B.token!==";"&&B.token!==""&&(Q=$(B),B.comment&&(Q.comment=B.comment),Pe=B.token!==";",ve.push({node:Q,visible:Pe}));return ve.length>0?new l(ve):(Q||(Q=new o(void 0),B.comment&&(Q.comment=B.comment)),Q)}function $(B){var Q,ve,Pe,tr,cr=le(B);if(B.token==="="){if(at(cr))return Q=cr.name,K(B),Pe=$(B),new u(new C(Q),Pe);if(qn(cr))return K(B),Pe=$(B),new u(cr.object,cr.index,Pe);if(gn(cr)&&at(cr.fn)&&(tr=!0,ve=[],Q=cr.name,cr.args.forEach(function(Xr,Pt){at(Xr)?ve[Pt]=Xr.name:tr=!1}),tr))return K(B),Pe=$(B),new s(Q,ve,Pe);throw Re(B,"Invalid left hand side of assignment operator =")}return cr}function le(B){for(var Q=Ee(B);B.token==="?";){var ve=B.conditionalLevel;B.conditionalLevel=B.nestingLevel,K(B);var Pe=Q,tr=$(B);if(B.token!==":")throw Re(B,"False part of conditional expression expected");B.conditionalLevel=null,K(B);var cr=$(B);Q=new c(Pe,tr,cr),B.conditionalLevel=ve}return Q}function Ee(B){for(var Q=me(B);B.token==="or";)K(B),Q=new x("or","or",[Q,me(B)]);return Q}function me(B){for(var Q=ge(B);B.token==="xor";)K(B),Q=new x("xor","xor",[Q,ge(B)]);return Q}function ge(B){for(var Q=Se(B);B.token==="and";)K(B),Q=new x("and","and",[Q,Se(B)]);return Q}function Se(B){for(var Q=xe(B);B.token==="|";)K(B),Q=new x("|","bitOr",[Q,xe(B)]);return Q}function xe(B){for(var Q=be(B);B.token==="^|";)K(B),Q=new x("^|","bitXor",[Q,be(B)]);return Q}function be(B){for(var Q=De(B);B.token==="&";)K(B),Q=new x("&","bitAnd",[Q,De(B)]);return Q}function De(B){for(var Q=[Ae(B)],ve=[],Pe={"==":"equal","!=":"unequal","<":"smaller",">":"larger","<=":"smallerEq",">=":"largerEq"};Xe(Pe,B.token);){var tr={name:B.token,fn:Pe[B.token]};ve.push(tr),K(B),Q.push(Ae(B))}return Q.length===1?Q[0]:Q.length===2?new x(ve[0].name,ve[0].fn,Q):new w(ve.map(cr=>cr.fn),Q)}function Ae(B){var Q,ve,Pe,tr;Q=We(B);for(var cr={"<<":"leftShift",">>":"rightArithShift",">>>":"rightLogShift"};Xe(cr,B.token);)ve=B.token,Pe=cr[ve],K(B),tr=[Q,We(B)],Q=new x(ve,Pe,tr);return Q}function We(B){var Q,ve,Pe,tr;Q=Je(B);for(var cr={to:"to",in:"to"};Xe(cr,B.token);)ve=B.token,Pe=cr[ve],K(B),ve==="in"&&B.token===""?Q=new x("*","multiply",[Q,new C("in")],!0):(tr=[Q,Je(B)],Q=new x(ve,Pe,tr));return Q}function Je(B){var Q,ve=[];if(B.token===":"?Q=new o(1):Q=J(B),B.token===":"&&B.conditionalLevel!==B.nestingLevel){for(ve.push(Q);B.token===":"&&ve.length<3;)K(B),B.token===")"||B.token==="]"||B.token===","||B.token===""?ve.push(new C("end")):ve.push(J(B));ve.length===3?Q=new y(ve[0],ve[2],ve[1]):Q=new y(ve[0],ve[1])}return Q}function J(B){var Q,ve,Pe,tr;Q=re(B);for(var cr={"+":"add","-":"subtract"};Xe(cr,B.token);){ve=B.token,Pe=cr[ve],K(B);var Xr=re(B);Xr.isPercentage?tr=[Q,new x("*","multiply",[Q,Xr])]:tr=[Q,Xr],Q=new x(ve,Pe,tr)}return Q}function re(B){var Q,ve,Pe,tr;Q=ye(B),ve=Q;for(var cr={"*":"multiply",".*":"dotMultiply","/":"divide","./":"dotDivide"};Xe(cr,B.token);)Pe=B.token,tr=cr[Pe],K(B),ve=ye(B),Q=new x(Pe,tr,[Q,ve]);return Q}function ye(B){var Q,ve;for(Q=j(B),ve=Q;B.tokenType===A.SYMBOL||B.token==="in"&&yr(Q)||B.tokenType===A.NUMBER&&!yr(ve)&&(!ct(ve)||ve.op==="!")||B.token==="(";)ve=j(B),Q=new x("*","multiply",[Q,ve],!0);return Q}function j(B){for(var Q=ne(B),ve=Q,Pe=[];B.token==="/"&&Nc(ve);)if(Pe.push(ht({},B)),K(B),B.tokenType===A.NUMBER)if(Pe.push(ht({},B)),K(B),B.tokenType===A.SYMBOL||B.token==="(")ht(B,Pe.pop()),Pe.pop(),ve=ne(B),Q=new x("/","divide",[Q,ve]);else{Pe.pop(),ht(B,Pe.pop());break}else{ht(B,Pe.pop());break}return Q}function ne(B){var Q,ve,Pe,tr;Q=ue(B);for(var cr={"%":"mod",mod:"mod"};Xe(cr,B.token);)ve=B.token,Pe=cr[ve],K(B),ve==="%"&&B.tokenType===A.DELIMITER&&B.token!=="("?Q=new x("/","divide",[Q,new o(100)],!1,!0):(tr=[Q,ue(B)],Q=new x(ve,Pe,tr));return Q}function ue(B){var Q,ve,Pe,tr={"-":"unaryMinus","+":"unaryPlus","~":"bitNot",not:"not"};return Xe(tr,B.token)?(Pe=tr[B.token],Q=B.token,K(B),ve=[ue(B)],new x(Q,Pe,ve)):Me(B)}function Me(B){var Q,ve,Pe,tr;return Q=Ce(B),(B.token==="^"||B.token===".^")&&(ve=B.token,Pe=ve==="^"?"pow":"dotPow",K(B),tr=[Q,ue(B)],Q=new x(ve,Pe,tr)),Q}function Ce(B){var Q,ve,Pe,tr;Q=Le(B);for(var cr={"!":"factorial","'":"ctranspose"};Xe(cr,B.token);)ve=B.token,Pe=cr[ve],k(B),tr=[Q],Q=new x(ve,Pe,tr),Q=fr(B,Q);return Q}function Le(B){var Q=[];if(B.tokenType===A.SYMBOL&&Xe(B.extraNodes,B.token)){var ve=B.extraNodes[B.token];if(k(B),B.token==="("){if(Q=[],z(B),k(B),B.token!==")")for(Q.push($(B));B.token===",";)k(B),Q.push($(B));if(B.token!==")")throw Re(B,"Parenthesis ) expected");oe(B),k(B)}return new ve(Q)}return Ie(B)}function Ie(B){var Q,ve;return B.tokenType===A.SYMBOL||B.tokenType===A.DELIMITER&&B.token in O?(ve=B.token,k(B),Xe(_,ve)?Q=new o(_[ve]):E.indexOf(ve)!==-1?Q=new o(t(ve,"number")):Q=new C(ve),Q=fr(B,Q),Q):or(B)}function fr(B,Q,ve){for(var Pe;(B.token==="("||B.token==="["||B.token===".")&&(!ve||ve.indexOf(B.token)!==-1);)if(Pe=[],B.token==="(")if(at(Q)||qn(Q)){if(z(B),k(B),B.token!==")")for(Pe.push($(B));B.token===",";)k(B),Pe.push($(B));if(B.token!==")")throw Re(B,"Parenthesis ) expected");oe(B),k(B),Q=new m(Q,Pe)}else return Q;else if(B.token==="["){if(z(B),k(B),B.token!=="]")for(Pe.push($(B));B.token===",";)k(B),Pe.push($(B));if(B.token!=="]")throw Re(B,"Parenthesis ] expected");oe(B),k(B),Q=new a(Q,new d(Pe))}else{k(B);var tr=B.tokenType===A.SYMBOL||B.tokenType===A.DELIMITER&&B.token in O;if(!tr)throw Re(B,"Property name expected after dot");Pe.push(new o(B.token)),k(B);var cr=!0;Q=new a(Q,new d(Pe,cr))}return Q}function or(B){var Q,ve;return B.token==='"'||B.token==="'"?(ve=Ke(B,B.token),Q=new o(ve),Q=fr(B,Q),Q):Pr(B)}function Ke(B,Q){for(var ve="";W(B)!==""&&W(B)!==Q;)if(W(B)==="\\\\"){G(B);var Pe=W(B),tr=T[Pe];if(tr!==void 0)ve+=tr,B.index+=1;else if(Pe==="u"){var cr=B.expression.slice(B.index+1,B.index+5);if(/^[0-9A-Fa-f]{4}$/.test(cr))ve+=String.fromCharCode(parseInt(cr,16)),B.index+=5;else throw Re(B,"Invalid unicode character \\\\u".concat(cr))}else throw Re(B,"Bad escape character \\\\".concat(Pe))}else ve+=W(B),G(B);if(k(B),B.token!==Q)throw Re(B,"End of string ".concat(Q," expected"));return k(B),ve}function Pr(B){var Q,ve,Pe,tr;if(B.token==="["){if(z(B),k(B),B.token!=="]"){var cr=ee(B);if(B.token===";"){for(Pe=1,ve=[cr];B.token===";";)k(B),B.token!=="]"&&(ve[Pe]=ee(B),Pe++);if(B.token!=="]")throw Re(B,"End of matrix ] expected");oe(B),k(B),tr=ve[0].items.length;for(var Xr=1;Xr{var{typed:r,parse:t}=e;return r(uT,{string:function(a){return t(a).compile()},"Array | Matrix":function(a){return je(a,function(i){return t(i).compile()})}})});var fT="evaluate",Q$=["typed","parse"],ng=F(fT,Q$,e=>{var{typed:r,parse:t}=e;return r(fT,{string:function(a){var i=Oo();return t(a).compile().evaluate(i)},"string, Map | Object":function(a,i){return t(a).compile().evaluate(i)},"Array | Matrix":function(a){var i=Oo();return je(a,function(u){return t(u).compile().evaluate(i)})},"Array | Matrix, Map | Object":function(a,i){return je(a,function(u){return t(u).compile().evaluate(i)})}})});var X$="Parser",J$=["evaluate"],ag=F(X$,J$,e=>{var{evaluate:r}=e;function t(){if(!(this instanceof t))throw new SyntaxError("Constructor must be called with the new operator");Object.defineProperty(this,"scope",{value:Oo(),writable:!1})}return t.prototype.type="Parser",t.prototype.isParser=!0,t.prototype.evaluate=function(n){return r(n,this.scope)},t.prototype.get=function(n){if(this.scope.has(n))return this.scope.get(n)},t.prototype.getAll=function(){return bM(this.scope)},t.prototype.getAllAsMap=function(){return this.scope},t.prototype.set=function(n,a){return this.scope.set(n,a),a},t.prototype.remove=function(n){this.scope.delete(n)},t.prototype.clear=function(){this.scope.clear()},t},{isClass:!0});var cT="parser",K$=["typed","Parser"],ig=F(cT,K$,e=>{var{typed:r,Parser:t}=e;return r(cT,{"":function(){return new t}})});var lT="lup",j$=["typed","matrix","abs","addScalar","divideScalar","multiplyScalar","subtractScalar","larger","equalScalar","unaryMinus","DenseMatrix","SparseMatrix","Spa"],og=F(lT,j$,e=>{var{typed:r,matrix:t,abs:n,addScalar:a,divideScalar:i,multiplyScalar:u,subtractScalar:l,larger:c,equalScalar:o,unaryMinus:s,DenseMatrix:m,SparseMatrix:d,Spa:h}=e;return r(lT,{DenseMatrix:function(w){return x(w)},SparseMatrix:function(w){return v(w)},Array:function(w){var C=t(w),b=x(C);return{L:b.L.valueOf(),U:b.U.valueOf(),p:b.p}}});function x(y){var w=y._size[0],C=y._size[1],b=Math.min(w,C),M=ar(y._data),A=[],S=[w,b],O=[],_=[b,C],E,T,R,q=[];for(E=0;E0)for(E=0;E0&&$.forEach(0,L-1,function(xe,be){d._forEachRow(xe,O,_,E,function(De,Ae){De>xe&&$.accumulate(De,s(u(Ae,be)))})});var me=L,ge=$.get(L),Se=n(ge);$.forEach(L+1,w-1,function(xe,be){var De=n(be);c(De,Se)&&(me=xe,Se=De,ge=be)}),L!==me&&(d._swapRows(L,me,T[1],O,_,E),d._swapRows(L,me,G[1],R,q,W),$.swap(L,me),oe(L,me)),$.forEach(0,w-1,function(xe,be){xe<=L?(R.push(be),q.push(xe)):(be=i(be,ge),o(be,0)||(O.push(be),_.push(xe)))})};for(L=0;L{var{typed:r,matrix:t,zeros:n,identity:a,isZero:i,equal:u,sign:l,sqrt:c,conj:o,unaryMinus:s,addScalar:m,divideScalar:d,multiplyScalar:h,subtractScalar:x,complex:v}=e;return ht(r(mT,{DenseMatrix:function(M){return w(M)},SparseMatrix:function(M){return C(M)},Array:function(M){var A=t(M),S=w(A);return{Q:S.Q.valueOf(),R:S.R.valueOf()}}}),{_denseQRimpl:y});function y(b){var M=b._size[0],A=b._size[1],S=a([M],"dense"),O=S._data,_=b.clone(),E=_._data,T,R,q,W=n([M],"");for(q=0;q0)for(var S=A[0][0].type==="Complex"?v(0):0,O=0;O=0;){var c=t[u+l],o=t[n+c];o===-1?(l--,i[r++]=c):(t[n+c]=t[a+o],++l,t[u+l]=o)}return r}function dT(e,r){if(!e)return null;var t=0,n,a=[],i=[],u=0,l=r,c=2*r;for(n=0;n=0;n--)e[n]!==-1&&(i[l+n]=i[u+e[n]],i[u+e[n]]=n);for(n=0;n{var{add:r,multiply:t,transpose:n}=e;return function(s,m){if(!m||s<=0||s>3)return null;var d=m._size,h=d[0],x=d[1],v=0,y=Math.max(16,10*Math.sqrt(x));y=Math.min(x-2,y);var w=a(s,m,h,x,y);vT(w,c,null);for(var C=w._index,b=w._ptr,M=b[x],A=[],S=[],O=0,_=x+1,E=2*(x+1),T=3*(x+1),R=4*(x+1),q=5*(x+1),W=6*(x+1),G=7*(x+1),H=A,L=i(x,b,S,O,T,H,E,G,_,W,R,q),k=u(x,b,S,q,R,W,y,_,T,H,E),K=0,z,oe,pe,ae,$,le,Ee,me,ge,Se,xe,be,De,Ae,We,Je;kJ?(le=pe,Ee=j,me=S[O+pe]-J):(le=C[j++],Ee=b[le],me=S[O+le]),$=1;$<=me;$++)z=C[Ee++],!((ge=S[_+z])<=0)&&(ye+=ge,S[_+z]=-ge,C[ue++]=z,S[E+z]!==-1&&(H[S[E+z]]=H[z]),H[z]!==-1?S[E+H[z]]=S[E+z]:S[T+S[q+z]]=S[E+z]);le!==pe&&(b[le]=ui(pe),S[W+le]=0)}for(J!==0&&(M=ue),S[q+pe]=ye,b[pe]=ne,S[O+pe]=ue-ne,S[R+pe]=-2,L=l(L,v,S,W,x),Se=ne;Se=L?S[W+le]-=ge:S[W+le]!==0&&(S[W+le]=S[q+le]+Me)}for(Se=ne;Se0?(Je+=Ce,C[Ae++]=le,We+=le):(b[le]=ui(pe),S[W+le]=0)}S[R+z]=Ae-be+1;var Le=Ae,Ie=be+S[O+z];for(j=De+1;j=0))for(We=H[z],z=S[G+We],S[G+We]=-1;z!==-1&&S[E+z]!==-1;z=S[E+z],L++){for(me=S[O+z],xe=S[R+z],j=b[z]+1;j<=b[z]+me-1;j++)S[W+C[j]]=L;var or=z;for(oe=S[E+z];oe!==-1;){var Ke=S[O+oe]===me&&S[R+oe]===xe;for(j=b[oe]+1;Ke&&j<=b[oe]+me-1;j++)S[W+C[j]]!==L&&(Ke=0);Ke?(b[oe]=ui(z),S[_+z]+=S[_+oe],S[_+oe]=0,S[R+oe]=-1,oe=S[E+oe],S[E+or]=oe):(or=oe,oe=S[E+oe])}}for(j=ne,Se=ne;Se=0;oe--)S[_+oe]>0||(S[E+oe]=S[T+b[oe]],S[T+b[oe]]=oe);for(le=x;le>=0;le--)S[_+le]<=0||b[le]!==-1&&(S[E+le]=S[T+b[le]],S[T+b[le]]=le);for(pe=0,z=0;z<=x;z++)b[z]===-1&&(pe=ug(z,pe,S,T,E,A,W));return A.splice(A.length-1,1),A};function a(o,s,m,d,h){var x=n(s);if(o===1&&d===m)return r(s,x);if(o===2){for(var v=x._index,y=x._ptr,w=0,C=0;Ch))for(var M=y[C+1];bv)m[y+A]=0,m[h+A]=-1,M++,s[A]=ui(o),m[y+o]++;else{var O=m[w+S];O!==-1&&(C[O]=A),m[b+A]=m[w+S],m[w+S]=A}}return M}function l(o,s,m,d,h){if(o<2||o+s<0){for(var x=0;x{var{transpose:r}=e;return function(t,n,a,i){if(!t||!n||!a)return null;var u=t._size,l=u[0],c=u[1],o,s,m,d,h,x,v,y=4*c+(i?c+l+1:0),w=[],C=0,b=c,M=2*c,A=3*c,S=4*c,O=5*c+1;for(m=0;m=1&&_[s]++,q.jleaf===2&&_[q.q]--}n[s]!==-1&&(w[C+s]=n[s])}for(s=0;s{var{add:r,multiply:t,transpose:n}=e,a=gT({add:r,multiply:t,transpose:n}),i=yT({transpose:n});return function(c,o,s){var m=o._ptr,d=o._size,h=d[1],x,v={};if(v.q=a(c,o),c&&!v.q)return null;if(s){var y=c?pT(o,null,v.q,0):o;v.parent=hT(y,1);var w=dT(v.parent,h);if(v.cp=i(y,v.parent,w,1),y&&v.parent&&v.cp&&u(y,v))for(v.unz=0,x=0;x=0;O--)for(E=o[O],T=o[O+1],_=E;_=0;S--)v[S]=-1,O=y[S],O!==-1&&(w[A+O]++===0&&(w[M+O]=S),w[C+S]=w[b+O],w[b+O]=S);for(c.lnz=0,c.m2=d,O=0;O=0;){e=n[d];var h=a?a[e]:e;Rc(u,e)||(fg(u,e),n[c+d]=h<0?0:bD(u[h]));var x=1;for(s=n[c+d],m=h<0?0:bD(u[h+1]);s{var{divideScalar:r,multiply:t,subtract:n}=e;return function(i,u,l,c,o,s,m){var d=i._values,h=i._index,x=i._ptr,v=i._size,y=v[1],w=u._values,C=u._index,b=u._ptr,M,A,S,O,_=DT(i,u,l,c,s);for(M=_;M{var{abs:r,divideScalar:t,multiply:n,subtract:a,larger:i,largerEq:u,SparseMatrix:l}=e,c=ST({divideScalar:t,multiply:n,subtract:a});return function(s,m,d){if(!s)return null;var h=s._size,x=h[1],v,y=100,w=100;m&&(v=m.q,y=m.lnz||y,w=m.unz||w);var C=[],b=[],M=[],A=new l({values:C,index:b,ptr:M,size:[x,x]}),S=[],O=[],_=[],E=new l({values:S,index:O,ptr:_,size:[x,x]}),T=[],R,q,W=[],G=[];for(R=0;R{var{typed:r,abs:t,add:n,multiply:a,transpose:i,divideScalar:u,subtract:l,larger:c,largerEq:o,SparseMatrix:s}=e,m=bT({add:n,multiply:a,transpose:i}),d=NT({abs:t,divideScalar:u,multiply:a,subtract:l,larger:c,largerEq:o,SparseMatrix:s});return r(AT,{"SparseMatrix, number, number":function(x,v,y){if(!Ze(v)||v<0||v>3)throw new Error("Symbolic Ordering and Analysis order must be an integer number in the interval [0, 3]");if(y<0||y>1)throw new Error("Partial pivoting threshold must be a number from 0 to 1");var w=m(v,x,!1),C=d(x,w,y);return{L:C.L,U:C.U,p:C.pinv,q:w.q,toString:function(){return"L: "+this.L.toString()+\` +U: \`+this.U.toString()+\` +p: \`+this.p.toString()+(this.q?\` +q: \`+this.q.toString():"")+\` +\`}}}})});function wD(e,r){var t,n=r.length,a=[];if(e)for(t=0;t{var{typed:r,matrix:t,lup:n,slu:a,usolve:i,lsolve:u,DenseMatrix:l}=e,c=_i({DenseMatrix:l});return r(MT,{"Array, Array | Matrix":function(d,h){d=t(d);var x=n(d),v=s(x.L,x.U,x.p,null,h);return v.valueOf()},"DenseMatrix, Array | Matrix":function(d,h){var x=n(d);return s(x.L,x.U,x.p,null,h)},"SparseMatrix, Array | Matrix":function(d,h){var x=n(d);return s(x.L,x.U,x.p,null,h)},"SparseMatrix, Array | Matrix, number, number":function(d,h,x,v){var y=a(d,x,v);return s(y.L,y.U,y.p,y.q,h)},"Object, Array | Matrix":function(d,h){return s(d.L,d.U,d.p,d.q,h)}});function o(m){if(Qe(m))return m;if(Mr(m))return t(m);throw new TypeError("Invalid Matrix LU decomposition")}function s(m,d,h,x,v){m=o(m),d=o(d),h&&(v=c(m,v,!0),v._data=wD(h,v._data));var y=u(m,v),w=i(d,y);return x&&(w._data=wD(x,w._data)),w}});var CT="polynomialRoot",pG=["typed","isZero","equalScalar","add","subtract","multiply","divide","sqrt","unaryMinus","cbrt","typeOf","im","re"],mg=F(CT,pG,e=>{var{typed:r,isZero:t,equalScalar:n,add:a,subtract:i,multiply:u,divide:l,sqrt:c,unaryMinus:o,cbrt:s,typeOf:m,im:d,re:h}=e;return r(CT,{"number|Complex, ...number|Complex":(x,v)=>{for(var y=[x,...v];y.length>0&&t(y[y.length-1]);)y.pop();if(y.length<2)throw new RangeError("Polynomial [".concat(x,", ").concat(v,"] must have a non-zero non-constant coefficient"));switch(y.length){case 2:return[o(l(y[0],y[1]))];case 3:{var[w,C,b]=y,M=u(2,b),A=u(C,C),S=u(4,b,w);if(n(A,S))return[l(o(C),M)];var O=c(i(A,S));return[l(i(O,C),M),l(i(o(O),C),M)]}case 4:{var[_,E,T,R]=y,q=o(u(3,R)),W=u(T,T),G=u(3,R,E),H=a(u(2,T,T,T),u(27,R,R,_)),L=u(9,R,T,E);if(n(W,G)&&n(H,L))return[l(T,q)];var k=i(W,G),K=i(H,L),z=a(u(18,R,T,E,_),u(T,T,E,E)),oe=a(u(4,T,T,T,_),u(4,R,E,E,E),u(27,R,R,_,_));if(n(z,oe))return[l(i(u(4,R,T,E),a(u(9,R,R,_),u(T,T,T))),u(R,k)),l(i(u(9,R,_),u(T,E)),u(2,k))];var pe;n(W,G)?pe=K:pe=l(a(K,c(i(u(K,K),u(4,k,k,k)))),2);var ae=!0,$=s(pe,ae).toArray().map(le=>l(a(T,le,l(k,le)),q));return $.map(le=>m(le)==="Complex"&&n(h(le),h(le)+d(le))?h(le):le)}default:throw new RangeError("only implemented for cubic or lower-order polynomials, not ".concat(y))}}})});var dG="Help",hG=["evaluate"],pg=F(dG,hG,e=>{var{evaluate:r}=e;function t(n){if(!(this instanceof t))throw new SyntaxError("Constructor must be called with the new operator");if(!n)throw new Error('Argument "doc" missing');this.doc=n}return t.prototype.type="Help",t.prototype.isHelp=!0,t.prototype.toString=function(){var n=this.doc||{},a=\` +\`;if(n.name&&(a+="Name: "+n.name+\` + +\`),n.category&&(a+="Category: "+n.category+\` + +\`),n.description&&(a+=\`Description: + \`+n.description+\` + +\`),n.syntax&&(a+=\`Syntax: + \`+n.syntax.join(\` + \`)+\` + +\`),n.examples){a+=\`Examples: +\`;for(var i=!1,u=r("config()"),l={config:m=>(i=!0,r("config(newConfig)",{newConfig:m}))},c=0;ci!=="mathjs").forEach(i=>{a[i]=n[i]}),new t(a)},t.prototype.valueOf=t.prototype.toString,t},{isClass:!0});var vG="Chain",gG=["?on","math","typed"],dg=F(vG,gG,e=>{var{on:r,math:t,typed:n}=e;function a(o){if(!(this instanceof a))throw new SyntaxError("Constructor must be called with the new operator");bu(o)?this.value=o.value:this.value=o}a.prototype.type="Chain",a.prototype.isChain=!0,a.prototype.done=function(){return this.value},a.prototype.valueOf=function(){return this.value},a.prototype.toString=function(){return lr(this.value)},a.prototype.toJSON=function(){return{mathjs:"Chain",value:this.value}},a.fromJSON=function(o){return new a(o.value)};function i(o,s){typeof s=="function"&&(a.prototype[o]=l(s))}function u(o,s){Du(a.prototype,o,function(){var d=s();if(typeof d=="function")return l(d)})}function l(o){return function(){if(arguments.length===0)return new a(o(this.value));for(var s=[this.value],m=0;mo[x])};for(var d in o)m(d)}};var c={expression:!0,docs:!0,type:!0,classes:!0,json:!0,error:!0,isChain:!0};return a.createProxy(t),r&&r("import",function(o,s,m){m||u(o,s)}),a},{isClass:!0});var DD={name:"e",category:"Constants",syntax:["e"],description:"Euler's number, the base of the natural logarithm. Approximately equal to 2.71828",examples:["e","e ^ 2","exp(2)","log(e)"],seealso:["exp"]};var ET={name:"false",category:"Constants",syntax:["false"],description:"Boolean value false",examples:["false"],seealso:["true"]};var TT={name:"i",category:"Constants",syntax:["i"],description:"Imaginary unit, defined as i*i=-1. A complex number is described as a + b*i, where a is the real part, and b is the imaginary part.",examples:["i","i * i","sqrt(-1)"],seealso:[]};var FT={name:"Infinity",category:"Constants",syntax:["Infinity"],description:"Infinity, a number which is larger than the maximum number that can be handled by a floating point number.",examples:["Infinity","1 / 0"],seealso:[]};var _T={name:"LN10",category:"Constants",syntax:["LN10"],description:"Returns the natural logarithm of 10, approximately equal to 2.302",examples:["LN10","log(10)"],seealso:[]};var OT={name:"LN2",category:"Constants",syntax:["LN2"],description:"Returns the natural logarithm of 2, approximately equal to 0.693",examples:["LN2","log(2)"],seealso:[]};var BT={name:"LOG10E",category:"Constants",syntax:["LOG10E"],description:"Returns the base-10 logarithm of E, approximately equal to 0.434",examples:["LOG10E","log(e, 10)"],seealso:[]};var PT={name:"LOG2E",category:"Constants",syntax:["LOG2E"],description:"Returns the base-2 logarithm of E, approximately equal to 1.442",examples:["LOG2E","log(e, 2)"],seealso:[]};var IT={name:"NaN",category:"Constants",syntax:["NaN"],description:"Not a number",examples:["NaN","0 / 0"],seealso:[]};var RT={name:"null",category:"Constants",syntax:["null"],description:"Value null",examples:["null"],seealso:["true","false"]};var kT={name:"phi",category:"Constants",syntax:["phi"],description:"Phi is the golden ratio. Two quantities are in the golden ratio if their ratio is the same as the ratio of their sum to the larger of the two quantities. Phi is defined as \`(1 + sqrt(5)) / 2\` and is approximately 1.618034...",examples:["phi"],seealso:[]};var SD={name:"pi",category:"Constants",syntax:["pi"],description:"The number pi is a mathematical constant that is the ratio of a circle's circumference to its diameter, and is approximately equal to 3.14159",examples:["pi","sin(pi/2)"],seealso:["tau"]};var qT={name:"SQRT1_2",category:"Constants",syntax:["SQRT1_2"],description:"Returns the square root of 1/2, approximately equal to 0.707",examples:["SQRT1_2","sqrt(1/2)"],seealso:[]};var LT={name:"SQRT2",category:"Constants",syntax:["SQRT2"],description:"Returns the square root of 2, approximately equal to 1.414",examples:["SQRT2","sqrt(2)"],seealso:[]};var zT={name:"tau",category:"Constants",syntax:["tau"],description:"Tau is the ratio constant of a circle's circumference to radius, equal to 2 * pi, approximately 6.2832.",examples:["tau","2 * pi"],seealso:["pi"]};var UT={name:"true",category:"Constants",syntax:["true"],description:"Boolean value true",examples:["true"],seealso:["false"]};var WT={name:"version",category:"Constants",syntax:["version"],description:"A string with the version number of math.js",examples:["version"],seealso:[]};var YT={name:"bignumber",category:"Construction",syntax:["bignumber(x)"],description:"Create a big number from a number or string.",examples:["0.1 + 0.2","bignumber(0.1) + bignumber(0.2)",'bignumber("7.2")','bignumber("7.2e500")',"bignumber([0.1, 0.2, 0.3])"],seealso:["boolean","complex","fraction","index","matrix","string","unit"]};var HT={name:"boolean",category:"Construction",syntax:["x","boolean(x)"],description:"Convert a string or number into a boolean.",examples:["boolean(0)","boolean(1)","boolean(3)",'boolean("true")','boolean("false")',"boolean([1, 0, 1, 1])"],seealso:["bignumber","complex","index","matrix","number","string","unit"]};var $T={name:"complex",category:"Construction",syntax:["complex()","complex(re, im)","complex(string)"],description:"Create a complex number.",examples:["complex()","complex(2, 3)",'complex("7 - 2i")'],seealso:["bignumber","boolean","index","matrix","number","string","unit"]};var GT={name:"createUnit",category:"Construction",syntax:["createUnit(definitions)","createUnit(name, definition)"],description:"Create a user-defined unit and register it with the Unit type.",examples:['createUnit("foo")','createUnit("knot", {definition: "0.514444444 m/s", aliases: ["knots", "kt", "kts"]})','createUnit("mph", "1 mile/hour")'],seealso:["unit","splitUnit"]};var VT={name:"fraction",category:"Construction",syntax:["fraction(num)","fraction(matrix)","fraction(num,den)","fraction({n: num, d: den})"],description:"Create a fraction from a number or from integer numerator and denominator.",examples:["fraction(0.125)","fraction(1, 3) + fraction(2, 5)","fraction({n: 333, d: 53})","fraction([sqrt(9), sqrt(10), sqrt(11)])"],seealso:["bignumber","boolean","complex","index","matrix","string","unit"]};var ZT={name:"index",category:"Construction",syntax:["[start]","[start:end]","[start:step:end]","[start1, start 2, ...]","[start1:end1, start2:end2, ...]","[start1:step1:end1, start2:step2:end2, ...]"],description:"Create an index to get or replace a subset of a matrix",examples:["A = [1, 2, 3; 4, 5, 6]","A[1, :]","A[1, 2] = 50","A[1:2, 1:2] = 1","B = [1, 2, 3]","B[B>1 and B<3]"],seealso:["bignumber","boolean","complex","matrix,","number","range","string","unit"]};var QT={name:"matrix",category:"Construction",syntax:["[]","[a1, b1, ...; a2, b2, ...]","matrix()",'matrix("dense")',"matrix([...])"],description:"Create a matrix.",examples:["[]","[1, 2, 3]","[1, 2, 3; 4, 5, 6]","matrix()","matrix([3, 4])",'matrix([3, 4; 5, 6], "sparse")','matrix([3, 4; 5, 6], "sparse", "number")'],seealso:["bignumber","boolean","complex","index","number","string","unit","sparse"]};var XT={name:"number",category:"Construction",syntax:["x","number(x)","number(unit, valuelessUnit)"],description:"Create a number or convert a string or boolean into a number.",examples:["2","2e3","4.05","number(2)",'number("7.2")',"number(true)","number([true, false, true, true])",'number(unit("52cm"), "m")'],seealso:["bignumber","boolean","complex","fraction","index","matrix","string","unit"]};var JT={name:"sparse",category:"Construction",syntax:["sparse()","sparse([a1, b1, ...; a1, b2, ...])",'sparse([a1, b1, ...; a1, b2, ...], "number")'],description:"Create a sparse matrix.",examples:["sparse()","sparse([3, 4; 5, 6])",'sparse([3, 0; 5, 0], "number")'],seealso:["bignumber","boolean","complex","index","number","string","unit","matrix"]};var KT={name:"splitUnit",category:"Construction",syntax:["splitUnit(unit: Unit, parts: Unit[])"],description:"Split a unit in an array of units whose sum is equal to the original unit.",examples:['splitUnit(1 m, ["feet", "inch"])'],seealso:["unit","createUnit"]};var jT={name:"string",category:"Construction",syntax:['"text"',"string(x)"],description:"Create a string or convert a value to a string",examples:['"Hello World!"',"string(4.2)","string(3 + 2i)"],seealso:["bignumber","boolean","complex","index","matrix","number","unit"]};var eF={name:"unit",category:"Construction",syntax:["value unit","unit(value, unit)","unit(string)"],description:"Create a unit.",examples:["5.5 mm","3 inch",'unit(7.1, "kilogram")','unit("23 deg")'],seealso:["bignumber","boolean","complex","index","matrix","number","string"]};var rF={name:"config",category:"Core",syntax:["config()","config(options)"],description:"Get configuration or change configuration.",examples:["config()","1/3 + 1/4",'config({number: "Fraction"})',"1/3 + 1/4"],seealso:[]};var tF={name:"import",category:"Core",syntax:["import(functions)","import(functions, options)"],description:"Import functions or constants from an object.",examples:["import({myFn: f(x)=x^2, myConstant: 32 })","myFn(2)","myConstant"],seealso:[]};var nF={name:"typed",category:"Core",syntax:["typed(signatures)","typed(name, signatures)"],description:"Create a typed function.",examples:['double = typed({ "number": f(x)=x+x, "string": f(x)=concat(x,x) })',"double(2)",'double("hello")'],seealso:[]};var aF={name:"derivative",category:"Algebra",syntax:["derivative(expr, variable)","derivative(expr, variable, {simplify: boolean})"],description:"Takes the derivative of an expression expressed in parser Nodes. The derivative will be taken over the supplied variable in the second parameter. If there are multiple variables in the expression, it will return a partial derivative.",examples:['derivative("2x^3", "x")','derivative("2x^3", "x", {simplify: false})','derivative("2x^2 + 3x + 4", "x")','derivative("sin(2x)", "x")','f = parse("x^2 + x")','x = parse("x")',"df = derivative(f, x)","df.evaluate({x: 3})"],seealso:["simplify","parse","evaluate"]};var iF={name:"leafCount",category:"Algebra",syntax:["leafCount(expr)"],description:"Computes the number of leaves in the parse tree of the given expression",examples:['leafCount("e^(i*pi)-1")','leafCount(parse("{a: 22/7, b: 10^(1/2)}"))'],seealso:["simplify"]};var oF={name:"lsolve",category:"Algebra",syntax:["x=lsolve(L, b)"],description:"Finds one solution of the linear system L * x = b where L is an [n x n] lower triangular matrix and b is a [n] column vector.",examples:["a = [-2, 3; 2, 1]","b = [11, 9]","x = lsolve(a, b)"],seealso:["lsolveAll","lup","lusolve","usolve","matrix","sparse"]};var sF={name:"lsolveAll",category:"Algebra",syntax:["x=lsolveAll(L, b)"],description:"Finds all solutions of the linear system L * x = b where L is an [n x n] lower triangular matrix and b is a [n] column vector.",examples:["a = [-2, 3; 2, 1]","b = [11, 9]","x = lsolve(a, b)"],seealso:["lsolve","lup","lusolve","usolve","matrix","sparse"]};var uF={name:"lup",category:"Algebra",syntax:["lup(m)"],description:"Calculate the Matrix LU decomposition with partial pivoting. Matrix A is decomposed in three matrices (L, U, P) where P * A = L * U",examples:["lup([[2, 1], [1, 4]])","lup(matrix([[2, 1], [1, 4]]))","lup(sparse([[2, 1], [1, 4]]))"],seealso:["lusolve","lsolve","usolve","matrix","sparse","slu","qr"]};var fF={name:"lusolve",category:"Algebra",syntax:["x=lusolve(A, b)","x=lusolve(lu, b)"],description:"Solves the linear system A * x = b where A is an [n x n] matrix and b is a [n] column vector.",examples:["a = [-2, 3; 2, 1]","b = [11, 9]","x = lusolve(a, b)"],seealso:["lup","slu","lsolve","usolve","matrix","sparse"]};var cF={name:"polynomialRoot",category:"Algebra",syntax:["x=polynomialRoot(-6, 3)","x=polynomialRoot(4, -4, 1)","x=polynomialRoot(-8, 12, -6, 1)"],description:"Finds the roots of a univariate polynomial given by its coefficients starting from constant, linear, and so on, increasing in degree.",examples:["a = polynomialRoot(-6, 11, -6, 1)"],seealso:["cbrt","sqrt"]};var lF={name:"qr",category:"Algebra",syntax:["qr(A)"],description:"Calculates the Matrix QR decomposition. Matrix \`A\` is decomposed in two matrices (\`Q\`, \`R\`) where \`Q\` is an orthogonal matrix and \`R\` is an upper triangular matrix.",examples:["qr([[1, -1, 4], [1, 4, -2], [1, 4, 2], [1, -1, 0]])"],seealso:["lup","slu","matrix"]};var mF={name:"rationalize",category:"Algebra",syntax:["rationalize(expr)","rationalize(expr, scope)","rationalize(expr, scope, detailed)"],description:"Transform a rationalizable expression in a rational fraction. If rational fraction is one variable polynomial then converts the numerator and denominator in canonical form, with decreasing exponents, returning the coefficients of numerator.",examples:['rationalize("2x/y - y/(x+1)")','rationalize("2x/y - y/(x+1)", true)'],seealso:["simplify"]};var pF={name:"resolve",category:"Algebra",syntax:["resolve(node, scope)"],description:"Recursively substitute variables in an expression tree.",examples:['resolve(parse("1 + x"), { x: 7 })','resolve(parse("size(text)"), { text: "Hello World" })','resolve(parse("x + y"), { x: parse("3z") })','resolve(parse("3x"), { x: parse("y+z"), z: parse("w^y") })'],seealso:["simplify","evaluate"],mayThrow:["ReferenceError"]};var dF={name:"simplify",category:"Algebra",syntax:["simplify(expr)","simplify(expr, rules)"],description:"Simplify an expression tree.",examples:['simplify("3 + 2 / 4")','simplify("2x + x")','f = parse("x * (x + 2 + x)")',"simplified = simplify(f)","simplified.evaluate({x: 2})"],seealso:["simplifyCore","derivative","evaluate","parse","rationalize","resolve"]};var hF={name:"simplifyConstant",category:"Algebra",syntax:["simplifyConstant(expr)","simplifyConstant(expr, options)"],description:"Replace constant subexpressions of node with their values.",examples:['simplifyConstant("(3-3)*x")','simplifyConstant(parse("z-cos(tau/8)"))'],seealso:["simplify","simplifyCore","evaluate"]};var vF={name:"simplifyCore",category:"Algebra",syntax:["simplifyCore(node)"],description:"Perform simple one-pass simplifications on an expression tree.",examples:['simplifyCore(parse("0*x"))','simplifyCore(parse("(x+0)*2"))'],seealso:["simplify","simplifyConstant","evaluate"]};var gF={name:"slu",category:"Algebra",syntax:["slu(A, order, threshold)"],description:"Calculate the Matrix LU decomposition with full pivoting. Matrix A is decomposed in two matrices (L, U) and two permutation vectors (pinv, q) where P * A * Q = L * U",examples:["slu(sparse([4.5, 0, 3.2, 0; 3.1, 2.9, 0, 0.9; 0, 1.7, 3, 0; 3.5, 0.4, 0, 1]), 1, 0.001)"],seealso:["lusolve","lsolve","usolve","matrix","sparse","lup","qr"]};var xF={name:"symbolicEqual",category:"Algebra",syntax:["symbolicEqual(expr1, expr2)","symbolicEqual(expr1, expr2, options)"],description:"Returns true if the difference of the expressions simplifies to 0",examples:['symbolicEqual("x*y","y*x")','symbolicEqual("abs(x^2)", "x^2")','symbolicEqual("abs(x)", "x", {context: {abs: {trivial: true}}})'],seealso:["simplify","evaluate"]};var yF={name:"usolve",category:"Algebra",syntax:["x=usolve(U, b)"],description:"Finds one solution of the linear system U * x = b where U is an [n x n] upper triangular matrix and b is a [n] column vector.",examples:["x=usolve(sparse([1, 1, 1, 1; 0, 1, 1, 1; 0, 0, 1, 1; 0, 0, 0, 1]), [1; 2; 3; 4])"],seealso:["usolveAll","lup","lusolve","lsolve","matrix","sparse"]};var bF={name:"usolveAll",category:"Algebra",syntax:["x=usolve(U, b)"],description:"Finds all solutions of the linear system U * x = b where U is an [n x n] upper triangular matrix and b is a [n] column vector.",examples:["x=usolve(sparse([1, 1, 1, 1; 0, 1, 1, 1; 0, 0, 1, 1; 0, 0, 0, 1]), [1; 2; 3; 4])"],seealso:["usolve","lup","lusolve","lsolve","matrix","sparse"]};var wF={name:"abs",category:"Arithmetic",syntax:["abs(x)"],description:"Compute the absolute value.",examples:["abs(3.5)","abs(-4.2)"],seealso:["sign"]};var DF={name:"add",category:"Operators",syntax:["x + y","add(x, y)"],description:"Add two values.",examples:["a = 2.1 + 3.6","a - 3.6","3 + 2i","3 cm + 2 inch",'"2.3" + "4"'],seealso:["subtract"]};var SF={name:"cbrt",category:"Arithmetic",syntax:["cbrt(x)","cbrt(x, allRoots)"],description:"Compute the cubic root value. If x = y * y * y, then y is the cubic root of x. When \`x\` is a number or complex number, an optional second argument \`allRoots\` can be provided to return all three cubic roots. If not provided, the principal root is returned",examples:["cbrt(64)","cube(4)","cbrt(-8)","cbrt(2 + 3i)","cbrt(8i)","cbrt(8i, true)","cbrt(27 m^3)"],seealso:["square","sqrt","cube","multiply"]};var NF={name:"ceil",category:"Arithmetic",syntax:["ceil(x)"],description:"Round a value towards plus infinity. If x is complex, both real and imaginary part are rounded towards plus infinity.",examples:["ceil(3.2)","ceil(3.8)","ceil(-4.2)"],seealso:["floor","fix","round"]};var AF={name:"cube",category:"Arithmetic",syntax:["cube(x)"],description:"Compute the cube of a value. The cube of x is x * x * x.",examples:["cube(2)","2^3","2 * 2 * 2"],seealso:["multiply","square","pow"]};var MF={name:"divide",category:"Operators",syntax:["x / y","divide(x, y)"],description:"Divide two values.",examples:["a = 2 / 3","a * 3","4.5 / 2","3 + 4 / 2","(3 + 4) / 2","18 km / 4.5"],seealso:["multiply"]};var CF={name:"dotDivide",category:"Operators",syntax:["x ./ y","dotDivide(x, y)"],description:"Divide two values element wise.",examples:["a = [1, 2, 3; 4, 5, 6]","b = [2, 1, 1; 3, 2, 5]","a ./ b"],seealso:["multiply","dotMultiply","divide"]};var EF={name:"dotMultiply",category:"Operators",syntax:["x .* y","dotMultiply(x, y)"],description:"Multiply two values element wise.",examples:["a = [1, 2, 3; 4, 5, 6]","b = [2, 1, 1; 3, 2, 5]","a .* b"],seealso:["multiply","divide","dotDivide"]};var TF={name:"dotPow",category:"Operators",syntax:["x .^ y","dotPow(x, y)"],description:"Calculates the power of x to y element wise.",examples:["a = [1, 2, 3; 4, 5, 6]","a .^ 2"],seealso:["pow"]};var FF={name:"exp",category:"Arithmetic",syntax:["exp(x)"],description:"Calculate the exponent of a value.",examples:["exp(1.3)","e ^ 1.3","log(exp(1.3))","x = 2.4","(exp(i*x) == cos(x) + i*sin(x)) # Euler's formula"],seealso:["expm","expm1","pow","log"]};var _F={name:"expm",category:"Arithmetic",syntax:["exp(x)"],description:"Compute the matrix exponential, expm(A) = e^A. The matrix must be square. Not to be confused with exp(a), which performs element-wise exponentiation.",examples:["expm([[0,2],[0,0]])"],seealso:["exp"]};var OF={name:"expm1",category:"Arithmetic",syntax:["expm1(x)"],description:"Calculate the value of subtracting 1 from the exponential value.",examples:["expm1(2)","pow(e, 2) - 1","log(expm1(2) + 1)"],seealso:["exp","pow","log"]};var BF={name:"fix",category:"Arithmetic",syntax:["fix(x)"],description:"Round a value towards zero. If x is complex, both real and imaginary part are rounded towards zero.",examples:["fix(3.2)","fix(3.8)","fix(-4.2)","fix(-4.8)"],seealso:["ceil","floor","round"]};var PF={name:"floor",category:"Arithmetic",syntax:["floor(x)"],description:"Round a value towards minus infinity.If x is complex, both real and imaginary part are rounded towards minus infinity.",examples:["floor(3.2)","floor(3.8)","floor(-4.2)"],seealso:["ceil","fix","round"]};var IF={name:"gcd",category:"Arithmetic",syntax:["gcd(a, b)","gcd(a, b, c, ...)"],description:"Compute the greatest common divisor.",examples:["gcd(8, 12)","gcd(-4, 6)","gcd(25, 15, -10)"],seealso:["lcm","xgcd"]};var RF={name:"hypot",category:"Arithmetic",syntax:["hypot(a, b, c, ...)","hypot([a, b, c, ...])"],description:"Calculate the hypotenusa of a list with values. ",examples:["hypot(3, 4)","sqrt(3^2 + 4^2)","hypot(-2)","hypot([3, 4, 5])"],seealso:["abs","norm"]};var kF={name:"invmod",category:"Arithmetic",syntax:["invmod(a, b)"],description:"Calculate the (modular) multiplicative inverse of a modulo b. Solution to the equation ax \\u2263 1 (mod b)",examples:["invmod(8, 12)","invmod(7, 13)","invmod(15151, 15122)"],seealso:["gcd","xgcd"]};var qF={name:"lcm",category:"Arithmetic",syntax:["lcm(x, y)"],description:"Compute the least common multiple.",examples:["lcm(4, 6)","lcm(6, 21)","lcm(6, 21, 5)"],seealso:["gcd"]};var LF={name:"log",category:"Arithmetic",syntax:["log(x)","log(x, base)"],description:"Compute the logarithm of a value. If no base is provided, the natural logarithm of x is calculated. If base if provided, the logarithm is calculated for the specified base. log(x, base) is defined as log(x) / log(base).",examples:["log(3.5)","a = log(2.4)","exp(a)","10 ^ 4","log(10000, 10)","log(10000) / log(10)","b = log(1024, 2)","2 ^ b"],seealso:["exp","log1p","log2","log10"]};var zF={name:"log10",category:"Arithmetic",syntax:["log10(x)"],description:"Compute the 10-base logarithm of a value.",examples:["log10(0.00001)","log10(10000)","10 ^ 4","log(10000) / log(10)","log(10000, 10)"],seealso:["exp","log"]};var UF={name:"log1p",category:"Arithmetic",syntax:["log1p(x)","log1p(x, base)"],description:"Calculate the logarithm of a \`value+1\`",examples:["log1p(2.5)","exp(log1p(1.4))","pow(10, 4)","log1p(9999, 10)","log1p(9999) / log(10)"],seealso:["exp","log","log2","log10"]};var WF={name:"log2",category:"Arithmetic",syntax:["log2(x)"],description:"Calculate the 2-base of a value. This is the same as calculating \`log(x, 2)\`.",examples:["log2(0.03125)","log2(16)","log2(16) / log2(2)","pow(2, 4)"],seealso:["exp","log1p","log","log10"]};var YF={name:"mod",category:"Operators",syntax:["x % y","x mod y","mod(x, y)"],description:"Calculates the modulus, the remainder of an integer division.",examples:["7 % 3","11 % 2","10 mod 4","isOdd(x) = x % 2","isOdd(2)","isOdd(3)"],seealso:["divide"]};var HF={name:"multiply",category:"Operators",syntax:["x * y","multiply(x, y)"],description:"multiply two values.",examples:["a = 2.1 * 3.4","a / 3.4","2 * 3 + 4","2 * (3 + 4)","3 * 2.1 km"],seealso:["divide"]};var $F={name:"norm",category:"Arithmetic",syntax:["norm(x)","norm(x, p)"],description:"Calculate the norm of a number, vector or matrix.",examples:["abs(-3.5)","norm(-3.5)","norm(3 - 4i)","norm([1, 2, -3], Infinity)","norm([1, 2, -3], -Infinity)","norm([3, 4], 2)","norm([[1, 2], [3, 4]], 1)",'norm([[1, 2], [3, 4]], "inf")','norm([[1, 2], [3, 4]], "fro")']};var GF={name:"nthRoot",category:"Arithmetic",syntax:["nthRoot(a)","nthRoot(a, root)"],description:'Calculate the nth root of a value. The principal nth root of a positive real number A, is the positive real solution of the equation "x^root = A".',examples:["4 ^ 3","nthRoot(64, 3)","nthRoot(9, 2)","sqrt(9)"],seealso:["nthRoots","pow","sqrt"]};var VF={name:"nthRoots",category:"Arithmetic",syntax:["nthRoots(A)","nthRoots(A, root)"],description:'Calculate the nth roots of a value. An nth root of a positive real number A, is a positive real solution of the equation "x^root = A". This function returns an array of complex values.',examples:["nthRoots(1)","nthRoots(1, 3)"],seealso:["sqrt","pow","nthRoot"]};var ZF={name:"pow",category:"Operators",syntax:["x ^ y","pow(x, y)"],description:"Calculates the power of x to y, x^y.",examples:["2^3","2*2*2","1 + e ^ (pi * i)","pow([[1, 2], [4, 3]], 2)","pow([[1, 2], [4, 3]], -1)"],seealso:["multiply","nthRoot","nthRoots","sqrt"]};var QF={name:"round",category:"Arithmetic",syntax:["round(x)","round(x, n)","round(unit, valuelessUnit)","round(unit, n, valuelessUnit)"],description:"round a value towards the nearest integer.If x is complex, both real and imaginary part are rounded towards the nearest integer. When n is specified, the value is rounded to n decimals.",examples:["round(3.2)","round(3.8)","round(-4.2)","round(-4.8)","round(pi, 3)","round(123.45678, 2)","round(3.241cm, 2, cm)","round([3.2, 3.8, -4.7])"],seealso:["ceil","floor","fix"]};var XF={name:"sign",category:"Arithmetic",syntax:["sign(x)"],description:"Compute the sign of a value. The sign of a value x is 1 when x>1, -1 when x<0, and 0 when x=0.",examples:["sign(3.5)","sign(-4.2)","sign(0)"],seealso:["abs"]};var JF={name:"sqrt",category:"Arithmetic",syntax:["sqrt(x)"],description:"Compute the square root value. If x = y * y, then y is the square root of x.",examples:["sqrt(25)","5 * 5","sqrt(-1)"],seealso:["square","sqrtm","multiply","nthRoot","nthRoots","pow"]};var KF={name:"sqrtm",category:"Arithmetic",syntax:["sqrtm(x)"],description:"Calculate the principal square root of a square matrix. The principal square root matrix \`X\` of another matrix \`A\` is such that \`X * X = A\`.",examples:["sqrtm([[33, 24], [48, 57]])"],seealso:["sqrt","abs","square","multiply"]};var jF={name:"sylvester",category:"Algebra",syntax:["sylvester(A,B,C)"],description:"Solves the real-valued Sylvester equation AX+XB=C for X",examples:["sylvester([[-1, -2], [1, 1]], [[-2, 1], [-1, 2]], [[-3, 2], [3, 0]])","A = [[-1, -2], [1, 1]]; B = [[2, -1], [1, -2]]; C = [[-3, 2], [3, 0]]","sylvester(A, B, C)"],seealso:["schur","lyap"]};var e_={name:"schur",category:"Algebra",syntax:["schur(A)"],description:"Performs a real Schur decomposition of the real matrix A = UTU'",examples:["schur([[1, 0], [-4, 3]])","A = [[1, 0], [-4, 3]]","schur(A)"],seealso:["lyap","sylvester"]};var r_={name:"lyap",category:"Algebra",syntax:["lyap(A,Q)"],description:"Solves the Continuous-time Lyapunov equation AP+PA'+Q=0 for P",examples:["lyap([[-2, 0], [1, -4]], [[3, 1], [1, 3]])","A = [[-2, 0], [1, -4]]","Q = [[3, 1], [1, 3]]","lyap(A,Q)"],seealso:["schur","sylvester"]};var t_={name:"square",category:"Arithmetic",syntax:["square(x)"],description:"Compute the square of a value. The square of x is x * x.",examples:["square(3)","sqrt(9)","3^2","3 * 3"],seealso:["multiply","pow","sqrt","cube"]};var n_={name:"subtract",category:"Operators",syntax:["x - y","subtract(x, y)"],description:"subtract two values.",examples:["a = 5.3 - 2","a + 2","2/3 - 1/6","2 * 3 - 3","2.1 km - 500m"],seealso:["add"]};var a_={name:"unaryMinus",category:"Operators",syntax:["-x","unaryMinus(x)"],description:"Inverse the sign of a value. Converts booleans and strings to numbers.",examples:["-4.5","-(-5.6)",'-"22"'],seealso:["add","subtract","unaryPlus"]};var i_={name:"unaryPlus",category:"Operators",syntax:["+x","unaryPlus(x)"],description:"Converts booleans and strings to numbers.",examples:["+true",'+"2"'],seealso:["add","subtract","unaryMinus"]};var o_={name:"xgcd",category:"Arithmetic",syntax:["xgcd(a, b)"],description:"Calculate the extended greatest common divisor for two values. The result is an array [d, x, y] with 3 entries, where d is the greatest common divisor, and d = x * a + y * b.",examples:["xgcd(8, 12)","gcd(8, 12)","xgcd(36163, 21199)"],seealso:["gcd","lcm"]};var s_={name:"bitAnd",category:"Bitwise",syntax:["x & y","bitAnd(x, y)"],description:"Bitwise AND operation. Performs the logical AND operation on each pair of the corresponding bits of the two given values by multiplying them. If both bits in the compared position are 1, the bit in the resulting binary representation is 1, otherwise, the result is 0",examples:["5 & 3","bitAnd(53, 131)","[1, 12, 31] & 42"],seealso:["bitNot","bitOr","bitXor","leftShift","rightArithShift","rightLogShift"]};var u_={name:"bitNot",category:"Bitwise",syntax:["~x","bitNot(x)"],description:"Bitwise NOT operation. Performs a logical negation on each bit of the given value. Bits that are 0 become 1, and those that are 1 become 0.",examples:["~1","~2","bitNot([2, -3, 4])"],seealso:["bitAnd","bitOr","bitXor","leftShift","rightArithShift","rightLogShift"]};var f_={name:"bitOr",category:"Bitwise",syntax:["x | y","bitOr(x, y)"],description:"Bitwise OR operation. Performs the logical inclusive OR operation on each pair of corresponding bits of the two given values. The result in each position is 1 if the first bit is 1 or the second bit is 1 or both bits are 1, otherwise, the result is 0.",examples:["5 | 3","bitOr([1, 2, 3], 4)"],seealso:["bitAnd","bitNot","bitXor","leftShift","rightArithShift","rightLogShift"]};var c_={name:"bitXor",category:"Bitwise",syntax:["bitXor(x, y)"],description:"Bitwise XOR operation, exclusive OR. Performs the logical exclusive OR operation on each pair of corresponding bits of the two given values. The result in each position is 1 if only the first bit is 1 or only the second bit is 1, but will be 0 if both are 0 or both are 1.",examples:["bitOr(1, 2)","bitXor([2, 3, 4], 4)"],seealso:["bitAnd","bitNot","bitOr","leftShift","rightArithShift","rightLogShift"]};var l_={name:"leftShift",category:"Bitwise",syntax:["x << y","leftShift(x, y)"],description:"Bitwise left logical shift of a value x by y number of bits.",examples:["4 << 1","8 >> 1"],seealso:["bitAnd","bitNot","bitOr","bitXor","rightArithShift","rightLogShift"]};var m_={name:"rightArithShift",category:"Bitwise",syntax:["x >> y","rightArithShift(x, y)"],description:"Bitwise right arithmetic shift of a value x by y number of bits.",examples:["8 >> 1","4 << 1","-12 >> 2"],seealso:["bitAnd","bitNot","bitOr","bitXor","leftShift","rightLogShift"]};var p_={name:"rightLogShift",category:"Bitwise",syntax:["x >>> y","rightLogShift(x, y)"],description:"Bitwise right logical shift of a value x by y number of bits.",examples:["8 >>> 1","4 << 1","-12 >>> 2"],seealso:["bitAnd","bitNot","bitOr","bitXor","leftShift","rightArithShift"]};var d_={name:"bellNumbers",category:"Combinatorics",syntax:["bellNumbers(n)"],description:"The Bell Numbers count the number of partitions of a set. A partition is a pairwise disjoint subset of S whose union is S. \`bellNumbers\` only takes integer arguments. The following condition must be enforced: n >= 0.",examples:["bellNumbers(3)","bellNumbers(8)"],seealso:["stirlingS2"]};var h_={name:"catalan",category:"Combinatorics",syntax:["catalan(n)"],description:"The Catalan Numbers enumerate combinatorial structures of many different types. catalan only takes integer arguments. The following condition must be enforced: n >= 0.",examples:["catalan(3)","catalan(8)"],seealso:["bellNumbers"]};var v_={name:"composition",category:"Combinatorics",syntax:["composition(n, k)"],description:"The composition counts of n into k parts. composition only takes integer arguments. The following condition must be enforced: k <= n.",examples:["composition(5, 3)"],seealso:["combinations"]};var g_={name:"stirlingS2",category:"Combinatorics",syntax:["stirlingS2(n, k)"],description:"he Stirling numbers of the second kind, counts the number of ways to partition a set of n labelled objects into k nonempty unlabelled subsets. \`stirlingS2\` only takes integer arguments. The following condition must be enforced: k <= n. If n = k or k = 1, then s(n,k) = 1.",examples:["stirlingS2(5, 3)"],seealso:["bellNumbers"]};var x_={name:"arg",category:"Complex",syntax:["arg(x)"],description:"Compute the argument of a complex value. If x = a+bi, the argument is computed as atan2(b, a).",examples:["arg(2 + 2i)","atan2(3, 2)","arg(2 + 3i)"],seealso:["re","im","conj","abs"]};var y_={name:"conj",category:"Complex",syntax:["conj(x)"],description:"Compute the complex conjugate of a complex value. If x = a+bi, the complex conjugate is a-bi.",examples:["conj(2 + 3i)","conj(2 - 3i)","conj(-5.2i)"],seealso:["re","im","abs","arg"]};var b_={name:"im",category:"Complex",syntax:["im(x)"],description:"Get the imaginary part of a complex number.",examples:["im(2 + 3i)","re(2 + 3i)","im(-5.2i)","im(2.4)"],seealso:["re","conj","abs","arg"]};var w_={name:"re",category:"Complex",syntax:["re(x)"],description:"Get the real part of a complex number.",examples:["re(2 + 3i)","im(2 + 3i)","re(-5.2i)","re(2.4)"],seealso:["im","conj","abs","arg"]};var D_={name:"evaluate",category:"Expression",syntax:["evaluate(expression)","evaluate(expression, scope)","evaluate([expr1, expr2, expr3, ...])","evaluate([expr1, expr2, expr3, ...], scope)"],description:"Evaluate an expression or an array with expressions.",examples:['evaluate("2 + 3")','evaluate("sqrt(16)")','evaluate("2 inch to cm")','evaluate("sin(x * pi)", { "x": 1/2 })','evaluate(["width=2", "height=4","width*height"])'],seealso:[]};var S_={name:"help",category:"Expression",syntax:["help(object)","help(string)"],description:"Display documentation on a function or data type.",examples:["help(sqrt)",'help("complex")'],seealso:[]};var N_={name:"distance",category:"Geometry",syntax:["distance([x1, y1], [x2, y2])","distance([[x1, y1], [x2, y2]])"],description:"Calculates the Euclidean distance between two points.",examples:["distance([0,0], [4,4])","distance([[0,0], [4,4]])"],seealso:[]};var A_={name:"intersect",category:"Geometry",syntax:["intersect(expr1, expr2, expr3, expr4)","intersect(expr1, expr2, expr3)"],description:"Computes the intersection point of lines and/or planes.",examples:["intersect([0, 0], [10, 10], [10, 0], [0, 10])","intersect([1, 0, 1], [4, -2, 2], [1, 1, 1, 6])"],seealso:[]};var M_={name:"and",category:"Logical",syntax:["x and y","and(x, y)"],description:"Logical and. Test whether two values are both defined with a nonzero/nonempty value.",examples:["true and false","true and true","2 and 4"],seealso:["not","or","xor"]};var C_={name:"not",category:"Logical",syntax:["not x","not(x)"],description:"Logical not. Flips the boolean value of given argument.",examples:["not true","not false","not 2","not 0"],seealso:["and","or","xor"]};var E_={name:"or",category:"Logical",syntax:["x or y","or(x, y)"],description:"Logical or. Test if at least one value is defined with a nonzero/nonempty value.",examples:["true or false","false or false","0 or 4"],seealso:["not","and","xor"]};var T_={name:"xor",category:"Logical",syntax:["x xor y","xor(x, y)"],description:"Logical exclusive or, xor. Test whether one and only one value is defined with a nonzero/nonempty value.",examples:["true xor false","false xor false","true xor true","0 xor 4"],seealso:["not","and","or"]};var F_={name:"column",category:"Matrix",syntax:["column(x, index)"],description:"Return a column from a matrix or array.",examples:["A = [[1, 2], [3, 4]]","column(A, 1)","column(A, 2)"],seealso:["row","matrixFromColumns"]};var __={name:"concat",category:"Matrix",syntax:["concat(A, B, C, ...)","concat(A, B, C, ..., dim)"],description:"Concatenate matrices. By default, the matrices are concatenated by the last dimension. The dimension on which to concatenate can be provided as last argument.",examples:["A = [1, 2; 5, 6]","B = [3, 4; 7, 8]","concat(A, B)","concat(A, B, 1)","concat(A, B, 2)"],seealso:["det","diag","identity","inv","ones","range","size","squeeze","subset","trace","transpose","zeros"]};var O_={name:"count",category:"Matrix",syntax:["count(x)"],description:"Count the number of elements of a matrix, array or string.",examples:["a = [1, 2; 3, 4; 5, 6]","count(a)","size(a)",'count("hello world")'],seealso:["size"]};var B_={name:"cross",category:"Matrix",syntax:["cross(A, B)"],description:"Calculate the cross product for two vectors in three dimensional space.",examples:["cross([1, 1, 0], [0, 1, 1])","cross([3, -3, 1], [4, 9, 2])","cross([2, 3, 4], [5, 6, 7])"],seealso:["multiply","dot"]};var P_={name:"ctranspose",category:"Matrix",syntax:["x'","ctranspose(x)"],description:"Complex Conjugate and Transpose a matrix",examples:["a = [1, 2, 3; 4, 5, 6]","a'","ctranspose(a)"],seealso:["concat","det","diag","identity","inv","ones","range","size","squeeze","subset","trace","zeros"]};var I_={name:"det",category:"Matrix",syntax:["det(x)"],description:"Calculate the determinant of a matrix",examples:["det([1, 2; 3, 4])","det([-2, 2, 3; -1, 1, 3; 2, 0, -1])"],seealso:["concat","diag","identity","inv","ones","range","size","squeeze","subset","trace","transpose","zeros"]};var R_={name:"diag",category:"Matrix",syntax:["diag(x)","diag(x, k)"],description:"Create a diagonal matrix or retrieve the diagonal of a matrix. When x is a vector, a matrix with the vector values on the diagonal will be returned. When x is a matrix, a vector with the diagonal values of the matrix is returned. When k is provided, the k-th diagonal will be filled in or retrieved, if k is positive, the values are placed on the super diagonal. When k is negative, the values are placed on the sub diagonal.",examples:["diag(1:3)","diag(1:3, 1)","a = [1, 2, 3; 4, 5, 6; 7, 8, 9]","diag(a)"],seealso:["concat","det","identity","inv","ones","range","size","squeeze","subset","trace","transpose","zeros"]};var k_={name:"diff",category:"Matrix",syntax:["diff(arr)","diff(arr, dim)"],description:["Create a new matrix or array with the difference of the passed matrix or array.","Dim parameter is optional and used to indicant the dimension of the array/matrix to apply the difference","If no dimension parameter is passed it is assumed as dimension 0","Dimension is zero-based in javascript and one-based in the parser","Arrays must be 'rectangular' meaning arrays like [1, 2]","If something is passed as a matrix it will be returned as a matrix but other than that all matrices are converted to arrays"],examples:["A = [1, 2, 4, 7, 0]","diff(A)","diff(A, 1)","B = [[1, 2], [3, 4]]","diff(B)","diff(B, 1)","diff(B, 2)","diff(B, bignumber(2))","diff([[1, 2], matrix([3, 4])], 2)"],seealso:["subtract","partitionSelect"]};var q_={name:"dot",category:"Matrix",syntax:["dot(A, B)","A * B"],description:"Calculate the dot product of two vectors. The dot product of A = [a1, a2, a3, ..., an] and B = [b1, b2, b3, ..., bn] is defined as dot(A, B) = a1 * b1 + a2 * b2 + a3 * b3 + ... + an * bn",examples:["dot([2, 4, 1], [2, 2, 3])","[2, 4, 1] * [2, 2, 3]"],seealso:["multiply","cross"]};var L_={name:"eigs",category:"Matrix",syntax:["eigs(x)"],description:"Calculate the eigenvalues and optionally eigenvectors of a square matrix",examples:["eigs([[5, 2.3], [2.3, 1]])","eigs([[1, 2, 3], [4, 5, 6], [7, 8, 9]], { precision: 1e-6, eigenvectors: false })"],seealso:["inv"]};var z_={name:"filter",category:"Matrix",syntax:["filter(x, test)"],description:"Filter items in a matrix.",examples:["isPositive(x) = x > 0","filter([6, -2, -1, 4, 3], isPositive)","filter([6, -2, 0, 1, 0], x != 0)"],seealso:["sort","map","forEach"]};var U_={name:"flatten",category:"Matrix",syntax:["flatten(x)"],description:"Flatten a multi dimensional matrix into a single dimensional matrix.",examples:["a = [1, 2, 3; 4, 5, 6]","size(a)","b = flatten(a)","size(b)"],seealso:["concat","resize","size","squeeze"]};var W_={name:"forEach",category:"Matrix",syntax:["forEach(x, callback)"],description:"Iterates over all elements of a matrix/array, and executes the given callback function.",examples:["numberOfPets = {}","addPet(n) = numberOfPets[n] = (numberOfPets[n] ? numberOfPets[n]:0 ) + 1;",'forEach(["Dog","Cat","Cat"], addPet)',"numberOfPets"],seealso:["map","sort","filter"]};var Y_={name:"getMatrixDataType",category:"Matrix",syntax:["getMatrixDataType(x)"],description:'Find the data type of all elements in a matrix or array, for example "number" if all items are a number and "Complex" if all values are complex numbers. If a matrix contains more than one data type, it will return "mixed".',examples:["getMatrixDataType([1, 2, 3])","getMatrixDataType([[5 cm], [2 inch]])",'getMatrixDataType([1, "text"])',"getMatrixDataType([1, bignumber(4)])"],seealso:["matrix","sparse","typeOf"]};var H_={name:"identity",category:"Matrix",syntax:["identity(n)","identity(m, n)","identity([m, n])"],description:"Returns the identity matrix with size m-by-n. The matrix has ones on the diagonal and zeros elsewhere.",examples:["identity(3)","identity(3, 5)","a = [1, 2, 3; 4, 5, 6]","identity(size(a))"],seealso:["concat","det","diag","inv","ones","range","size","squeeze","subset","trace","transpose","zeros"]};var $_={name:"inv",category:"Matrix",syntax:["inv(x)"],description:"Calculate the inverse of a matrix",examples:["inv([1, 2; 3, 4])","inv(4)","1 / 4"],seealso:["concat","det","diag","identity","ones","range","size","squeeze","subset","trace","transpose","zeros"]};var G_={name:"pinv",category:"Matrix",syntax:["pinv(x)"],description:"Calculate the Moore\\u2013Penrose inverse of a matrix",examples:["pinv([1, 2; 3, 4])","pinv([[1, 0], [0, 1], [0, 1]])","pinv(4)"],seealso:["inv"]};var V_={name:"kron",category:"Matrix",syntax:["kron(x, y)"],description:"Calculates the kronecker product of 2 matrices or vectors.",examples:["kron([[1, 0], [0, 1]], [[1, 2], [3, 4]])","kron([1,1], [2,3,4])"],seealso:["multiply","dot","cross"]};var Z_={name:"map",category:"Matrix",syntax:["map(x, callback)"],description:"Create a new matrix or array with the results of the callback function executed on each entry of the matrix/array.",examples:["map([1, 2, 3], square)"],seealso:["filter","forEach"]};var Q_={name:"matrixFromColumns",category:"Matrix",syntax:["matrixFromColumns(...arr)","matrixFromColumns(row1, row2)","matrixFromColumns(row1, row2, row3)"],description:"Create a dense matrix from vectors as individual columns.",examples:["matrixFromColumns([1, 2, 3], [[4],[5],[6]])"],seealso:["matrix","matrixFromRows","matrixFromFunction","zeros"]};var X_={name:"matrixFromFunction",category:"Matrix",syntax:["matrixFromFunction(size, fn)","matrixFromFunction(size, fn, format)","matrixFromFunction(size, fn, format, datatype)","matrixFromFunction(size, format, fn)","matrixFromFunction(size, format, datatype, fn)"],description:"Create a matrix by evaluating a generating function at each index.",examples:["f(I) = I[1] - I[2]","matrixFromFunction([3,3], f)","g(I) = I[1] - I[2] == 1 ? 4 : 0",'matrixFromFunction([100, 100], "sparse", g)',"matrixFromFunction([5], random)"],seealso:["matrix","matrixFromRows","matrixFromColumns","zeros"]};var J_={name:"matrixFromRows",category:"Matrix",syntax:["matrixFromRows(...arr)","matrixFromRows(row1, row2)","matrixFromRows(row1, row2, row3)"],description:"Create a dense matrix from vectors as individual rows.",examples:["matrixFromRows([1, 2, 3], [[4],[5],[6]])"],seealso:["matrix","matrixFromColumns","matrixFromFunction","zeros"]};var K_={name:"ones",category:"Matrix",syntax:["ones(m)","ones(m, n)","ones(m, n, p, ...)","ones([m])","ones([m, n])","ones([m, n, p, ...])"],description:"Create a matrix containing ones.",examples:["ones(3)","ones(3, 5)","ones([2,3]) * 4.5","a = [1, 2, 3; 4, 5, 6]","ones(size(a))"],seealso:["concat","det","diag","identity","inv","range","size","squeeze","subset","trace","transpose","zeros"]};var j_={name:"partitionSelect",category:"Matrix",syntax:["partitionSelect(x, k)","partitionSelect(x, k, compare)"],description:"Partition-based selection of an array or 1D matrix. Will find the kth smallest value, and mutates the input array. Uses Quickselect.",examples:["partitionSelect([5, 10, 1], 2)",'partitionSelect(["C", "B", "A", "D"], 1, compareText)',"arr = [5, 2, 1]","partitionSelect(arr, 0) # returns 1, arr is now: [1, 2, 5]","arr","partitionSelect(arr, 1, 'desc') # returns 2, arr is now: [5, 2, 1]","arr"],seealso:["sort"]};var eO={name:"range",category:"Type",syntax:["start:end","start:step:end","range(start, end)","range(start, end, step)","range(string)"],description:"Create a range. Lower bound of the range is included, upper bound is excluded.",examples:["1:5","3:-1:-3","range(3, 7)","range(0, 12, 2)",'range("4:10")',"range(1m, 1m, 3m)","a = [1, 2, 3, 4; 5, 6, 7, 8]","a[1:2, 1:2]"],seealso:["concat","det","diag","identity","inv","ones","size","squeeze","subset","trace","transpose","zeros"]};var rO={name:"reshape",category:"Matrix",syntax:["reshape(x, sizes)"],description:"Reshape a multi dimensional array to fit the specified dimensions.",examples:["reshape([1, 2, 3, 4, 5, 6], [2, 3])","reshape([[1, 2], [3, 4]], [1, 4])","reshape([[1, 2], [3, 4]], [4])","reshape([1, 2, 3, 4], [-1, 2])"],seealso:["size","squeeze","resize"]};var tO={name:"resize",category:"Matrix",syntax:["resize(x, size)","resize(x, size, defaultValue)"],description:"Resize a matrix.",examples:["resize([1,2,3,4,5], [3])","resize([1,2,3], [5])","resize([1,2,3], [5], -1)","resize(2, [2, 3])",'resize("hello", [8], "!")'],seealso:["size","subset","squeeze","reshape"]};var nO={name:"rotate",category:"Matrix",syntax:["rotate(w, theta)","rotate(w, theta, v)"],description:"Returns a 2-D rotation matrix (2x2) for a given angle (in radians). Returns a 2-D rotation matrix (3x3) of a given angle (in radians) around given axis.",examples:["rotate([1, 0], pi / 2)",'rotate(matrix([1, 0]), unit("35deg"))','rotate([1, 0, 0], unit("90deg"), [0, 0, 1])','rotate(matrix([1, 0, 0]), unit("90deg"), matrix([0, 0, 1]))'],seealso:["matrix","rotationMatrix"]};var aO={name:"rotationMatrix",category:"Matrix",syntax:["rotationMatrix(theta)","rotationMatrix(theta, v)","rotationMatrix(theta, v, format)"],description:"Returns a 2-D rotation matrix (2x2) for a given angle (in radians). Returns a 2-D rotation matrix (3x3) of a given angle (in radians) around given axis.",examples:["rotationMatrix(pi / 2)",'rotationMatrix(unit("45deg"), [0, 0, 1])','rotationMatrix(1, matrix([0, 0, 1]), "sparse")'],seealso:["cos","sin"]};var iO={name:"row",category:"Matrix",syntax:["row(x, index)"],description:"Return a row from a matrix or array.",examples:["A = [[1, 2], [3, 4]]","row(A, 1)","row(A, 2)"],seealso:["column","matrixFromRows"]};var oO={name:"size",category:"Matrix",syntax:["size(x)"],description:"Calculate the size of a matrix.",examples:["size(2.3)",'size("hello world")',"a = [1, 2; 3, 4; 5, 6]","size(a)","size(1:6)"],seealso:["concat","count","det","diag","identity","inv","ones","range","squeeze","subset","trace","transpose","zeros"]};var sO={name:"sort",category:"Matrix",syntax:["sort(x)","sort(x, compare)"],description:'Sort the items in a matrix. Compare can be a string "asc", "desc", "natural", or a custom sort function.',examples:["sort([5, 10, 1])",'sort(["C", "B", "A", "D"], "natural")',"sortByLength(a, b) = size(a)[1] - size(b)[1]",'sort(["Langdon", "Tom", "Sara"], sortByLength)','sort(["10", "1", "2"], "natural")'],seealso:["map","filter","forEach"]};var uO={name:"squeeze",category:"Matrix",syntax:["squeeze(x)"],description:"Remove inner and outer singleton dimensions from a matrix.",examples:["a = zeros(3,2,1)","size(squeeze(a))","b = zeros(1,1,3)","size(squeeze(b))"],seealso:["concat","det","diag","identity","inv","ones","range","size","subset","trace","transpose","zeros"]};var fO={name:"subset",category:"Matrix",syntax:["value(index)","value(index) = replacement","subset(value, [index])","subset(value, [index], replacement)"],description:"Get or set a subset of the entries of a matrix or characters of a string. Indexes are one-based. There should be one index specification for each dimension of the target. Each specification can be a single index, a list of indices, or a range in colon notation \`l:u\`. In a range, both the lower bound l and upper bound u are included; and if a bound is omitted it defaults to the most extreme valid value. The cartesian product of the indices specified in each dimension determines the target of the operation.",examples:["d = [1, 2; 3, 4]","e = []","e[1, 1:2] = [5, 6]","e[2, :] = [7, 8]","f = d * e","f[2, 1]","f[:, 1]","f[[1,2], [1,3]] = [9, 10; 11, 12]","f"],seealso:["concat","det","diag","identity","inv","ones","range","size","squeeze","trace","transpose","zeros"]};var cO={name:"trace",category:"Matrix",syntax:["trace(A)"],description:"Calculate the trace of a matrix: the sum of the elements on the main diagonal of a square matrix.",examples:["A = [1, 2, 3; -1, 2, 3; 2, 0, 3]","trace(A)"],seealso:["concat","det","diag","identity","inv","ones","range","size","squeeze","subset","transpose","zeros"]};var lO={name:"transpose",category:"Matrix",syntax:["x'","transpose(x)"],description:"Transpose a matrix",examples:["a = [1, 2, 3; 4, 5, 6]","a'","transpose(a)"],seealso:["concat","det","diag","identity","inv","ones","range","size","squeeze","subset","trace","zeros"]};var mO={name:"zeros",category:"Matrix",syntax:["zeros(m)","zeros(m, n)","zeros(m, n, p, ...)","zeros([m])","zeros([m, n])","zeros([m, n, p, ...])"],description:"Create a matrix containing zeros.",examples:["zeros(3)","zeros(3, 5)","a = [1, 2, 3; 4, 5, 6]","zeros(size(a))"],seealso:["concat","det","diag","identity","inv","ones","range","size","squeeze","subset","trace","transpose"]};var pO={name:"fft",category:"Matrix",syntax:["fft(x)"],description:"Calculate N-dimensional fourier transform",examples:["fft([[1, 0], [1, 0]])"],seealso:["ifft"]};var dO={name:"ifft",category:"Matrix",syntax:["ifft(x)"],description:"Calculate N-dimensional inverse fourier transform",examples:["ifft([[2, 2], [0, 0]])"],seealso:["fft"]};var hO={name:"combinations",category:"Probability",syntax:["combinations(n, k)"],description:"Compute the number of combinations of n items taken k at a time",examples:["combinations(7, 5)"],seealso:["combinationsWithRep","permutations","factorial"]};var vO={name:"combinationsWithRep",category:"Probability",syntax:["combinationsWithRep(n, k)"],description:"Compute the number of combinations of n items taken k at a time with replacements.",examples:["combinationsWithRep(7, 5)"],seealso:["combinations","permutations","factorial"]};var gO={name:"factorial",category:"Probability",syntax:["n!","factorial(n)"],description:"Compute the factorial of a value",examples:["5!","5 * 4 * 3 * 2 * 1","3!"],seealso:["combinations","combinationsWithRep","permutations","gamma"]};var xO={name:"gamma",category:"Probability",syntax:["gamma(n)"],description:"Compute the gamma function. For small values, the Lanczos approximation is used, and for large values the extended Stirling approximation.",examples:["gamma(4)","3!","gamma(1/2)","sqrt(pi)"],seealso:["factorial"]};var yO={name:"lgamma",category:"Probability",syntax:["lgamma(n)"],description:"Logarithm of the gamma function for real, positive numbers and complex numbers, using Lanczos approximation for numbers and Stirling series for complex numbers.",examples:["lgamma(4)","lgamma(1/2)","lgamma(i)","lgamma(complex(1.1, 2))"],seealso:["gamma"]};var bO={name:"kldivergence",category:"Probability",syntax:["kldivergence(x, y)"],description:"Calculate the Kullback-Leibler (KL) divergence between two distributions.",examples:["kldivergence([0.7,0.5,0.4], [0.2,0.9,0.5])"],seealso:[]};var wO={name:"multinomial",category:"Probability",syntax:["multinomial(A)"],description:"Multinomial Coefficients compute the number of ways of picking a1, a2, ..., ai unordered outcomes from \`n\` possibilities. multinomial takes one array of integers as an argument. The following condition must be enforced: every ai > 0.",examples:["multinomial([1, 2, 1])"],seealso:["combinations","factorial"]};var DO={name:"permutations",category:"Probability",syntax:["permutations(n)","permutations(n, k)"],description:"Compute the number of permutations of n items taken k at a time",examples:["permutations(5)","permutations(5, 3)"],seealso:["combinations","combinationsWithRep","factorial"]};var SO={name:"pickRandom",category:"Probability",syntax:["pickRandom(array)","pickRandom(array, number)","pickRandom(array, weights)","pickRandom(array, number, weights)","pickRandom(array, weights, number)"],description:"Pick a random entry from a given array.",examples:["pickRandom(0:10)","pickRandom([1, 3, 1, 6])","pickRandom([1, 3, 1, 6], 2)","pickRandom([1, 3, 1, 6], [2, 3, 2, 1])","pickRandom([1, 3, 1, 6], 2, [2, 3, 2, 1])","pickRandom([1, 3, 1, 6], [2, 3, 2, 1], 2)"],seealso:["random","randomInt"]};var NO={name:"random",category:"Probability",syntax:["random()","random(max)","random(min, max)","random(size)","random(size, max)","random(size, min, max)"],description:"Return a random number.",examples:["random()","random(10, 20)","random([2, 3])"],seealso:["pickRandom","randomInt"]};var AO={name:"randomInt",category:"Probability",syntax:["randomInt(max)","randomInt(min, max)","randomInt(size)","randomInt(size, max)","randomInt(size, min, max)"],description:"Return a random integer number",examples:["randomInt(10, 20)","randomInt([2, 3], 10)"],seealso:["pickRandom","random"]};var MO={name:"compare",category:"Relational",syntax:["compare(x, y)"],description:"Compare two values. Returns 1 when x > y, -1 when x < y, and 0 when x == y.",examples:["compare(2, 3)","compare(3, 2)","compare(2, 2)","compare(5cm, 40mm)","compare(2, [1, 2, 3])"],seealso:["equal","unequal","smaller","smallerEq","largerEq","compareNatural","compareText"]};var CO={name:"compareNatural",category:"Relational",syntax:["compareNatural(x, y)"],description:"Compare two values of any type in a deterministic, natural way. Returns 1 when x > y, -1 when x < y, and 0 when x == y.",examples:["compareNatural(2, 3)","compareNatural(3, 2)","compareNatural(2, 2)","compareNatural(5cm, 40mm)",'compareNatural("2", "10")',"compareNatural(2 + 3i, 2 + 4i)","compareNatural([1, 2, 4], [1, 2, 3])","compareNatural([1, 5], [1, 2, 3])","compareNatural([1, 2], [1, 2])","compareNatural({a: 2}, {a: 4})"],seealso:["equal","unequal","smaller","smallerEq","largerEq","compare","compareText"]};var EO={name:"compareText",category:"Relational",syntax:["compareText(x, y)"],description:"Compare two strings lexically. Comparison is case sensitive. Returns 1 when x > y, -1 when x < y, and 0 when x == y.",examples:['compareText("B", "A")','compareText("A", "B")','compareText("A", "A")','compareText("2", "10")','compare("2", "10")',"compare(2, 10)",'compareNatural("2", "10")','compareText("B", ["A", "B", "C"])'],seealso:["compare","compareNatural"]};var TO={name:"deepEqual",category:"Relational",syntax:["deepEqual(x, y)"],description:"Check equality of two matrices element wise. Returns true if the size of both matrices is equal and when and each of the elements are equal.",examples:["deepEqual([1,3,4], [1,3,4])","deepEqual([1,3,4], [1,3])"],seealso:["equal","unequal","smaller","larger","smallerEq","largerEq","compare"]};var FO={name:"equal",category:"Relational",syntax:["x == y","equal(x, y)"],description:"Check equality of two values. Returns true if the values are equal, and false if not.",examples:["2+2 == 3","2+2 == 4","a = 3.2","b = 6-2.8","a == b","50cm == 0.5m"],seealso:["unequal","smaller","larger","smallerEq","largerEq","compare","deepEqual","equalText"]};var _O={name:"equalText",category:"Relational",syntax:["equalText(x, y)"],description:"Check equality of two strings. Comparison is case sensitive. Returns true if the values are equal, and false if not.",examples:['equalText("Hello", "Hello")','equalText("a", "A")','equal("2e3", "2000")','equalText("2e3", "2000")','equalText("B", ["A", "B", "C"])'],seealso:["compare","compareNatural","compareText","equal"]};var OO={name:"larger",category:"Relational",syntax:["x > y","larger(x, y)"],description:"Check if value x is larger than y. Returns true if x is larger than y, and false if not.",examples:["2 > 3","5 > 2*2","a = 3.3","b = 6-2.8","(a > b)","(b < a)","5 cm > 2 inch"],seealso:["equal","unequal","smaller","smallerEq","largerEq","compare"]};var BO={name:"largerEq",category:"Relational",syntax:["x >= y","largerEq(x, y)"],description:"Check if value x is larger or equal to y. Returns true if x is larger or equal to y, and false if not.",examples:["2 >= 1+1","2 > 1+1","a = 3.2","b = 6-2.8","(a >= b)"],seealso:["equal","unequal","smallerEq","smaller","compare"]};var PO={name:"smaller",category:"Relational",syntax:["x < y","smaller(x, y)"],description:"Check if value x is smaller than value y. Returns true if x is smaller than y, and false if not.",examples:["2 < 3","5 < 2*2","a = 3.3","b = 6-2.8","(a < b)","5 cm < 2 inch"],seealso:["equal","unequal","larger","smallerEq","largerEq","compare"]};var IO={name:"smallerEq",category:"Relational",syntax:["x <= y","smallerEq(x, y)"],description:"Check if value x is smaller or equal to value y. Returns true if x is smaller than y, and false if not.",examples:["2 <= 1+1","2 < 1+1","a = 3.2","b = 6-2.8","(a <= b)"],seealso:["equal","unequal","larger","smaller","largerEq","compare"]};var RO={name:"unequal",category:"Relational",syntax:["x != y","unequal(x, y)"],description:"Check unequality of two values. Returns true if the values are unequal, and false if they are equal.",examples:["2+2 != 3","2+2 != 4","a = 3.2","b = 6-2.8","a != b","50cm != 0.5m","5 cm != 2 inch"],seealso:["equal","smaller","larger","smallerEq","largerEq","compare","deepEqual"]};var kO={name:"setCartesian",category:"Set",syntax:["setCartesian(set1, set2)"],description:"Create the cartesian product of two (multi)sets. Multi-dimension arrays will be converted to single-dimension arrays and the values will be sorted in ascending order before the operation.",examples:["setCartesian([1, 2], [3, 4])"],seealso:["setUnion","setIntersect","setDifference","setPowerset"]};var qO={name:"setDifference",category:"Set",syntax:["setDifference(set1, set2)"],description:"Create the difference of two (multi)sets: every element of set1, that is not the element of set2. Multi-dimension arrays will be converted to single-dimension arrays before the operation.",examples:["setDifference([1, 2, 3, 4], [3, 4, 5, 6])","setDifference([[1, 2], [3, 4]], [[3, 4], [5, 6]])"],seealso:["setUnion","setIntersect","setSymDifference"]};var LO={name:"setDistinct",category:"Set",syntax:["setDistinct(set)"],description:"Collect the distinct elements of a multiset. A multi-dimension array will be converted to a single-dimension array before the operation.",examples:["setDistinct([1, 1, 1, 2, 2, 3])"],seealso:["setMultiplicity"]};var zO={name:"setIntersect",category:"Set",syntax:["setIntersect(set1, set2)"],description:"Create the intersection of two (multi)sets. Multi-dimension arrays will be converted to single-dimension arrays before the operation.",examples:["setIntersect([1, 2, 3, 4], [3, 4, 5, 6])","setIntersect([[1, 2], [3, 4]], [[3, 4], [5, 6]])"],seealso:["setUnion","setDifference"]};var UO={name:"setIsSubset",category:"Set",syntax:["setIsSubset(set1, set2)"],description:"Check whether a (multi)set is a subset of another (multi)set: every element of set1 is the element of set2. Multi-dimension arrays will be converted to single-dimension arrays before the operation.",examples:["setIsSubset([1, 2], [3, 4, 5, 6])","setIsSubset([3, 4], [3, 4, 5, 6])"],seealso:["setUnion","setIntersect","setDifference"]};var WO={name:"setMultiplicity",category:"Set",syntax:["setMultiplicity(element, set)"],description:"Count the multiplicity of an element in a multiset. A multi-dimension array will be converted to a single-dimension array before the operation.",examples:["setMultiplicity(1, [1, 2, 2, 4])","setMultiplicity(2, [1, 2, 2, 4])"],seealso:["setDistinct","setSize"]};var YO={name:"setPowerset",category:"Set",syntax:["setPowerset(set)"],description:"Create the powerset of a (multi)set: the powerset contains very possible subsets of a (multi)set. A multi-dimension array will be converted to a single-dimension array before the operation.",examples:["setPowerset([1, 2, 3])"],seealso:["setCartesian"]};var HO={name:"setSize",category:"Set",syntax:["setSize(set)","setSize(set, unique)"],description:'Count the number of elements of a (multi)set. When the second parameter "unique" is true, count only the unique values. A multi-dimension array will be converted to a single-dimension array before the operation.',examples:["setSize([1, 2, 2, 4])","setSize([1, 2, 2, 4], true)"],seealso:["setUnion","setIntersect","setDifference"]};var $O={name:"setSymDifference",category:"Set",syntax:["setSymDifference(set1, set2)"],description:"Create the symmetric difference of two (multi)sets. Multi-dimension arrays will be converted to single-dimension arrays before the operation.",examples:["setSymDifference([1, 2, 3, 4], [3, 4, 5, 6])","setSymDifference([[1, 2], [3, 4]], [[3, 4], [5, 6]])"],seealso:["setUnion","setIntersect","setDifference"]};var GO={name:"setUnion",category:"Set",syntax:["setUnion(set1, set2)"],description:"Create the union of two (multi)sets. Multi-dimension arrays will be converted to single-dimension arrays before the operation.",examples:["setUnion([1, 2, 3, 4], [3, 4, 5, 6])","setUnion([[1, 2], [3, 4]], [[3, 4], [5, 6]])"],seealso:["setIntersect","setDifference"]};var VO={name:"zpk2tf",category:"Signal",syntax:["zpk2tf(z, p, k)"],description:"Compute the transfer function of a zero-pole-gain model.",examples:["zpk2tf([1, 2], [-1, -2], 1)","zpk2tf([1, 2], [-1, -2])","zpk2tf([1 - 3i, 2 + 2i], [-1, -2])"],seealso:[]};var ZO={name:"freqz",category:"Signal",syntax:["freqz(b, a)","freqz(b, a, w)"],description:"Calculates the frequency response of a filter given its numerator and denominator coefficients.",examples:["freqz([1, 2], [1, 2, 3])","freqz([1, 2], [1, 2, 3], [0, 1])","freqz([1, 2], [1, 2, 3], 512)"],seealso:[]};var QO={name:"erf",category:"Special",syntax:["erf(x)"],description:"Compute the erf function of a value using a rational Chebyshev approximations for different intervals of x",examples:["erf(0.2)","erf(-0.5)","erf(4)"],seealso:[]};var XO={name:"zeta",category:"Special",syntax:["zeta(s)"],description:"Compute the Riemann Zeta Function using an infinite series and Riemanns Functional Equation for the entire complex plane",examples:["zeta(0.2)","zeta(-0.5)","zeta(4)"],seealso:[]};var JO={name:"mad",category:"Statistics",syntax:["mad(a, b, c, ...)","mad(A)"],description:"Compute the median absolute deviation of a matrix or a list with values. The median absolute deviation is defined as the median of the absolute deviations from the median.",examples:["mad(10, 20, 30)","mad([1, 2, 3])"],seealso:["mean","median","std","abs"]};var KO={name:"max",category:"Statistics",syntax:["max(a, b, c, ...)","max(A)","max(A, dimension)"],description:"Compute the maximum value of a list of values.",examples:["max(2, 3, 4, 1)","max([2, 3, 4, 1])","max([2, 5; 4, 3])","max([2, 5; 4, 3], 1)","max([2, 5; 4, 3], 2)","max(2.7, 7.1, -4.5, 2.0, 4.1)","min(2.7, 7.1, -4.5, 2.0, 4.1)"],seealso:["mean","median","min","prod","std","sum","variance"]};var jO={name:"mean",category:"Statistics",syntax:["mean(a, b, c, ...)","mean(A)","mean(A, dimension)"],description:"Compute the arithmetic mean of a list of values.",examples:["mean(2, 3, 4, 1)","mean([2, 3, 4, 1])","mean([2, 5; 4, 3])","mean([2, 5; 4, 3], 1)","mean([2, 5; 4, 3], 2)","mean([1.0, 2.7, 3.2, 4.0])"],seealso:["max","median","min","prod","std","sum","variance"]};var e3={name:"median",category:"Statistics",syntax:["median(a, b, c, ...)","median(A)"],description:"Compute the median of all values. The values are sorted and the middle value is returned. In case of an even number of values, the average of the two middle values is returned.",examples:["median(5, 2, 7)","median([3, -1, 5, 7])"],seealso:["max","mean","min","prod","std","sum","variance","quantileSeq"]};var r3={name:"min",category:"Statistics",syntax:["min(a, b, c, ...)","min(A)","min(A, dimension)"],description:"Compute the minimum value of a list of values.",examples:["min(2, 3, 4, 1)","min([2, 3, 4, 1])","min([2, 5; 4, 3])","min([2, 5; 4, 3], 1)","min([2, 5; 4, 3], 2)","min(2.7, 7.1, -4.5, 2.0, 4.1)","max(2.7, 7.1, -4.5, 2.0, 4.1)"],seealso:["max","mean","median","prod","std","sum","variance"]};var t3={name:"mode",category:"Statistics",syntax:["mode(a, b, c, ...)","mode(A)","mode(A, a, b, B, c, ...)"],description:"Computes the mode of all values as an array. In case mode being more than one, multiple values are returned in an array.",examples:["mode(2, 1, 4, 3, 1)","mode([1, 2.7, 3.2, 4, 2.7])","mode(1, 4, 6, 1, 6)"],seealso:["max","mean","min","median","prod","std","sum","variance"]};var n3={name:"prod",category:"Statistics",syntax:["prod(a, b, c, ...)","prod(A)"],description:"Compute the product of all values.",examples:["prod(2, 3, 4)","prod([2, 3, 4])","prod([2, 5; 4, 3])"],seealso:["max","mean","min","median","min","std","sum","variance"]};var a3={name:"quantileSeq",category:"Statistics",syntax:["quantileSeq(A, prob[, sorted])","quantileSeq(A, [prob1, prob2, ...][, sorted])","quantileSeq(A, N[, sorted])"],description:\`Compute the prob order quantile of a matrix or a list with values. The sequence is sorted and the middle value is returned. Supported types of sequence values are: Number, BigNumber, Unit Supported types of probablity are: Number, BigNumber. + +In case of a (multi dimensional) array or matrix, the prob order quantile of all elements will be calculated.\`,examples:["quantileSeq([3, -1, 5, 7], 0.5)","quantileSeq([3, -1, 5, 7], [1/3, 2/3])","quantileSeq([3, -1, 5, 7], 2)","quantileSeq([-1, 3, 5, 7], 0.5, true)"],seealso:["mean","median","min","max","prod","std","sum","variance"]};var i3={name:"std",category:"Statistics",syntax:["std(a, b, c, ...)","std(A)","std(A, dimension)","std(A, normalization)","std(A, dimension, normalization)"],description:'Compute the standard deviation of all values, defined as std(A) = sqrt(variance(A)). Optional parameter normalization can be "unbiased" (default), "uncorrected", or "biased".',examples:["std(2, 4, 6)","std([2, 4, 6, 8])",'std([2, 4, 6, 8], "uncorrected")','std([2, 4, 6, 8], "biased")',"std([1, 2, 3; 4, 5, 6])"],seealso:["max","mean","min","median","prod","sum","variance"]};var o3={name:"cumsum",category:"Statistics",syntax:["cumsum(a, b, c, ...)","cumsum(A)"],description:"Compute the cumulative sum of all values.",examples:["cumsum(2, 3, 4, 1)","cumsum([2, 3, 4, 1])","cumsum([1, 2; 3, 4])","cumsum([1, 2; 3, 4], 1)","cumsum([1, 2; 3, 4], 2)"],seealso:["max","mean","median","min","prod","std","sum","variance"]};var s3={name:"sum",category:"Statistics",syntax:["sum(a, b, c, ...)","sum(A)","sum(A, dimension)"],description:"Compute the sum of all values.",examples:["sum(2, 3, 4, 1)","sum([2, 3, 4, 1])","sum([2, 5; 4, 3])"],seealso:["max","mean","median","min","prod","std","sum","variance"]};var u3={name:"variance",category:"Statistics",syntax:["variance(a, b, c, ...)","variance(A)","variance(A, dimension)","variance(A, normalization)","variance(A, dimension, normalization)"],description:'Compute the variance of all values. Optional parameter normalization can be "unbiased" (default), "uncorrected", or "biased".',examples:["variance(2, 4, 6)","variance([2, 4, 6, 8])",'variance([2, 4, 6, 8], "uncorrected")','variance([2, 4, 6, 8], "biased")',"variance([1, 2, 3; 4, 5, 6])"],seealso:["max","mean","min","median","min","prod","std","sum"]};var f3={name:"corr",category:"Statistics",syntax:["corr(A,B)"],description:"Compute the correlation coefficient of a two list with values, For matrices, the matrix correlation coefficient is calculated.",examples:["corr([2, 4, 6, 8],[1, 2, 3, 6])","corr(matrix([[1, 2.2, 3, 4.8, 5], [1, 2, 3, 4, 5]]), matrix([[4, 5.3, 6.6, 7, 8], [1, 2, 3, 4, 5]]))"],seealso:["max","mean","min","median","min","prod","std","sum"]};var c3={name:"acos",category:"Trigonometry",syntax:["acos(x)"],description:"Compute the inverse cosine of a value in radians.",examples:["acos(0.5)","acos(cos(2.3))"],seealso:["cos","atan","asin"]};var l3={name:"acosh",category:"Trigonometry",syntax:["acosh(x)"],description:"Calculate the hyperbolic arccos of a value, defined as \`acosh(x) = ln(sqrt(x^2 - 1) + x)\`.",examples:["acosh(1.5)"],seealso:["cosh","asinh","atanh"]};var m3={name:"acot",category:"Trigonometry",syntax:["acot(x)"],description:"Calculate the inverse cotangent of a value.",examples:["acot(0.5)","acot(cot(0.5))","acot(2)"],seealso:["cot","atan"]};var p3={name:"acoth",category:"Trigonometry",syntax:["acoth(x)"],description:"Calculate the hyperbolic arccotangent of a value, defined as \`acoth(x) = (ln((x+1)/x) + ln(x/(x-1))) / 2\`.",examples:["acoth(2)","acoth(0.5)"],seealso:["acsch","asech"]};var d3={name:"acsc",category:"Trigonometry",syntax:["acsc(x)"],description:"Calculate the inverse cotangent of a value.",examples:["acsc(2)","acsc(csc(0.5))","acsc(0.5)"],seealso:["csc","asin","asec"]};var h3={name:"acsch",category:"Trigonometry",syntax:["acsch(x)"],description:"Calculate the hyperbolic arccosecant of a value, defined as \`acsch(x) = ln(1/x + sqrt(1/x^2 + 1))\`.",examples:["acsch(0.5)"],seealso:["asech","acoth"]};var v3={name:"asec",category:"Trigonometry",syntax:["asec(x)"],description:"Calculate the inverse secant of a value.",examples:["asec(0.5)","asec(sec(0.5))","asec(2)"],seealso:["acos","acot","acsc"]};var g3={name:"asech",category:"Trigonometry",syntax:["asech(x)"],description:"Calculate the inverse secant of a value.",examples:["asech(0.5)"],seealso:["acsch","acoth"]};var x3={name:"asin",category:"Trigonometry",syntax:["asin(x)"],description:"Compute the inverse sine of a value in radians.",examples:["asin(0.5)","asin(sin(0.5))"],seealso:["sin","acos","atan"]};var y3={name:"asinh",category:"Trigonometry",syntax:["asinh(x)"],description:"Calculate the hyperbolic arcsine of a value, defined as \`asinh(x) = ln(x + sqrt(x^2 + 1))\`.",examples:["asinh(0.5)"],seealso:["acosh","atanh"]};var b3={name:"atan",category:"Trigonometry",syntax:["atan(x)"],description:"Compute the inverse tangent of a value in radians.",examples:["atan(0.5)","atan(tan(0.5))"],seealso:["tan","acos","asin"]};var w3={name:"atan2",category:"Trigonometry",syntax:["atan2(y, x)"],description:"Computes the principal value of the arc tangent of y/x in radians.",examples:["atan2(2, 2) / pi","angle = 60 deg in rad","x = cos(angle)","y = sin(angle)","atan2(y, x)"],seealso:["sin","cos","tan"]};var D3={name:"atanh",category:"Trigonometry",syntax:["atanh(x)"],description:"Calculate the hyperbolic arctangent of a value, defined as \`atanh(x) = ln((1 + x)/(1 - x)) / 2\`.",examples:["atanh(0.5)"],seealso:["acosh","asinh"]};var S3={name:"cos",category:"Trigonometry",syntax:["cos(x)"],description:"Compute the cosine of x in radians.",examples:["cos(2)","cos(pi / 4) ^ 2","cos(180 deg)","cos(60 deg)","sin(0.2)^2 + cos(0.2)^2"],seealso:["acos","sin","tan"]};var N3={name:"cosh",category:"Trigonometry",syntax:["cosh(x)"],description:"Compute the hyperbolic cosine of x in radians.",examples:["cosh(0.5)"],seealso:["sinh","tanh","coth"]};var A3={name:"cot",category:"Trigonometry",syntax:["cot(x)"],description:"Compute the cotangent of x in radians. Defined as 1/tan(x)",examples:["cot(2)","1 / tan(2)"],seealso:["sec","csc","tan"]};var M3={name:"coth",category:"Trigonometry",syntax:["coth(x)"],description:"Compute the hyperbolic cotangent of x in radians.",examples:["coth(2)","1 / tanh(2)"],seealso:["sech","csch","tanh"]};var C3={name:"csc",category:"Trigonometry",syntax:["csc(x)"],description:"Compute the cosecant of x in radians. Defined as 1/sin(x)",examples:["csc(2)","1 / sin(2)"],seealso:["sec","cot","sin"]};var E3={name:"csch",category:"Trigonometry",syntax:["csch(x)"],description:"Compute the hyperbolic cosecant of x in radians. Defined as 1/sinh(x)",examples:["csch(2)","1 / sinh(2)"],seealso:["sech","coth","sinh"]};var T3={name:"sec",category:"Trigonometry",syntax:["sec(x)"],description:"Compute the secant of x in radians. Defined as 1/cos(x)",examples:["sec(2)","1 / cos(2)"],seealso:["cot","csc","cos"]};var F3={name:"sech",category:"Trigonometry",syntax:["sech(x)"],description:"Compute the hyperbolic secant of x in radians. Defined as 1/cosh(x)",examples:["sech(2)","1 / cosh(2)"],seealso:["coth","csch","cosh"]};var _3={name:"sin",category:"Trigonometry",syntax:["sin(x)"],description:"Compute the sine of x in radians.",examples:["sin(2)","sin(pi / 4) ^ 2","sin(90 deg)","sin(30 deg)","sin(0.2)^2 + cos(0.2)^2"],seealso:["asin","cos","tan"]};var O3={name:"sinh",category:"Trigonometry",syntax:["sinh(x)"],description:"Compute the hyperbolic sine of x in radians.",examples:["sinh(0.5)"],seealso:["cosh","tanh"]};var B3={name:"tan",category:"Trigonometry",syntax:["tan(x)"],description:"Compute the tangent of x in radians.",examples:["tan(0.5)","sin(0.5) / cos(0.5)","tan(pi / 4)","tan(45 deg)"],seealso:["atan","sin","cos"]};var P3={name:"tanh",category:"Trigonometry",syntax:["tanh(x)"],description:"Compute the hyperbolic tangent of x in radians.",examples:["tanh(0.5)","sinh(0.5) / cosh(0.5)"],seealso:["sinh","cosh"]};var I3={name:"to",category:"Units",syntax:["x to unit","to(x, unit)"],description:"Change the unit of a value.",examples:["5 inch to cm","3.2kg to g","16 bytes in bits"],seealso:[]};var R3={name:"bin",category:"Utils",syntax:["bin(value)"],description:"Format a number as binary",examples:["bin(2)"],seealso:["oct","hex"]};var k3={name:"clone",category:"Utils",syntax:["clone(x)"],description:"Clone a variable. Creates a copy of primitive variables,and a deep copy of matrices",examples:["clone(3.5)","clone(2 - 4i)","clone(45 deg)","clone([1, 2; 3, 4])",'clone("hello world")'],seealso:[]};var q3={name:"format",category:"Utils",syntax:["format(value)","format(value, precision)"],description:"Format a value of any type as string.",examples:["format(2.3)","format(3 - 4i)","format([])","format(pi, 3)"],seealso:["print"]};var L3={name:"hasNumericValue",category:"Utils",syntax:["hasNumericValue(x)"],description:"Test whether a value is an numeric value. In case of a string, true is returned if the string contains a numeric value.",examples:["hasNumericValue(2)",'hasNumericValue("2")','isNumeric("2")',"hasNumericValue(0)","hasNumericValue(bignumber(500))","hasNumericValue(fraction(0.125))","hasNumericValue(2 + 3i)",'hasNumericValue([2.3, "foo", false])'],seealso:["isInteger","isZero","isNegative","isPositive","isNaN","isNumeric"]};var z3={name:"hex",category:"Utils",syntax:["hex(value)"],description:"Format a number as hexadecimal",examples:["hex(240)"],seealso:["bin","oct"]};var U3={name:"isInteger",category:"Utils",syntax:["isInteger(x)"],description:"Test whether a value is an integer number.",examples:["isInteger(2)","isInteger(3.5)","isInteger([3, 0.5, -2])"],seealso:["isNegative","isNumeric","isPositive","isZero"]};var W3={name:"isNaN",category:"Utils",syntax:["isNaN(x)"],description:"Test whether a value is NaN (not a number)",examples:["isNaN(2)","isNaN(0 / 0)","isNaN(NaN)","isNaN(Infinity)"],seealso:["isNegative","isNumeric","isPositive","isZero"]};var Y3={name:"isNegative",category:"Utils",syntax:["isNegative(x)"],description:"Test whether a value is negative: smaller than zero.",examples:["isNegative(2)","isNegative(0)","isNegative(-4)","isNegative([3, 0.5, -2])"],seealso:["isInteger","isNumeric","isPositive","isZero"]};var H3={name:"isNumeric",category:"Utils",syntax:["isNumeric(x)"],description:"Test whether a value is a numeric value. Returns true when the input is a number, BigNumber, Fraction, or boolean.",examples:["isNumeric(2)",'isNumeric("2")','hasNumericValue("2")',"isNumeric(0)","isNumeric(bignumber(500))","isNumeric(fraction(0.125))","isNumeric(2 + 3i)",'isNumeric([2.3, "foo", false])'],seealso:["isInteger","isZero","isNegative","isPositive","isNaN","hasNumericValue"]};var $3={name:"isPositive",category:"Utils",syntax:["isPositive(x)"],description:"Test whether a value is positive: larger than zero.",examples:["isPositive(2)","isPositive(0)","isPositive(-4)","isPositive([3, 0.5, -2])"],seealso:["isInteger","isNumeric","isNegative","isZero"]};var G3={name:"isPrime",category:"Utils",syntax:["isPrime(x)"],description:"Test whether a value is prime: has no divisors other than itself and one.",examples:["isPrime(3)","isPrime(-2)","isPrime([2, 17, 100])"],seealso:["isInteger","isNumeric","isNegative","isZero"]};var V3={name:"isZero",category:"Utils",syntax:["isZero(x)"],description:"Test whether a value is zero.",examples:["isZero(2)","isZero(0)","isZero(-4)","isZero([3, 0, -2, 0])"],seealso:["isInteger","isNumeric","isNegative","isPositive"]};var Z3={name:"numeric",category:"Utils",syntax:["numeric(x)"],description:"Convert a numeric input to a specific numeric type: number, BigNumber, or Fraction.",examples:['numeric("4")','numeric("4", "number")','numeric("4", "BigNumber")','numeric("4", "Fraction")','numeric(4, "Fraction")','numeric(fraction(2, 5), "number")'],seealso:["number","fraction","bignumber","string","format"]};var Q3={name:"oct",category:"Utils",syntax:["oct(value)"],description:"Format a number as octal",examples:["oct(56)"],seealso:["bin","hex"]};var X3={name:"print",category:"Utils",syntax:["print(template, values)","print(template, values, precision)"],description:"Interpolate values into a string template.",examples:['print("Lucy is $age years old", {age: 5})','print("The value of pi is $pi", {pi: pi}, 3)','print("Hello, $user.name!", {user: {name: "John"}})','print("Values: $1, $2, $3", [6, 9, 4])'],seealso:["format"]};var J3={name:"typeOf",category:"Utils",syntax:["typeOf(x)"],description:"Get the type of a variable.",examples:["typeOf(3.5)","typeOf(2 - 4i)","typeOf(45 deg)",'typeOf("hello world")'],seealso:["getMatrixDataType"]};var K3={name:"solveODE",category:"Numeric",syntax:["solveODE(func, tspan, y0)","solveODE(func, tspan, y0, options)"],description:"Numerical Integration of Ordinary Differential Equations.",examples:["f(t,y) = y","tspan = [0, 4]","solveODE(f, tspan, 1)","solveODE(f, tspan, [1, 2])",'solveODE(f, tspan, 1, { method:"RK23", maxStep:0.1 })'],seealso:["derivative","simplifyCore"]};var j3={bignumber:YT,boolean:HT,complex:$T,createUnit:GT,fraction:VT,index:ZT,matrix:QT,number:XT,sparse:JT,splitUnit:KT,string:jT,unit:eF,e:DD,E:DD,false:ET,i:TT,Infinity:FT,LN2:OT,LN10:_T,LOG2E:PT,LOG10E:BT,NaN:IT,null:RT,pi:SD,PI:SD,phi:kT,SQRT1_2:qT,SQRT2:LT,tau:zT,true:UT,version:WT,speedOfLight:{description:"Speed of light in vacuum",examples:["speedOfLight"]},gravitationConstant:{description:"Newtonian constant of gravitation",examples:["gravitationConstant"]},planckConstant:{description:"Planck constant",examples:["planckConstant"]},reducedPlanckConstant:{description:"Reduced Planck constant",examples:["reducedPlanckConstant"]},magneticConstant:{description:"Magnetic constant (vacuum permeability)",examples:["magneticConstant"]},electricConstant:{description:"Electric constant (vacuum permeability)",examples:["electricConstant"]},vacuumImpedance:{description:"Characteristic impedance of vacuum",examples:["vacuumImpedance"]},coulomb:{description:"Coulomb's constant",examples:["coulomb"]},elementaryCharge:{description:"Elementary charge",examples:["elementaryCharge"]},bohrMagneton:{description:"Borh magneton",examples:["bohrMagneton"]},conductanceQuantum:{description:"Conductance quantum",examples:["conductanceQuantum"]},inverseConductanceQuantum:{description:"Inverse conductance quantum",examples:["inverseConductanceQuantum"]},magneticFluxQuantum:{description:"Magnetic flux quantum",examples:["magneticFluxQuantum"]},nuclearMagneton:{description:"Nuclear magneton",examples:["nuclearMagneton"]},klitzing:{description:"Von Klitzing constant",examples:["klitzing"]},bohrRadius:{description:"Borh radius",examples:["bohrRadius"]},classicalElectronRadius:{description:"Classical electron radius",examples:["classicalElectronRadius"]},electronMass:{description:"Electron mass",examples:["electronMass"]},fermiCoupling:{description:"Fermi coupling constant",examples:["fermiCoupling"]},fineStructure:{description:"Fine-structure constant",examples:["fineStructure"]},hartreeEnergy:{description:"Hartree energy",examples:["hartreeEnergy"]},protonMass:{description:"Proton mass",examples:["protonMass"]},deuteronMass:{description:"Deuteron Mass",examples:["deuteronMass"]},neutronMass:{description:"Neutron mass",examples:["neutronMass"]},quantumOfCirculation:{description:"Quantum of circulation",examples:["quantumOfCirculation"]},rydberg:{description:"Rydberg constant",examples:["rydberg"]},thomsonCrossSection:{description:"Thomson cross section",examples:["thomsonCrossSection"]},weakMixingAngle:{description:"Weak mixing angle",examples:["weakMixingAngle"]},efimovFactor:{description:"Efimov factor",examples:["efimovFactor"]},atomicMass:{description:"Atomic mass constant",examples:["atomicMass"]},avogadro:{description:"Avogadro's number",examples:["avogadro"]},boltzmann:{description:"Boltzmann constant",examples:["boltzmann"]},faraday:{description:"Faraday constant",examples:["faraday"]},firstRadiation:{description:"First radiation constant",examples:["firstRadiation"]},loschmidt:{description:"Loschmidt constant at T=273.15 K and p=101.325 kPa",examples:["loschmidt"]},gasConstant:{description:"Gas constant",examples:["gasConstant"]},molarPlanckConstant:{description:"Molar Planck constant",examples:["molarPlanckConstant"]},molarVolume:{description:"Molar volume of an ideal gas at T=273.15 K and p=101.325 kPa",examples:["molarVolume"]},sackurTetrode:{description:"Sackur-Tetrode constant at T=1 K and p=101.325 kPa",examples:["sackurTetrode"]},secondRadiation:{description:"Second radiation constant",examples:["secondRadiation"]},stefanBoltzmann:{description:"Stefan-Boltzmann constant",examples:["stefanBoltzmann"]},wienDisplacement:{description:"Wien displacement law constant",examples:["wienDisplacement"]},molarMass:{description:"Molar mass constant",examples:["molarMass"]},molarMassC12:{description:"Molar mass constant of carbon-12",examples:["molarMassC12"]},gravity:{description:"Standard acceleration of gravity (standard acceleration of free-fall on Earth)",examples:["gravity"]},planckLength:{description:"Planck length",examples:["planckLength"]},planckMass:{description:"Planck mass",examples:["planckMass"]},planckTime:{description:"Planck time",examples:["planckTime"]},planckCharge:{description:"Planck charge",examples:["planckCharge"]},planckTemperature:{description:"Planck temperature",examples:["planckTemperature"]},derivative:aF,lsolve:oF,lsolveAll:sF,lup:uF,lusolve:fF,leafCount:iF,polynomialRoot:cF,resolve:pF,simplify:dF,simplifyConstant:hF,simplifyCore:vF,symbolicEqual:xF,rationalize:mF,slu:gF,usolve:yF,usolveAll:bF,qr:lF,abs:wF,add:DF,cbrt:SF,ceil:NF,cube:AF,divide:MF,dotDivide:CF,dotMultiply:EF,dotPow:TF,exp:FF,expm:_F,expm1:OF,fix:BF,floor:PF,gcd:IF,hypot:RF,lcm:qF,log:LF,log2:WF,log1p:UF,log10:zF,mod:YF,multiply:HF,norm:$F,nthRoot:GF,nthRoots:VF,pow:ZF,round:QF,sign:XF,sqrt:JF,sqrtm:KF,square:t_,subtract:n_,unaryMinus:a_,unaryPlus:i_,xgcd:o_,invmod:kF,bitAnd:s_,bitNot:u_,bitOr:f_,bitXor:c_,leftShift:l_,rightArithShift:m_,rightLogShift:p_,bellNumbers:d_,catalan:h_,composition:v_,stirlingS2:g_,config:rF,import:tF,typed:nF,arg:x_,conj:y_,re:w_,im:b_,evaluate:D_,help:S_,distance:N_,intersect:A_,and:M_,not:C_,or:E_,xor:T_,concat:__,count:O_,cross:B_,column:F_,ctranspose:P_,det:I_,diag:R_,diff:k_,dot:q_,getMatrixDataType:Y_,identity:H_,filter:z_,flatten:U_,forEach:W_,inv:$_,pinv:G_,eigs:L_,kron:V_,matrixFromFunction:X_,matrixFromRows:J_,matrixFromColumns:Q_,map:Z_,ones:K_,partitionSelect:j_,range:eO,resize:tO,reshape:rO,rotate:nO,rotationMatrix:aO,row:iO,size:oO,sort:sO,squeeze:uO,subset:fO,trace:cO,transpose:lO,zeros:mO,fft:pO,ifft:dO,sylvester:jF,schur:e_,lyap:r_,solveODE:K3,combinations:hO,combinationsWithRep:vO,factorial:gO,gamma:xO,kldivergence:bO,lgamma:yO,multinomial:wO,permutations:DO,pickRandom:SO,random:NO,randomInt:AO,compare:MO,compareNatural:CO,compareText:EO,deepEqual:TO,equal:FO,equalText:_O,larger:OO,largerEq:BO,smaller:PO,smallerEq:IO,unequal:RO,setCartesian:kO,setDifference:qO,setDistinct:LO,setIntersect:zO,setIsSubset:UO,setMultiplicity:WO,setPowerset:YO,setSize:HO,setSymDifference:$O,setUnion:GO,zpk2tf:VO,freqz:ZO,erf:QO,zeta:XO,cumsum:o3,mad:JO,max:KO,mean:jO,median:e3,min:r3,mode:t3,prod:n3,quantileSeq:a3,std:i3,sum:s3,variance:u3,corr:f3,acos:c3,acosh:l3,acot:m3,acoth:p3,acsc:d3,acsch:h3,asec:v3,asech:g3,asin:x3,asinh:y3,atan:b3,atanh:D3,atan2:w3,cos:S3,cosh:N3,cot:A3,coth:M3,csc:C3,csch:E3,sec:T3,sech:F3,sin:_3,sinh:O3,tan:B3,tanh:P3,to:I3,clone:k3,format:q3,bin:R3,oct:Q3,hex:z3,isNaN:W3,isInteger:U3,isNegative:Y3,isNumeric:H3,hasNumericValue:L3,isPositive:$3,isPrime:G3,isZero:V3,print:X3,typeOf:J3,numeric:Z3};var eB="help",xG=["typed","mathWithTransform","Help"],hg=F(eB,xG,e=>{var{typed:r,mathWithTransform:t,Help:n}=e;return r(eB,{any:function(i){var u,l=i;if(typeof i!="string"){for(u in t)if(Xe(t,u)&&i===t[u]){l=u;break}}var c=wt(j3,l);if(!c){var o=typeof l=="function"?l.name:l;throw new Error('No documentation found on "'+o+'"')}return new n(c)}})});var rB="chain",yG=["typed","Chain"],vg=F(rB,yG,e=>{var{typed:r,Chain:t}=e;return r(rB,{"":function(){return new t},any:function(a){return new t(a)}})});var tB="det",bG=["typed","matrix","subtractScalar","multiply","divideScalar","isZero","unaryMinus"],gg=F(tB,bG,e=>{var{typed:r,matrix:t,subtractScalar:n,multiply:a,divideScalar:i,isZero:u,unaryMinus:l}=e;return r(tB,{any:function(s){return ar(s)},"Array | Matrix":function(s){var m;switch(Qe(s)?m=s.size():Array.isArray(s)?(s=t(s),m=s.size()):m=[],m.length){case 0:return ar(s);case 1:if(m[0]===1)return ar(s.valueOf()[0]);if(m[0]===0)return 1;throw new RangeError("Matrix must be square (size: "+lr(m)+")");case 2:{var d=m[0],h=m[1];if(d===h)return c(s.clone().valueOf(),d,h);if(h===0)return 1;throw new RangeError("Matrix must be square (size: "+lr(m)+")")}default:throw new RangeError("Matrix must be two dimensional (size: "+lr(m)+")")}}});function c(o,s,m){if(s===1)return ar(o[0][0]);if(s===2)return n(a(o[0][0],o[1][1]),a(o[1][0],o[0][1]));for(var d=!1,h=new Array(s).fill(0).map((O,_)=>_),x=0;x{var{typed:r,matrix:t,divideScalar:n,addScalar:a,multiply:i,unaryMinus:u,det:l,identity:c,abs:o}=e;return r(nB,{"Array | Matrix":function(d){var h=Qe(d)?d.size():ur(d);switch(h.length){case 1:if(h[0]===1)return Qe(d)?t([n(1,d.valueOf()[0])]):[n(1,d[0])];throw new RangeError("Matrix must be square (size: "+lr(h)+")");case 2:{var x=h[0],v=h[1];if(x===v)return Qe(d)?t(s(d.valueOf(),x,v),d.storage()):s(d,x,v);throw new RangeError("Matrix must be square (size: "+lr(h)+")")}default:throw new RangeError("Matrix must be two dimensional (size: "+lr(h)+")")}},any:function(d){return n(1,d)}});function s(m,d,h){var x,v,y,w,C;if(d===1){if(w=m[0][0],w===0)throw Error("Cannot calculate inverse, determinant is zero");return[[n(1,w)]]}else if(d===2){var b=l(m);if(b===0)throw Error("Cannot calculate inverse, determinant is zero");return[[n(m[1][1],b),n(u(m[0][1]),b)],[n(u(m[1][0]),b),n(m[0][0],b)]]}else{var M=m.concat();for(x=0;xO&&(O=o(M[x][S]),_=x),x++;if(O===0)throw Error("Cannot calculate inverse, determinant is zero");x=_,x!==S&&(C=M[S],M[S]=M[x],M[x]=C,C=A[S],A[S]=A[x],A[x]=C);var E=M[S],T=A[S];for(x=0;x{var{typed:r,matrix:t,inv:n,deepEqual:a,equal:i,dotDivide:u,dot:l,ctranspose:c,divideScalar:o,multiply:s,add:m,Complex:d}=e;return r(aB,{"Array | Matrix":function(b){var M=Qe(b)?b.size():ur(b);switch(M.length){case 1:return w(b)?c(b):M[0]===1?n(b):u(c(b),l(b,b));case 2:{if(w(b))return c(b);var A=M[0],S=M[1];if(A===S)try{return n(b)}catch(O){if(!(O instanceof Error&&O.message.match(/Cannot calculate inverse, determinant is zero/)))throw O}return Qe(b)?t(h(b.valueOf(),A,S),b.storage()):h(b,A,S)}default:throw new RangeError("Matrix must be two dimensional (size: "+lr(M)+")")}},any:function(b){return i(b,0)?ar(b):o(1,b)}});function h(C,b,M){var{C:A,F:S}=v(C,b,M),O=s(n(s(c(A),A)),c(A)),_=s(c(S),n(s(S,c(S))));return s(_,O)}function x(C,b,M){for(var A=ar(C),S=0,O=0;O_.filter((T,R)=>R!y(l(A[E],A[E])));return{C:S,F:O}}function y(C){return i(m(C,d(1,1)),m(0,d(1,1)))}function w(C){return a(m(C,d(1,1)),m(s(C,0),d(1,1)))}});function iB(e){var{addScalar:r,subtract:t,flatten:n,multiply:a,multiplyScalar:i,divideScalar:u,sqrt:l,abs:c,bignumber:o,diag:s,size:m,reshape:d,inv:h,qr:x,usolve:v,usolveAll:y,equal:w,complex:C,larger:b,smaller:M,matrixFromColumns:A,dot:S}=e;function O(ae,$,le,Ee){var me=arguments.length>4&&arguments[4]!==void 0?arguments[4]:!0,ge=_(ae,$,le,Ee,me);E(ae,$,le,Ee,me,ge);var{values:Se,C:xe}=T(ae,$,le,Ee,me);if(me){var be=R(ae,$,xe,ge,Se,le,Ee);return{values:Se,eigenvectors:be}}return{values:Se}}function _(ae,$,le,Ee,me){var ge=Ee==="BigNumber",Se=Ee==="Complex",xe=ge?o(0):0,be=ge?o(1):Se?C(1):1,De=ge?o(1):1,Ae=ge?o(10):2,We=i(Ae,Ae),Je;me&&(Je=Array($).fill(be));for(var J=!1;!J;){J=!0;for(var re=0;re<$;re++){for(var ye=xe,j=xe,ne=0;ne<$;ne++)re!==ne&&(ye=r(ye,c(ae[ne][re])),j=r(j,c(ae[re][ne])));if(!w(ye,0)&&!w(j,0)){for(var ue=De,Me=ye,Ce=u(j,Ae),Le=i(j,Ae);M(Me,Ce);)Me=i(Me,We),ue=i(ue,Ae);for(;b(Me,Le);)Me=u(Me,We),ue=u(ue,Ae);var Ie=M(u(r(Me,j),ue),i(r(ye,j),.95));if(Ie){J=!1;for(var fr=u(1,ue),or=0;or<$;or++)re!==or&&(ae[re][or]=i(ae[re][or],fr),ae[or][re]=i(ae[or][re],ue));me&&(Je[re]=i(Je[re],fr))}}}}return me?s(Je):null}function E(ae,$,le,Ee,me,ge){var Se=Ee==="BigNumber",xe=Ee==="Complex",be=Se?o(0):xe?C(0):0;Se&&(le=o(le));for(var De=0;De<$-2;De++){for(var Ae=0,We=be,Je=De+1;Je<$;Je++){var J=ae[Je][De];M(c(We),c(J))&&(We=J,Ae=Je)}if(!M(c(We),le)){if(Ae!==De+1){var re=ae[Ae];ae[Ae]=ae[De+1],ae[De+1]=re;for(var ye=0;ye<$;ye++){var j=ae[ye][Ae];ae[ye][Ae]=ae[ye][De+1],ae[ye][De+1]=j}if(me){var ne=ge[Ae];ge[Ae]=ge[De+1],ge[De+1]=ne}}for(var ue=De+2;ue<$;ue++){var Me=u(ae[ue][De],We);if(Me!==0){for(var Ce=0;Ce<$;Ce++)ae[ue][Ce]=t(ae[ue][Ce],i(Me,ae[De+1][Ce]));for(var Le=0;Le<$;Le++)ae[Le][De+1]=r(ae[Le][De+1],i(Me,ae[Le][ue]));if(me)for(var Ie=0;Ie<$;Ie++)ge[ue][Ie]=t(ge[ue][Ie],i(Me,ge[De+1][Ie]))}}}}return ge}function T(ae,$,le,Ee,me){var ge=Ee==="BigNumber",Se=Ee==="Complex",xe=ge?o(1):Se?C(1):1;ge&&(le=o(le));for(var be=ar(ae),De=[],Ae=$,We=[],Je=me?s(Array($).fill(xe)):void 0,J=me?s(Array(Ae).fill(xe)):void 0,re=0;re<=100;){re+=1;for(var ye=be[Ae-1][Ae-1],j=0;j1&&(J=s(Array(Ae-1).fill(xe)))),Ae-=1,be.pop();for(var Ce=0;Ce2&&(J=s(Array(Ae-2).fill(xe)))),Ae-=2,be.pop(),be.pop();for(var Ie=0;Ie+t(c(Ke),c(Pr))),re>100){var fr=Error("The eigenvalues failed to converge. Only found these eigenvalues: "+De.join(", "));throw fr.values=De,fr.vectors=[],fr}var or=me?a(Je,H(We,$)):void 0;return{values:De,C:or}}function R(ae,$,le,Ee,me,ge,Se){var xe=h(le),be=a(xe,ae,le),De=Se==="BigNumber",Ae=Se==="Complex",We=De?o(0):Ae?C(0):0,Je=De?o(1):Ae?C(1):1,J=[],re=[];for(var ye of me){var j=L(J,ye,w);j===-1?(J.push(ye),re.push(1)):re[j]+=1}for(var ne=[],ue=J.length,Me=Array($).fill(We),Ce=s(Array($).fill(Je)),Le=function(){var or=J[Ie],Ke=t(be,a(or,Ce)),Pr=y(Ke,Me);for(Pr.shift();Pr.lengtha(ce,we)),ne.push(...Pr.map(we=>({value:or,vector:n(we)})))},Ie=0;Ie=5)return null;for(xe=0;;){var be=v(ae,Se);if(M(oe(z(Se,[be])),Ee))break;if(++xe>=10)return null;Se=pe(be)}return Se}function K(ae,$,le){var Ee=le==="BigNumber",me=le==="Complex",ge=Array(ae).fill(0).map(Se=>2*Math.random()-1);return Ee&&(ge=ge.map(Se=>o(Se))),me&&(ge=ge.map(Se=>C(Se))),ge=z(ge,$),pe(ge,le)}function z(ae,$){var le=m(ae);for(var Ee of $)Ee=d(Ee,le),ae=t(ae,a(u(S(Ee,ae),S(Ee,Ee)),Ee));return ae}function oe(ae){return c(l(S(ae,ae)))}function pe(ae,$){var le=$==="BigNumber",Ee=$==="Complex",me=le?o(1):Ee?C(1):1;return a(u(me,oe(ae)),ae)}return O}function oB(e){var{config:r,addScalar:t,subtract:n,abs:a,atan:i,cos:u,sin:l,multiplyScalar:c,inv:o,bignumber:s,multiply:m,add:d}=e;function h(E,T){var R=arguments.length>2&&arguments[2]!==void 0?arguments[2]:r.epsilon,q=arguments.length>3?arguments[3]:void 0,W=arguments.length>4?arguments[4]:void 0;if(q==="number")return x(E,R,W);if(q==="BigNumber")return v(E,R,W);throw TypeError("Unsupported data type: "+q)}function x(E,T,R){var q=E.length,W=Math.abs(T/q),G,H;if(R){H=new Array(q);for(var L=0;L=Math.abs(W);){var K=k[0][0],z=k[0][1];G=y(E[K][K],E[z][z],E[K][z]),E=A(E,G,K,z),R&&(H=C(H,G,K,z)),k=S(E)}for(var oe=Array(q).fill(0),pe=0;pe=a(W);){var K=k[0][0],z=k[0][1];G=w(E[K][K],E[z][z],E[K][z]),E=M(E,G,K,z),R&&(H=b(H,G,K,z)),k=O(E)}for(var oe=Array(q).fill(0),pe=0;pe({value:W[$],vector:ae}));return{values:W,eigenvectors:pe}}return h}var SG="eigs",NG=["config","typed","matrix","addScalar","equal","subtract","abs","atan","cos","sin","multiplyScalar","divideScalar","inv","bignumber","multiply","add","larger","column","flatten","number","complex","sqrt","diag","size","reshape","qr","usolve","usolveAll","im","re","smaller","matrixFromColumns","dot"],bg=F(SG,NG,e=>{var{config:r,typed:t,matrix:n,addScalar:a,subtract:i,equal:u,abs:l,atan:c,cos:o,sin:s,multiplyScalar:m,divideScalar:d,inv:h,bignumber:x,multiply:v,add:y,larger:w,column:C,flatten:b,number:M,complex:A,sqrt:S,diag:O,size:_,reshape:E,qr:T,usolve:R,usolveAll:q,im:W,re:G,smaller:H,matrixFromColumns:L,dot:k}=e,K=oB({config:r,addScalar:a,subtract:i,column:C,flatten:b,equal:u,abs:l,atan:c,cos:o,sin:s,multiplyScalar:m,inv:h,bignumber:x,complex:A,multiply:v,add:y}),z=iB({config:r,addScalar:a,subtract:i,multiply:v,multiplyScalar:m,flatten:b,divideScalar:d,sqrt:S,abs:l,bignumber:x,diag:O,size:_,reshape:E,qr:T,inv:h,usolve:R,usolveAll:q,equal:u,complex:A,larger:w,smaller:H,matrixFromColumns:L,dot:k});return t("eigs",{Array:function(ge){return oe(n(ge))},"Array, number|BigNumber":function(ge,Se){return oe(n(ge),{precision:Se})},"Array, Object"(me,ge){return oe(n(me),ge)},Matrix:function(ge){return oe(ge,{matricize:!0})},"Matrix, number|BigNumber":function(ge,Se){return oe(ge,{precision:Se,matricize:!0})},"Matrix, Object":function(ge,Se){var xe={matricize:!0};return ht(xe,Se),oe(ge,xe)}});function oe(me){var ge,Se=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},xe="eigenvectors"in Se?Se.eigenvectors:!0,be=(ge=Se.precision)!==null&&ge!==void 0?ge:r.epsilon,De=pe(me,be,xe);return Se.matricize&&(De.values=n(De.values),xe&&(De.eigenvectors=De.eigenvectors.map(Ae=>{var{value:We,vector:Je}=Ae;return{value:We,vector:n(Je)}}))),xe&&Object.defineProperty(De,"vectors",{enumerable:!1,get:()=>{throw new Error("eigs(M).vectors replaced with eigs(M).eigenvectors")}}),De}function pe(me,ge,Se){var xe=me.toArray(),be=me.size();if(be.length!==2||be[0]!==be[1])throw new RangeError("Matrix must be square (size: ".concat(lr(be),")"));var De=be[0];if($(xe,De,ge)&&(le(xe,De),ae(xe,De,ge))){var Ae=Ee(me,xe,De);return K(xe,De,ge,Ae,Se)}var We=Ee(me,xe,De);return z(xe,De,ge,We,Se)}function ae(me,ge,Se){for(var xe=0;xe{var{typed:r,abs:t,add:n,identity:a,inv:i,multiply:u}=e;return r(sB,{Matrix:function(m){var d=m.size();if(d.length!==2||d[0]!==d[1])throw new RangeError("Matrix must be square (size: "+lr(d)+")");for(var h=d[0],x=1e-15,v=l(m),y=c(v,x),w=y.q,C=y.j,b=u(m,Math.pow(2,-C)),M=a(h),A=a(h),S=1,O=b,_=-1,E=1;E<=w;E++)E>1&&(O=u(O,b),_=-_),S=S*(w-E+1)/((2*w-E+1)*E),M=n(M,u(S,O)),A=n(A,u(S*_,O));for(var T=u(i(A),M),R=0;R{var{typed:r,abs:t,add:n,multiply:a,map:i,sqrt:u,subtract:l,inv:c,size:o,max:s,identity:m}=e,d=1e3,h=1e-6;function x(v){var y,w=0,C=v,b=m(o(v));do{var M=C;if(C=a(.5,n(M,c(b))),b=a(.5,n(b,c(M))),y=s(t(l(C,M))),y>h&&++w>d)throw new Error("computing square root of matrix: iterative method could not converge")}while(y>h);return C}return r(uB,{"Array | Matrix":function(y){var w=Qe(y)?y.size():ur(y);switch(w.length){case 1:if(w[0]===1)return i(y,u);throw new RangeError("Matrix must be square (size: "+lr(w)+")");case 2:{var C=w[0],b=w[1];if(C===b)return x(y);throw new RangeError("Matrix must be square (size: "+lr(w)+")")}default:throw new RangeError("Matrix must be at most two dimensional (size: "+lr(w)+")")}}})});var fB="sylvester",CG=["typed","schur","matrixFromColumns","matrix","multiply","range","concat","transpose","index","subset","add","subtract","identity","lusolve","abs"],Sg=F(fB,CG,e=>{var{typed:r,schur:t,matrixFromColumns:n,matrix:a,multiply:i,range:u,concat:l,transpose:c,index:o,subset:s,add:m,subtract:d,identity:h,lusolve:x,abs:v}=e;return r(fB,{"Matrix, Matrix, Matrix":y,"Array, Matrix, Matrix":function(C,b,M){return y(a(C),b,M)},"Array, Array, Matrix":function(C,b,M){return y(a(C),a(b),M)},"Array, Matrix, Array":function(C,b,M){return y(a(C),b,a(M))},"Matrix, Array, Matrix":function(C,b,M){return y(C,a(b),M)},"Matrix, Array, Array":function(C,b,M){return y(C,a(b),a(M))},"Matrix, Matrix, Array":function(C,b,M){return y(C,b,a(M))},"Array, Array, Array":function(C,b,M){return y(a(C),a(b),a(M)).toArray()}});function y(w,C,b){for(var M=C.size()[0],A=w.size()[0],S=t(w),O=S.T,_=S.U,E=t(i(-1,C)),T=E.T,R=E.U,q=i(i(c(_),b),R),W=u(0,A),G=[],H=(Ae,We)=>l(Ae,We,1),L=(Ae,We)=>l(Ae,We,0),k=0;k1e-5){for(var K=L(s(q,o(W,k)),s(q,o(W,k+1))),z=0;z{var{typed:r,matrix:t,identity:n,multiply:a,qr:i,norm:u,subtract:l}=e;return r(cB,{Array:function(s){var m=c(t(s));return{U:m.U.valueOf(),T:m.T.valueOf()}},Matrix:function(s){return c(s)}});function c(o){var s=o.size()[0],m=o,d=n(s),h=0,x;do{x=m;var v=i(m),y=v.Q,w=v.R;if(m=a(w,y),d=a(d,y),h++>100)break}while(u(l(m,x))>1e-4);return{U:d,T:m}}});var lB="lyap",TG=["typed","matrix","sylvester","multiply","transpose"],Ag=F(lB,TG,e=>{var{typed:r,matrix:t,sylvester:n,multiply:a,transpose:i}=e;return r(lB,{"Matrix, Matrix":function(l,c){return n(l,i(l),a(-1,c))},"Array, Matrix":function(l,c){return n(t(l),i(t(l)),a(-1,c))},"Matrix, Array":function(l,c){return n(l,i(t(l)),t(a(-1,c)))},"Array, Array":function(l,c){return n(t(l),i(t(l)),t(a(-1,c))).toArray()}})});var FG="divide",_G=["typed","matrix","multiply","equalScalar","divideScalar","inv"],Mg=F(FG,_G,e=>{var{typed:r,matrix:t,multiply:n,equalScalar:a,divideScalar:i,inv:u}=e,l=jr({typed:r,equalScalar:a}),c=qt({typed:r});return r("divide",Dm({"Array | Matrix, Array | Matrix":function(s,m){return n(s,u(m))},"DenseMatrix, any":function(s,m){return c(s,m,i,!1)},"SparseMatrix, any":function(s,m){return l(s,m,i,!1)},"Array, any":function(s,m){return c(t(s),m,i,!1).valueOf()},"any, Array | Matrix":function(s,m){return n(s,u(m))}},i.signatures))});var mB="distance",OG=["typed","addScalar","subtractScalar","divideScalar","multiplyScalar","deepEqual","sqrt","abs"],Cg=F(mB,OG,e=>{var{typed:r,addScalar:t,subtractScalar:n,multiplyScalar:a,divideScalar:i,deepEqual:u,sqrt:l,abs:c}=e;return r(mB,{"Array, Array, Array":function(A,S,O){if(A.length===2&&S.length===2&&O.length===2){if(!s(A))throw new TypeError("Array with 2 numbers or BigNumbers expected for first argument");if(!s(S))throw new TypeError("Array with 2 numbers or BigNumbers expected for second argument");if(!s(O))throw new TypeError("Array with 2 numbers or BigNumbers expected for third argument");if(u(S,O))throw new TypeError("LinePoint1 should not be same with LinePoint2");var _=n(O[1],S[1]),E=n(S[0],O[0]),T=n(a(O[0],S[1]),a(S[0],O[1]));return y(A[0],A[1],_,E,T)}else throw new TypeError("Invalid Arguments: Try again")},"Object, Object, Object":function(A,S,O){if(Object.keys(A).length===2&&Object.keys(S).length===2&&Object.keys(O).length===2){if(!s(A))throw new TypeError("Values of pointX and pointY should be numbers or BigNumbers");if(!s(S))throw new TypeError("Values of lineOnePtX and lineOnePtY should be numbers or BigNumbers");if(!s(O))throw new TypeError("Values of lineTwoPtX and lineTwoPtY should be numbers or BigNumbers");if(u(x(S),x(O)))throw new TypeError("LinePoint1 should not be same with LinePoint2");if("pointX"in A&&"pointY"in A&&"lineOnePtX"in S&&"lineOnePtY"in S&&"lineTwoPtX"in O&&"lineTwoPtY"in O){var _=n(O.lineTwoPtY,S.lineOnePtY),E=n(S.lineOnePtX,O.lineTwoPtX),T=n(a(O.lineTwoPtX,S.lineOnePtY),a(S.lineOnePtX,O.lineTwoPtY));return y(A.pointX,A.pointY,_,E,T)}else throw new TypeError("Key names do not match")}else throw new TypeError("Invalid Arguments: Try again")},"Array, Array":function(A,S){if(A.length===2&&S.length===3){if(!s(A))throw new TypeError("Array with 2 numbers or BigNumbers expected for first argument");if(!m(S))throw new TypeError("Array with 3 numbers or BigNumbers expected for second argument");return y(A[0],A[1],S[0],S[1],S[2])}else if(A.length===3&&S.length===6){if(!m(A))throw new TypeError("Array with 3 numbers or BigNumbers expected for first argument");if(!h(S))throw new TypeError("Array with 6 numbers or BigNumbers expected for second argument");return w(A[0],A[1],A[2],S[0],S[1],S[2],S[3],S[4],S[5])}else if(A.length===S.length&&A.length>0){if(!d(A))throw new TypeError("All values of an array should be numbers or BigNumbers");if(!d(S))throw new TypeError("All values of an array should be numbers or BigNumbers");return C(A,S)}else throw new TypeError("Invalid Arguments: Try again")},"Object, Object":function(A,S){if(Object.keys(A).length===2&&Object.keys(S).length===3){if(!s(A))throw new TypeError("Values of pointX and pointY should be numbers or BigNumbers");if(!m(S))throw new TypeError("Values of xCoeffLine, yCoeffLine and constant should be numbers or BigNumbers");if("pointX"in A&&"pointY"in A&&"xCoeffLine"in S&&"yCoeffLine"in S&&"constant"in S)return y(A.pointX,A.pointY,S.xCoeffLine,S.yCoeffLine,S.constant);throw new TypeError("Key names do not match")}else if(Object.keys(A).length===3&&Object.keys(S).length===6){if(!m(A))throw new TypeError("Values of pointX, pointY and pointZ should be numbers or BigNumbers");if(!h(S))throw new TypeError("Values of x0, y0, z0, a, b and c should be numbers or BigNumbers");if("pointX"in A&&"pointY"in A&&"x0"in S&&"y0"in S&&"z0"in S&&"a"in S&&"b"in S&&"c"in S)return w(A.pointX,A.pointY,A.pointZ,S.x0,S.y0,S.z0,S.a,S.b,S.c);throw new TypeError("Key names do not match")}else if(Object.keys(A).length===2&&Object.keys(S).length===2){if(!s(A))throw new TypeError("Values of pointOneX and pointOneY should be numbers or BigNumbers");if(!s(S))throw new TypeError("Values of pointTwoX and pointTwoY should be numbers or BigNumbers");if("pointOneX"in A&&"pointOneY"in A&&"pointTwoX"in S&&"pointTwoY"in S)return C([A.pointOneX,A.pointOneY],[S.pointTwoX,S.pointTwoY]);throw new TypeError("Key names do not match")}else if(Object.keys(A).length===3&&Object.keys(S).length===3){if(!m(A))throw new TypeError("Values of pointOneX, pointOneY and pointOneZ should be numbers or BigNumbers");if(!m(S))throw new TypeError("Values of pointTwoX, pointTwoY and pointTwoZ should be numbers or BigNumbers");if("pointOneX"in A&&"pointOneY"in A&&"pointOneZ"in A&&"pointTwoX"in S&&"pointTwoY"in S&&"pointTwoZ"in S)return C([A.pointOneX,A.pointOneY,A.pointOneZ],[S.pointTwoX,S.pointTwoY,S.pointTwoZ]);throw new TypeError("Key names do not match")}else throw new TypeError("Invalid Arguments: Try again")},Array:function(A){if(!v(A))throw new TypeError("Incorrect array format entered for pairwise distance calculation");return b(A)}});function o(M){return typeof M=="number"||rr(M)}function s(M){return M.constructor!==Array&&(M=x(M)),o(M[0])&&o(M[1])}function m(M){return M.constructor!==Array&&(M=x(M)),o(M[0])&&o(M[1])&&o(M[2])}function d(M){return Array.isArray(M)||(M=x(M)),M.every(o)}function h(M){return M.constructor!==Array&&(M=x(M)),o(M[0])&&o(M[1])&&o(M[2])&&o(M[3])&&o(M[4])&&o(M[5])}function x(M){for(var A=Object.keys(M),S=[],O=0;OA.length!==2||!o(A[0])||!o(A[1])))return!1}else if(M[0].length===3&&o(M[0][0])&&o(M[0][1])&&o(M[0][2])){if(M.some(A=>A.length!==3||!o(A[0])||!o(A[1])||!o(A[2])))return!1}else return!1;return!0}function y(M,A,S,O,_){var E=c(t(t(a(S,M),a(O,A)),_)),T=l(t(a(S,S),a(O,O)));return i(E,T)}function w(M,A,S,O,_,E,T,R,q){var W=[n(a(n(_,A),q),a(n(E,S),R)),n(a(n(E,S),T),a(n(O,M),q)),n(a(n(O,M),R),a(n(_,A),T))];W=l(t(t(a(W[0],W[0]),a(W[1],W[1])),a(W[2],W[2])));var G=l(t(t(a(T,T),a(R,R)),a(q,q)));return i(W,G)}function C(M,A){for(var S=M.length,O=0,_=0,E=0;E{var{typed:r,config:t,abs:n,add:a,addScalar:i,matrix:u,multiply:l,multiplyScalar:c,divideScalar:o,subtract:s,smaller:m,equalScalar:d,flatten:h,isZero:x,isNumeric:v}=e;return r("intersect",{"Array, Array, Array":y,"Array, Array, Array, Array":w,"Matrix, Matrix, Matrix":function(R,q,W){var G=y(R.valueOf(),q.valueOf(),W.valueOf());return G===null?null:u(G)},"Matrix, Matrix, Matrix, Matrix":function(R,q,W,G){var H=w(R.valueOf(),q.valueOf(),W.valueOf(),G.valueOf());return H===null?null:u(H)}});function y(T,R,q){if(T=C(T),R=C(R),q=C(q),!M(T))throw new TypeError("Array with 3 numbers or BigNumbers expected for first argument");if(!M(R))throw new TypeError("Array with 3 numbers or BigNumbers expected for second argument");if(!A(q))throw new TypeError("Array with 4 numbers expected as third argument");return E(T[0],T[1],T[2],R[0],R[1],R[2],q[0],q[1],q[2],q[3])}function w(T,R,q,W){if(T=C(T),R=C(R),q=C(q),W=C(W),T.length===2){if(!b(T))throw new TypeError("Array with 2 numbers or BigNumbers expected for first argument");if(!b(R))throw new TypeError("Array with 2 numbers or BigNumbers expected for second argument");if(!b(q))throw new TypeError("Array with 2 numbers or BigNumbers expected for third argument");if(!b(W))throw new TypeError("Array with 2 numbers or BigNumbers expected for fourth argument");return S(T,R,q,W)}else if(T.length===3){if(!M(T))throw new TypeError("Array with 3 numbers or BigNumbers expected for first argument");if(!M(R))throw new TypeError("Array with 3 numbers or BigNumbers expected for second argument");if(!M(q))throw new TypeError("Array with 3 numbers or BigNumbers expected for third argument");if(!M(W))throw new TypeError("Array with 3 numbers or BigNumbers expected for fourth argument");return _(T[0],T[1],T[2],R[0],R[1],R[2],q[0],q[1],q[2],W[0],W[1],W[2])}else throw new TypeError("Arrays with two or thee dimensional points expected")}function C(T){return T.length===1?T[0]:T.length>1&&Array.isArray(T[0])&&T.every(R=>Array.isArray(R)&&R.length===1)?h(T):T}function b(T){return T.length===2&&v(T[0])&&v(T[1])}function M(T){return T.length===3&&v(T[0])&&v(T[1])&&v(T[2])}function A(T){return T.length===4&&v(T[0])&&v(T[1])&&v(T[2])&&v(T[3])}function S(T,R,q,W){var G=T,H=q,L=s(G,R),k=s(H,W),K=s(c(L[0],k[1]),c(k[0],L[1]));if(x(K)||m(n(K),t.epsilon))return null;var z=c(k[0],G[1]),oe=c(k[1],G[0]),pe=c(k[0],H[1]),ae=c(k[1],H[0]),$=o(i(s(s(z,oe),pe),ae),K);return a(l(L,$),G)}function O(T,R,q,W,G,H,L,k,K,z,oe,pe){var ae=c(s(T,R),s(q,W)),$=c(s(G,H),s(L,k)),le=c(s(K,z),s(oe,pe));return i(i(ae,$),le)}function _(T,R,q,W,G,H,L,k,K,z,oe,pe){var ae=O(T,L,z,L,R,k,oe,k,q,K,pe,K),$=O(z,L,W,T,oe,k,G,R,pe,K,H,q),le=O(T,L,W,T,R,k,G,R,q,K,H,q),Ee=O(z,L,z,L,oe,k,oe,k,pe,K,pe,K),me=O(W,T,W,T,G,R,G,R,H,q,H,q),ge=s(c(ae,$),c(le,Ee)),Se=s(c(me,Ee),c($,$));if(x(Se))return null;var xe=o(ge,Se),be=o(i(ae,c(xe,$)),Ee),De=i(T,c(xe,s(W,T))),Ae=i(R,c(xe,s(G,R))),We=i(q,c(xe,s(H,q))),Je=i(L,c(be,s(z,L))),J=i(k,c(be,s(oe,k))),re=i(K,c(be,s(pe,K)));return d(De,Je)&&d(Ae,J)&&d(We,re)?[De,Ae,We]:null}function E(T,R,q,W,G,H,L,k,K,z){var oe=c(T,L),pe=c(W,L),ae=c(R,k),$=c(G,k),le=c(q,K),Ee=c(H,K),me=s(s(s(z,oe),ae),le),ge=s(s(s(i(i(pe,$),Ee),oe),ae),le),Se=o(me,ge),xe=i(T,c(Se,s(W,T))),be=i(R,c(Se,s(G,R))),De=i(q,c(Se,s(H,q)));return[xe,be,De]}});var pB="sum",IG=["typed","config","add","numeric"],nf=F(pB,IG,e=>{var{typed:r,config:t,add:n,numeric:a}=e;return r(pB,{"Array | Matrix":i,"Array | Matrix, number | BigNumber":u,"...":function(c){if(Ba(c))throw new TypeError("Scalar values expected in function sum");return i(c)}});function i(l){var c;return An(l,function(o){try{c=c===void 0?o:n(c,o)}catch(s){throw Et(s,"sum",o)}}),c===void 0&&(c=a(0,t.number)),typeof c=="string"&&(c=a(c,t.number)),c}function u(l,c){try{var o=ko(l,c,n);return o}catch(s){throw Et(s,"sum")}}});var Tg="cumsum",RG=["typed","add","unaryPlus"],af=F(Tg,RG,e=>{var{typed:r,add:t,unaryPlus:n}=e;return r(Tg,{Array:a,Matrix:function(o){return o.create(a(o.valueOf()))},"Array, number | BigNumber":u,"Matrix, number | BigNumber":function(o,s){return o.create(u(o.valueOf(),s))},"...":function(o){if(Ba(o))throw new TypeError("All values expected to be scalar in function cumsum");return a(o)}});function a(c){try{return i(c)}catch(o){throw Et(o,Tg)}}function i(c){if(c.length===0)return[];for(var o=[n(c[0])],s=1;s=s.length)throw new tn(o,s.length);try{return l(c,o)}catch(m){throw Et(m,Tg)}}function l(c,o){var s,m,d;if(o<=0){var h=c[0][0];if(Array.isArray(h)){for(d=Km(c),m=[],s=0;s{var{typed:r,add:t,divide:n}=e;return r(dB,{"Array | Matrix":i,"Array | Matrix, number | BigNumber":a,"...":function(l){if(Ba(l))throw new TypeError("Scalar values expected in function mean");return i(l)}});function a(u,l){try{var c=ko(u,l,t),o=Array.isArray(u)?ur(u):u.size();return n(c,o[l])}catch(s){throw Et(s,"mean")}}function i(u){var l,c=0;if(An(u,function(o){try{l=l===void 0?o:t(l,o),c++}catch(s){throw Et(s,"mean",o)}}),c===0)throw new Error("Cannot calculate the mean of an empty array");return n(l,c)}});var hB="median",qG=["typed","add","divide","compare","partitionSelect"],Fg=F(hB,qG,e=>{var{typed:r,add:t,divide:n,compare:a,partitionSelect:i}=e;function u(o){try{o=gr(o.valueOf());var s=o.length;if(s===0)throw new Error("Cannot calculate median of an empty array");if(s%2===0){for(var m=s/2-1,d=i(o,m+1),h=o[m],x=0;x0&&(h=o[x]);return c(h,d)}else{var v=i(o,(s-1)/2);return l(v)}}catch(y){throw Et(y,"median")}}var l=r({"number | BigNumber | Complex | Unit":function(s){return s}}),c=r({"number | BigNumber | Complex | Unit, number | BigNumber | Complex | Unit":function(s,m){return n(t(s,m),2)}});return r(hB,{"Array | Matrix":u,"Array | Matrix, number | BigNumber":function(s,m){throw new Error("median(A, dim) is not yet supported")},"...":function(s){if(Ba(s))throw new TypeError("Scalar values expected in function median");return u(s)}})});var vB="mad",LG=["typed","abs","map","median","subtract"],_g=F(vB,LG,e=>{var{typed:r,abs:t,map:n,median:a,subtract:i}=e;return r(vB,{"Array | Matrix":u,"...":function(c){return u(c)}});function u(l){if(l=gr(l.valueOf()),l.length===0)throw new Error("Cannot calculate median absolute deviation (mad) of an empty array");try{var c=a(l);return a(n(l,function(o){return t(i(o,c))}))}catch(o){throw o instanceof TypeError&&o.message.indexOf("median")!==-1?new TypeError(o.message.replace("median","mad")):Et(o,"mad")}}});var ND="unbiased",gB="variance",zG=["typed","add","subtract","multiply","divide","apply","isNaN"],sf=F(gB,zG,e=>{var{typed:r,add:t,subtract:n,multiply:a,divide:i,apply:u,isNaN:l}=e;return r(gB,{"Array | Matrix":function(m){return c(m,ND)},"Array | Matrix, string":c,"Array | Matrix, number | BigNumber":function(m,d){return o(m,d,ND)},"Array | Matrix, number | BigNumber, string":o,"...":function(m){return c(m,ND)}});function c(s,m){var d,h=0;if(s.length===0)throw new SyntaxError("Function variance requires one or more parameters (0 provided)");if(An(s,function(y){try{d=d===void 0?y:t(d,y),h++}catch(w){throw Et(w,"variance",y)}}),h===0)throw new Error("Cannot calculate variance of an empty array");var x=i(d,h);if(d=void 0,An(s,function(y){var w=n(y,x);d=d===void 0?a(w,w):t(d,a(w,w))}),l(d))return d;switch(m){case"uncorrected":return i(d,h);case"biased":return i(d,h+1);case"unbiased":{var v=rr(d)?d.mul(0):0;return h===1?v:i(d,h-1)}default:throw new Error('Unknown normalization "'+m+'". Choose "unbiased" (default), "uncorrected", or "biased".')}}function o(s,m,d){try{if(s.length===0)throw new SyntaxError("Function variance requires one or more parameters (0 provided)");return u(s,m,h=>c(h,d))}catch(h){throw Et(h,"variance")}}});var xB="quantileSeq",UG=["typed","?bignumber","add","subtract","divide","multiply","partitionSelect","compare","isInteger","smaller","smallerEq","larger"],uf=F(xB,UG,e=>{var{typed:r,bignumber:t,add:n,subtract:a,divide:i,multiply:u,partitionSelect:l,compare:c,isInteger:o,smaller:s,smallerEq:m,larger:d}=e,h=qo({typed:r,isInteger:o});return r(xB,{"Array | Matrix, number | BigNumber":(C,b)=>v(C,b,!1),"Array | Matrix, number | BigNumber, number":(C,b,M)=>x(C,b,!1,M,v),"Array | Matrix, number | BigNumber, boolean":v,"Array | Matrix, number | BigNumber, boolean, number":(C,b,M,A)=>x(C,b,M,A,v),"Array | Matrix, Array | Matrix":(C,b)=>y(C,b,!1),"Array | Matrix, Array | Matrix, number":(C,b,M)=>x(C,b,!1,M,y),"Array | Matrix, Array | Matrix, boolean":y,"Array | Matrix, Array | Matrix, boolean, number":(C,b,M,A)=>x(C,b,M,A,y)});function x(C,b,M,A,S){return h(C,A,O=>S(O,b,M))}function v(C,b,M){var A,S=C.valueOf();if(s(b,0))throw new Error("N/prob must be non-negative");if(m(b,1))return sr(b)?w(S,b,M):t(w(S,b,M));if(d(b,1)){if(!o(b))throw new Error("N must be a positive integer");if(d(b,4294967295))throw new Error("N must be less than or equal to 2^32-1, as that is the maximum length of an Array");var O=n(b,1);A=[];for(var _=0;s(_,b);_++){var E=i(_+1,O);A.push(w(S,E,M))}return sr(b)?A:t(A)}}function y(C,b,M){for(var A=C.valueOf(),S=b.valueOf(),O=[],_=0;_0&&(T=A[q])}return n(u(T,a(1,E)),u(R,E))}});var yB="std",WG=["typed","map","sqrt","variance"],ff=F(yB,WG,e=>{var{typed:r,map:t,sqrt:n,variance:a}=e;return r(yB,{"Array | Matrix":i,"Array | Matrix, string":i,"Array | Matrix, number | BigNumber":i,"Array | Matrix, number | BigNumber, string":i,"...":function(l){return i(l)}});function i(u,l){if(u.length===0)throw new SyntaxError("Function std requires one or more parameters (0 provided)");try{var c=a.apply(null,arguments);return Nt(c)?t(c,n):n(c)}catch(o){throw o instanceof TypeError&&o.message.indexOf(" variance")!==-1?new TypeError(o.message.replace(" variance"," std")):o}}});var bB="corr",YG=["typed","matrix","mean","sqrt","sum","add","subtract","multiply","pow","divide"],Og=F(bB,YG,e=>{var{typed:r,matrix:t,sqrt:n,sum:a,add:i,subtract:u,multiply:l,pow:c,divide:o}=e;return r(bB,{"Array, Array":function(h,x){return s(h,x)},"Matrix, Matrix":function(h,x){var v=s(h.toArray(),x.toArray());return Array.isArray(v)?t(v):v}});function s(d,h){var x=[];if(Array.isArray(d[0])&&Array.isArray(h[0])){if(d.length!==h.length)throw new SyntaxError("Dimension mismatch. Array A and B must have the same length.");for(var v=0;vi(S,l(O,h[_])),0),C=a(d.map(S=>c(S,2))),b=a(h.map(S=>c(S,2))),M=u(l(x,w),l(v,y)),A=n(l(u(l(x,C),c(v,2)),u(l(x,b),c(y,2))));return o(M,A)}});var wB="combinations",HG=["typed"],Bg=F(wB,HG,e=>{var{typed:r}=e;return r(wB,{"number, number":kw,"BigNumber, BigNumber":function(n,a){var i=n.constructor,u,l,c=n.minus(a),o=new i(1);if(!DB(n)||!DB(a))throw new TypeError("Positive integer value expected in function combinations");if(a.gt(n))throw new TypeError("k must be less than n in function combinations");if(u=o,a.lt(c))for(l=o;l.lte(c);l=l.plus(o))u=u.times(a.plus(l)).dividedBy(l);else for(l=o;l.lte(a);l=l.plus(o))u=u.times(c.plus(l)).dividedBy(l);return u}})});function DB(e){return e.isInteger()&&e.gte(0)}var SB="combinationsWithRep",$G=["typed"],Pg=F(SB,$G,e=>{var{typed:r}=e;return r(SB,{"number, number":function(n,a){if(!Ze(n)||n<0)throw new TypeError("Positive integer value expected in function combinationsWithRep");if(!Ze(a)||a<0)throw new TypeError("Positive integer value expected in function combinationsWithRep");if(n<1)throw new TypeError("k must be less than or equal to n + k - 1");if(a{var{typed:r,config:t,multiplyScalar:n,pow:a,BigNumber:i,Complex:u}=e;function l(o){if(o.im===0)return _c(o.re);if(o.re<.5){var s=new u(1-o.re,-o.im),m=new u(Math.PI*o.re,Math.PI*o.im);return new u(Math.PI).div(m.sin()).div(l(s))}o=new u(o.re-1,o.im);for(var d=new u(Ts[0],0),h=1;h2;)d-=2,x+=d,h=h.times(x);return new i(h.toPrecision(i.precision))}});var MB="lgamma",VG=["Complex","typed"],Rg=F(MB,VG,e=>{var{Complex:r,typed:t}=e,n=7,a=7,i=[-.029550653594771242,.00641025641025641,-.0019175269175269176,.0008417508417508417,-.0005952380952380953,.0007936507936507937,-.002777777777777778,.08333333333333333];return t(MB,{number:Oc,Complex:u,BigNumber:function(){throw new Error("mathjs doesn't yet provide an implementation of the algorithm lgamma for BigNumber")}});function u(o){var s=6.283185307179586,m=1.1447298858494002,d=.1;if(o.isNaN())return new r(NaN,NaN);if(o.im===0)return new r(Oc(o.re),0);if(o.re>=n||Math.abs(o.im)>=a)return l(o);if(o.re<=d){var h=nM(s,o.im)*Math.floor(.5*o.re+.25),x=o.mul(Math.PI).sin().log(),v=u(new r(1-o.re,-o.im));return new r(m,h).sub(x).sub(v)}else return o.im>=0?c(o):c(o.conjugate()).conjugate()}function l(o){for(var s=o.sub(.5).mul(o.log()).sub(o).add(Hw),m=new r(1,0).div(o),d=m.div(o),h=i[0],x=i[1],v=2*d.re,y=d.re*d.re+d.im*d.im,w=2;w<8;w++){var C=x;x=-y*h+i[w],h=v*h+C}var b=m.mul(d.mul(h).add(x));return s.add(b)}function c(o){var s=0,m=0,d=o;for(o=o.add(1);o.re<=n;){d=d.mul(o);var h=d.im<0?1:0;h!==0&&m===0&&s++,m=h,o=o.add(1)}return l(o).sub(d.log()).sub(new r(0,s*2*Math.PI*1))}});var CB="factorial",ZG=["typed","gamma"],kg=F(CB,ZG,e=>{var{typed:r,gamma:t}=e;return r(CB,{number:function(a){if(a<0)throw new Error("Value must be non-negative");return t(a+1)},BigNumber:function(a){if(a.isNegative())throw new Error("Value must be non-negative");return t(a.plus(1))},"Array | Matrix":r.referToSelf(n=>a=>je(a,n))})});var EB="kldivergence",QG=["typed","matrix","divide","sum","multiply","map","dotDivide","log","isNumeric"],qg=F(EB,QG,e=>{var{typed:r,matrix:t,divide:n,sum:a,multiply:i,map:u,dotDivide:l,log:c,isNumeric:o}=e;return r(EB,{"Array, Array":function(d,h){return s(t(d),t(h))},"Matrix, Array":function(d,h){return s(d,t(h))},"Array, Matrix":function(d,h){return s(t(d),h)},"Matrix, Matrix":function(d,h){return s(d,h)}});function s(m,d){var h=d.size().length,x=m.size().length;if(h>1)throw new Error("first object must be one dimensional");if(x>1)throw new Error("second object must be one dimensional");if(h!==x)throw new Error("Length of two vectors must be equal");var v=a(m);if(v===0)throw new Error("Sum of elements in first object must be non zero");var y=a(d);if(y===0)throw new Error("Sum of elements in second object must be non zero");var w=n(m,a(m)),C=n(d,a(d)),b=a(i(w,u(l(w,C),M=>c(M))));return o(b)?b:Number.NaN}});var TB="multinomial",XG=["typed","add","divide","multiply","factorial","isInteger","isPositive"],Lg=F(TB,XG,e=>{var{typed:r,add:t,divide:n,multiply:a,factorial:i,isInteger:u,isPositive:l}=e;return r(TB,{"Array | Matrix":function(o){var s=0,m=1;return An(o,function(d){if(!u(d)||!l(d))throw new TypeError("Positive integer value expected in function multinomial");s=t(s,d),m=a(m,i(d))}),n(i(s),m)}})});var FB="permutations",JG=["typed","factorial"],zg=F(FB,JG,e=>{var{typed:r,factorial:t}=e;return r(FB,{"number | BigNumber":t,"number, number":function(a,i){if(!Ze(a)||a<0)throw new TypeError("Positive integer value expected in function permutations");if(!Ze(i)||i<0)throw new TypeError("Positive integer value expected in function permutations");if(i>a)throw new TypeError("second argument k must be less than or equal to first argument n");return da(a-i+1,a)},"BigNumber, BigNumber":function(a,i){var u,l;if(!_B(a)||!_B(i))throw new TypeError("Positive integer value expected in function permutations");if(i.gt(a))throw new TypeError("second argument k must be less than or equal to first argument n");var c=a.mul(0).add(1);for(u=c,l=a.minus(i).plus(1);l.lte(a);l=l.plus(1))u=u.times(l);return u}})});function _B(e){return e.isInteger()&&e.gte(0)}var _D=ca(ZB(),1),aV=(0,_D.default)(Date.now());function to(e){var r;function t(a){r=a===null?aV:(0,_D.default)(String(a))}t(e);function n(){return r()}return n}var QB="pickRandom",iV=["typed","config","?on"],Wg=F(QB,iV,e=>{var{typed:r,config:t,on:n}=e,a=to(t.randomSeed);return n&&n("config",function(u,l){u.randomSeed!==l.randomSeed&&(a=to(u.randomSeed))}),r(QB,{"Array | Matrix":function(l){return i(l,{})},"Array | Matrix, Object":function(l,c){return i(l,c)},"Array | Matrix, number":function(l,c){return i(l,{number:c})},"Array | Matrix, Array | Matrix":function(l,c){return i(l,{weights:c})},"Array | Matrix, Array | Matrix, number":function(l,c,o){return i(l,{number:o,weights:c})},"Array | Matrix, number, Array | Matrix":function(l,c,o){return i(l,{number:c,weights:o})}});function i(u,l){var{number:c,weights:o,elementWise:s=!0}=l,m=typeof c>"u";m&&(c=1);var d=Qe(u)?u.create:Qe(o)?o.create:null;u=u.valueOf(),o&&(o=o.valueOf()),s===!0&&(u=gr(u),o=gr(o));var h=0;if(typeof o<"u"){if(o.length!==u.length)throw new Error("Weights must have the same length as possibles");for(var x=0,v=o.length;x"u")C=u[Math.floor(a()*y)];else for(var b=a()*h,M=0,A=u.length;M1)for(var n=0,a=e.shift();n{var{typed:r,config:t,on:n}=e,a=to(t.randomSeed);return n&&n("config",function(l,c){l.randomSeed!==c.randomSeed&&(a=to(l.randomSeed))}),r(XB,{"":()=>u(0,1),number:l=>u(0,l),"number, number":(l,c)=>u(l,c),"Array | Matrix":l=>i(l,0,1),"Array | Matrix, number":(l,c)=>i(l,0,c),"Array | Matrix, number, number":(l,c,o)=>i(l,c,o)});function i(l,c,o){var s=kc(l.valueOf(),()=>u(c,o));return Qe(l)?l.create(s):s}function u(l,c){return l+a()*(c-l)}});var JB="randomInt",sV=["typed","config","?on"],Hg=F(JB,sV,e=>{var{typed:r,config:t,on:n}=e,a=to(t.randomSeed);return n&&n("config",function(l,c){l.randomSeed!==c.randomSeed&&(a=to(l.randomSeed))}),r(JB,{"":()=>u(0,1),number:l=>u(0,l),"number, number":(l,c)=>u(l,c),"Array | Matrix":l=>i(l,0,1),"Array | Matrix, number":(l,c)=>i(l,0,c),"Array | Matrix, number, number":(l,c,o)=>i(l,c,o)});function i(l,c,o){var s=kc(l.valueOf(),()=>u(c,o));return Qe(l)?l.create(s):s}function u(l,c){return Math.floor(l+a()*(c-l))}});var KB="stirlingS2",uV=["typed","addScalar","subtractScalar","multiplyScalar","divideScalar","pow","factorial","combinations","isNegative","isInteger","number","?bignumber","larger"],$g=F(KB,uV,e=>{var{typed:r,addScalar:t,subtractScalar:n,multiplyScalar:a,divideScalar:i,pow:u,factorial:l,combinations:c,isNegative:o,isInteger:s,number:m,bignumber:d,larger:h}=e,x=[],v=[];return r(KB,{"number | BigNumber, number | BigNumber":function(w,C){if(!s(w)||o(w)||!s(C)||o(C))throw new TypeError("Non-negative integer value expected in function stirlingS2");if(h(C,w))throw new TypeError("k must be less than or equal to n in function stirlingS2");var b=!(sr(w)&&sr(C)),M=b?v:x,A=b?d:m,S=m(w),O=m(C);if(M[S]&&M[S].length>O)return M[S][O];for(var _=0;_<=S;++_)if(M[_]||(M[_]=[A(_===0?1:0)]),_!==0)for(var E=M[_],T=M[_-1],R=E.length;R<=_&&R<=O;++R)R===_?E[R]=1:E[R]=t(a(A(R),T[R]),T[R-1]);return M[S][O]}})});var jB="bellNumbers",fV=["typed","addScalar","isNegative","isInteger","stirlingS2"],Gg=F(jB,fV,e=>{var{typed:r,addScalar:t,isNegative:n,isInteger:a,stirlingS2:i}=e;return r(jB,{"number | BigNumber":function(l){if(!a(l)||n(l))throw new TypeError("Non-negative integer value expected in function bellNumbers");for(var c=0,o=0;o<=l;o++)c=t(c,i(l,o));return c}})});var eP="catalan",cV=["typed","addScalar","divideScalar","multiplyScalar","combinations","isNegative","isInteger"],Vg=F(eP,cV,e=>{var{typed:r,addScalar:t,divideScalar:n,multiplyScalar:a,combinations:i,isNegative:u,isInteger:l}=e;return r(eP,{"number | BigNumber":function(o){if(!l(o)||u(o))throw new TypeError("Non-negative integer value expected in function catalan");return n(i(a(o,2),o),t(o,1))}})});var rP="composition",lV=["typed","addScalar","combinations","isNegative","isPositive","isInteger","larger"],Zg=F(rP,lV,e=>{var{typed:r,addScalar:t,combinations:n,isPositive:a,isNegative:i,isInteger:u,larger:l}=e;return r(rP,{"number | BigNumber, number | BigNumber":function(o,s){if(!u(o)||!a(o)||!u(s)||!a(s))throw new TypeError("Positive integer value expected in function composition");if(l(s,o))throw new TypeError("k must be less than or equal to n in function composition");return n(t(o,-1),t(s,-1))}})});var tP="leafCount",mV=["parse","typed"],Qg=F(tP,mV,e=>{var{parse:r,typed:t}=e;function n(a){var i=0;return a.forEach(u=>{i+=n(u)}),i||1}return t(tP,{Node:function(i){return n(i)}})});function OD(e){return yr(e)||ct(e)&&e.isUnary()&&yr(e.args[0])}function qc(e){return!!(yr(e)||(gn(e)||ct(e))&&e.args.every(qc)||en(e)&&qc(e.content))}function nP(e,r){var t=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);r&&(n=n.filter(function(a){return Object.getOwnPropertyDescriptor(e,a).enumerable})),t.push.apply(t,n)}return t}function BD(e){for(var r=1;r{var{FunctionNode:r,OperatorNode:t,SymbolNode:n}=e,a=!0,i=!1,u="defaultF",l={add:{trivial:a,total:a,commutative:a,associative:a},unaryPlus:{trivial:a,total:a,commutative:a,associative:a},subtract:{trivial:i,total:a,commutative:i,associative:i},multiply:{trivial:a,total:a,commutative:a,associative:a},divide:{trivial:i,total:a,commutative:i,associative:i},paren:{trivial:a,total:a,commutative:a,associative:i},defaultF:{trivial:i,total:a,commutative:i,associative:i}},c={divide:{total:i},log:{total:i}},o={subtract:{total:i},abs:{trivial:a},log:{total:a}};function s(b,M){var A=arguments.length>2&&arguments[2]!==void 0?arguments[2]:l,S=u;if(typeof b=="string"?S=b:ct(b)?S=b.fn.toString():gn(b)?S=b.name:en(b)&&(S="paren"),Xe(A,S)){var O=A[S];if(Xe(O,M))return O[M];if(Xe(l,S))return l[S][M]}if(Xe(A,u)){var _=A[u];return Xe(_,M)?_[M]:l[u][M]}if(Xe(l,S)){var E=l[S];if(Xe(E,M))return E[M]}return l[u][M]}function m(b){var M=arguments.length>1&&arguments[1]!==void 0?arguments[1]:l;return s(b,"commutative",M)}function d(b){var M=arguments.length>1&&arguments[1]!==void 0?arguments[1]:l;return s(b,"associative",M)}function h(b,M){var A=BD({},b);for(var S in M)Xe(b,S)?A[S]=BD(BD({},M[S]),b[S]):A[S]=M[S];return A}function x(b,M){if(!b.args||b.args.length===0)return b;b.args=v(b,M);for(var A=0;A2&&d(b,M)){for(var _=b.args.pop();b.args.length>0;)_=A([b.args.pop(),_]);b.args=_.args}}}function w(b,M){if(!(!b.args||b.args.length===0)){for(var A=C(b),S=b.args.length,O=0;O2&&d(b,M)){for(var _=b.args.shift();b.args.length>0;)_=A([_,b.args.shift()]);b.args=_.args}}}function C(b){return ct(b)?function(M){try{return new t(b.op,b.fn,M,b.implicit)}catch(A){return console.error(A),[]}}:function(M){return new r(new n(b.name),M)}}return{createMakeNodeFunction:C,hasProperty:s,isCommutative:m,isAssociative:d,mergeContext:h,flatten:x,allChildren:v,unflattenr:y,unflattenl:w,defaultContext:l,realContext:c,positiveContext:o}});var hV="simplify",vV=["config","typed","parse","add","subtract","multiply","divide","pow","isZero","equal","resolve","simplifyConstant","simplifyCore","?fraction","?bignumber","mathWithTransform","matrix","AccessorNode","ArrayNode","ConstantNode","FunctionNode","IndexNode","ObjectNode","OperatorNode","ParenthesisNode","SymbolNode"],Xg=F(hV,vV,e=>{var{config:r,typed:t,parse:n,add:a,subtract:i,multiply:u,divide:l,pow:c,isZero:o,equal:s,resolve:m,simplifyConstant:d,simplifyCore:h,fraction:x,bignumber:v,mathWithTransform:y,matrix:w,AccessorNode:C,ArrayNode:b,ConstantNode:M,FunctionNode:A,IndexNode:S,ObjectNode:O,OperatorNode:_,ParenthesisNode:E,SymbolNode:T}=e,{hasProperty:R,isCommutative:q,isAssociative:W,mergeContext:G,flatten:H,unflattenr:L,unflattenl:k,createMakeNodeFunction:K,defaultContext:z,realContext:oe,positiveContext:pe}=cf({FunctionNode:A,OperatorNode:_,SymbolNode:T});t.addConversion({from:"Object",to:"Map",convert:Ki});var ae=t("simplify",{Node:xe,"Node, Map":(j,ne)=>xe(j,!1,ne),"Node, Map, Object":(j,ne,ue)=>xe(j,!1,ne,ue),"Node, Array":xe,"Node, Array, Map":xe,"Node, Array, Map, Object":xe});t.removeConversion({from:"Object",to:"Map",convert:Ki}),ae.defaultContext=z,ae.realContext=oe,ae.positiveContext=pe;function $(j){return j.transform(function(ne,ue,Me){return en(ne)?$(ne.content):ne})}var le={true:!0,false:!0,e:!0,i:!0,Infinity:!0,LN2:!0,LN10:!0,LOG2E:!0,LOG10E:!0,NaN:!0,phi:!0,pi:!0,SQRT1_2:!0,SQRT2:!0,tau:!0};ae.rules=[h,{l:"log(e)",r:"1"},{s:"n-n1 -> n+-n1",assuming:{subtract:{total:!0}}},{s:"n-n -> 0",assuming:{subtract:{total:!1}}},{s:"-(cl*v) -> v * (-cl)",assuming:{multiply:{commutative:!0},subtract:{total:!0}}},{s:"-(cl*v) -> (-cl) * v",assuming:{multiply:{commutative:!1},subtract:{total:!0}}},{s:"-(v*cl) -> v * (-cl)",assuming:{multiply:{commutative:!1},subtract:{total:!0}}},{l:"-(n1/n2)",r:"-n1/n2"},{l:"-v",r:"v * (-1)"},{l:"(n1 + n2)*(-1)",r:"n1*(-1) + n2*(-1)",repeat:!0},{l:"n/n1^n2",r:"n*n1^-n2"},{l:"n/n1",r:"n*n1^-1"},{s:"(n1*n2)^n3 -> n1^n3 * n2^n3",assuming:{multiply:{commutative:!0}}},{s:"(n1*n2)^(-1) -> n2^(-1) * n1^(-1)",assuming:{multiply:{commutative:!1}}},{s:"(n ^ n1) ^ n2 -> n ^ (n1 * n2)",assuming:{divide:{total:!0}}},{l:" vd * ( vd * n1 + n2)",r:"vd^2 * n1 + vd * n2"},{s:" vd * (vd^n4 * n1 + n2) -> vd^(1+n4) * n1 + vd * n2",assuming:{divide:{total:!0}}},{s:"vd^n3 * ( vd * n1 + n2) -> vd^(n3+1) * n1 + vd^n3 * n2",assuming:{divide:{total:!0}}},{s:"vd^n3 * (vd^n4 * n1 + n2) -> vd^(n3+n4) * n1 + vd^n3 * n2",assuming:{divide:{total:!0}}},{l:"n*n",r:"n^2"},{s:"n * n^n1 -> n^(n1+1)",assuming:{divide:{total:!0}}},{s:"n^n1 * n^n2 -> n^(n1+n2)",assuming:{divide:{total:!0}}},d,{s:"n+n -> 2*n",assuming:{add:{total:!0}}},{l:"n+-n",r:"0"},{l:"vd*n + vd",r:"vd*(n+1)"},{l:"n3*n1 + n3*n2",r:"n3*(n1+n2)"},{l:"n3^(-n4)*n1 + n3 * n2",r:"n3^(-n4)*(n1 + n3^(n4+1) *n2)"},{l:"n3^(-n4)*n1 + n3^n5 * n2",r:"n3^(-n4)*(n1 + n3^(n4+n5)*n2)"},{s:"n*vd + vd -> (n+1)*vd",assuming:{multiply:{commutative:!1}}},{s:"vd + n*vd -> (1+n)*vd",assuming:{multiply:{commutative:!1}}},{s:"n1*n3 + n2*n3 -> (n1+n2)*n3",assuming:{multiply:{commutative:!1}}},{s:"n^n1 * n -> n^(n1+1)",assuming:{divide:{total:!0},multiply:{commutative:!1}}},{s:"n1*n3^(-n4) + n2 * n3 -> (n1 + n2*n3^(n4 + 1))*n3^(-n4)",assuming:{multiply:{commutative:!1}}},{s:"n1*n3^(-n4) + n2 * n3^n5 -> (n1 + n2*n3^(n4 + n5))*n3^(-n4)",assuming:{multiply:{commutative:!1}}},{l:"n*cd + cd",r:"(n+1)*cd"},{s:"cd*n + cd -> cd*(n+1)",assuming:{multiply:{commutative:!1}}},{s:"cd + cd*n -> cd*(1+n)",assuming:{multiply:{commutative:!1}}},d,{s:"(-n)*n1 -> -(n*n1)",assuming:{subtract:{total:!0}}},{s:"n1*(-n) -> -(n1*n)",assuming:{subtract:{total:!0},multiply:{commutative:!1}}},{s:"ce+ve -> ve+ce",assuming:{add:{commutative:!0}},imposeContext:{add:{commutative:!1}}},{s:"vd*cd -> cd*vd",assuming:{multiply:{commutative:!0}},imposeContext:{multiply:{commutative:!1}}},{l:"n+-n1",r:"n-n1"},{l:"n+-(n1)",r:"n-(n1)"},{s:"n*(n1^-1) -> n/n1",assuming:{multiply:{commutative:!0}}},{s:"n*n1^-n2 -> n/n1^n2",assuming:{multiply:{commutative:!0}}},{s:"n^-1 -> 1/n",assuming:{multiply:{commutative:!0}}},{l:"n^1",r:"n"},{s:"n*(n1/n2) -> (n*n1)/n2",assuming:{multiply:{associative:!0}}},{s:"n-(n1+n2) -> n-n1-n2",assuming:{addition:{associative:!0,commutative:!0}}},{l:"1*n",r:"n",imposeContext:{multiply:{commutative:!0}}},{s:"n1/(n2/n3) -> (n1*n3)/n2",assuming:{multiply:{associative:!0}}},{l:"n1/(-n2)",r:"-n1/n2"}];function Ee(j,ne){var ue={};if(j.s){var Me=j.s.split("->");if(Me.length===2)ue.l=Me[0],ue.r=Me[1];else throw SyntaxError("Could not parse rule: "+j.s)}else ue.l=j.l,ue.r=j.r;ue.l=$(n(ue.l)),ue.r=$(n(ue.r));for(var Ce of["imposeContext","repeat","assuming"])Ce in j&&(ue[Ce]=j[Ce]);if(j.evaluate&&(ue.evaluate=n(j.evaluate)),W(ue.l,ne)){var Le=!q(ue.l,ne),Ie;Le&&(Ie=Se());var fr=K(ue.l),or=Se();ue.expanded={},ue.expanded.l=fr([ue.l,or]),H(ue.expanded.l,ne),L(ue.expanded.l,ne),ue.expanded.r=fr([ue.r,or]),Le&&(ue.expandedNC1={},ue.expandedNC1.l=fr([Ie,ue.l]),ue.expandedNC1.r=fr([Ie,ue.r]),ue.expandedNC2={},ue.expandedNC2.l=fr([Ie,ue.expanded.l]),ue.expandedNC2.r=fr([Ie,ue.expanded.r]))}return ue}function me(j,ne){for(var ue=[],Me=0;Me2&&arguments[2]!==void 0?arguments[2]:Oo(),Me=arguments.length>3&&arguments[3]!==void 0?arguments[3]:{},Ce=Me.consoleDebug;ne=me(ne||ae.rules,Me.context);var Le=m(j,ue);Le=$(Le);for(var Ie={},fr=Le.toString({parenthesis:"all"});!Ie[fr];){Ie[fr]=!0,ge=0;var or=fr;Ce&&console.log("Working on: ",fr);for(var Ke=0;Ke ").concat(ne[Ke].r.toString()))),Ce){var ee=Le.toString({parenthesis:"all"});ee!==or&&(console.log("Applying",Pr,"produced",ee),or=ee)}k(Le,Me.context)}fr=Le.toString({parenthesis:"all"})}return Le}function be(j,ne,ue){var Me=j;if(j)for(var Ce=0;Ce1&&(or=Le(j.args.slice(0,fr))),Ce=j.args.slice(fr),Me=Ce.length===1?Ce[0]:Le(Ce),ue.push(Le([or,Me]))}return ue}function We(j,ne){var ue={placeholders:{}};if(!j.placeholders&&!ne.placeholders)return ue;if(j.placeholders){if(!ne.placeholders)return j}else return ne;for(var Me in j.placeholders)if(Xe(j.placeholders,Me)&&(ue.placeholders[Me]=j.placeholders[Me],Xe(ne.placeholders,Me)&&!ye(j.placeholders[Me],ne.placeholders[Me])))return null;for(var Ce in ne.placeholders)Xe(ne.placeholders,Ce)&&(ue.placeholders[Ce]=ne.placeholders[Ce]);return ue}function Je(j,ne){var ue=[];if(j.length===0||ne.length===0)return ue;for(var Me,Ce=0;Ce2)throw new Error("permuting >2 commutative non-associative rule arguments not yet implemented");var or=re(j.args[0],ne.args[1],ue);if(or.length===0)return[];var Ke=re(j.args[1],ne.args[0],ue);if(Ke.length===0)return[];Le=[or,Ke]}Ce=J(Le)}else if(ne.args.length>=2&&j.args.length===2){for(var Pr=Ae(ne,ue),ee=[],ce=0;ce2)throw Error("Unexpected non-binary associative function: "+j.toString());return[]}}else if(j instanceof T){if(j.name.length===0)throw new Error("Symbol in rule has 0 length...!?");if(le[j.name]){if(j.name!==ne.name)return[]}else switch(j.name[1]>="a"&&j.name[1]<="z"?j.name.substring(0,2):j.name[0]){case"n":case"_p":Ce[0].placeholders[j.name]=ne;break;case"c":case"cl":if(yr(ne))Ce[0].placeholders[j.name]=ne;else return[];break;case"v":if(!yr(ne))Ce[0].placeholders[j.name]=ne;else return[];break;case"vl":if(at(ne))Ce[0].placeholders[j.name]=ne;else return[];break;case"cd":if(OD(ne))Ce[0].placeholders[j.name]=ne;else return[];break;case"vd":if(!OD(ne))Ce[0].placeholders[j.name]=ne;else return[];break;case"ce":if(qc(ne))Ce[0].placeholders[j.name]=ne;else return[];break;case"ve":if(!qc(ne))Ce[0].placeholders[j.name]=ne;else return[];break;default:throw new Error("Invalid symbol in rule: "+j.name)}}else if(j instanceof M){if(!s(j.value,ne.value))return[]}else return[];return Ce}function ye(j,ne){if(j instanceof M&&ne instanceof M){if(!s(j.value,ne.value))return!1}else if(j instanceof T&&ne instanceof T){if(j.name!==ne.name)return!1}else if(j instanceof _&&ne instanceof _||j instanceof A&&ne instanceof A){if(j instanceof _){if(j.op!==ne.op||j.fn!==ne.fn)return!1}else if(j instanceof A&&j.name!==ne.name)return!1;if(j.args.length!==ne.args.length)return!1;for(var ue=0;ue{var{typed:r,config:t,mathWithTransform:n,matrix:a,fraction:i,bignumber:u,AccessorNode:l,ArrayNode:c,ConstantNode:o,FunctionNode:s,IndexNode:m,ObjectNode:d,OperatorNode:h,SymbolNode:x}=e,{isCommutative:v,isAssociative:y,allChildren:w,createMakeNodeFunction:C}=cf({FunctionNode:s,OperatorNode:h,SymbolNode:x}),b=r("simplifyConstant",{Node:H=>O(G(H,{})),"Node, Object":function(L,k){return O(G(L,k))}});function M(H){return ma(H)?H.valueOf():H instanceof Array?H.map(M):Qe(H)?a(M(H.valueOf())):H}function A(H,L,k){try{return n[H].apply(null,L)}catch{return L=L.map(M),E(n[H].apply(null,L),k)}}var S=r({Fraction:R,number:function(L){return L<0?T(new o(-L)):new o(L)},BigNumber:function(L){return L<0?T(new o(-L)):new o(L)},Complex:function(L){throw new Error("Cannot convert Complex number to Node")},string:function(L){return new o(L)},Matrix:function(L){return new c(L.valueOf().map(k=>S(k)))}});function O(H){return Nr(H)?H:S(H)}function _(H,L){var k=L&&L.exactFractions!==!1;if(k&&isFinite(H)&&i){var K=i(H),z=L&&typeof L.fractionsLimit=="number"?L.fractionsLimit:1/0;if(K.valueOf()===H&&K.n0;)if(yr(K[0])&&typeof K[0].value!="string"){var z=E(K.shift().value,k);jt(H)?H=H.items[z-1]:(H=H.valueOf()[z-1],H instanceof Array&&(H=a(H)))}else if(K.length>1&&yr(K[1])&&typeof K[1].value!="string"){var oe=E(K[1].value,k),pe=[],ae=jt(H)?H.items:H.valueOf();for(var $ of ae)if(jt($))pe.push($.items[oe-1]);else if(Qe(H))pe.push($[oe-1]);else break;if(pe.length===ae.length)jt(H)?H=new c(pe):H=a(pe),K.splice(1,1);else break}else break;return K.length===L.dimensions.length?new l(O(H),L):K.length>0?(L=new m(K),new l(O(H),L)):H}if(Ci(H)&&L.dimensions.length===1&&yr(L.dimensions[0])){var le=L.dimensions[0].value;return le in H.properties?H.properties[le]:new o}return new l(O(H),L)}function W(H,L,k,K){var z=L.shift(),oe=L.reduce((pe,ae)=>{if(!Nr(ae)){var $=pe.pop();if(Nr($))return[$,ae];try{return pe.push(A(H,[$,ae],K)),pe}catch{pe.push($)}}pe.push(O(pe.pop()));var le=pe.length===1?pe[0]:k(pe);return[k([le,O(ae)])]},[z]);return oe.length===1?oe[0]:k([oe[0],S(oe[1])])}function G(H,L){switch(H.type){case"SymbolNode":return H;case"ConstantNode":switch(typeof H.value){case"number":return E(H.value,L);case"string":return H.value;default:if(!isNaN(H.value))return E(H.value,L)}return H;case"FunctionNode":if(n[H.name]&&n[H.name].rawArgs)return H;{var k=["add","multiply"];if(k.indexOf(H.name)===-1){var K=H.args.map(De=>G(De,L));if(!K.some(Nr))try{return A(H.name,K,L)}catch{}if(H.name==="size"&&K.length===1&&jt(K[0])){for(var z=[],oe=K[0];jt(oe);)z.push(oe.items.length),oe=oe.items[0];return a(z)}return new s(H.name,K.map(O))}}case"OperatorNode":{var pe=H.fn.toString(),ae,$,le=C(H);if(ct(H)&&H.isUnary())ae=[G(H.args[0],L)],Nr(ae[0])?$=le(ae):$=A(pe,ae,L);else if(y(H,L.context))if(ae=w(H,L.context),ae=ae.map(De=>G(De,L)),v(pe,L.context)){for(var Ee=[],me=[],ge=0;ge1?($=W(pe,Ee,le,L),me.unshift($),$=W(pe,me,le,L)):$=W(pe,ae,le,L)}else $=W(pe,ae,le,L);else ae=H.args.map(De=>G(De,L)),$=W(pe,ae,le,L);return $}case"ParenthesisNode":return G(H.content,L);case"AccessorNode":return q(G(H.object,L),G(H.index,L),L);case"ArrayNode":{var Se=H.items.map(De=>G(De,L));return Se.some(Nr)?new c(Se.map(O)):a(Se)}case"IndexNode":return new m(H.dimensions.map(De=>b(De,L)));case"ObjectNode":{var xe={};for(var be in H.properties)xe[be]=b(H.properties[be],L);return new d(xe)}case"AssignmentNode":case"BlockNode":case"FunctionAssignmentNode":case"RangeNode":case"ConditionalNode":default:throw new Error("Unimplemented node type in simplifyConstant: ".concat(H.type))}}return b});var aP="simplifyCore",yV=["typed","parse","equal","isZero","add","subtract","multiply","divide","pow","AccessorNode","ArrayNode","ConstantNode","FunctionNode","IndexNode","ObjectNode","OperatorNode","ParenthesisNode","SymbolNode"],Kg=F(aP,yV,e=>{var{typed:r,parse:t,equal:n,isZero:a,add:i,subtract:u,multiply:l,divide:c,pow:o,AccessorNode:s,ArrayNode:m,ConstantNode:d,FunctionNode:h,IndexNode:x,ObjectNode:v,OperatorNode:y,ParenthesisNode:w,SymbolNode:C}=e,b=new d(0),M=new d(1),A=new d(!0),S=new d(!1);function O(R){return ct(R)&&["and","not","or"].includes(R.op)}var{hasProperty:_,isCommutative:E}=cf({FunctionNode:h,OperatorNode:y,SymbolNode:C});function T(R){var q=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},W=q?q.context:void 0;if(_(R,"trivial",W)){if(gn(R)&&R.args.length===1)return T(R.args[0],q);var G=!1,H=0;if(R.forEach(me=>{++H,H===1&&(G=T(me,q))}),H===1)return G}var L=R;if(gn(L)){var k=rT(L.name);if(k){if(L.args.length>2&&_(L,"associative",W))for(;L.args.length>2;){var K=L.args.pop(),z=L.args.pop();L.args.push(new y(k,L.name,[K,z]))}L=new y(k,L.name,L.args)}else return new h(T(L.fn),L.args.map(me=>T(me,q)))}if(ct(L)&&L.isUnary()){var oe=T(L.args[0],q);if(L.op==="~"&&ct(oe)&&oe.isUnary()&&oe.op==="~"||L.op==="not"&&ct(oe)&&oe.isUnary()&&oe.op==="not"&&O(oe.args[0]))return oe.args[0];var pe=!0;if(L.op==="-"&&ct(oe)&&(oe.isBinary()&&oe.fn==="subtract"&&(L=new y("-","subtract",[oe.args[1],oe.args[0]]),pe=!1),oe.isUnary()&&oe.op==="-"))return oe.args[0];if(pe)return new y(L.op,L.fn,[oe])}if(ct(L)&&L.isBinary()){var ae=T(L.args[0],q),$=T(L.args[1],q);if(L.op==="+"){if(yr(ae)&&a(ae.value))return $;if(yr($)&&a($.value))return ae;ct($)&&$.isUnary()&&$.op==="-"&&($=$.args[0],L=new y("-","subtract",[ae,$]))}if(L.op==="-")return ct($)&&$.isUnary()&&$.op==="-"?T(new y("+","add",[ae,$.args[0]]),q):yr(ae)&&a(ae.value)?T(new y("-","unaryMinus",[$])):yr($)&&a($.value)?ae:new y(L.op,L.fn,[ae,$]);if(L.op==="*"){if(yr(ae)){if(a(ae.value))return b;if(n(ae.value,1))return $}if(yr($)){if(a($.value))return b;if(n($.value,1))return ae;if(E(L,W))return new y(L.op,L.fn,[$,ae],L.implicit)}return new y(L.op,L.fn,[ae,$],L.implicit)}if(L.op==="/")return yr(ae)&&a(ae.value)?b:yr($)&&n($.value,1)?ae:new y(L.op,L.fn,[ae,$]);if(L.op==="^"&&yr($)){if(a($.value))return M;if(n($.value,1))return ae}if(L.op==="and"){if(yr(ae))if(ae.value){if(O($))return $;if(yr($))return $.value?A:S}else return S;if(yr($))if($.value){if(O(ae))return ae}else return S}if(L.op==="or"){if(yr(ae)){if(ae.value)return A;if(O($))return $}if(yr($)){if($.value)return A;if(O(ae))return ae}}return new y(L.op,L.fn,[ae,$])}if(ct(L))return new y(L.op,L.fn,L.args.map(me=>T(me,q)));if(jt(L))return new m(L.items.map(me=>T(me,q)));if(qn(L))return new s(T(L.object,q),T(L.index,q));if(Qn(L))return new x(L.dimensions.map(me=>T(me,q)));if(Ci(L)){var le={};for(var Ee in L.properties)le[Ee]=T(L.properties[Ee],q);return new v(le)}return L}return r(aP,{Node:T,"Node,Object":T})});var bV="resolve",wV=["typed","parse","ConstantNode","FunctionNode","OperatorNode","ParenthesisNode"],jg=F(bV,wV,e=>{var{typed:r,parse:t,ConstantNode:n,FunctionNode:a,OperatorNode:i,ParenthesisNode:u}=e;function l(c,o){var s=arguments.length>2&&arguments[2]!==void 0?arguments[2]:new Set;if(!o)return c;if(at(c)){if(s.has(c.name)){var m=Array.from(s).join(", ");throw new ReferenceError("recursive loop of variable definitions among {".concat(m,"}"))}var d=o.get(c.name);if(Nr(d)){var h=new Set(s);return h.add(c.name),l(d,o,h)}else return typeof d=="number"?t(String(d)):d!==void 0?new n(d):c}else if(ct(c)){var x=c.args.map(function(y){return l(y,o,s)});return new i(c.op,c.fn,x,c.implicit)}else{if(en(c))return new u(l(c.content,o,s));if(gn(c)){var v=c.args.map(function(y){return l(y,o,s)});return new a(c.name,v)}}return c.map(y=>l(y,o,s))}return r("resolve",{Node:l,"Node, Map | null | undefined":l,"Node, Object":(c,o)=>l(c,Ki(o)),"Array | Matrix":r.referToSelf(c=>o=>o.map(s=>c(s))),"Array | Matrix, null | undefined":r.referToSelf(c=>o=>o.map(s=>c(s))),"Array, Object":r.referTo("Array,Map",c=>(o,s)=>c(o,Ki(s))),"Matrix, Object":r.referTo("Matrix,Map",c=>(o,s)=>c(o,Ki(s))),"Array | Matrix, Map":r.referToSelf(c=>(o,s)=>o.map(m=>c(m,s)))})});var iP="symbolicEqual",DV=["parse","simplify","typed","OperatorNode"],e0=F(iP,DV,e=>{var{parse:r,simplify:t,typed:n,OperatorNode:a}=e;function i(u,l){var c=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{},o=new a("-","subtract",[u,l]),s=t(o,{},c);return yr(s)&&!s.value}return n(iP,{"Node, Node":i,"Node, Node, Object":i})});var oP="derivative",SV=["typed","config","parse","simplify","equal","isZero","numeric","ConstantNode","FunctionNode","OperatorNode","ParenthesisNode","SymbolNode"],r0=F(oP,SV,e=>{var{typed:r,config:t,parse:n,simplify:a,equal:i,isZero:u,numeric:l,ConstantNode:c,FunctionNode:o,OperatorNode:s,ParenthesisNode:m,SymbolNode:d}=e;function h(b,M){var A=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{simplify:!0},S={};y(S,b,M.name);var O=w(b,S);return A.simplify?a(O):O}r.addConversion({from:"identifier",to:"SymbolNode",convert:n});var x=r(oP,{"Node, SymbolNode":h,"Node, SymbolNode, Object":h});r.removeConversion({from:"identifier",to:"SymbolNode",convert:n}),x._simplify=!0,x.toTex=function(b){return v.apply(null,b.args)};var v=r("_derivTex",{"Node, SymbolNode":function(M,A){return yr(M)&&Fr(M.value)==="string"?v(n(M.value).toString(),A.toString(),1):v(M.toTex(),A.toString(),1)},"Node, ConstantNode":function(M,A){if(Fr(A.value)==="string")return v(M,n(A.value));throw new Error("The second parameter to 'derivative' is a non-string constant")},"Node, SymbolNode, ConstantNode":function(M,A,S){return v(M.toString(),A.name,S.value)},"string, string, number":function(M,A,S){var O;return S===1?O="{d\\\\over d"+A+"}":O="{d^{"+S+"}\\\\over d"+A+"^{"+S+"}}",O+"\\\\left[".concat(M,"\\\\right]")}}),y=r("constTag",{"Object, ConstantNode, string":function(M,A){return M[A]=!0,!0},"Object, SymbolNode, string":function(M,A,S){return A.name!==S?(M[A]=!0,!0):!1},"Object, ParenthesisNode, string":function(M,A,S){return y(M,A.content,S)},"Object, FunctionAssignmentNode, string":function(M,A,S){return A.params.indexOf(S)===-1?(M[A]=!0,!0):y(M,A.expr,S)},"Object, FunctionNode | OperatorNode, string":function(M,A,S){if(A.args.length>0){for(var O=y(M,A.args[0],S),_=1;_0){var O=M.args.filter(function(H){return A[H]===void 0}),_=O.length===1?O[0]:new s("*","multiply",O),E=S.concat(w(_,A));return new s("*","multiply",E)}return new s("+","add",M.args.map(function(H){return new s("*","multiply",M.args.map(function(L){return L===H?w(L,A):L.clone()}))}))}if(M.op==="/"&&M.isBinary()){var T=M.args[0],R=M.args[1];return A[R]!==void 0?new s("/","divide",[w(T,A),R]):A[T]!==void 0?new s("*","multiply",[new s("-","unaryMinus",[T]),new s("/","divide",[w(R,A),new s("^","pow",[R.clone(),C(2)])])]):new s("/","divide",[new s("-","subtract",[new s("*","multiply",[w(T,A),R.clone()]),new s("*","multiply",[T.clone(),w(R,A)])]),new s("^","pow",[R.clone(),C(2)])])}if(M.op==="^"&&M.isBinary()){var q=M.args[0],W=M.args[1];if(A[q]!==void 0)return yr(q)&&(u(q.value)||i(q.value,1))?C(0):new s("*","multiply",[M,new s("*","multiply",[new o("log",[q.clone()]),w(W.clone(),A)])]);if(A[W]!==void 0){if(yr(W)){if(u(W.value))return C(0);if(i(W.value,1))return w(q,A)}var G=new s("^","pow",[q.clone(),new s("-","subtract",[W,C(1)])]);return new s("*","multiply",[W.clone(),new s("*","multiply",[w(q,A),G])])}return new s("*","multiply",[new s("^","pow",[q.clone(),W.clone()]),new s("+","add",[new s("*","multiply",[w(q,A),new s("/","divide",[W.clone(),q.clone()])]),new s("*","multiply",[w(W,A),new o("log",[q.clone()])])])])}throw new Error('Cannot process operator "'+M.op+'" in derivative: the operator is not supported, undefined, or the number of arguments passed to it are not supported')}});function C(b,M){return new c(l(b,M||t.number))}return x});var sP="rationalize",NV=["config","typed","equal","isZero","add","subtract","multiply","divide","pow","parse","simplifyConstant","simplifyCore","simplify","?bignumber","?fraction","mathWithTransform","matrix","AccessorNode","ArrayNode","ConstantNode","FunctionNode","IndexNode","ObjectNode","OperatorNode","SymbolNode","ParenthesisNode"],t0=F(sP,NV,e=>{var{config:r,typed:t,equal:n,isZero:a,add:i,subtract:u,multiply:l,divide:c,pow:o,parse:s,simplifyConstant:m,simplifyCore:d,simplify:h,fraction:x,bignumber:v,mathWithTransform:y,matrix:w,AccessorNode:C,ArrayNode:b,ConstantNode:M,FunctionNode:A,IndexNode:S,ObjectNode:O,OperatorNode:_,SymbolNode:E,ParenthesisNode:T}=e;function R(L){var k=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},K=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!1,z=W(),oe=q(L,k,!0,z.firstRules),pe=oe.variables.length,ae={exactFractions:!1},$={exactFractions:!0};if(L=oe.expression,pe>=1){L=G(L);var le,Ee,me=!0,ge=!1;L=h(L,z.firstRules,{},ae);for(var Se;Ee=me?z.distrDivRules:z.sucDivRules,L=h(L,Ee,{},$),me=!me,Se=L.toString(),Se!==le;)ge=!0,le=Se;ge&&(L=h(L,z.firstRulesAgain,{},ae)),L=h(L,z.finalRules,{},ae)}var xe=[],be={};return L.type==="OperatorNode"&&L.isBinary()&&L.op==="/"?(pe===1&&(L.args[0]=H(L.args[0],xe),L.args[1]=H(L.args[1])),K&&(be.numerator=L.args[0],be.denominator=L.args[1])):(pe===1&&(L=H(L,xe)),K&&(be.numerator=L,be.denominator=null)),K?(be.coefficients=xe,be.variables=oe.variables,be.expression=L,be):L}return t(sP,{Node:R,"Node, boolean":(L,k)=>R(L,{},k),"Node, Object":R,"Node, Object, boolean":R});function q(L,k,K,z){var oe=[],pe=h(L,z,k,{exactFractions:!1});K=!!K;var ae="+-*"+(K?"/":"");le(pe);var $={};return $.expression=pe,$.variables=oe,$;function le(Ee){var me=Ee.type;if(me==="FunctionNode")throw new Error("There is an unsolved function call");if(me==="OperatorNode")if(Ee.op==="^"){if(Ee.args[1].type!=="ConstantNode"||!Ze(parseFloat(Ee.args[1].value)))throw new Error("There is a non-integer exponent");le(Ee.args[0])}else{if(ae.indexOf(Ee.op)===-1)throw new Error("Operator "+Ee.op+" invalid in polynomial expression");for(var ge=0;ge1;if(z==="OperatorNode"&&L.isBinary()){var pe=!1,ae;if(L.op==="^"&&(L.args[0].type==="ParenthesisNode"||L.args[0].type==="OperatorNode")&&L.args[1].type==="ConstantNode"&&(ae=parseFloat(L.args[1].value),pe=ae>=2&&Ze(ae)),pe){if(ae>2){var $=L.args[0],le=new _("^","pow",[L.args[0].cloneDeep(),new M(ae-1)]);L=new _("*","multiply",[$,le])}else L=new _("*","multiply",[L.args[0],L.args[0].cloneDeep()]);oe&&(K==="content"?k.content=L:k.args[K]=L)}}if(z==="ParenthesisNode")G(L.content,L,"content");else if(z!=="ConstantNode"&&z!=="SymbolNode")for(var Ee=0;Ee=0;$--)if(k[$]!==0){var le=new M(pe?k[$]:Math.abs(k[$])),Ee=k[$]<0?"-":"+";if($>0){var me=new E(oe);if($>1){var ge=new M($);me=new _("^","pow",[me,ge])}k[$]===-1&&pe?le=new _("-","unaryMinus",[me]):Math.abs(k[$])===1?le=me:le=new _("*","multiply",[le,me])}pe?ae=le:Ee==="+"?ae=new _("+","add",[ae,le]):ae=new _("-","subtract",[ae,le]),pe=!1}if(pe)return new M(0);return ae;function Se(xe,be,De){var Ae=xe.type;if(Ae==="FunctionNode")throw new Error("There is an unsolved function call");if(Ae==="OperatorNode"){if("+-*^".indexOf(xe.op)===-1)throw new Error("Operator "+xe.op+" invalid");if(be!==null){if((xe.fn==="unaryMinus"||xe.fn==="pow")&&be.fn!=="add"&&be.fn!=="subtract"&&be.fn!=="multiply")throw new Error("Invalid "+xe.op+" placing");if((xe.fn==="subtract"||xe.fn==="add"||xe.fn==="multiply")&&be.fn!=="add"&&be.fn!=="subtract")throw new Error("Invalid "+xe.op+" placing");if((xe.fn==="subtract"||xe.fn==="add"||xe.fn==="unaryMinus")&&De.noFil!==0)throw new Error("Invalid "+xe.op+" placing")}(xe.op==="^"||xe.op==="*")&&(De.fire=xe.op);for(var We=0;Wez&&(k[Je]=0),k[Je]+=De.cte*(De.oper==="+"?1:-1),z=Math.max(Je,z);return}De.cte=Je,De.fire===""&&(k[0]+=De.cte*(De.oper==="+"?1:-1))}else throw new Error("Type "+Ae+" is not allowed")}}});var uP="zpk2tf",AV=["typed","add","multiply","Complex","number"],n0=F(uP,AV,e=>{var{typed:r,add:t,multiply:n,Complex:a,number:i}=e;return r(uP,{"Array,Array,number":function(o,s,m){return u(o,s,m)},"Array,Array":function(o,s){return u(o,s,1)},"Matrix,Matrix,number":function(o,s,m){return u(o.valueOf(),s.valueOf(),m)},"Matrix,Matrix":function(o,s){return u(o.valueOf(),s.valueOf(),1)}});function u(c,o,s){c.some(C=>C.type==="BigNumber")&&(c=c.map(C=>i(C))),o.some(C=>C.type==="BigNumber")&&(o=o.map(C=>i(C)));for(var m=[a(1,0)],d=[a(1,0)],h=0;h=0&&m-d{var{typed:r,add:t,multiply:n,Complex:a,divide:i,matrix:u}=e;return r(fP,{"Array, Array":function(s,m){var d=c(512);return l(s,m,d)},"Array, Array, Array":function(s,m,d){return l(s,m,d)},"Array, Array, number":function(s,m,d){if(d<0)throw new Error("w must be a positive number");var h=c(d);return l(s,m,h)},"Matrix, Matrix":function(s,m){var d=c(512),{w:h,h:x}=l(s.valueOf(),m.valueOf(),d);return{w:u(h),h:u(x)}},"Matrix, Matrix, Matrix":function(s,m,d){var{h}=l(s.valueOf(),m.valueOf(),d.valueOf());return{h:u(h),w:u(d)}},"Matrix, Matrix, number":function(s,m,d){if(d<0)throw new Error("w must be a positive number");var h=c(d),{h:x}=l(s.valueOf(),m.valueOf(),h);return{h:u(x),w:u(h)}}});function l(o,s,m){for(var d=[],h=[],x=0;x{var{classes:r}=e;return function(n,a){var i=r[a&&a.mathjs];return i&&typeof i.fromJSON=="function"?i.fromJSON(a):a}});var TV="replacer",FV=[],o0=F(TV,FV,()=>function(r,t){return typeof t=="number"&&(!isFinite(t)||isNaN(t))?{mathjs:"number",value:String(t)}:t});var cP="12.4.1";var s0=F("true",[],()=>!0),u0=F("false",[],()=>!1),f0=F("null",[],()=>null),c0=va("Infinity",["config","?BigNumber"],e=>{var{config:r,BigNumber:t}=e;return r.number==="BigNumber"?new t(1/0):1/0}),l0=va("NaN",["config","?BigNumber"],e=>{var{config:r,BigNumber:t}=e;return r.number==="BigNumber"?new t(NaN):NaN}),m0=va("pi",["config","?BigNumber"],e=>{var{config:r,BigNumber:t}=e;return r.number==="BigNumber"?Ic(t):HM}),p0=va("tau",["config","?BigNumber"],e=>{var{config:r,BigNumber:t}=e;return r.number==="BigNumber"?mE(t):$M}),d0=va("e",["config","?BigNumber"],e=>{var{config:r,BigNumber:t}=e;return r.number==="BigNumber"?cE(t):GM}),h0=va("phi",["config","?BigNumber"],e=>{var{config:r,BigNumber:t}=e;return r.number==="BigNumber"?lE(t):VM}),v0=va("LN2",["config","?BigNumber"],e=>{var{config:r,BigNumber:t}=e;return r.number==="BigNumber"?new t(2).ln():Math.LN2}),g0=va("LN10",["config","?BigNumber"],e=>{var{config:r,BigNumber:t}=e;return r.number==="BigNumber"?new t(10).ln():Math.LN10}),x0=va("LOG2E",["config","?BigNumber"],e=>{var{config:r,BigNumber:t}=e;return r.number==="BigNumber"?new t(1).div(new t(2).ln()):Math.LOG2E}),y0=va("LOG10E",["config","?BigNumber"],e=>{var{config:r,BigNumber:t}=e;return r.number==="BigNumber"?new t(1).div(new t(10).ln()):Math.LOG10E}),b0=va("SQRT1_2",["config","?BigNumber"],e=>{var{config:r,BigNumber:t}=e;return r.number==="BigNumber"?new t("0.5").sqrt():Math.SQRT1_2}),w0=va("SQRT2",["config","?BigNumber"],e=>{var{config:r,BigNumber:t}=e;return r.number==="BigNumber"?new t(2).sqrt():Math.SQRT2}),D0=va("i",["Complex"],e=>{var{Complex:r}=e;return r.I}),lP=F("PI",["pi"],e=>{var{pi:r}=e;return r}),mP=F("E",["e"],e=>{var{e:r}=e;return r}),S0=F("version",[],()=>cP);function va(e,r,t){return F(e,r,t,{recreateOnConfigChange:!0})}var N0=Er("speedOfLight","299792458","m s^-1"),A0=Er("gravitationConstant","6.67430e-11","m^3 kg^-1 s^-2"),M0=Er("planckConstant","6.62607015e-34","J s"),C0=Er("reducedPlanckConstant","1.0545718176461565e-34","J s"),E0=Er("magneticConstant","1.25663706212e-6","N A^-2"),T0=Er("electricConstant","8.8541878128e-12","F m^-1"),F0=Er("vacuumImpedance","376.730313667","ohm"),_0=Er("coulomb","8.987551792261171e9","N m^2 C^-2"),O0=Er("elementaryCharge","1.602176634e-19","C"),B0=Er("bohrMagneton","9.2740100783e-24","J T^-1"),P0=Er("conductanceQuantum","7.748091729863649e-5","S"),I0=Er("inverseConductanceQuantum","12906.403729652257","ohm"),R0=Er("magneticFluxQuantum","2.0678338484619295e-15","Wb"),k0=Er("nuclearMagneton","5.0507837461e-27","J T^-1"),q0=Er("klitzing","25812.807459304513","ohm");var L0=Er("bohrRadius","5.29177210903e-11","m"),z0=Er("classicalElectronRadius","2.8179403262e-15","m"),U0=Er("electronMass","9.1093837015e-31","kg"),W0=Er("fermiCoupling","1.1663787e-5","GeV^-2"),Y0=bx("fineStructure",.0072973525693),H0=Er("hartreeEnergy","4.3597447222071e-18","J"),$0=Er("protonMass","1.67262192369e-27","kg"),G0=Er("deuteronMass","3.3435830926e-27","kg"),V0=Er("neutronMass","1.6749271613e-27","kg"),Z0=Er("quantumOfCirculation","3.6369475516e-4","m^2 s^-1"),Q0=Er("rydberg","10973731.568160","m^-1"),X0=Er("thomsonCrossSection","6.6524587321e-29","m^2"),J0=bx("weakMixingAngle",.2229),K0=bx("efimovFactor",22.7),j0=Er("atomicMass","1.66053906660e-27","kg"),ex=Er("avogadro","6.02214076e23","mol^-1"),rx=Er("boltzmann","1.380649e-23","J K^-1"),tx=Er("faraday","96485.33212331001","C mol^-1"),nx=Er("firstRadiation","3.7417718521927573e-16","W m^2"),ax=Er("loschmidt","2.686780111798444e25","m^-3"),ix=Er("gasConstant","8.31446261815324","J K^-1 mol^-1"),ox=Er("molarPlanckConstant","3.990312712893431e-10","J s mol^-1"),sx=Er("molarVolume","0.022413969545014137","m^3 mol^-1"),ux=bx("sackurTetrode",-1.16487052358),fx=Er("secondRadiation","0.014387768775039337","m K"),cx=Er("stefanBoltzmann","5.67037441918443e-8","W m^-2 K^-4"),lx=Er("wienDisplacement","2.897771955e-3","m K"),mx=Er("molarMass","0.99999999965e-3","kg mol^-1"),px=Er("molarMassC12","11.9999999958e-3","kg mol^-1"),dx=Er("gravity","9.80665","m s^-2"),hx=Er("planckLength","1.616255e-35","m"),vx=Er("planckMass","2.176435e-8","kg"),gx=Er("planckTime","5.391245e-44","s"),xx=Er("planckCharge","1.87554603778e-18","C"),yx=Er("planckTemperature","1.416785e+32","K");function Er(e,r,t){var n=["config","Unit","BigNumber"];return F(e,n,a=>{var{config:i,Unit:u,BigNumber:l}=a,c=i.number==="BigNumber"?new l(r):parseFloat(r),o=new u(c,t);return o.fixPrefix=!0,o})}function bx(e,r){var t=["config","BigNumber"];return F(e,t,n=>{var{config:a,BigNumber:i}=n;return a.number==="BigNumber"?new i(r):r})}var _V="apply",OV=["typed","isInteger"],wx=F(_V,OV,e=>{var{typed:r,isInteger:t}=e,n=qo({typed:r,isInteger:t});return r("apply",{"...any":function(i){var u=i[1];sr(u)?i[1]=u-1:rr(u)&&(i[1]=u.minus(1));try{return n.apply(null,i)}catch(l){throw mt(l)}}})},{isTransformFunction:!0});var BV="column",PV=["typed","Index","matrix","range"],Dx=F(BV,PV,e=>{var{typed:r,Index:t,matrix:n,range:a}=e,i=Wu({typed:r,Index:t,matrix:n,range:a});return r("column",{"...any":function(l){var c=l.length-1,o=l[c];sr(o)&&(l[c]=o-1);try{return i.apply(null,l)}catch(s){throw mt(s)}}})},{isTransformFunction:!0});function lf(e,r,t){var n=e.filter(function(c){return at(c)&&!(c.name in r)&&!t.has(c.name)})[0];if(!n)throw new Error('No undefined variable found in inline expression "'+e+'"');var a=n.name,i=new Map,u=new Eu(t,i,new Set([a])),l=e.compile();return function(o){return i.set(a,o),l.evaluate(u)}}var IV="filter",RV=["typed"],Sx=F(IV,RV,e=>{var{typed:r}=e;function t(a,i,u){var l,c;return a[0]&&(l=a[0].compile().evaluate(u)),a[1]&&(at(a[1])||_a(a[1])?c=a[1].compile().evaluate(u):c=lf(a[1],i,u)),n(l,c)}t.rawArgs=!0;var n=r("filter",{"Array, function":pP,"Matrix, function":function(i,u){return i.create(pP(i.toArray(),u))},"Array, RegExp":Mu,"Matrix, RegExp":function(i,u){return i.create(Mu(i.toArray(),u))}});return t},{isTransformFunction:!0});function pP(e,r){return Om(e,function(t,n,a){return Ia(r,t,[n+1],a,"filter")})}var kV="forEach",qV=["typed"],Nx=F(kV,qV,e=>{var{typed:r}=e;function t(a,i,u){var l,c;return a[0]&&(l=a[0].compile().evaluate(u)),a[1]&&(at(a[1])||_a(a[1])?c=a[1].compile().evaluate(u):c=lf(a[1],i,u)),n(l,c)}t.rawArgs=!0;var n=r("forEach",{"Array | Matrix, function":function(i,u){var l=function c(o,s){if(Array.isArray(o))Fo(o,function(m,d){c(m,s.concat(d+1))});else return Ia(u,o,s,i,"forEach")};l(i.valueOf(),[])}});return t},{isTransformFunction:!0});var LV="index",zV=["Index","getMatrixDataType"],Ax=F(LV,zV,e=>{var{Index:r,getMatrixDataType:t}=e;return function(){for(var a=[],i=0,u=arguments.length;i0?0:2;else if(l&&l.isSet===!0)l=l.map(function(o){return o-1});else if(Mr(l)||Qe(l))t(l)!=="boolean"&&(l=l.map(function(o){return o-1}));else if(sr(l))l--;else if(rr(l))l=l.toNumber()-1;else if(typeof l!="string")throw new TypeError("Dimension must be an Array, Matrix, number, string, or Range");a[i]=l}var c=new r;return r.apply(c,a),c}},{isTransformFunction:!0});var UV="map",WV=["typed"],Mx=F(UV,WV,e=>{var{typed:r}=e;function t(a,i,u){var l,c;return a[0]&&(l=a[0].compile().evaluate(u)),a[1]&&(at(a[1])||_a(a[1])?c=a[1].compile().evaluate(u):c=lf(a[1],i,u)),n(l,c)}t.rawArgs=!0;var n=r("map",{"Array, function":function(i,u){return dP(i,u,i)},"Matrix, function":function(i,u){return i.create(dP(i.valueOf(),u,i))}});return t},{isTransformFunction:!0});function dP(e,r,t){function n(a,i){return Array.isArray(a)?Xn(a,function(u,l){return n(u,i.concat(l+1))}):Ia(r,a,i,t,"map")}return n(e,[])}function Cn(e){if(e.length===2&&Nt(e[0])){e=e.slice();var r=e[1];sr(r)?e[1]=r-1:rr(r)&&(e[1]=r.minus(1))}return e}var YV="max",HV=["typed","config","numeric","larger"],Cx=F(YV,HV,e=>{var{typed:r,config:t,numeric:n,larger:a}=e,i=ef({typed:r,config:t,numeric:n,larger:a});return r("max",{"...any":function(l){l=Cn(l);try{return i.apply(null,l)}catch(c){throw mt(c)}}})},{isTransformFunction:!0});var $V="mean",GV=["typed","add","divide"],Ex=F($V,GV,e=>{var{typed:r,add:t,divide:n}=e,a=of({typed:r,add:t,divide:n});return r("mean",{"...any":function(u){u=Cn(u);try{return a.apply(null,u)}catch(l){throw mt(l)}}})},{isTransformFunction:!0});var VV="min",ZV=["typed","config","numeric","smaller"],Tx=F(VV,ZV,e=>{var{typed:r,config:t,numeric:n,smaller:a}=e,i=rf({typed:r,config:t,numeric:n,smaller:a});return r("min",{"...any":function(l){l=Cn(l);try{return i.apply(null,l)}catch(c){throw mt(c)}}})},{isTransformFunction:!0});var QV="range",XV=["typed","config","?matrix","?bignumber","smaller","smallerEq","larger","largerEq","add","isPositive"],Fx=F(QV,XV,e=>{var{typed:r,config:t,matrix:n,bignumber:a,smaller:i,smallerEq:u,larger:l,largerEq:c,add:o,isPositive:s}=e,m=$u({typed:r,config:t,matrix:n,bignumber:a,smaller:i,smallerEq:u,larger:l,largerEq:c,add:o,isPositive:s});return r("range",{"...any":function(h){var x=h.length-1,v=h[x];return typeof v!="boolean"&&h.push(!0),m.apply(null,h)}})},{isTransformFunction:!0});var JV="row",KV=["typed","Index","matrix","range"],_x=F(JV,KV,e=>{var{typed:r,Index:t,matrix:n,range:a}=e,i=Gu({typed:r,Index:t,matrix:n,range:a});return r("row",{"...any":function(l){var c=l.length-1,o=l[c];sr(o)&&(l[c]=o-1);try{return i.apply(null,l)}catch(s){throw mt(s)}}})},{isTransformFunction:!0});var jV="subset",eZ=["typed","matrix","zeros","add"],Ox=F(jV,eZ,e=>{var{typed:r,matrix:t,zeros:n,add:a}=e,i=Vu({typed:r,matrix:t,zeros:n,add:a});return r("subset",{"...any":function(l){try{return i.apply(null,l)}catch(c){throw mt(c)}}})},{isTransformFunction:!0});var rZ="concat",tZ=["typed","matrix","isInteger"],Bx=F(rZ,tZ,e=>{var{typed:r,matrix:t,isInteger:n}=e,a=Uu({typed:r,matrix:t,isInteger:n});return r("concat",{"...any":function(u){var l=u.length-1,c=u[l];sr(c)?u[l]=c-1:rr(c)&&(u[l]=c.minus(1));try{return a.apply(null,u)}catch(o){throw mt(o)}}})},{isTransformFunction:!0});var hP="diff",nZ=["typed","matrix","subtract","number","bignumber"],Px=F(hP,nZ,e=>{var{typed:r,matrix:t,subtract:n,number:a,bignumber:i}=e,u=Yu({typed:r,matrix:t,subtract:n,number:a,bignumber:i});return r(hP,{"...any":function(c){c=Cn(c);try{return u.apply(null,c)}catch(o){throw mt(o)}}})},{isTransformFunction:!0});var aZ="std",iZ=["typed","map","sqrt","variance"],Ix=F(aZ,iZ,e=>{var{typed:r,map:t,sqrt:n,variance:a}=e,i=ff({typed:r,map:t,sqrt:n,variance:a});return r("std",{"...any":function(l){l=Cn(l);try{return i.apply(null,l)}catch(c){throw mt(c)}}})},{isTransformFunction:!0});var vP="sum",oZ=["typed","config","add","numeric"],Rx=F(vP,oZ,e=>{var{typed:r,config:t,add:n,numeric:a}=e,i=nf({typed:r,config:t,add:n,numeric:a});return r(vP,{"...any":function(l){l=Cn(l);try{return i.apply(null,l)}catch(c){throw mt(c)}}})},{isTransformFunction:!0});var sZ="quantileSeq",uZ=["typed","bignumber","add","subtract","divide","multiply","partitionSelect","compare","isInteger","smaller","smallerEq","larger"],kx=F(sZ,uZ,e=>{var{typed:r,bignumber:t,add:n,subtract:a,divide:i,multiply:u,partitionSelect:l,compare:c,isInteger:o,smaller:s,smallerEq:m,larger:d}=e,h=uf({typed:r,bignumber:t,add:n,subtract:a,divide:i,multiply:u,partitionSelect:l,compare:c,isInteger:o,smaller:s,smallerEq:m,larger:d});return r("quantileSeq",{"Array | Matrix, number | BigNumber":h,"Array | Matrix, number | BigNumber, number":(v,y,w)=>h(v,y,x(w)),"Array | Matrix, number | BigNumber, boolean":h,"Array | Matrix, number | BigNumber, boolean, number":(v,y,w,C)=>h(v,y,w,x(C)),"Array | Matrix, Array | Matrix":h,"Array | Matrix, Array | Matrix, number":(v,y,w)=>h(v,y,x(w)),"Array | Matrix, Array | Matrix, boolean":h,"Array | Matrix, Array | Matrix, boolean, number":(v,y,w,C)=>h(v,y,w,x(C))});function x(v){return Cn([[],v])[1]}},{isTransformFunction:!0});var gP="cumsum",fZ=["typed","add","unaryPlus"],qx=F(gP,fZ,e=>{var{typed:r,add:t,unaryPlus:n}=e,a=af({typed:r,add:t,unaryPlus:n});return r(gP,{"...any":function(u){if(u.length===2&&Nt(u[0])){var l=u[1];sr(l)?u[1]=l-1:rr(l)&&(u[1]=l.minus(1))}try{return a.apply(null,u)}catch(c){throw mt(c)}}})},{isTransformFunction:!0});var xP="variance",cZ=["typed","add","subtract","multiply","divide","apply","isNaN"],Lx=F(xP,cZ,e=>{var{typed:r,add:t,subtract:n,multiply:a,divide:i,apply:u,isNaN:l}=e,c=sf({typed:r,add:t,subtract:n,multiply:a,divide:i,apply:u,isNaN:l});return r(xP,{"...any":function(s){s=Cn(s);try{return c.apply(null,s)}catch(m){throw mt(m)}}})},{isTransformFunction:!0});var yP="print",lZ=["typed","matrix","zeros","add"],zx=F(yP,lZ,e=>{var{typed:r,matrix:t,zeros:n,add:a}=e,i=Qu({typed:r,matrix:t,zeros:n,add:a});return r(yP,{"string, Object | Array":function(c,o){return i(u(c),o)},"string, Object | Array, number | Object":function(c,o,s){return i(u(c),o,s)}});function u(l){return l.replace(qd,c=>{var o=c.slice(1).split("."),s=o.map(function(m){return!isNaN(m)&&m.length>0?parseInt(m)-1:m});return"$"+s.join(".")})}},{isTransformFunction:!0});var mZ="and",pZ=["typed","matrix","zeros","add","equalScalar","not","concat"],Ux=F(mZ,pZ,e=>{var{typed:r,matrix:t,equalScalar:n,zeros:a,not:i,concat:u}=e,l=ju({typed:r,matrix:t,equalScalar:n,zeros:a,not:i,concat:u});function c(o,s,m){var d=o[0].compile().evaluate(m);if(!Nt(d)&&!l(d,!0))return!1;var h=o[1].compile().evaluate(m);return l(d,h)}return c.rawArgs=!0,c},{isTransformFunction:!0});var dZ="or",hZ=["typed","matrix","equalScalar","DenseMatrix","concat"],Wx=F(dZ,hZ,e=>{var{typed:r,matrix:t,equalScalar:n,DenseMatrix:a,concat:i}=e,u=zu({typed:r,matrix:t,equalScalar:n,DenseMatrix:a,concat:i});function l(c,o,s){var m=c[0].compile().evaluate(s);if(!Nt(m)&&u(m,!1))return!0;var d=c[1].compile().evaluate(s);return u(m,d)}return l.rawArgs=!0,l},{isTransformFunction:!0});var vZ="bitAnd",gZ=["typed","matrix","zeros","add","equalScalar","not","concat"],Yx=F(vZ,gZ,e=>{var{typed:r,matrix:t,equalScalar:n,zeros:a,not:i,concat:u}=e,l=qu({typed:r,matrix:t,equalScalar:n,zeros:a,not:i,concat:u});function c(o,s,m){var d=o[0].compile().evaluate(m);if(!Nt(d)){if(isNaN(d))return NaN;if(d===0||d===!1)return 0}var h=o[1].compile().evaluate(m);return l(d,h)}return c.rawArgs=!0,c},{isTransformFunction:!0});var xZ="bitOr",yZ=["typed","matrix","equalScalar","DenseMatrix","concat"],Hx=F(xZ,yZ,e=>{var{typed:r,matrix:t,equalScalar:n,DenseMatrix:a,concat:i}=e,u=Lu({typed:r,matrix:t,equalScalar:n,DenseMatrix:a,concat:i});function l(c,o,s){var m=c[0].compile().evaluate(s);if(!Nt(m)){if(isNaN(m))return NaN;if(m===-1)return-1;if(m===!0)return 1}var d=c[1].compile().evaluate(s);return u(m,d)}return l.rawArgs=!0,l},{isTransformFunction:!0});var Ge=Hm({config:Oe}),pt=$m({}),ID=d0({BigNumber:Ge,config:Oe}),bP=u0({}),wP=Y0({BigNumber:Ge,config:Oe}),Uo=Gm({}),RD=D0({Complex:pt}),DP=c0({BigNumber:Ge,config:Oe}),SP=g0({BigNumber:Ge,config:Oe}),NP=y0({BigNumber:Ge,config:Oe}),Lc=Zm({}),AP=l0({BigNumber:Ge,config:Oe}),MP=f0({}),CP=h0({BigNumber:Ge,config:Oe}),EP=Vm({}),kD=Rm({}),TP=b0({BigNumber:Ge,config:Oe}),FP=ux({BigNumber:Ge,config:Oe}),qD=p0({BigNumber:Ge,config:Oe}),_P=s0({}),OP=S0({}),_r=Xm({Matrix:Lc}),BP=K0({BigNumber:Ge,config:Oe}),PP=v0({BigNumber:Ge,config:Oe}),$x=m0({BigNumber:Ge,config:Oe}),IP=o0({}),RP=w0({BigNumber:Ge,config:Oe}),te=Im({BigNumber:Ge,Complex:pt,DenseMatrix:_r,Fraction:Uo}),Gx=Np({BigNumber:Ge,config:Oe,typed:te}),kP=J0({BigNumber:Ge,config:Oe}),En=Ap({typed:te}),qP=Oh({Complex:pt,config:Oe,typed:te}),LP=Ph({BigNumber:Ge,typed:te}),zP=Rh({BigNumber:Ge,Complex:pt,config:Oe,typed:te}),Qt=Cp({typed:te}),UP=jp({typed:te}),WP=Lh({BigNumber:Ge,Complex:pt,config:Oe,typed:te}),YP=Uh({typed:te}),LD=Wh({typed:te}),HP=Hh({Complex:pt,config:Oe,typed:te}),ea=hp({BigNumber:Ge,typed:te}),$P=Jp({typed:te}),GP=dp({typed:te}),VP=Jm({typed:te}),zc=Bg({typed:te}),Uc=vp({Complex:pt,typed:te}),Wo=ed({typed:te}),Vx=$h({typed:te}),ZP=Vh({BigNumber:Ge,typed:te}),QP=Qh({BigNumber:Ge,typed:te}),XP=_p({typed:te}),Ir=cp({config:Oe,typed:te}),JP=Fd({typed:te}),zD=Op({typed:te}),KP=Bp({Complex:pt,typed:te}),jP=ud({typed:te}),eI=cd({typed:te}),mf=Pd({typed:te}),Zx=ld({typed:te}),rI=kd({format:mf,typed:te}),Qx=rd({typed:te}),Ln=ep({typed:te}),no=tp({typed:te}),Yo=ip({typed:te}),qa=op({typed:te}),tI=x0({BigNumber:Ge,config:Oe}),nI=Rg({Complex:pt,typed:te}),aI=kp({Complex:pt,config:Oe,typed:te}),UD=qp({Complex:pt,config:Oe,typed:te}),Ho=dd({typed:te}),Ot=Lp({typed:te}),Wc=nd({typed:te}),Oi=mp({typed:te}),iI=Rd({format:mf,typed:te}),oI=Wg({config:Oe,typed:te}),sI=Qu({typed:te}),uI=Yg({config:Oe,typed:te}),Xx=td({typed:te}),fI=Jh({BigNumber:Ge,typed:te}),WD=Wp({BigNumber:Ge,Fraction:Uo,complex:Uc,typed:te}),Yc=jh({typed:te}),Bi=lp({Matrix:Lc,equalScalar:Ir,typed:te}),cI=Dp({typed:te}),lI=Hp({typed:te}),mI=pp({typed:te}),ga=Ep({typed:te}),pI=rv({typed:te}),YD=up({typed:te}),dI=Bh({Complex:pt,config:Oe,typed:te}),hI=kh({BigNumber:Ge,typed:te}),Jx=qo({isInteger:Ln,typed:te}),vI=qh({BigNumber:Ge,Complex:pt,config:Oe,typed:te}),gI=Id({format:mf,typed:te}),xI=Pg({typed:te}),yI=Gh({typed:te}),bI=Xh({BigNumber:Ge,typed:te}),pf=sp({typed:te}),wI=zd({typed:te}),DI=Hg({config:Oe,typed:te}),SI=Kh({BigNumber:Ge,typed:te}),NI=ev({typed:te}),AI=Fh({SparseMatrix:Bi,typed:te}),La=Yp({Complex:pt,config:Oe,typed:te}),MI=tv({typed:te}),fi=Sp({typed:te}),CI=Ih({BigNumber:Ge,Complex:pt,config:Oe,typed:te}),EI=Zh({BigNumber:Ge,typed:te}),Bs=gp({Fraction:Uo,typed:te}),$o=np({typed:te}),$e=xp({DenseMatrix:_r,Matrix:Lc,SparseMatrix:Bi,typed:te}),TI=yp({isZero:qa,matrix:$e,typed:te}),FI=Od({isNaN:pf,isNumeric:$o,typed:te}),za=Ud({bignumber:ea,fraction:Bs,number:Oi}),HD=Bd({config:Oe,multiplyScalar:Ot,numeric:za,typed:te}),$D=xd({isInteger:Ln,matrix:$e,typed:te}),cn=Dd({matrix:$e,config:Oe,typed:te}),_I=Sd({matrix:$e,typed:te}),df=Nd({matrix:$e,typed:te}),GD=Gp({BigNumber:Ge,config:Oe,matrix:$e,typed:te}),ln=Md({BigNumber:Ge,config:Oe,matrix:$e,typed:te}),OI=zh({Complex:pt,config:Oe,typed:te}),VD=Tp({BigNumber:Ge,Complex:pt,Fraction:Uo,config:Oe,isNegative:no,matrix:$e,typed:te,unaryMinus:fi}),Gr=Uu({isInteger:Ln,matrix:$e,typed:te}),BI=id({prod:HD,size:cn,typed:te}),Kx=Ad({conj:Wo,transpose:df,typed:te}),ZD=sd({DenseMatrix:_r,SparseMatrix:Bi,matrix:$e,typed:te}),Mt=Wd({numeric:za,typed:te}),hf=Qd({DenseMatrix:_r,concat:Gr,divideScalar:Mt,equalScalar:Ir,matrix:$e,typed:te}),xa=uh({DenseMatrix:_r,concat:Gr,equalScalar:Ir,matrix:$e,typed:te}),vf=fd({matrix:$e,typed:te}),PI=ap({isNumeric:$o,typed:te}),ao=md({BigNumber:Ge,DenseMatrix:_r,SparseMatrix:Bi,config:Oe,matrix:$e,typed:te}),II=pd({matrix:$e,multiplyScalar:Ot,typed:te}),Hc=gh({DenseMatrix:_r,concat:Gr,config:Oe,matrix:$e,typed:te}),RI=eh({DenseMatrix:_r,concat:Gr,equalScalar:Ir,matrix:$e,typed:te,zeros:ln}),QD=Xd({DenseMatrix:_r,divideScalar:Mt,equalScalar:Ir,matrix:$e,multiplyScalar:Ot,subtractScalar:ga,typed:te}),jx=wp({flatten:vf,matrix:$e,size:cn,typed:te}),kI=Up({BigNumber:Ge,concat:Gr,equalScalar:Ir,matrix:$e,typed:te}),qI=hd({BigNumber:Ge,config:Oe,matrix:$e,typed:te}),ey=sg({addScalar:Qt,complex:Uc,conj:Wo,divideScalar:Mt,equal:xa,identity:ao,isZero:qa,matrix:$e,multiplyScalar:Ot,sign:WD,sqrt:La,subtractScalar:ga,typed:te,unaryMinus:fi,zeros:ln}),LI=yd({config:Oe,matrix:$e}),zI=rh({DenseMatrix:_r,concat:Gr,equalScalar:Ir,matrix:$e,typed:te,zeros:ln}),Ps=Hd({BigNumber:Ge,DenseMatrix:_r,config:Oe,equalScalar:Ir,matrix:$e,typed:te,zeros:ln}),Tn=lh({DenseMatrix:_r,concat:Gr,config:Oe,matrix:$e,typed:te}),Bt=$p({DenseMatrix:_r,concat:Gr,equalScalar:Ir,matrix:$e,subtractScalar:ga,typed:te,unaryMinus:fi}),UI=Ld({concat:Gr,matrix:$e,typed:te}),WI=bh({DenseMatrix:_r,concat:Gr,config:Oe,equalScalar:Ir,matrix:$e,typed:te}),ry=Jd({DenseMatrix:_r,divideScalar:Mt,equalScalar:Ir,matrix:$e,multiplyScalar:Ot,subtractScalar:ga,typed:te}),YI=ad({DenseMatrix:_r,concat:Gr,matrix:$e,typed:te}),Lr=pv({DenseMatrix:_r,SparseMatrix:Bi,addScalar:Qt,concat:Gr,equalScalar:Ir,matrix:$e,typed:te}),HI=Yh({BigNumber:Ge,DenseMatrix:_r,concat:Gr,equalScalar:Ir,matrix:$e,typed:te}),$I=qu({concat:Gr,equalScalar:Ir,matrix:$e,typed:te}),GI=Lu({DenseMatrix:_r,concat:Gr,equalScalar:Ir,matrix:$e,typed:te}),VI=Kp({DenseMatrix:_r,concat:Gr,matrix:$e,typed:te}),ZI=Vg({addScalar:Qt,combinations:zc,divideScalar:Mt,isInteger:Ln,isNegative:no,multiplyScalar:Ot,typed:te}),Go=ah({BigNumber:Ge,DenseMatrix:_r,Fraction:Uo,concat:Gr,config:Oe,equalScalar:Ir,matrix:$e,typed:te}),XD=oh({concat:Gr,matrix:$e,typed:te}),QI=af({add:Lr,typed:te,unaryPlus:Gx}),ty=xh({equal:xa,typed:te}),XI=Yu({matrix:$e,number:Oi,subtract:Bt,typed:te}),JI=Cg({abs:En,addScalar:Qt,deepEqual:ty,divideScalar:Mt,multiplyScalar:Ot,sqrt:La,subtractScalar:ga,typed:te}),$c=vv({addScalar:Qt,conj:Wo,multiplyScalar:Ot,size:cn,typed:te}),KI=fh({compareText:XD,isZero:qa,typed:te}),JD=Pu({DenseMatrix:_r,config:Oe,equalScalar:Ir,matrix:$e,round:Ps,typed:te,zeros:ln}),jI=Ip({BigNumber:Ge,DenseMatrix:_r,concat:Gr,config:Oe,equalScalar:Ir,matrix:$e,round:Ps,typed:te,zeros:ln}),e4=dv({abs:En,addScalar:Qt,divideScalar:Mt,isPositive:Yo,multiplyScalar:Ot,smaller:Tn,sqrt:La,typed:te}),KD=Sh({DenseMatrix:_r,smaller:Tn}),yn=Nh({ImmutableDenseMatrix:KD,getMatrixDataType:Zx}),Fn=hh({DenseMatrix:_r,concat:Gr,config:Oe,matrix:$e,typed:te}),ny=$d({Complex:pt,config:Oe,divideScalar:Mt,typed:te}),r4=Kd({DenseMatrix:_r,divideScalar:Mt,equalScalar:Ir,matrix:$e,multiplyScalar:Ot,subtractScalar:ga,typed:te}),t4=bp({flatten:vf,matrix:$e,size:cn,typed:te}),n4=rf({config:Oe,numeric:za,smaller:Tn,typed:te}),jD=Iu({DenseMatrix:_r,concat:Gr,config:Oe,equalScalar:Ir,matrix:$e,round:Ps,typed:te,zeros:ln}),it=zp({addScalar:Qt,dot:$c,equalScalar:Ir,matrix:$e,multiplyScalar:Ot,typed:te}),a4=Vd({Complex:pt,config:Oe,divideScalar:Mt,typed:te}),i4=zu({DenseMatrix:_r,concat:Gr,equalScalar:Ir,matrix:$e,typed:te}),Gc=wh({compare:Go,isNaN:pf,isNumeric:$o,typed:te}),o4=th({DenseMatrix:_r,concat:Gr,equalScalar:Ir,matrix:$e,typed:te,zeros:ln}),eS=cg({SparseMatrix:Bi,abs:En,add:Lr,divideScalar:Mt,larger:Fn,largerEq:Hc,multiply:it,subtract:Bt,transpose:df,typed:te}),ra=Vu({add:Lr,matrix:$e,typed:te,zeros:ln}),ay=nf({add:Lr,config:Oe,numeric:za,typed:te}),s4=gv({add:Lr,matrix:$e,typed:te}),rS=jd({DenseMatrix:_r,divideScalar:Mt,equalScalar:Ir,matrix:$e,multiplyScalar:Ot,subtractScalar:ga,typed:te}),u4=n0({Complex:pt,add:Lr,multiply:it,number:Oi,typed:te}),iy=Fp({DenseMatrix:_r,config:Oe,equalScalar:Ir,matrix:$e,round:Ps,typed:te,zeros:ln}),ci=ih({compare:Go,typed:te}),f4=Zg({addScalar:Qt,combinations:zc,isInteger:Ln,isNegative:no,isPositive:Yo,larger:Fn,typed:te}),c4=od({matrix:$e,multiply:it,subtract:Bt,typed:te}),tS=gg({divideScalar:Mt,isZero:qa,matrix:$e,multiply:it,subtractScalar:ga,typed:te,unaryMinus:fi}),l4=Qp({concat:Gr,equalScalar:Ir,matrix:$e,multiplyScalar:Ot,typed:te}),nS=Ah({larger:Fn,smaller:Tn}),aS=Pp({Complex:pt,DenseMatrix:_r,ceil:iy,equalScalar:Ir,floor:JD,matrix:$e,typed:te,zeros:ln}),iS=xv({Index:yn,typed:te}),m4=Eg({abs:En,add:Lr,addScalar:Qt,config:Oe,divideScalar:Mt,equalScalar:Ir,flatten:vf,isNumeric:$o,isZero:qa,matrix:$e,multiply:it,multiplyScalar:Ot,smaller:Tn,subtract:Bt,typed:te}),p4=Vp({BigNumber:Ge,add:Lr,config:Oe,equal:xa,isInteger:Ln,mod:jD,smaller:Tn,typed:te,xgcd:GD}),d4=Rp({concat:Gr,equalScalar:Ir,matrix:$e,typed:te}),h4=Gd({Complex:pt,config:Oe,divideScalar:Mt,log:ny,typed:te}),oy=ef({config:Oe,larger:Fn,numeric:za,typed:te}),v4=nv({DenseMatrix:_r,Index:yn,compareNatural:ci,size:cn,subset:ra,typed:te}),g4=iv({DenseMatrix:_r,Index:yn,compareNatural:ci,size:cn,subset:ra,typed:te}),x4=sv({Index:yn,compareNatural:ci,size:cn,subset:ra,typed:te}),y4=fv({Index:yn,compareNatural:ci,size:cn,subset:ra,typed:te}),Is=ph({DenseMatrix:_r,concat:Gr,config:Oe,matrix:$e,typed:te}),b4=Dh({compare:Go,compareNatural:ci,matrix:$e,typed:te}),w4=ju({concat:Gr,equalScalar:Ir,matrix:$e,not:Wc,typed:te,zeros:ln}),Rs=$u({bignumber:ea,matrix:$e,add:Lr,config:Oe,isPositive:Yo,larger:Fn,largerEq:Hc,smaller:Tn,smallerEq:Is,typed:te}),D4=Gu({Index:yn,matrix:$e,range:Rs,typed:te}),oS=av({DenseMatrix:_r,Index:yn,compareNatural:ci,size:cn,subset:ra,typed:te}),S4=uv({Index:yn,compareNatural:ci,size:cn,subset:ra,typed:te}),sS=lv({Index:yn,concat:Gr,setDifference:oS,size:cn,subset:ra,typed:te}),uS=Mh({FibonacciHeap:nS,addScalar:Qt,equalScalar:Ir}),fS=Wu({Index:yn,matrix:$e,range:Rs,typed:te}),Vo=xg({abs:En,addScalar:Qt,det:tS,divideScalar:Mt,identity:ao,matrix:$e,multiply:it,typed:te,unaryMinus:fi}),cS=og({DenseMatrix:_r,Spa:uS,SparseMatrix:Bi,abs:En,addScalar:Qt,divideScalar:Mt,equalScalar:Ir,larger:Fn,matrix:$e,multiplyScalar:Ot,subtractScalar:ga,typed:te,unaryMinus:fi}),N4=yg({Complex:pt,add:Lr,ctranspose:Kx,deepEqual:ty,divideScalar:Mt,dot:$c,dotDivide:hf,equal:xa,inv:Vo,matrix:$e,multiply:it,typed:te}),ya=Yd({Complex:pt,config:Oe,fraction:Bs,identity:ao,inv:Vo,matrix:$e,multiply:it,number:Oi,typed:te}),lS=ov({DenseMatrix:_r,Index:yn,compareNatural:ci,size:cn,subset:ra,typed:te}),A4=mv({Index:yn,concat:Gr,setIntersect:lS,setSymDifference:sS,size:cn,subset:ra,typed:te}),M4=Dg({abs:En,add:Lr,identity:ao,inv:Vo,map:Ho,max:oy,multiply:it,size:cn,sqrt:La,subtract:Bt,typed:te}),wr=Eh({BigNumber:Ge,Complex:pt,Fraction:Uo,abs:En,addScalar:Qt,config:Oe,divideScalar:Mt,equal:xa,fix:aS,format:mf,isNumeric:$o,multiplyScalar:Ot,number:Oi,pow:ya,round:Ps,subtractScalar:ga}),C4=F0({BigNumber:Ge,Unit:wr,config:Oe}),E4=lx({BigNumber:Ge,Unit:wr,config:Oe}),T4=j0({BigNumber:Ge,Unit:wr,config:Oe}),F4=B0({BigNumber:Ge,Unit:wr,config:Oe}),_4=rx({BigNumber:Ge,Unit:wr,config:Oe}),O4=P0({BigNumber:Ge,Unit:wr,config:Oe}),B4=_0({BigNumber:Ge,Unit:wr,config:Oe}),P4=G0({BigNumber:Ge,Unit:wr,config:Oe}),I4=Zd({DenseMatrix:_r,concat:Gr,equalScalar:Ir,matrix:$e,pow:ya,typed:te}),R4=T0({BigNumber:Ge,Unit:wr,config:Oe}),k4=O0({BigNumber:Ge,Unit:wr,config:Oe}),q4=wg({abs:En,add:Lr,identity:ao,inv:Vo,multiply:it,typed:te}),L4=tx({BigNumber:Ge,Unit:wr,config:Oe}),mS=Cd({addScalar:Qt,ceil:iy,conj:Wo,divideScalar:Mt,dotDivide:hf,exp:zD,i:RD,log2:UD,matrix:$e,multiplyScalar:Ot,pow:ya,tau:qD,typed:te}),sy=Ig({BigNumber:Ge,Complex:pt,config:Oe,multiplyScalar:Ot,pow:ya,typed:te}),z4=A0({BigNumber:Ge,Unit:wr,config:Oe}),U4=H0({BigNumber:Ge,Unit:wr,config:Oe}),W4=Ed({conj:Wo,dotDivide:hf,fft:mS,typed:te}),Y4=q0({BigNumber:Ge,Unit:wr,config:Oe}),H4=ax({BigNumber:Ge,Unit:wr,config:Oe}),$4=E0({BigNumber:Ge,Unit:wr,config:Oe}),G4=mx({BigNumber:Ge,Unit:wr,config:Oe}),V4=ox({BigNumber:Ge,Unit:wr,config:Oe}),Z4=V0({BigNumber:Ge,Unit:wr,config:Oe}),Q4=k0({BigNumber:Ge,Unit:wr,config:Oe}),X4=xx({BigNumber:Ge,Unit:wr,config:Oe}),J4=hx({BigNumber:Ge,Unit:wr,config:Oe}),K4=yx({BigNumber:Ge,Unit:wr,config:Oe}),j4=$0({BigNumber:Ge,Unit:wr,config:Oe}),eR=Z0({BigNumber:Ge,Unit:wr,config:Oe}),rR=C0({BigNumber:Ge,Unit:wr,config:Oe}),tR=Q0({BigNumber:Ge,Unit:wr,config:Oe}),nR=fx({BigNumber:Ge,Unit:wr,config:Oe}),aR=N0({BigNumber:Ge,Unit:wr,config:Oe}),iR=cx({BigNumber:Ge,Unit:wr,config:Oe}),oR=X0({BigNumber:Ge,Unit:wr,config:Oe}),sR=ex({BigNumber:Ge,Unit:wr,config:Oe}),uR=L0({BigNumber:Ge,Unit:wr,config:Oe}),fR=_h({Unit:wr,typed:te}),an=Mg({divideScalar:Mt,equalScalar:Ir,inv:Vo,matrix:$e,multiply:it,typed:te}),cR=U0({BigNumber:Ge,Unit:wr,config:Oe}),gf=kg({gamma:sy,typed:te}),lR=nx({BigNumber:Ge,Unit:wr,config:Oe}),mR=dx({BigNumber:Ge,Unit:wr,config:Oe}),pR=I0({BigNumber:Ge,Unit:wr,config:Oe}),pS=lg({DenseMatrix:_r,lsolve:QD,lup:cS,matrix:$e,slu:eS,typed:te,usolve:ry}),dR=R0({BigNumber:Ge,Unit:wr,config:Oe}),hR=px({BigNumber:Ge,Unit:wr,config:Oe}),vR=Lg({add:Lr,divide:an,factorial:gf,isInteger:Ln,isPositive:Yo,multiply:it,typed:te}),gR=zg({factorial:gf,typed:te}),xR=vx({BigNumber:Ge,Unit:wr,config:Oe}),yR=mg({add:Lr,cbrt:VD,divide:an,equalScalar:Ir,im:Qx,isZero:qa,multiply:it,re:Xx,sqrt:La,subtract:Bt,typeOf:YD,typed:te,unaryMinus:fi}),bR=cv({compareNatural:ci,typed:te}),wR=Td({abs:En,add:Lr,bignumber:ea,divide:an,isNegative:no,isPositive:Yo,larger:Fn,map:Ho,matrix:$e,max:oy,multiply:it,smaller:Tn,subtract:Bt,typed:te,unaryMinus:fi}),dS=$g({bignumber:ea,addScalar:Qt,combinations:zc,divideScalar:Mt,factorial:gf,isInteger:Ln,isNegative:no,larger:Fn,multiplyScalar:Ot,number:Oi,pow:ya,subtractScalar:ga,typed:te}),DR=Th({Unit:wr,typed:te}),SR=Gg({addScalar:Qt,isInteger:Ln,isNegative:no,stirlingS2:dS,typed:te}),hS=bg({abs:En,add:Lr,addScalar:Qt,atan:LD,bignumber:ea,column:fS,complex:Uc,config:Oe,cos:Vx,diag:ZD,divideScalar:Mt,dot:$c,equal:xa,flatten:vf,im:Qx,inv:Vo,larger:Fn,matrix:$e,matrixFromColumns:jx,multiply:it,multiplyScalar:Ot,number:Oi,qr:ey,re:Xx,reshape:$D,sin:Yc,size:cn,smaller:Tn,sqrt:La,subtract:Bt,typed:te,usolve:ry,usolveAll:rS}),NR=W0({BigNumber:Ge,Unit:wr,config:Oe}),AR=ix({BigNumber:Ge,Unit:wr,config:Oe}),MR=qg({divide:an,dotDivide:hf,isNumeric:$o,log:ny,map:Ho,matrix:$e,multiply:it,sum:ay,typed:te}),vS=of({add:Lr,divide:an,typed:te}),CR=sx({BigNumber:Ge,Unit:wr,config:Oe}),ER=M0({BigNumber:Ge,Unit:wr,config:Oe}),TR=uf({bignumber:ea,add:Lr,compare:Go,divide:an,isInteger:Ln,larger:Fn,multiply:it,partitionSelect:Gc,smaller:Tn,smallerEq:Is,subtract:Bt,typed:te}),uy=sf({add:Lr,apply:Jx,divide:an,isNaN:pf,multiply:it,subtract:Bt,typed:te}),FR=z0({BigNumber:Ge,Unit:wr,config:Oe}),gS=Fg({add:Lr,compare:Go,divide:an,partitionSelect:Gc,typed:te}),_R=Og({add:Lr,divide:an,matrix:$e,mean:vS,multiply:it,pow:ya,sqrt:La,subtract:Bt,sum:ay,typed:te}),OR=a0({Complex:pt,add:Lr,divide:an,matrix:$e,multiply:it,typed:te}),BR=_g({abs:En,map:Ho,median:gS,subtract:Bt,typed:te}),PR=ff({map:Ho,sqrt:La,typed:te,variance:uy}),IR=_d({BigNumber:Ge,Complex:pt,add:Lr,config:Oe,divide:an,equal:xa,factorial:gf,gamma:sy,isNegative:no,multiply:it,pi:$x,pow:ya,sin:Yc,smallerEq:Is,subtract:Bt,typed:te}),fy=hv({abs:En,add:Lr,conj:Wo,ctranspose:Kx,eigs:hS,equalScalar:Ir,larger:Fn,matrix:$e,multiply:it,pow:ya,smaller:Tn,sqrt:La,typed:te}),xS=wd({BigNumber:Ge,DenseMatrix:_r,SparseMatrix:Bi,addScalar:Qt,config:Oe,cos:Vx,matrix:$e,multiplyScalar:Ot,norm:fy,sin:Yc,typed:te,unaryMinus:fi}),RR=gx({BigNumber:Ge,Unit:wr,config:Oe}),yS=Ng({identity:ao,matrix:$e,multiply:it,norm:fy,qr:ey,subtract:Bt,typed:te}),kR=bd({multiply:it,rotationMatrix:xS,typed:te}),bS=Sg({abs:En,add:Lr,concat:Gr,identity:ao,index:iS,lusolve:pS,matrix:$e,matrixFromColumns:jx,multiply:it,range:Rs,schur:yS,subset:ra,subtract:Bt,transpose:df,typed:te}),qR=Ag({matrix:$e,multiply:it,sylvester:bS,transpose:df,typed:te});var xf={},yf={},LR={},_n=bv({mathWithTransform:yf}),bf=Yv({Node:_n}),io=$v({Node:_n}),ks=Vv({Node:_n}),zR=Jv({Node:_n}),wf=Av({Node:_n}),UR=_v({Node:_n,ResultSet:kD}),WR=Bv({Node:_n}),Zo=kv({Node:_n}),YR=Qv({Node:_n}),bZ=i0({classes:LR}),wS=dg({math:xf,typed:te}),HR=Lv({Node:_n,typed:te}),wZ=vg({Chain:wS,typed:te}),Df=Uv({Node:_n,size:cn}),Sf=Sv({Node:_n,subset:ra}),$R=Tv({matrix:$e,Node:_n,subset:ra}),Qo=Kv({Unit:wr,Node:_n,math:xf}),Xo=eg({Node:_n,SymbolNode:Qo,math:xf}),Ua=rg({AccessorNode:Sf,ArrayNode:wf,AssignmentNode:$R,BlockNode:UR,ConditionalNode:WR,ConstantNode:Zo,FunctionAssignmentNode:HR,FunctionNode:Xo,IndexNode:Df,ObjectNode:bf,OperatorNode:io,ParenthesisNode:ks,RangeNode:YR,RelationalNode:zR,SymbolNode:Qo,config:Oe,numeric:za,typed:te}),GR=jg({ConstantNode:Zo,FunctionNode:Xo,OperatorNode:io,ParenthesisNode:ks,parse:Ua,typed:te}),DS=Jg({bignumber:ea,fraction:Bs,AccessorNode:Sf,ArrayNode:wf,ConstantNode:Zo,FunctionNode:Xo,IndexNode:Df,ObjectNode:bf,OperatorNode:io,SymbolNode:Qo,config:Oe,mathWithTransform:yf,matrix:$e,typed:te}),DZ=tg({parse:Ua,typed:te}),SS=Kg({AccessorNode:Sf,ArrayNode:wf,ConstantNode:Zo,FunctionNode:Xo,IndexNode:Df,ObjectNode:bf,OperatorNode:io,ParenthesisNode:ks,SymbolNode:Qo,add:Lr,divide:an,equal:xa,isZero:qa,multiply:it,parse:Ua,pow:ya,subtract:Bt,typed:te}),NS=ng({parse:Ua,typed:te}),VR=pg({evaluate:NS}),ZR=ag({evaluate:NS}),cy=Xg({bignumber:ea,fraction:Bs,AccessorNode:Sf,ArrayNode:wf,ConstantNode:Zo,FunctionNode:Xo,IndexNode:Df,ObjectNode:bf,OperatorNode:io,ParenthesisNode:ks,SymbolNode:Qo,add:Lr,config:Oe,divide:an,equal:xa,isZero:qa,mathWithTransform:yf,matrix:$e,multiply:it,parse:Ua,pow:ya,resolve:GR,simplifyConstant:DS,simplifyCore:SS,subtract:Bt,typed:te}),SZ=e0({OperatorNode:io,parse:Ua,simplify:cy,typed:te}),NZ=Qg({parse:Ua,typed:te}),AZ=ig({Parser:ZR,typed:te}),MZ=t0({bignumber:ea,fraction:Bs,AccessorNode:Sf,ArrayNode:wf,ConstantNode:Zo,FunctionNode:Xo,IndexNode:Df,ObjectNode:bf,OperatorNode:io,ParenthesisNode:ks,SymbolNode:Qo,add:Lr,config:Oe,divide:an,equal:xa,isZero:qa,mathWithTransform:yf,matrix:$e,multiply:it,parse:Ua,pow:ya,simplify:cy,simplifyConstant:DS,simplifyCore:SS,subtract:Bt,typed:te}),CZ=r0({ConstantNode:Zo,FunctionNode:Xo,OperatorNode:io,ParenthesisNode:ks,SymbolNode:Qo,config:Oe,equal:xa,isZero:qa,numeric:za,parse:Ua,simplify:cy,typed:te}),EZ=hg({Help:VR,mathWithTransform:yf,typed:te});ht(xf,{e:ID,false:bP,fineStructure:wP,i:RD,Infinity:DP,LN10:SP,LOG10E:NP,NaN:AP,null:MP,phi:CP,SQRT1_2:TP,sackurTetrode:FP,tau:qD,true:_P,E:ID,version:OP,efimovFactor:BP,LN2:PP,pi:$x,replacer:IP,reviver:bZ,SQRT2:RP,typed:te,unaryPlus:Gx,PI:$x,weakMixingAngle:kP,abs:En,acos:qP,acot:LP,acsc:zP,addScalar:Qt,arg:UP,asech:WP,asinh:YP,atan:LD,atanh:HP,bignumber:ea,bitNot:$P,boolean:GP,clone:VP,combinations:zc,complex:Uc,conj:Wo,cos:Vx,cot:ZP,csc:QP,cube:XP,equalScalar:Ir,erf:JP,exp:zD,expm1:KP,filter:jP,forEach:eI,format:mf,getMatrixDataType:Zx,hex:rI,im:Qx,isInteger:Ln,isNegative:no,isPositive:Yo,isZero:qa,LOG2E:tI,lgamma:nI,log10:aI,log2:UD,map:Ho,multiplyScalar:Ot,not:Wc,number:Oi,oct:iI,pickRandom:oI,print:sI,random:uI,re:Xx,sec:fI,sign:WD,sin:Yc,splitUnit:cI,square:lI,string:mI,subtractScalar:ga,tan:pI,typeOf:YD,acosh:dI,acsch:hI,apply:Jx,asec:vI,bin:gI,chain:wZ,combinationsWithRep:xI,cosh:yI,csch:bI,isNaN:pf,isPrime:wI,randomInt:DI,sech:SI,sinh:NI,sparse:AI,sqrt:La,tanh:MI,unaryMinus:fi,acoth:CI,coth:EI,fraction:Bs,isNumeric:$o,matrix:$e,matrixFromFunction:TI,mode:FI,numeric:za,prod:HD,reshape:$D,size:cn,squeeze:_I,transpose:df,xgcd:GD,zeros:ln,asin:OI,cbrt:VD,concat:Gr,count:BI,ctranspose:Kx,diag:ZD,divideScalar:Mt,dotDivide:hf,equal:xa,flatten:vf,hasNumericValue:PI,identity:ao,kron:II,largerEq:Hc,leftShift:RI,lsolve:QD,matrixFromColumns:jx,nthRoot:kI,ones:qI,qr:ey,resize:LI,rightArithShift:zI,round:Ps,smaller:Tn,subtract:Bt,to:UI,unequal:WI,usolve:ry,xor:YI,add:Lr,atan2:HI,bitAnd:$I,bitOr:GI,bitXor:VI,catalan:ZI,compare:Go,compareText:XD,cumsum:QI,deepEqual:ty,diff:XI,distance:JI,dot:$c,equalText:KI,floor:JD,gcd:jI,hypot:e4,larger:Fn,log:ny,lsolveAll:r4,matrixFromRows:t4,min:n4,mod:jD,multiply:it,nthRoots:a4,or:i4,partitionSelect:Gc,rightLogShift:o4,slu:eS,subset:ra,sum:ay,trace:s4,usolveAll:rS,zpk2tf:u4,ceil:iy,compareNatural:ci,composition:f4,cross:c4,det:tS,dotMultiply:l4,fix:aS,index:iS,intersect:m4,invmod:p4,lcm:d4,log1p:h4,max:oy,setCartesian:v4,setDistinct:g4,setIsSubset:x4,setPowerset:y4,smallerEq:Is,sort:b4,and:w4,range:Rs,row:D4,setDifference:oS,setMultiplicity:S4,setSymDifference:sS,column:fS,inv:Vo,lup:cS,pinv:N4,pow:ya,setIntersect:lS,setUnion:A4,sqrtm:M4,vacuumImpedance:C4,wienDisplacement:E4,atomicMass:T4,bohrMagneton:F4,boltzmann:_4,conductanceQuantum:O4,coulomb:B4,deuteronMass:P4,dotPow:I4,electricConstant:R4,elementaryCharge:k4,expm:q4,faraday:L4,fft:mS,gamma:sy,gravitationConstant:z4,hartreeEnergy:U4,ifft:W4,klitzing:Y4,loschmidt:H4,magneticConstant:$4,molarMass:G4,molarPlanckConstant:V4,neutronMass:Z4,nuclearMagneton:Q4,planckCharge:X4,planckLength:J4,planckTemperature:K4,protonMass:j4,quantumOfCirculation:eR,reducedPlanckConstant:rR,rydberg:tR,secondRadiation:nR,speedOfLight:aR,stefanBoltzmann:iR,thomsonCrossSection:oR,avogadro:sR,bohrRadius:uR,createUnit:fR,divide:an,electronMass:cR,factorial:gf,firstRadiation:lR,gravity:mR,inverseConductanceQuantum:pR,lusolve:pS,magneticFluxQuantum:dR,molarMassC12:hR,multinomial:vR,parse:Ua,permutations:gR,planckMass:xR,polynomialRoot:yR,resolve:GR,setSize:bR,simplifyConstant:DS,solveODE:wR,stirlingS2:dS,unit:DR,bellNumbers:SR,compile:DZ,eigs:hS,fermiCoupling:NR,gasConstant:AR,kldivergence:MR,mean:vS,molarVolume:CR,planckConstant:ER,quantileSeq:TR,simplifyCore:SS,variance:uy,classicalElectronRadius:FR,evaluate:NS,median:gS,simplify:cy,symbolicEqual:SZ,corr:_R,freqz:OR,leafCount:NZ,mad:BR,parser:AZ,rationalize:MZ,std:PR,zeta:IR,derivative:CZ,norm:fy,rotationMatrix:xS,help:EZ,planckTime:RR,schur:yS,rotate:kR,sylvester:bS,lyap:qR,config:Oe});ht(yf,xf,{filter:Sx({typed:te}),forEach:Nx({typed:te}),map:Mx({typed:te}),apply:wx({isInteger:Ln,typed:te}),or:Wx({DenseMatrix:_r,concat:Gr,equalScalar:Ir,matrix:$e,typed:te}),and:Ux({add:Lr,concat:Gr,equalScalar:Ir,matrix:$e,not:Wc,typed:te,zeros:ln}),concat:Bx({isInteger:Ln,matrix:$e,typed:te}),max:Cx({config:Oe,larger:Fn,numeric:za,typed:te}),print:zx({add:Lr,matrix:$e,typed:te,zeros:ln}),bitAnd:Yx({add:Lr,concat:Gr,equalScalar:Ir,matrix:$e,not:Wc,typed:te,zeros:ln}),diff:Px({bignumber:ea,matrix:$e,number:Oi,subtract:Bt,typed:te}),min:Tx({config:Oe,numeric:za,smaller:Tn,typed:te}),subset:Ox({add:Lr,matrix:$e,typed:te,zeros:ln}),bitOr:Hx({DenseMatrix:_r,concat:Gr,equalScalar:Ir,matrix:$e,typed:te}),cumsum:qx({add:Lr,typed:te,unaryPlus:Gx}),index:Ax({Index:yn,getMatrixDataType:Zx}),sum:Rx({add:Lr,config:Oe,numeric:za,typed:te}),range:Fx({bignumber:ea,matrix:$e,add:Lr,config:Oe,isPositive:Yo,larger:Fn,largerEq:Hc,smaller:Tn,smallerEq:Is,typed:te}),row:_x({Index:yn,matrix:$e,range:Rs,typed:te}),column:Dx({Index:yn,matrix:$e,range:Rs,typed:te}),mean:Ex({add:Lr,divide:an,typed:te}),quantileSeq:kx({add:Lr,bignumber:ea,compare:Go,divide:an,isInteger:Ln,larger:Fn,multiply:it,partitionSelect:Gc,smaller:Tn,smallerEq:Is,subtract:Bt,typed:te}),variance:Lx({add:Lr,apply:Jx,divide:an,isNaN:pf,multiply:it,subtract:Bt,typed:te}),std:Ix({map:Ho,sqrt:La,typed:te,variance:uy})});ht(LR,{BigNumber:Ge,Complex:pt,Fraction:Uo,Matrix:Lc,Node:_n,ObjectNode:bf,OperatorNode:io,ParenthesisNode:ks,Range:EP,RelationalNode:zR,ResultSet:kD,ArrayNode:wf,BlockNode:UR,ConditionalNode:WR,ConstantNode:Zo,DenseMatrix:_r,RangeNode:YR,Chain:wS,FunctionAssignmentNode:HR,SparseMatrix:Bi,IndexNode:Df,ImmutableDenseMatrix:KD,Index:yn,AccessorNode:Sf,AssignmentNode:$R,FibonacciHeap:nS,Spa:uS,Unit:wr,SymbolNode:Qo,FunctionNode:Xo,Help:VR,Parser:ZR});wS.createProxy(xf);var AS=PD;var jR=ca(Am(),1);var XR=ca(QR(),1);function JR(e){var r=new XR.default;return e.on=r.on.bind(r),e.off=r.off.bind(r),e.once=r.once.bind(r),e.emit=r.emit.bind(r),e}function KR(e,r,t,n){function a(y,w){var C=arguments.length;if(C!==1&&C!==2)throw new ha("import",C,1,2);w||(w={});function b(O,_,E){if(Array.isArray(_))_.forEach(q=>b(O,q));else if(typeof _=="object")for(var T in _)Xe(_,T)&&b(O,_[T],T);else if(As(_)||E!==void 0){var R=As(_)?x(_)?_.fn+".transform":_.fn:E;if(Xe(O,R)&&O[R]!==_&&!w.silent)throw new Error('Cannot import "'+R+'" twice');O[R]=_}else if(!w.silent)throw new TypeError("Factory, Object, or Array expected")}var M={};b(M,y);for(var A in M)if(Xe(M,A)){var S=M[A];if(As(S))o(S,w);else if(s(S))i(A,S,w);else if(!w.silent)throw new TypeError("Factory, Object, or Array expected")}}function i(y,w,C){if(C.wrap&&typeof w=="function"&&(w=c(w)),m(w)&&(w=e(y,{[w.signature]:w})),e.isTypedFunction(t[y])&&e.isTypedFunction(w)){C.override?w=e(y,w.signatures):w=e(t[y],w),t[y]=w,delete n[y],u(y,w),t.emit("import",y,function(){return w});return}if(t[y]===void 0||C.override){t[y]=w,delete n[y],u(y,w),t.emit("import",y,function(){return w});return}if(!C.silent)throw new Error('Cannot import "'+y+'": already exists')}function u(y,w){w&&typeof w.transform=="function"?(t.expression.transform[y]=w.transform,d(y)&&(t.expression.mathWithTransform[y]=w.transform)):(delete t.expression.transform[y],d(y)&&(t.expression.mathWithTransform[y]=w))}function l(y){delete t.expression.transform[y],d(y)?t.expression.mathWithTransform[y]=t[y]:delete t.expression.mathWithTransform[y]}function c(y){var w=function(){for(var b=[],M=0,A=arguments.length;M2&&arguments[2]!==void 0?arguments[2]:y.fn;if(Jb(C,"."))throw new Error("Factory name should not contain a nested path. Name: "+JSON.stringify(C));var b=x(y)?t.expression.transform:t,M=C in t.expression.transform,A=Xe(b,C)?b[C]:void 0,S=function(){var _={};y.dependencies.map(ew).forEach(T=>{if(Jb(T,"."))throw new Error("Factory dependency should not contain a nested path. Name: "+JSON.stringify(T));T==="math"?_.math=t:T==="mathWithTransform"?_.mathWithTransform=t.expression.mathWithTransform:T==="classes"?_.classes=t:_[T]=t[T]});var E=y(_);if(E&&typeof E.transform=="function")throw new Error('Transforms cannot be attached to factory functions. Please create a separate function for it with exports.path="expression.transform"');if(A===void 0||w.override)return E;if(e.isTypedFunction(A)&&e.isTypedFunction(E))return e(A,E);if(w.silent)return A;throw new Error('Cannot import "'+C+'": already exists')};!y.meta||y.meta.lazy!==!1?(Du(b,C,S),A&&M?l(C):(x(y)||h(y))&&Du(t.expression.mathWithTransform,C,()=>b[C])):(b[C]=S(),A&&M?l(C):(x(y)||h(y))&&Du(t.expression.mathWithTransform,C,()=>b[C])),n[C]=y,t.emit("import",C,S)}function s(y){return typeof y=="function"||typeof y=="number"||typeof y=="string"||typeof y=="boolean"||y===null||Ht(y)||Kt(y)||rr(y)||ma(y)||Qe(y)||Array.isArray(y)}function m(y){return typeof y=="function"&&typeof y.signature=="string"}function d(y){return!Xe(v,y)}function h(y){return y.fn.indexOf(".")===-1&&!Xe(v,y.fn)&&(!y.meta||!y.meta.isClass)}function x(y){return y!==void 0&&y.meta!==void 0&&y.meta.isTransformFunction===!0||!1}var v={expression:!0,type:!0,docs:!0,error:!0,json:!0,chain:!0};return a}function ly(e,r){var t=ht({},Ds,r);if(typeof Object.create!="function")throw new Error("ES5 not supported by this JavaScript engine. Please load the es5-shim and es5-sham library for compatibility.");var n=JR({isNumber:sr,isComplex:Kt,isBigNumber:rr,isFraction:ma,isUnit:Ht,isString:St,isArray:Mr,isMatrix:Qe,isCollection:Nt,isDenseMatrix:Xi,isSparseMatrix:pa,isRange:To,isIndex:Ai,isBoolean:cm,isResultSet:lm,isHelp:yu,isFunction:mm,isDate:pm,isRegExp:dm,isObject:Mi,isNull:hm,isUndefined:vm,isAccessorNode:qn,isArrayNode:jt,isAssignmentNode:gm,isBlockNode:xm,isConditionalNode:ym,isConstantNode:yr,isFunctionAssignmentNode:_a,isFunctionNode:gn,isIndexNode:Qn,isNode:Nr,isObjectNode:Ci,isOperatorNode:ct,isParenthesisNode:en,isRangeNode:bm,isRelationalNode:wm,isSymbolNode:at,isChain:bu});n.config=HA(t,n.emit),n.expression={transform:{},mathWithTransform:{config:n.config}};var a=[],i=[];function u(s){if(As(s))return s(n);var m=s[Object.keys(s)[0]];if(As(m))return m(n);if(!UA(s))throw console.warn("Factory object with properties \`type\`, \`name\`, and \`factory\` expected",s),new Error("Factory object with properties \`type\`, \`name\`, and \`factory\` expected");var d=a.indexOf(s),h;return d===-1?(s.math===!0?h=s.factory(n.type,t,u,n.typed,n):h=s.factory(n.type,t,u,n.typed),a.push(s),i.push(h)):h=i[d],h}var l={};function c(){for(var s=arguments.length,m=new Array(s),d=0;d{Ub(l).forEach(s=>{s&&s.meta&&s.meta.recreateOnConfigChange&&o(s,{override:!0})})}),n.create=ly.bind(null,e),n.factory=F,n.import(Ub(LA(e))),n.ArgumentsError=ha,n.DimensionError=pr,n.IndexError=tn,n}var vy=ca(fm());var r5=ca(e5()),TS=class{constructor(){this.lang="en";this.all={en:{hintText:{dragDropModifierKeys:"Hold \${1} to Pin and \${2} to Copy",createListItem:"Select/Create List Item Frame",dragDropProperties:"Drag and drop properties to link them into the list",newItem:"+ New",selectNote:"Select Note...",newFrame:"New"},defaults:{spaceNote:"Current Note",spaceContext:"Current Space"},commands:{h1:"Heading 1",h2:"Heading 2",h3:"Heading 3",h4:"Heading 4",h5:"Heading 5",h6:"Heading 6",columns:"Columns",tabs:"Tabs",button:"Button",label:"Label",column:"Column",idea:"New",group:"Group",paragraph:"Text",card:"Card",progress:"Progress",rating:"Rating",circularProgress:"Circular Progress",list:"Bullet List","ordered-list":"Numbered List",todo:"To-do List",quote:"Quote",internal:"Link to Note",context:"Embed Existing Context",flow:"Embed Note or Space",board:"New Board",divider:"Divider",note:"Note Block",link:"Web Link",callout:"Callout",bookmark:"Bookmark",table:"New Table",codeblock:"Code Block",toggle:"Toggle",emoji:"Emoji",image:"Image",newNote:"New Note",tag:"Tag",makeMenu:"Flow Menu",selectStyle:"Style",toggleKeyboard:"Toggle Keyboard",rows:"Rows",masonry:"Gallery"},styles:{bold:"Bold",italics:"Italics",strikethrough:"Strikethrough",code:"Code",link:"Web Link",blocklink:"Link to Note",textColor:"Text Color",highlight:"Highlight"},commandsSuggest:{noResult:"No result"},commandPalette:{enable:"Enable",disabled:"Disable",openFlow:"Open Flow Blocks in Selection",closeFlow:"Close Flow Blocks in Selection",toggleBold:"Toggle Bold",toggleItalics:"Toggle Italics",openSpaces:"Open Spaces",migrateData:"Migrate Spaces From 0.7",blink:"Blink",openFileContext:"Open Explorer",convertPathToSpace:"Convert to Space",revealFile:"Reveal File in Spaces",releaseNotes:"Release Notes",toggleBacklinks:"Toggle Backlinks",collapseAllFolders:"Collapse All Folders",addFileSpace:"Add File to Space",removeFileSpace:"Remove File from Space"},frames:{sections:{kit:"Kit",paths:"Paths"},label:{label:"Label",description:"Label"},note:{label:"Note",description:"Link to a note"},table:{label:"Table",description:"Table"},context:{label:"Context",description:"Display a context view from another space"},calendar:{label:"Calendar View"},field:{label:"Field",description:"Dynamic node that displays a value based on property type"},event:{label:"Event"},divider:{label:"Divider",description:"Divider to separate your content"},button:{label:"Button",description:"Buttons can perform actions and open links"},callout:{label:"Callout",description:"Callout to highlight important information"},toggle:{label:"Toggle",description:"Toggle to show/hide content"}},menu:{newView:"New View",closeSpace:"Close Space",customView:"Custom View",detailsView:"Details View",catalogView:"Catalog View",galleryView:"Gallery View",deleteContext:"Delete Context",openSpace:"Open Space",revealInDefault:"Reveal in Finder",setNone:"None",fileMetadataDescription:"This note only",openFilePane:"Open in a new pane",rename:"Rename",changeToFolderNote:"New Space from Note",moveFile:"Move file to...",moveFolder:"Move folder to...",duplicate:"Make a copy",edit:"Edit",delete:"Delete",getHelp:"Make.md Community",vault:"Vault",openVault:"Open Another Vault",openVaultInFolder:"Open Vault Folder",obSettings:"Obsidian Settings",commandPalette:"Command Palette",backToSpace:"Back to Spaces",collapseAllSections:"Collapse All Spaces",expandAllSections:"Expand All Spaces",collapseAllFolders:"Collapse All Folders",expandAllFolders:"Expand All Folders",spaceTitle:"Add/Remove in Space",home:"Home",waypoints:"Waypoints",none:"None",tableView:"Table View",cardView:"Card View",boardView:"Board View",listView:"List View",flowView:"Flow View",groupBy:"Group By",sortBy:"Sort By",newFilter:"New Filter",clearFilters:"Clear Filters",hide:"Hide",unhideFields:"Unhide All Properties",importDataview:"Import All Dataview Properties",saveAllProperties:"Save All Properties to Files",mergeProperties:"Merge Properties",removeFromSpace:"Unpin from Space",removeFromWaypoints:"Unpin from Waypoints",editCode:"Edit Code",editProperties:"Edit Properties",deleteProperty:"Delete Property",hideProperty:"Hide Property",unhideProperty:"Unhide Property",saveProperty:"Save Property",sortAscending:"Sort Ascending",sortDescending:"Sort Descending",deleteRow:"Delete Item",collapseAll:"Collapse All",customSort:"Custom Sort",groupSpaces:"Group Spaces",fileNameSortAlphaAsc:"File Name (A to Z)",fileNameSortAlphaDesc:"File Name (Z to A)",fileNameSortNumericalAsc:"File Name (1 to 9)",fileNameSortNumericalDesc:"File Name (9 to 1)",createdTimeSortAsc:"Created Time (new to old)",createdTimeSortDesc:"Created Time (old to new)",modifiedTimeSortAsc:"Modified Time (new to old)",modifiedTimeSortDesc:"Modified Time (old to new)",sizeSortAsc:"Size (smallest to largest)",sizeSortDesc:"Size (largest to smallest)",spaces:"Spaces",tags:"Tags",manageHiddenFiles:"Manage Hidden Files",manageActions:"Manage Actions",deleteSpace:"Delete",changeColor:"Change Color",changePropertyType:"Change Type",deleteFiles:"Delete Files",createFolderSpace:"Create Space from Folder",folder:"Folder",syncToContext:"Add Property to Context",setIcon:"Set Icon",copyEmbedLink:"Copy Embed Link",moveUp:"Move Up",moveDown:"Move Down",moveTo:"Move To",groupNodes:"Group Nodes",moveFrame:"Move Frame",renameFrame:"Rename Frame",deleteFrame:"Delete Frame",insertAbove:"Insert Above",insertBelow:"Insert Below"},editor:{rows:"Rows",columns:"Columns",catalog:"Catalog",gallery:"Gallery",grid:"Grid",scaleToFit:"Change to Fit",scaleToFill:"Change to Fill",fit:"Fit",strokeNone:"None",strokeSolid:"Solid",strokeDotted:"Dotted",strokeDashed:"Dashed",size:"Size",gap:"Gap",marginLeft:"Left",marginTop:"Top",marginRight:"Right",marginBottom:"Bottom",minimize:"Minimize",paddingLeft:"Left",paddingTop:"Top",paddingRight:"Right",paddingBottom:"Bottom",unlinkProperty:"Unlink Property",linkedProperty:"Linked Property",linkProperty:"Link Property",currentSpace:"Current Space",linkName:"\${1} Link",linkThumbnail:"\${1} Thumbnail",linkSticker:"\${1} Sticker",opacity:"Opacity",shadowSpread:"Spread",shadowBlur:"Blur",width:"Width",height:"Height",margin:"Margin",padding:"Padding",bold:"Bold",italic:"Italic",underline:"Underline",alignLeft:"Align Left",alignCenter:"Align Center",alignRight:"Align Right",alignJustify:"Align Justify",numberOfLines:"Lines",createVerticalSection:"Create Vertical Section",createHorizontalSection:"Create Horizontal Section",themeColors:"Theme Colors",uiColors:"UI Colors",hex:"Hex"},buttons:{add:"Add",addFilter:"Add Filter",addCondition:"Add Condition",customize:"Customize",moreOptions:"More Options",saveProperty:"Save Property",newNote:"New Note",changeIcon:"Change Sticker",removeIcon:"Remove Sticker",addIcon:"Add Sticker",addCover:"Add Cover",changeBanner:"Change Cover",changeBannerShort:"Cover",saveChanges:"Save Changes",removeBanner:"Remove Cover",rename:"Change Name",editFrame:"Edit Frame",saveSpace:"Save Space",createSpace:"New Space",createFolder:"New Folder",createNote:"New Note",createCanvas:"New Canvas",addIntoSpace:"New Pin",addSmartSearch:"Add Live Search",addItem:"Add Item",addProperty:"Add Property",editProperty:"Edit Property",addContext:"Add Context",cancel:"Cancel",search:"Search",delete:"Delete",toggleFlow:"Toggle Flow",openFlow:"Open Flow",hideFlow:"Hide Flow",openLink:"Open Link",addToSpace:"Add to Space",addToSpaceShort:"Pin",addTag:"Add Tag",tag:"Tag",syncFields:"Sync Properties",convertTable:"Convert to Markdown",cutTable:"Cut Table",deleteTable:"Delete Table",blink:"Blink",addFile:"Add Item",merge:"Merge",saveView:"Save View",saveTable:"Save Table",renameView:"Rename View",deleteView:"Delete View",renameTable:"Rename Table",renameTag:"Rename Tag",createTag:"Create Tag",currentFolder:"Current Folder",sync:"Sync",pasteCSS:"Paste CSS",save:"Save",run:"Run"},metadataTypes:{fileName:"File Name",contexts:"Contexts",path:"Path",folder:"Folder",sticker:"Sticker",color:"Color",created:"Created",lastModified:"Last Modified",extension:"Extension",size:"Size",tags:"Tags",inlinks:"Linked Mentions",outlinks:"Links",label:"Label",fileMetadata:"File Metadata",frontmatter:"Frontmatter"},filterTypes:{contains:"contains",notContains:"does not contain",is:"is",isNot:"is not",before:"before",after:"on or after",anyOf:"is any of",noneOf:"is none of",checked:"is checked",unchecked:"is unchecked",isEmpty:"is empty",isNotEmpty:"is not empty",isSameDate:"is same date",isSameDateAsToday:"today"},sortTypes:{alphaAsc:"A to Z",alphaDesc:"Z to A",earliest:"Earliest",latest:"Latest",checkAsc:"Checked \\u2192 Unchecked",checkDesc:"Unchecked \\u2192 Checked",itemsAsc:"Least Items",itemsDesc:"Most Items"},properties:{defaultField:"Name",audio:{label:"Audio",description:"Audio"},text:{label:"Text",description:"Text field"},number:{label:"Number",description:"Number field with optional unit"},boolean:{label:"Yes/No",description:"Yes or No toggle to indicate the status"},date:{label:"Date",description:"Select a date from a calendar"},option:{label:"Option",description:"Select one or multiple option from a list"},file:{label:"File"},link:{label:"Link",description:"Link to another note or a website"},tags:{label:"Tags",description:"Use tags to quickly organize your items"},object:{label:"Object",description:"Store any complex objects"},context:{label:"Relation",description:"Connect to another context property and create a relation"},image:{label:"Image",description:"Select any image from your system or from the internet"},color:{label:"Color",description:"Use colors to label your items or status"},space:{label:"Context",description:"Link to a context"},icon:{label:"Sticker",description:"Use stickers to uniquely label your items or status"},super:{label:"Super Property",links:"Open Link",properties:"Update Property",api:"API",obsidianCommands:"Run Command",runCommand:"Run Command",performAction:"Perform Action",whenClicked:"When Clicked"},fileProperty:{name:"Name",label:"Formula",createdTime:"Created",modifiedTime:"Last Edited",sticker:"Sticker",links:"Links",tags:"Tags",spaces:"Spaces",extension:"Extension",size:"Size",preview:"Note Preview",parentFolder:"Folder",description:"Use a formula to dynamically display a property"}},views:{navigator:"Navigator",explorer:"Explorer",space:"Space"},subViews:{spaceItems:"Items",spaceContext:"Context",spaceLists:"Lists",spaceActions:"Actions",spaceTemplates:"Templates",smartSearch:"Live Searches",filesAndFolders:"Files and Folders"},labels:{duplicateTable:"Duplicate Table",moveTable:"Move Table",editFormula:"Edit Formula",editObject:"Edit Object",properties:"Properties",newAction:"New Action",newTable:"New Table",createFolder:"New Folder Name",rename:"Rename",createNew:"New",default:"Default",done:"Done",tables:"Tables",selectDateFormat:"Select/Type Date Format",renameSection:"Edit Space",createSection:"New Folder",createNote:"New Note",contextMaker:"Context Maker",select:"Select",pinnedItems:"Pinned Items",collapse:"Collapse",expand:"Expand",all:"All",none:"None",view:"View",findStickers:"Find Sticker",mergeProperties:"Merge Properties",placeholder:"Type '\${1}' for commands",notePlaceholder:"New Note for \${1}",itemsSelected:"\${1} Selected",selectNote:"Select Note",selectIcon:"Select Icon",selectImage:"Select Image",selectSpace:"Select Space",styleSmall:"Small",styleMedium:"Medium",styleLarge:"Large",hiddenFilePattern:"Name, Suffixes and Extension",hiddenFileSpecific:"Exclude specific files and folders",textPlaceholder:"Enter Text",noFile:"is not created yet. Click to create.",navigatorSearchPlaceholder:"Search by Text or Filters",blinkPlaceholder:"Quickly Search a File, Folder, Tag... Press Tab to Edit",searchPlaceholder:"Type to search...",contextItemSelectPlaceholder:"Find Item",linkItemSelectPlaceholder:"Find or Create Note",pinNotePlaceholder:"Select a Note or Space to Pin",optionItemSelectPlaceholder:"Select Option",viewItemSelectPlaceholder:"Select View",tagItemSelectPlaceholder:"Find Tag",spaceSelectPlaceholder:"Select any Folder or Tag",propertyItemSelectPlaceholder:"Select Property",sortItemSelectPlaceholder:"Select Sort",filterItemSelectPlaceholder:"Select Filter",imageSelectPlaceholder:"Select an image or paste a URL",imageNotFoundPlaceholder:"No Images Found",syncFrontmatterProperty:"Sync Frontmatter Property",newProperty:"New Property",newPropertyShort:"New Property",propertyType:"Type",propertyDynamic:"Dyanmic",propertyValueSpace:"Space",propertyValueProperty:"Property",propertyLookup:"Edit Formula",dateFormat:"Date Format",propertyFileProp:"Property",multiple:"Multiple",filesCount:"{$1} Files",hiddenFiles:"Hidden Files",addExtension:"Add Rule",saveView:"Save View",saveTable:"Save Table",renameView:"Rename View",renameTable:"Rename Table",syncMetadata:"Sync Metadata",syncProperties:"Sync Properties",selectContext:"Select Context",metadata:"Metadata",backlinks:"Backlinks",spaces:"Spaces",context:"Context",content:"Content",deleteSpace:"Delete Space",deleteFiles:"Delete Files",outgoingLinks:"Outgoing Links",moveTo:"Move to",addTo:"Pin to",copyTo:"Copy to",reorderIn:"Reorder in",border:"Border",corners:"Corners",color:"Color",backgroundColor:"Background",cornerRadius:"Radius",onClick:"On Click",layout:"Layout",element:"Element",name:"Name",display:"Display",alignment:"Alignment",margin:"Margin",padding:"Padding",gap:"Gap",width:"Width",height:"Height",opacity:"Opacity",shadow:"Shadow",shadowBlur:"Blur",shadowSpread:"Spread",typography:"Typography",layers:"Layers",fontSize:"Size",props:"Props",styles:"Styles",events:"Events",code:"Code",selectedLayers:"\${1} Layers"},descriptions:{spaceActions:"Create actions that runs when you press a button",spaceLists:"Create lists to track data and organize them in your space",spaceItems:"Add new items to the space or pin items to the space",spaceTemplates:"Create templates to quickly add items to your space",smartSearch:"Automatically pin notes to this space based on a set of searches",hiddenFileOptions:"Exclude any files and folders by name, suffix or extension.",deleteSpace:"Deleting the space will also delete the folder and its contents.",deleteFiles:"Delete \${1} files/folders and their contents?",addContext:"Contexts lets you connect properties from your tags",spaceProperties:"Define Properties for your Space Items",syncMetadata:"Select which fields from your notes to start syncing with the context.",syncProperties:"Contexts defines and syncs the same fields across your notes depending on their folder or tag.",selectContext:"Select which folder or tag context you want to sync the fields."},flowView:{emptyDoc:"Empty Document",itemsCount:" Items",emptyFolder:"This Folder is Empty"},notice:{duplicateFile:"Folder already contains note with same name",addedToSection:"Added to Space",fileExists:"File Already Exists",folderExists:"Folder Already Exists",noPropertyName:"Property Name is Required",duplicatePropertyName:"Duplicate Property Name",newSpaceName:"Enter a name for your space",duplicateSpaceName:"Space name already exists",cantConvertNoteToSpace:"The view is not a note",templateSaved:"Template saved to space: "},settings:{layoutVertical:"Vertical",layoutHorizontal:"Horizontal",sectionSidebar:"Spaces",sectionEditor:"Maker Mode",sectionFlow:"Flow",sectionAdvanced:"Advanced",sectionDataview:"Dataview",sectionContext:"Context",sectionStickers:"Stickers",sectionNavigator:"Navigator",sectionDefault:"Default Spaces",sectionSpaceView:"Space View",sectionBlink:"Blink",sectionInlineContext:"Inline Context",sectionFlowBlock:"Flow Block",sectionFlowMenu:"Flow Menu",sectionFlowStyler:"Flow Styler",experimental:{name:"Experimental",desc:"Experimental features that are subject to change and may not be optimized for performance"},generateThumbnails:{name:"Generate Thumbnails",desc:"Create thumbnails for images to speed up performance"},minimalThemeFix:{name:"Minimal Theme Fix",description:"Apply fixes for the popular theme Minimal"},inlineStickerMenu:{name:"Inline Stickers",desc:"Add inline stickers by typing :"},openSpacesOnLaunch:{name:"Open Spaces as Default Tab",desc:"Open the Spaces tab when Obsidian launches"},defaultSpaceTemplate:{name:"Default Space Template",desc:"Select the default template for new spaces"},defaultDateFormat:{name:"Default Date Format",desc:"Set the default date format, example: yyyy-MM-dd (see https://date-fns.org/v2.30.0/docs/format)"},newNotePlaceholder:{name:"New Note Placeholder",desc:"Default name for new notes"},folderIndentationLines:{name:"Show Folder Indentation Lines",desc:"Turn on to show a line on the left of folders to indicate indentation"},folderNoteLocation:{name:"Folder Note Location Inside Folder",desc:"Turn on to have folder notes inside the folder, turn off to have it outside"},folderViewDefault:{name:"Show Folder Note by Default",desc:"Show the folder note by default when opening a folder"},internalLinkFlowEditor:{name:"Open Flow Blocks on Internal Link Click",desc:"Turn on to toggle Flow Blocks directly by clicking on internal links, otherwise a tooltip will be shown"},syncContextToFrontmatter:{name:"Sync Context Fields to Frontmatter",desc:"Turn on to automatically save all context fields to frontmatter fields, not just existing frontmatter fields."},syncFormulaToFrontmatter:{name:"Sync Formula Fields to Frontmatter",desc:"Turn on to save calculated formula values to frontmatter fields."},inlineBacklinks:{name:"Show Inline Backlinks (Inline Context required)",desc:"Show editable backlinks at the bottom of your notes"},dataviewInlineContext:{name:"Show Dataview in Inline Context",desc:"Show dataview when inline context is enabled"},inlineContextExplorer:{name:"Inline Context",desc:"Display the context and a banner at the top of your notes"},inlineContextExpanded:{name:"Auto Expand Inline Context",desc:"Expand the inline context sections when opening a note"},inlineContextHorizontal:{name:"Inline Title and Sticker Layout",desc:"Layout for inline title and sticker in Inline Context"},hideFrontmatter:{name:"Hide Frontmatter Properties",desc:"Hide the frontmatter properties in inline context"},openFileContext:{name:"Auto Open Explorer",desc:"Automatically open explorer panel in the right panel"},folderNote:{name:"Enable Folder Note",desc:"Access the folder note in the folder page and hide the folder note from spaces"},expandFolder:{name:"Auto Expand Folder",desc:"Auto expand folders on click"},hoverPreview:{name:"Preview on Hover",desc:"Preview on Hover while holding Control/Command key"},activeFile:{name:"Reveal Active File",desc:"Automatically reveal the active file in Spaces"},contexts:{name:"Contexts",desc:"Contexts allows you to have full control over the metadata of your files"},spaces:{name:"Navigator",desc:"The navigator lets you create and organize your spaces"},spacesStickers:{name:"Stickers",desc:"Use Emojis to make it easier to find your notes"},spacesAlias:{name:"Alias",desc:"Use the alias metadata to show in Spaces"},spacesFileExplorerDual:{name:"Compatibility Mode",desc:"This will improve the compatibility of plugins while using Spaces"},spacesDeleteOption:{name:"Delete File Option",desc:"Select how you want files to be deleted"},spacesDeleteOptions:{permanant:"Delete Permanently",trash:"Move to Obsidian Trash","system-trash":"Move to System Trash"},hideRibbon:{name:"App Ribbon",desc:"Show/hide the left menu aka. ribbon"},spaceView:{name:"Space View",desc:"Open the space view when you click on a space"},defaultSpaces:{name:"Default Spaces",desc:"Recommended spaces for quickly organizing your vault"},homeSpace:{name:"Home Space",desc:"An easy-to-access space where you can add/organize your other spaces"},tagSpaces:{name:"Tag Spaces",desc:"Automatically create spaces for each of your tags"},readableLineWidth:{name:"Readable Line Width",desc:"Use Readable Line Width"},sidebarTabs:{name:"Sidebar Tabs",desc:"Show/hide other sidebar tabs"},spacesPerformance:{name:"Performance Mode",desc:"Turn on performance mode for Spaces, may affect scrolling appearance. Requires Restart"},indexSVG:{name:"Use SVGs as Stickers",desc:"Use any svg file in your vault as a sticker"},inlineStyler:{name:"Flow Styler",desc:"Select text to add styling"},inlineStylerColor:{name:"Text and Highlight Colors \\u{1F9EA}",desc:"Select text color and highlight color, (this may change in the future because of the limitations with HTML and Obsidian)"},spaceRowHeight:{name:"Row Height",desc:"The height for each row in spaces (in pixels), default is 28"},coverHeight:{name:"Cover Height",desc:"The height for the cover of the note or space, default is 200"},makeChar:{name:"Flow Menu Trigger",desc:"Character to open the Flow Menu"},mobileMakeBar:{name:"Flow Styler (Mobile)",desc:"Replaces the mobile toolbar"},editorMarkSans:{name:"Mark Sans \\u{1F9EA}",desc:"Use the editor without Markdown."},editorMakerMode:{name:"Flow (Beta)",desc:"An integrated and intuitive editor experience"},editorMakePlacholder:{name:"Flow Menu Hint Text",desc:"Show a hint text on how to open the Flow Menu Shortcut"},blink:{name:"Blink",desc:"A faster way to search and edit your notes"},editorMakeMenu:{name:"Flow Menu",desc:"Open the Flow menu to quickly add content"},editorMakeMenuTrigger:{name:"Flow Menu Shortcut",desc:"Trigger key to use flow menu"},editorFlowReplace:{name:"Flow Block",desc:"Open your internal links or toggle your embeds in the flow block."},editorFlowStyle:{name:"Flow Block Style",desc:"Select a theme for your flow block",seamless:"Seamless",classic:"Classic",minimal:"Minimal"}}}};this.lang="en";let r=r5.default.locale();["en"].includes(r)&&(this.lang=r)}get texts(){return this.all.en}},Tr=new TS().texts;var RZ=ca(fm());var _Z=(e,r)=>{let t=n=>n=="builtin"?"Builtin":n=="api"?"Spaces":"Action";return[...(e.actionsIndex.get(r)??[]).map(n=>({name:n.schema.name,description:"Action",value:\`\${r}/#;\${n.schema.id}\`,section:"Action"}))??[],...[...e.cli.allCommands()].map(n=>({name:n.schema.name,description:t(n.schema.type),value:n.path,section:t(n.schema.type)}))]};var t5=({field:e,value:r})=>r=="ctime"?{value:\`parseDate(prop('\${e}')['metadata']['file']['\${r}'])\`,type:"date"}:{value:\`prop('\${e}')['metadata']['file']['\${r}']\`,type:"string"},my=(e,r,t,n)=>{let a=wc(e);if(a)return r=="fileprop"&&a.field?t5(a):(r=="option"&&a.source?.length>0&&(a.source=="$commands"?a.options=t.cli.allCommands():a.source=="$links"?a.options=t.spaceManager.allPaths().map(i=>({name:i,value:i})):a.source=="$super"?a.options=_Z(t,n):a.source=="$properties"&&(a.options=t.contextsIndex.get(n)?.cols?.map(i=>({name:i.name,value:i.name}))??[])),[...n5(r).configKeys??[],"alias","default"].reduce((i,u)=>({...i,[u]:a[u]}),{}));if(!r)return{};if(!a)if(r=="context")e?.length>0?a={space:e}:a={};else if(r.startsWith("date"))e?.length>0?a={format:e}:a={};else if(r.startsWith("fileprop"))if(e?.length>0){let[i,u]=e.split(".");a=t5({field:i,value:u})}else a={};else r.startsWith("option")&&(e?.length>0?a={options:Sn(e).map(u=>({name:u,value:u}))}:a={});return a??{}};var n5=(e,r)=>r==Fa?Af.find(t=>t.type=="file"):r=="tags"?Af.find(t=>t.type=="tags-multi"):r=="aliases"?Af.find(t=>t.type=="option-multi"):r=="sticker"?Af.find(t=>e=="icon"):Af.find(t=>e==t.type)||Af.find(t=>e==t.multiType),Af=[{type:"unknown",label:"",restricted:!0,icon:"ui//file-question"},{type:"text",label:Tr.properties.text.label,metadata:!0,icon:"ui//text",primative:!0,description:Tr.properties.text.description},{type:"number",label:Tr.properties.number.label,metadata:!0,icon:"ui//binary",configKeys:["unit"],primative:!0,description:Tr.properties.number.description},{type:"boolean",label:Tr.properties.boolean.label,metadata:!0,icon:"ui//check-square",primative:!0,description:Tr.properties.boolean.description},{type:"date",label:Tr.properties.date.label,metadata:!0,icon:"ui//calendar",configKeys:["format"],primative:!0,description:Tr.properties.date.description},{type:"option",label:Tr.properties.option.label,multi:!0,multiType:"option-multi",icon:"ui//list",configKeys:["options","source"],description:Tr.properties.option.description},{type:"tags-multi",label:Tr.properties.tags.label,icon:"ui//tags",description:Tr.properties.tags.description},{type:"file",label:Tr.properties.file.label,restricted:!0,icon:"ui//mk-make-h3"},{type:"fileprop",label:Tr.properties.fileProperty.label,icon:"ui//formula",configKeys:["field","value","type"],description:Tr.properties.fileProperty.description},{type:"link",label:Tr.properties.link.label,multi:!0,multiType:"link-multi",metadata:!0,icon:"ui//file-text",primative:!0,description:Tr.properties.link.description},{type:"context",label:Tr.properties.context.label,icon:"ui//mk-make-note",multi:!0,multiType:"context-multi",configKeys:["space"],description:Tr.properties.context.description},{type:"object",label:Tr.properties.object.label,multi:!0,multiType:"object-multi",metadata:!0,icon:"ui//list-tree",configKeys:["type","typeName"],description:Tr.properties.object.description},{type:"icon",label:Tr.properties.icon.label,multi:!0,multiType:"icon-multi",icon:"ui//gem",restricted:!0,primative:!0,description:Tr.properties.icon.description},{type:"image",label:Tr.properties.image.label,multi:!0,multiType:"image-multi",metadata:!0,icon:"ui//mk-make-image",primative:!0,description:Tr.properties.image.description},{type:"color",label:Tr.properties.color.label,icon:"ui//mk-make-image",restricted:!0,description:Tr.properties.color.description},{type:"space",label:Tr.properties.space.label,icon:"ui//layout-grid",restricted:!0,description:Tr.properties.space.description},{type:"table",label:Tr.properties.space.label,icon:"ui//layout-grid",restricted:!0,description:Tr.properties.space.description},{type:"super",label:Tr.properties.super.label,icon:"ui//zap",restricted:!0,configKeys:["dynamic","field"]},{type:"input",label:Tr.properties.super.label,icon:"ui//input",restricted:!0}];var qs="files",hy={id:qs,name:"Files",type:"db",primary:"true"},OZ="filesView",BZ={id:OZ,name:"All",type:"view",def:JSON.stringify({db:qs,icon:"ui//file-stack"})},PZ="main",IZ=e=>({id:e,name:e,type:"frame",def:"",predicate:"",primary:"true"}),N4e={uniques:[],cols:["id","name","type","def","predicate","primary"],rows:[IZ(PZ),BZ]},py={uniques:[],cols:["id","name","type","def","predicate","primary"],rows:[hy]},a5={uniques:["name,schemaId"],cols:["name","schemaId","type","value","attrs","hidden","unique","primary"]},dy={...a5,rows:[{name:Fa,schemaId:qs,type:"file",primary:"true",hidden:"",unique:"",attrs:"",value:""},{name:Tr.properties.fileProperty.createdTime,schemaId:qs,type:"fileprop",value:Fa+".ctime",hidden:"",unique:"",attrs:"",primary:"true"}]};var A4e=[{name:Tr.properties.defaultField,schemaId:"",type:"text",primary:"true"}],FS={...a5,rows:[{name:Fa,schemaId:qs,type:"file",primary:"true",hidden:"",unique:"",attrs:"",value:""}]};var M4e={schema:hy,cols:dy.rows,rows:[]},C4e={schema:hy,cols:dy.rows,rows:[]},E4e={schema:hy,cols:FS.rows,rows:[]},i5=(e,r)=>e.filter(t=>r.find(n=>n.id==t.schemaId&&n.type=="db")).reduce((t,n)=>({...t,...t[n.schemaId]?{[n.schemaId]:{uniques:n.unique=="true"?[...t[n.schemaId].uniques,n.name]:t[n.schemaId].uniques,cols:[...t[n.schemaId].cols,n.name],rows:[]}}:{[n.schemaId]:{uniques:n.unique=="true"?[n.name]:[],cols:[n.name],rows:[]}}}),{});var T4e={m_schema:py,m_fields:dy,...i5(dy.rows,py.rows)},F4e={m_schema:py,m_fields:FS,...i5(FS.rows,py.rows)};var _S="spaces://$tags";var fRe={name:Tr.menu.waypoints,displayName:Tr.menu.waypoints,path:"spaces://$waypoints",label:{name:Tr.menu.waypoints,thumbnail:"",sticker:"ui//tags",color:""},type:"default"},cRe={name:Tr.menu.tags,displayName:Tr.menu.tags,path:"spaces://$tags",label:{thumbnail:"",name:Tr.menu.tags,sticker:"ui//tags",color:""},type:"default"},lRe={name:Tr.menu.vault,displayName:Tr.menu.vault,path:"/",label:{thumbnail:"",name:Tr.menu.vault,sticker:"ui//vault",color:""},type:"default"};var o5=(e,r,t,n,a,i,u)=>{if(!t)return"";let l=new Map;Object.keys(a).forEach(o=>l.set(o,a[o])),l.set("$properties",n),l.set("$paths",r),i&&l.set("$current",i);let c;try{e.evaluate("current = current()",l),c=e.evaluate(t,l),c=ws("",c)}catch(o){if(u)throw o}return c};var OS=e=>{let r=new Map;e.filter(u=>u.type=="fileprop"||u.name.startsWith("tags")).forEach(u=>{let{value:l}=my(u.value,u.type),c=[];try{let s=Ua(l).filter(m=>m.type=="FunctionNode").filter(m=>m.fn.name=="prop"&&m.args[0].type=="ConstantNode").map(m=>m.args[0]?.value);c.push(...s)}catch{}let o=u.name;r.has(o)||r.set(o,new Set);for(let s of c){let m=s;m!==o&&r.get(o).add(m)}});let t=new Set,n=[],a=new Set,i=u=>{if(a.has(u))throw new Error("Circular dependency detected");if(!t.has(u)){a.add(u);let l=r.get(u)||new Set;for(let c of l)i(c);t.add(u),a.delete(u),n.push(u)}};for(let u of e)t.has(u.name)||i(u.name);return n},s5=(e,r,t,n,a,i)=>{if(!t)return{};let u=i??OS(n),l=r.get(t[Fa])?.metadata?.property??{},c=Object.keys(l).filter(m=>n.some(d=>d.name==m)).reduce((m,d)=>({...m,[d]:ws(d,l[d])}),{}),o=u.map(m=>n.find(d=>d.name==m)).filter(m=>m&&(m.type=="fileprop"||m.name=="tags")),s=n.reduce((m,d)=>({...m,[d.name]:d}),{});return{...t,...c,...o.reduce((m,d)=>{let{value:h}=my(d.value,d.type);return{...m,[d.name]:o5(e,r,h,s,{...t,...m},a)}},{})}};var u5=(e,r)=>{let t=e?Sn(e):[],n=r?Sn(r):[];return n.every(a=>t.some(i=>i==a))&&t.every(a=>n.some(i=>i==a))},Mf=(e,r)=>e==r,BS=(e,r)=>(e??"").length==0,PS=(e,r)=>(e??"").toLowerCase().includes((r??"").toLowerCase()),IS=(e,r)=>parseFloat(e)>parseFloat(r),RS=(e,r)=>parseInt(e){let t=isNaN(Date.parse(e))?new Date(parseInt(e)):new Date(e),n=isNaN(Date.parse(r))?new Date(parseInt(r)):new Date(r);return t.valueOf()>=n.valueOf()},c5=(e,r)=>{let t=isNaN(Date.parse(e))?new Date(parseInt(e)):new Date(e),n=isNaN(Date.parse(r))?new Date(parseInt(r)):new Date(r);return t.valueOf(){let t=e?Sn(e):[],n=r?Sn(r):[];return t.length==0?!1:n.some(a=>t.some(i=>i==a))},l5=(e,r)=>{if(!e)return!1;let t=new Date(\`\${e.toString().replace(".",":")}\`),n=new Date(\`\${r}\`);return t.getMonth()===n.getMonth()&&t.getDate()===n.getDate()},m5=e=>{if(!e)return!1;let r=new Date(\`\${e.toString()}T00:00\`),t=new Date;return r.getMonth()===t.getMonth()&&r.getDate()===t.getDate()};var Cf={isNotEmpty:{type:["text","file","number","option","option-multi","link","link-multi","image"],fn:(e,r)=>!BS(e,""),valueType:"none"},isEmpty:{type:["text","file","number","option","option-multi","link","link-multi","image"],fn:(e,r)=>BS(e,""),valueType:"none"},include:{fn:(e,r)=>PS(e,r),type:["text","file","link","image"],valueType:"text"},notInclude:{type:["text","file","link","image"],fn:(e,r)=>!PS(e,r),valueType:"text"},is:{type:["text"],fn:(e,r)=>Mf(e,r),valueType:"text"},isNot:{type:["text"],fn:(e,r)=>!Mf(e,r),valueType:"text"},equal:{type:["number"],fn:(e,r)=>Mf(e,r),valueType:"number"},isLink:{type:["link","context"],fn:(e,r)=>Mf(e,r),valueType:"link"},isNotLink:{type:["link","context"],fn:(e,r)=>!Mf(e,r),valueType:"link"},isGreatThan:{type:["number"],fn:(e,r)=>IS(e,r),valueType:"number"},isLessThan:{type:["number"],fn:(e,r)=>RS(e,r),valueType:"number"},isLessThanOrEqual:{type:["number"],fn:(e,r)=>!IS(e,r),valueType:"number"},isGreatThanOrEqual:{type:["number"],fn:(e,r)=>!RS(e,r),valueType:"number"},dateBefore:{type:["date"],fn:(e,r)=>c5(e,r),valueType:"date"},dateAfter:{type:["date"],fn:(e,r)=>f5(e,r),valueType:"date"},isSameDate:{type:["date"],fn:(e,r)=>l5(e,r),valueType:"date"},isSameDateAsToday:{type:["date"],fn:(e,r)=>m5(e,r),valueType:"none"},isExactList:{type:["option","option-multi","link-multi","context-multi","tags-multi"],fn:(e,r)=>u5(e,r),valueType:"list"},isAnyInList:{type:["option","context","link","option-multi","link-multi","context-multi","tags-multi"],fn:(e,r)=>kS(e,r),valueType:"list"},isNoneInList:{type:["option","context","link","option-multi","link-multi","context-multi","tags-multi"],fn:(e,r)=>!kS(e,r),valueType:"list"},isTrue:{type:["boolean"],fn:(e,r)=>e=="true",valueType:"none"},isFalse:{type:["boolean"],fn:(e,r)=>e!="true",valueType:"none"}};var qZ=(e,r,t)=>r.reduce((a,i)=>{let[u,l]=a,c=i.type=="context"?p5(l,i,t):i.type=="path"?h5(l,i,t):i.type=="frontmatter"?d5(l,i,t):v5(l,i,t),o=l.filter(s=>!c.includes(s));return[[...u,...c],o]},[[],e])[0],LZ=(e,r,t)=>r.reduce((n,a)=>a.type=="context"?p5(n,a,t):a.type=="path"?h5(n,a,t):a.type=="frontmatter"?d5(n,a,t):v5(n,a,t),e),p5=(e,r,t)=>{let n=Cf[r.fn];return!n||n.valueType!="none"&&r.value.length==0?[]:e.filter(a=>{let[i,u]=r.field.split("."),l=a.metadata?.property;if(!a.spaces?.includes(i)||!l||!l[u])return!1;let c=!0;if(n){let o=r.fType=="property"?t[r.value]:r.value;c=n.fn(ws(u,l[u]),o)}return c})},d5=(e,r,t)=>{let n=Cf[r.fn];return!n||n.valueType!="none"&&r.value.length==0?[]:e.filter(a=>{let i=a.metadata?.property;if(!i||i[r.field]===void 0)return!1;let u=!0;if(n){let l=r.fType=="property"?t[r.value]:r.value;u=n.fn(ws(r.field,i[r.field]),l)}return u})},h5=(e,r,t)=>{let n=Cf[r.fn];return!n||n.valueType!="none"&&r.value.length==0?[]:e.filter(a=>{let i="";r.field=="outlinks"?i=bs(a.outlinks??[]):r.field=="inlinks"?i=bs(a.inlinks??[]):r.field=="tags"&&(i=bs(a.tags??[]));let u=!0;if(n){let l=r.fType=="property"?t[r.value]:r.value;u=n.fn(i,l)}return u})},v5=(e,r,t)=>{let n=Cf[r.fn];return!n||n.valueType!="none"&&r.value.length==0?[]:e.filter(a=>{let i=!0;if(n){let u=r.fType=="property"?t[r.value]:r.value;i=n.fn(a.metadata?.[r.type]?.[r.field],u)}return i})},g5=(e,r,t)=>e.reduce((a,i)=>!a||i.filters.length==0?!1:i.type=="any"?qZ([r],i.filters,t).length>0:LZ([r],i.filters,t).length>0,!0);var x5=(e,r)=>e.hiddenExtensions.some(t=>r.endsWith(t))||r.startsWith(e.spacesFolder+"/#")||e.hiddenFiles.some(t=>t==r);var y5=(e,r,t)=>{if(!e)return{changed:!1,cache:null};if(!r)return{changed:!1,cache:{path:e.path,frames:{},schemas:[]}};let n=Object.values(r).map(l=>l.schema),a=n.filter(l=>l.type=="frame").reduce((l,c)=>({...l,[c.id]:r[c.id]}),{}),i={path:e.path,frames:a,schemas:n},u=!0;return t&&vy.default.isEqual(i,t)&&(u=!1),{changed:u,cache:i}},b5=(e,r,t,n,a,i,u)=>{let l={};if(!e)return{changed:!1,cache:null};if(!r)return{changed:!1,cache:{cols:[],path:e.path,schemas:[],outlinks:[],contexts:[],paths:[],tables:{},space:e,spaceMap:l,dbExists:!1}};let c=Object.values(r).map(A=>A.schema),o=c.find(A=>A.primary=="true"),s=OS(r[o.id].cols),m={...r[o.id],rows:r[o.id].rows.map(A=>s5(u,i,A,r[o.id].cols,i.get(e.path),s))},d={...r,[o.id]:m},h=m.cols?.filter(A=>A.type.startsWith("context"))??[],x=m.cols?.filter(A=>A.type.startsWith("link"))??[],v=ti(h.map(A=>A.value));h.forEach(A=>{l[A.name]={},m.rows.forEach(S=>{Sn(S[A.name]).forEach(O=>l[A.name][O]=[...l[A.name][O]??[],S[Fa]])})});let y=d[qs]?.rows?.map(A=>A[Fa])??[],w=NA(t??[],y),C=ti(m.rows.reduce((A,S)=>ti([...A,...[...h,...x].flatMap(O=>Sn(S[O.name]).map(_=>Dc(_)))]),[])),b={cols:m.cols,path:e.path,contexts:v,outlinks:C,paths:w,tables:d,schemas:c,space:e,spaceMap:l,dbExists:a},M=!0;return n&&vy.default.isEqual(b,n)&&(M=!0),{changed:M,cache:b}},w5=(e,r,t,n)=>{let a={};for(let[i,u]of e){let l=t.get(i)?.defPath??i,c=e.get(l)??u,o=u?.parent??"",s=u?.type??"",m=u?.subtype??"",d=c?.label,h=n?.get(i),{changed:x,cache:v}=qS(i,r,t,c,d,s,m,o,h);a[i]={changed:x,cache:v}}return a},qS=(e,r,t,n,a,i,u,l,c)=>{let o=(W,G,H)=>W?.length>0||W?.length>0?W:G=="space"?H=="Spaces/Home"?"ui//home":H=="/"?"ui//vault":H.startsWith("spaces://")?"ui//tags":"ui//folder":"ui//file",s={label:n?.label,path:e,name:yc(e),displayName:yc(e)},m=[],d=n?.tags?.map(W=>W)??[],h=x5(r,e),x=(W,G,H=new Set)=>{let L=[];for(let k of G){let K=W.get(k)?.contexts??[];for(let z of K)H.has(z)||(L.push(z),H.add(z),L.push(...x(W,[bc(z)],H)))}return L};if(t.has(l))for(let W of t.get(l).contexts??[])m.push(W);m.push(...d);let v=a?.name,y=n?.properties?um(n.properties[r.fmKeyAlias]):[],w=o(a?.sticker,i,e),C=a?.color??"",b=n?.inlinks??[],M=n?.links??[],A=r.spacesUseAlias?y[0]??v:v,S={...s,name:v,tags:ti(m),type:i,subtype:u,displayName:A,parent:l,label:{name:v,sticker:w,color:C,thumbnail:a?.thumbnail??"",preview:a?.preview??""},metadata:{...n},inlinks:b,outlinks:M},O=[];u=="tag"&&O.push(_S);for(let W of m)O.push(bc(W));let _=new Set,E=(W,G)=>{if(!_.has(W)){if(_.add(W),G.dependencies?.length>0)for(let H of G.dependencies)t.has(H)&&E(H,t.get(H));if(G.defPath==e&&(h=!0),u!="tag"&&u!="default"&&G.space&&G.space.path==l){O.push(W);return}if(G.metadata?.filters?.length>0&&g5(G.metadata.filters,{...S,spaces:O},G.properties)){O.push(W);return}if(G.metadata?.links?.length>0&&(G.metadata?.links??[]).find(L=>L==S.path)){O.push(W);return}}};for(let[W,G]of t)E(W,G);let T=x(t,O);O.push(...T.map(W=>bc(W))),S.tags.push(...T);let R=h?{...S,spaces:[],hidden:h}:{...S,spaces:ti(O),hidden:h},q=!0;return c&&vy.default.isEqual(R,c)&&(q=!1),{changed:q,cache:R}};function D5(e){let{path:r,settings:t,spacesCache:n,pathMetadata:a,label:i,type:u,subtype:l,parent:c,oldMetadata:o}=e;return qS(r,t,n,a,i,u,l,c,o)}function LS(e,r){let{space:t,mdb:n,paths:a,oldCache:i,dbExists:u,pathsIndex:l}=e;return b5(t,n,a,i,u,l,r)}function S5(e,r){let{map:t,pathsIndex:n}=e,a=new Map;for(let[i,u]of t)a.set(i,LS({...u,pathsIndex:n},r));return a}function N5(e){let{pathCache:r,settings:t,spacesCache:n,oldMetadata:a}=e;return w5(r,t,n,a)}function A5(e){let{space:r,mdb:t,oldCache:n}=e;return y5(r,t,n)}var zZ=self,UZ={...AS,createAdd:F("add",[],()=>function(r,t){return r+t})},zS=ly(UZ);zS.import(Lb,{override:!0});zZ.onmessage=async e=>{let{payload:r,job:t}=e.data,n;t.type=="path"?n=D5(r):t.type=="context"?n=LS(r,zS):t.type=="contexts"?n=S5(r,zS):t.type=="frames"?n=A5(r):t.type=="paths"&&(n=N5(r));try{postMessage({job:t,result:n})}catch(a){console.log(a),postMessage({job:t,result:{$error:\`Failed to index \${t.type} \${t.path}: \${a}\`}})}}; +/*! + * decimal.js v10.4.3 + * An arbitrary-precision Decimal type for JavaScript. + * https://github.com/MikeMcl/decimal.js + * Copyright (c) 2022 Michael Mclaughlin + * MIT Licence + */ +/** + * @license + * Lodash + * Copyright OpenJS Foundation and other contributors + * Released under MIT license + * Based on Underscore.js 1.8.3 + * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors + */ +/** + * @license Complex.js v2.1.1 12/05/2020 + * + * Copyright (c) 2020, Robert Eisele (robert@xarg.org) + * Dual licensed under the MIT or GPL Version 2 licenses. + **/ +/** + * @license Fraction.js v4.3.0 20/08/2023 + * https://www.xarg.org/2014/03/rational-numbers-in-javascript/ + * + * Copyright (c) 2023, Robert Eisele (robert@raw.org) + * Dual licensed under the MIT or GPL Version 2 licenses. + **/ +//! authors : Tim Wood, Iskren Chernev, Moment.js contributors +//! license : MIT +//! moment.js +//! momentjs.com +//! version : 2.29.4 +`, { "name": "Superstate Indexer" }); +} + +// src/core/superstate/workers/indexer/indexer.ts +var Indexer = class { + constructor(numWorkers, cache2) { + this.numWorkers = numWorkers; + this.cache = cache2; + this.workers = []; + this.busy = []; + this.reloadQueue = []; + this.reloadSet = /* @__PURE__ */ new Set(); + this.callbacks = /* @__PURE__ */ new Map(); + for (let index2 = 0; index2 < numWorkers; index2++) { + const worker = new Worker2({ name: "Make.md Superstate Indexer " + (index2 + 1) }); + worker.onmessage = (evt) => this.finish(evt.data.job, evt.data.result, index2); + this.workers.push(worker); + this.busy.push(false); + } + } + reload(jerb) { + const jobKey = stringifyJob(jerb); + const promise = new Promise((resolve2, reject) => { + if (this.callbacks.has(jobKey)) + this.callbacks.get(jobKey)?.push([resolve2, reject]); + else + this.callbacks.set(jobKey, [[resolve2, reject]]); + }); + if (this.reloadSet.has(jobKey)) + return promise; + this.reloadSet.add(jobKey); + const workerId = this.nextAvailableWorker(); + if (workerId !== void 0) { + this.send(jerb, workerId); + } else { + this.reloadQueue.push(jerb); + } + return promise; + } + finish(jerb, data2, index2) { + const jobKey = stringifyJob(jerb); + const calls = [].concat(this.callbacks.get(jobKey) ?? []); + this.reloadSet.delete(jobKey); + this.callbacks.delete(jobKey); + this.busy[index2] = false; + const job = this.reloadQueue.shift(); + if (job !== void 0) + this.send(job, index2); + if ("$error" in data2) { + for (const [_15, reject] of calls) + reject(data2["$error"]); + } else { + for (const [callback, _15] of calls) + callback(data2); + } + } + async send(job, workerId) { + if (job.type == "paths") { + const payload = { + settings: this.cache.settings, + spacesCache: this.cache.spacesIndex, + pathCache: this.cache.spaceManager.allCaches(), + oldMetadata: this.cache.pathsIndex + }; + this.message(workerId, { + job, + payload + }); + this.busy[workerId] = true; + return; + } + if (job.type == "path") { + const spaceState = this.cache.spacesIndex.get(job.path); + const cachePath = spaceState?.defPath ? spaceState?.defPath : job.path; + const pathMetadata = await this.cache.spaceManager.readPathCache(cachePath) ?? await this.cache.spaceManager.readPathCache(job.path); + const label = pathMetadata?.label; + const parent = await this.cache.spaceManager.parentPathForPath(job.path); + const type = spaceState ? "space" : "file"; + const subtype = spaceState ? spaceState.type : pathMetadata?.subtype; + const payload = { + path: job.path, + settings: this.cache.settings, + spacesCache: this.cache.spacesIndex, + pathMetadata, + label, + parent, + type, + subtype, + oldMetadata: this.cache.pathsIndex.get(job.path) + }; + this.message(workerId, { + job, + payload + }); + this.busy[workerId] = true; return; } - switch (filterFnTypes[filter4.fn]?.valueType) { - case "text": - case "number": - { - saveFilterValue(filter4.value); - } - break; - case "date": { - const saveValue = (date2) => { - saveFilterValue(format(date2, "yyyy-MM-dd")); - }; - const offset2 = e5.target.getBoundingClientRect(); - const date = new Date(filter4.value); - showDatePickerMenu( - props.superstate.ui, - offset2, - date.getTime() ? date : null, - saveValue, - 0 /* None */ - ); - break; - } - case "link": { - const saveValue = (value) => { - saveFilterValue(value); - }; - showLinkMenu(e5, props.superstate, saveValue); - break; - } - case "space": { - const saveValue = (value) => { - saveFilterValue(value); - }; - showSpacesMenu(e5, props.superstate, saveValue); - break; - } - case "list": - { - const fieldType = filter4.fType; - const saveOptions = (options2, values2) => { - saveFilterValue(serializeMultiString(values2)); - }; - let options = []; - if (fieldType.startsWith("option")) { - options = parseMultiString(filter4.value).map((f2) => ({ - name: f2, - value: f2 - })); - } else if (fieldType.startsWith("tags")) { - options = props.superstate.spaceManager.readTags().map((f2) => ({ - value: f2, - name: f2 - })); - } else if (fieldType.startsWith("links")) { - options = props.superstate.spaceManager.allPaths().map((f2) => ({ - name: pathNameToString(f2), - value: f2, - description: f2 - })); + if (job.type == "context") { + const space2 = this.cache.spacesIndex.get(job.path)?.space; + if (!space2 || !space2.path) { + this.message(workerId, { + job, + payload: { + space: space2, + mdb: null, + paths: [...this.cache.spacesMap.getInverse(job.path)], + oldCache: this.cache.contextsIndex.get(job.path), + pathsIndex: this.cache.pathsIndex } - const offset2 = e5.target.getBoundingClientRect(); - props.superstate.ui.openMenu(offset2, { - ui: props.superstate.ui, - multi: true, - editable: true, - value: parseMultiString(filter4.value), - options, - saveOptions, - placeholder: i18n_default.labels.optionItemSelectPlaceholder, - searchable: false, - showAll: true - }); - } - break; - } - }; - const addDefGroup = () => { - setFilters((p) => [ - ...p, - { - type: "any", - trueFalse: true, - filters: [] + }); + this.busy[workerId] = true; + return; } - ]); - }; - const removeDefGroup = (groupIndex) => { - setFilters(filters.filter((f2, i4) => i4 == groupIndex ? false : true)); - }; - const setDefFilter = (filter4, groupIndex, filterIndex) => { - if (!filter4) + const dbExists = await this.cache.spaceManager.spaceInitiated(space2.path); + this.cache.spaceManager.readAllTables(space2.path).then((mdb) => { + this.message(workerId, { + job, + payload: { + space: space2, + mdb, + paths: [...this.cache.spacesMap.getInverse(job.path)], + oldCache: this.cache.contextsIndex.get(job.path), + dbExists, + pathsIndex: this.cache.pathsIndex + } + }); + this.busy[workerId] = true; + }); return; - if (filters.length == 0) { - setFilters([ - { - type: "all", - trueFalse: true, - filters: [ + } + if (job.type == "contexts") { + const spaces2 = this.cache.allSpaces().filter((f2) => f2.type != "default").map((f2) => f2.space); + const payloads = /* @__PURE__ */ new Map(); + for (const space2 of spaces2) { + const dbExists = await this.cache.spaceManager.spaceInitiated(space2.path); + await this.cache.spaceManager.readAllTables(space2.path).then((mdb) => { + payloads.set( + space2.path, { - type: filter4.type, - field: filter4.field, - fType: filter4.vType, - fn: filter4.defaultFilter, - value: "" + space: space2, + mdb, + paths: [...this.cache.spacesMap.getInverse(space2.path)], + oldCache: this.cache.contextsIndex.get(space2.path), + dbExists } - ] + ); + }); + } + this.message(workerId, { + job, + payload: { + map: payloads, + pathsIndex: this.cache.pathsIndex } - ]); - return; + }); + this.busy[workerId] = true; } - if (filters[groupIndex]?.filters.length == 0) { - setFilters( - filters.map( - (f2, i4) => i4 == groupIndex ? { - ...f2, - filters: [ - { - type: filter4.type, - field: filter4.field, - fType: filter4.vType, - fn: filter4.defaultFilter, - value: "" - } - ] - } : f2 - ) - ); + if (job.type == "frames") { + const space2 = this.cache.spacesIndex.get(job.path)?.space; + if (!space2) { + this.message(workerId, { + job, + payload: { + space: space2, + mdb: null, + oldCache: this.cache.framesIndex.get(job.path) + } + }); + this.busy[workerId] = true; + return; + } + this.cache.spaceManager.readAllFrames(space2.path).then((mdb) => { + this.message(workerId, { + job, + payload: { + space: space2, + mdb, + oldCache: this.cache.framesIndex.get(job.path) + } + }); + this.busy[workerId] = true; + }); return; } - setFilters( - filters.map( - (f2, i4) => i4 == groupIndex ? { - ...f2, - filters: !f2.filters || filterIndex == f2.filters.length ? [ - ...f2.filters ?? [], - { - type: filter4.type, - field: filter4.field, - fType: filter4.vType, - fn: filter4.defaultFilter, - value: "" - } - ] : f2.filters.map( - (g, k2) => k2 == filterIndex ? { - ...g, - type: filter4.type, - field: filter4.field, - fType: filter4.vType, - fn: filter4.defaultFilter - } : g - ) - } : f2 - ) - ); - }; - const setDefFilterFn = (fn, groupIndex, filterIndex) => { - setFilters( - filters.map( - (f2, i4) => i4 == groupIndex ? { - ...f2, - filters: f2.filters.map( - (g, k2) => k2 == filterIndex ? { - ...g, - fn - } : g - ) - } : f2 - ) - ); - }; - const setDefFilterValue = (value, groupIndex, filterIndex) => { - setFilters( - filters.map( - (f2, i4) => i4 == groupIndex ? { - ...f2, - filters: f2.filters.map( - (g, k2) => k2 == filterIndex ? { - ...g, - value - } : g - ) - } : f2 - ) - ); - }; - const removeDefFilter = (filterIndex, groupIndex) => { - setFilters( - filters.map( - (f2, i4) => i4 == groupIndex ? { - ...f2, - filters: f2.filters.filter( - (g, k2) => k2 == filterIndex ? false : true - ) - } : f2 - ) + } + message(workerId, message) { + this.workers[workerId].postMessage( + message ); - }; - const setGroupType = (groupIndex, type) => { - if (groupIndex == 0 && filters.length == 0) { - setFilters([ - { - type, - trueFalse: true, - filters: [] - } - ]); - } else { - setFilters( - filters.map( - (f2, i4) => i4 == groupIndex ? { - ...f2, - type - } : f2 - ) - ); - } - }; - const selectGroupType = (e5, i4) => { - const offset2 = e5.target.getBoundingClientRect(); - const filters2 = ["any", "all"]; - props.superstate.ui.openMenu(offset2, { - ui: props.superstate.ui, - multi: false, - editable: false, - value: [], - options: filters2.map((f2) => ({ - name: f2 == "any" ? "or" : "and", - value: f2 - })), - saveOptions: (_15, value) => setGroupType(i4, value[0]), - searchable: false, - showAll: true - }); - }; - const selectFilter = (e5, i4, k2) => { - const offset2 = e5.target.getBoundingClientRect(); - const { type, field, fType } = filters[i4].filters[k2]; - const _filters = fType == "any" ? allPredicateFns(filterFnTypes) : predicateFnsForType(fType, filterFnTypes); - props.superstate.ui.openMenu(offset2, { - ui: props.superstate.ui, - multi: false, - editable: true, - value: [], - options: _filters.map((f2) => ({ name: filterFnLabels[f2], value: f2 })), - saveOptions: (_15, value) => setDefFilterFn(value[0], i4, k2), - placeholder: i18n_default.labels.contextItemSelectPlaceholder, - searchable: true, - showAll: true - }); - }; - const selectField = async (e5, i4, k2) => { - const offset2 = e5.target.getBoundingClientRect(); - props.superstate.ui.openMenu(offset2, { - ui: props.superstate.ui, - multi: false, - editable: false, - value: [], - options: props.fields.map((f2) => ({ - name: f2.label, - value: f2, - section: f2.type, - description: f2.description - })), - saveOptions: (_15, value) => setDefFilter(value[0], i4, k2), - placeholder: i18n_default.labels.contextItemSelectPlaceholder, - searchable: true, - showAll: true, - sections: props.sections, - showSections: true - }); - }; - return /* @__PURE__ */ import_react49.default.createElement("div", { - className: "mk-query" - }, filters.length == 0 ? /* @__PURE__ */ import_react49.default.createElement(DefFilterGroup, { - superstate: props.superstate, - selectGroupType, - group: null, - addDefGroup, - selectField, - i: 0, - removeable: props.removeable, - removeDefGroup - }) : filters.map((f2, i4) => /* @__PURE__ */ import_react49.default.createElement(DefFilterGroup, { - superstate: props.superstate, - key: i4, - group: f2, - selectGroupType, - addDefGroup, - selectField, - removeable: props.removeable, - i: i4, - removeDefGroup - }, f2.filters.map((filter4, k2, arr) => /* @__PURE__ */ import_react49.default.createElement(import_react49.default.Fragment, { - key: k2 - }, /* @__PURE__ */ import_react49.default.createElement(DefFilter, { - superstate: props.superstate, - key: k2, - filter: filter4, - i: i4, - k: k2, - selectField, - selectFilter, - selectFilterValue, - removeDefFilter, - linkProps: props.linkProps - }), k2 != arr.length - 1 && /* @__PURE__ */ import_react49.default.createElement("div", { - className: "mk-filter", - onClick: (e5) => selectGroupType(e5, i4) - }, /* @__PURE__ */ import_react49.default.createElement("span", null, f2.type == "any" ? "or" : "and"))))))); + } + nextAvailableWorker() { + const index2 = this.busy.indexOf(false); + return index2 == -1 ? void 0 : index2; + } }; -var DefFilter = (props) => { - const { - filter: filter4, - selectField, - selectFilter, - selectFilterValue, - removeDefFilter, - i: i4, - k: k2 - } = props; - const filterFieldName = props.superstate.allMetadata[filter4.type]?.properties.find( - (f2) => f2.field == filter4.field - )?.label ?? filter4.field; - return /* @__PURE__ */ import_react49.default.createElement("div", { - className: "mk-filter" - }, /* @__PURE__ */ import_react49.default.createElement("span", { - onClick: (e5) => selectField(e5, i4, k2) - }, filter4.field.length == 0 ? i18n_default.labels.select : filterFieldName), filter4.field.length > 0 && /* @__PURE__ */ import_react49.default.createElement("span", { - onClick: (e5) => selectFilter(e5, i4, k2) - }, !filterFnLabels[filter4.fn] ? i18n_default.labels.select : filterFnLabels[filter4.fn]), filter4.field.length > 0 && filterFnLabels[filter4.fn] && filterFnTypes[filter4.fn]?.valueType != "none" && /* @__PURE__ */ import_react49.default.createElement(import_react49.default.Fragment, null, /* @__PURE__ */ import_react49.default.createElement("span", null, /* @__PURE__ */ import_react49.default.createElement(FilterValueSpan, { - superstate: props.superstate, - fieldType: filter4.fType, - filter: filter4, - selectFilterValue: (e5, h3) => selectFilterValue(e5, h3, i4, k2) - })), props.linkProps && props.linkProps.length > 0 && /* @__PURE__ */ import_react49.default.createElement("span", { - onClick: (e5) => { - e5.stopPropagation(); - props.superstate.ui.openMenu( - e5.currentTarget.getBoundingClientRect(), - { - ui: props.superstate.ui, - multi: false, - editable: false, - value: [], - options: props.linkProps.map((f2) => ({ - name: f2.name, - value: f2.name, - section: f2.type - })), - saveOptions: (_15, value) => selectFilterValue( - e5, - { - ...filter4, - fType: "property", - value: value[0] - }, - i4, - k2 - ), - placeholder: i18n_default.labels.contextItemSelectPlaceholder, - searchable: true, - showAll: true, - sections: [], - showSections: false - } - ); - } - }, /* @__PURE__ */ import_react49.default.createElement("div", { - className: "mk-icon-xsmall", - dangerouslySetInnerHTML: { - __html: props.superstate.ui.getSticker("ui//plug") - } - }))), /* @__PURE__ */ import_react49.default.createElement("span", { - onClick: (e5) => { - removeDefFilter(k2, i4); - e5.stopPropagation(); - } - }, /* @__PURE__ */ import_react49.default.createElement("div", { - className: "mk-icon-xsmall", - dangerouslySetInnerHTML: { - __html: props.superstate.ui.getSticker("ui//close") + +// src/core/superstate/workers/search/search.worker.ts +function Worker3() { + return inlineWorker('"use strict";function he(t){return Array.isArray(t)?t:typeof t=="string"?[t]:[]}var xe=(t,e)=>e.indexOf(t)>0?e.indexOf(t):e.length;function k(t){return k=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(e){return typeof e}:function(e){return e&&typeof Symbol=="function"&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},k(t)}function x(t){if(t===null||t===!0||t===!1)return NaN;var e=Number(t);return isNaN(e)?e:e<0?Math.ceil(e):Math.floor(e)}function f(t,e){if(e.length1?"s":"")+" required, but only "+e.length+" present")}function m(t){f(1,arguments);var e=Object.prototype.toString.call(t);return t instanceof Date||k(t)==="object"&&e==="[object Date]"?new Date(t.getTime()):typeof t=="number"||e==="[object Number]"?new Date(t):((typeof t=="string"||e==="[object String]")&&typeof console<"u"&&(console.warn("Starting with v2.0.0-beta.1 date-fns doesn\'t accept strings as date arguments. Please use `parseISO` to parse strings. See: https://github.com/date-fns/date-fns/blob/master/docs/upgradeGuide.md#string-arguments"),console.warn(new Error().stack)),new Date(NaN))}function J(t,e){f(2,arguments);var r=m(t).getTime(),a=x(e);return new Date(r+a)}var Ke={};function T(){return Ke}function z(t){var e=new Date(Date.UTC(t.getFullYear(),t.getMonth(),t.getDate(),t.getHours(),t.getMinutes(),t.getSeconds(),t.getMilliseconds()));return e.setUTCFullYear(t.getFullYear()),t.getTime()-e.getTime()}function K(t){return f(1,arguments),t instanceof Date||k(t)==="object"&&Object.prototype.toString.call(t)==="[object Date]"}function Z(t){if(f(1,arguments),!K(t)&&typeof t!="number")return!1;var e=m(t);return!isNaN(Number(e))}function ee(t,e){f(2,arguments);var r=x(e);return J(t,-r)}var Ze=864e5;function te(t){f(1,arguments);var e=m(t),r=e.getTime();e.setUTCMonth(0,1),e.setUTCHours(0,0,0,0);var a=e.getTime(),n=r-a;return Math.floor(n/Ze)+1}function O(t){f(1,arguments);var e=1,r=m(t),a=r.getUTCDay(),n=(a=n.getTime()?r+1:e.getTime()>=i.getTime()?r:r-1}function re(t){f(1,arguments);var e=_(t),r=new Date(0);r.setUTCFullYear(e,0,4),r.setUTCHours(0,0,0,0);var a=O(r);return a}var et=6048e5;function ae(t){f(1,arguments);var e=m(t),r=O(e).getTime()-re(e).getTime();return Math.round(r/et)+1}function S(t,e){var r,a,n,o,i,s,d,l;f(1,arguments);var p=T(),c=x((r=(a=(n=(o=e?.weekStartsOn)!==null&&o!==void 0?o:e==null||(i=e.locale)===null||i===void 0||(s=i.options)===null||s===void 0?void 0:s.weekStartsOn)!==null&&n!==void 0?n:p.weekStartsOn)!==null&&a!==void 0?a:(d=p.locale)===null||d===void 0||(l=d.options)===null||l===void 0?void 0:l.weekStartsOn)!==null&&r!==void 0?r:0);if(!(c>=0&&c<=6))throw new RangeError("weekStartsOn must be between 0 and 6 inclusively");var h=m(t),g=h.getUTCDay(),v=(g=1&&g<=7))throw new RangeError("firstWeekContainsDate must be between 1 and 7 inclusively");var v=new Date(0);v.setUTCFullYear(c+1,0,g),v.setUTCHours(0,0,0,0);var N=S(v,e),D=new Date(0);D.setUTCFullYear(c,0,g),D.setUTCHours(0,0,0,0);var E=S(D,e);return p.getTime()>=N.getTime()?c+1:p.getTime()>=E.getTime()?c:c-1}function ne(t,e){var r,a,n,o,i,s,d,l;f(1,arguments);var p=T(),c=x((r=(a=(n=(o=e?.firstWeekContainsDate)!==null&&o!==void 0?o:e==null||(i=e.locale)===null||i===void 0||(s=i.options)===null||s===void 0?void 0:s.firstWeekContainsDate)!==null&&n!==void 0?n:p.firstWeekContainsDate)!==null&&a!==void 0?a:(d=p.locale)===null||d===void 0||(l=d.options)===null||l===void 0?void 0:l.firstWeekContainsDate)!==null&&r!==void 0?r:1),h=L(t,e),g=new Date(0);g.setUTCFullYear(h,0,c),g.setUTCHours(0,0,0,0);var v=S(g,e);return v}var tt=6048e5;function oe(t,e){f(1,arguments);var r=m(t),a=S(r,e).getTime()-ne(r,e).getTime();return Math.round(a/tt)+1}function u(t,e){for(var r=t<0?"-":"",a=Math.abs(t).toString();a.length0?a:1-a;return u(r==="yy"?n%100:n,r.length)},M:function(e,r){var a=e.getUTCMonth();return r==="M"?String(a+1):u(a+1,2)},d:function(e,r){return u(e.getUTCDate(),r.length)},a:function(e,r){var a=e.getUTCHours()/12>=1?"pm":"am";switch(r){case"a":case"aa":return a.toUpperCase();case"aaa":return a;case"aaaaa":return a[0];case"aaaa":default:return a==="am"?"a.m.":"p.m."}},h:function(e,r){return u(e.getUTCHours()%12||12,r.length)},H:function(e,r){return u(e.getUTCHours(),r.length)},m:function(e,r){return u(e.getUTCMinutes(),r.length)},s:function(e,r){return u(e.getUTCSeconds(),r.length)},S:function(e,r){var a=r.length,n=e.getUTCMilliseconds(),o=Math.floor(n*Math.pow(10,a-3));return u(o,r.length)}},b=rt;var F={am:"am",pm:"pm",midnight:"midnight",noon:"noon",morning:"morning",afternoon:"afternoon",evening:"evening",night:"night"},at={G:function(e,r,a){var n=e.getUTCFullYear()>0?1:0;switch(r){case"G":case"GG":case"GGG":return a.era(n,{width:"abbreviated"});case"GGGGG":return a.era(n,{width:"narrow"});case"GGGG":default:return a.era(n,{width:"wide"})}},y:function(e,r,a){if(r==="yo"){var n=e.getUTCFullYear(),o=n>0?n:1-n;return a.ordinalNumber(o,{unit:"year"})}return b.y(e,r)},Y:function(e,r,a,n){var o=L(e,n),i=o>0?o:1-o;if(r==="YY"){var s=i%100;return u(s,2)}return r==="Yo"?a.ordinalNumber(i,{unit:"year"}):u(i,r.length)},R:function(e,r){var a=_(e);return u(a,r.length)},u:function(e,r){var a=e.getUTCFullYear();return u(a,r.length)},Q:function(e,r,a){var n=Math.ceil((e.getUTCMonth()+1)/3);switch(r){case"Q":return String(n);case"QQ":return u(n,2);case"Qo":return a.ordinalNumber(n,{unit:"quarter"});case"QQQ":return a.quarter(n,{width:"abbreviated",context:"formatting"});case"QQQQQ":return a.quarter(n,{width:"narrow",context:"formatting"});case"QQQQ":default:return a.quarter(n,{width:"wide",context:"formatting"})}},q:function(e,r,a){var n=Math.ceil((e.getUTCMonth()+1)/3);switch(r){case"q":return String(n);case"qq":return u(n,2);case"qo":return a.ordinalNumber(n,{unit:"quarter"});case"qqq":return a.quarter(n,{width:"abbreviated",context:"standalone"});case"qqqqq":return a.quarter(n,{width:"narrow",context:"standalone"});case"qqqq":default:return a.quarter(n,{width:"wide",context:"standalone"})}},M:function(e,r,a){var n=e.getUTCMonth();switch(r){case"M":case"MM":return b.M(e,r);case"Mo":return a.ordinalNumber(n+1,{unit:"month"});case"MMM":return a.month(n,{width:"abbreviated",context:"formatting"});case"MMMMM":return a.month(n,{width:"narrow",context:"formatting"});case"MMMM":default:return a.month(n,{width:"wide",context:"formatting"})}},L:function(e,r,a){var n=e.getUTCMonth();switch(r){case"L":return String(n+1);case"LL":return u(n+1,2);case"Lo":return a.ordinalNumber(n+1,{unit:"month"});case"LLL":return a.month(n,{width:"abbreviated",context:"standalone"});case"LLLLL":return a.month(n,{width:"narrow",context:"standalone"});case"LLLL":default:return a.month(n,{width:"wide",context:"standalone"})}},w:function(e,r,a,n){var o=oe(e,n);return r==="wo"?a.ordinalNumber(o,{unit:"week"}):u(o,r.length)},I:function(e,r,a){var n=ae(e);return r==="Io"?a.ordinalNumber(n,{unit:"week"}):u(n,r.length)},d:function(e,r,a){return r==="do"?a.ordinalNumber(e.getUTCDate(),{unit:"date"}):b.d(e,r)},D:function(e,r,a){var n=te(e);return r==="Do"?a.ordinalNumber(n,{unit:"dayOfYear"}):u(n,r.length)},E:function(e,r,a){var n=e.getUTCDay();switch(r){case"E":case"EE":case"EEE":return a.day(n,{width:"abbreviated",context:"formatting"});case"EEEEE":return a.day(n,{width:"narrow",context:"formatting"});case"EEEEEE":return a.day(n,{width:"short",context:"formatting"});case"EEEE":default:return a.day(n,{width:"wide",context:"formatting"})}},e:function(e,r,a,n){var o=e.getUTCDay(),i=(o-n.weekStartsOn+8)%7||7;switch(r){case"e":return String(i);case"ee":return u(i,2);case"eo":return a.ordinalNumber(i,{unit:"day"});case"eee":return a.day(o,{width:"abbreviated",context:"formatting"});case"eeeee":return a.day(o,{width:"narrow",context:"formatting"});case"eeeeee":return a.day(o,{width:"short",context:"formatting"});case"eeee":default:return a.day(o,{width:"wide",context:"formatting"})}},c:function(e,r,a,n){var o=e.getUTCDay(),i=(o-n.weekStartsOn+8)%7||7;switch(r){case"c":return String(i);case"cc":return u(i,r.length);case"co":return a.ordinalNumber(i,{unit:"day"});case"ccc":return a.day(o,{width:"abbreviated",context:"standalone"});case"ccccc":return a.day(o,{width:"narrow",context:"standalone"});case"cccccc":return a.day(o,{width:"short",context:"standalone"});case"cccc":default:return a.day(o,{width:"wide",context:"standalone"})}},i:function(e,r,a){var n=e.getUTCDay(),o=n===0?7:n;switch(r){case"i":return String(o);case"ii":return u(o,r.length);case"io":return a.ordinalNumber(o,{unit:"day"});case"iii":return a.day(n,{width:"abbreviated",context:"formatting"});case"iiiii":return a.day(n,{width:"narrow",context:"formatting"});case"iiiiii":return a.day(n,{width:"short",context:"formatting"});case"iiii":default:return a.day(n,{width:"wide",context:"formatting"})}},a:function(e,r,a){var n=e.getUTCHours(),o=n/12>=1?"pm":"am";switch(r){case"a":case"aa":return a.dayPeriod(o,{width:"abbreviated",context:"formatting"});case"aaa":return a.dayPeriod(o,{width:"abbreviated",context:"formatting"}).toLowerCase();case"aaaaa":return a.dayPeriod(o,{width:"narrow",context:"formatting"});case"aaaa":default:return a.dayPeriod(o,{width:"wide",context:"formatting"})}},b:function(e,r,a){var n=e.getUTCHours(),o;switch(n===12?o=F.noon:n===0?o=F.midnight:o=n/12>=1?"pm":"am",r){case"b":case"bb":return a.dayPeriod(o,{width:"abbreviated",context:"formatting"});case"bbb":return a.dayPeriod(o,{width:"abbreviated",context:"formatting"}).toLowerCase();case"bbbbb":return a.dayPeriod(o,{width:"narrow",context:"formatting"});case"bbbb":default:return a.dayPeriod(o,{width:"wide",context:"formatting"})}},B:function(e,r,a){var n=e.getUTCHours(),o;switch(n>=17?o=F.evening:n>=12?o=F.afternoon:n>=4?o=F.morning:o=F.night,r){case"B":case"BB":case"BBB":return a.dayPeriod(o,{width:"abbreviated",context:"formatting"});case"BBBBB":return a.dayPeriod(o,{width:"narrow",context:"formatting"});case"BBBB":default:return a.dayPeriod(o,{width:"wide",context:"formatting"})}},h:function(e,r,a){if(r==="ho"){var n=e.getUTCHours()%12;return n===0&&(n=12),a.ordinalNumber(n,{unit:"hour"})}return b.h(e,r)},H:function(e,r,a){return r==="Ho"?a.ordinalNumber(e.getUTCHours(),{unit:"hour"}):b.H(e,r)},K:function(e,r,a){var n=e.getUTCHours()%12;return r==="Ko"?a.ordinalNumber(n,{unit:"hour"}):u(n,r.length)},k:function(e,r,a){var n=e.getUTCHours();return n===0&&(n=24),r==="ko"?a.ordinalNumber(n,{unit:"hour"}):u(n,r.length)},m:function(e,r,a){return r==="mo"?a.ordinalNumber(e.getUTCMinutes(),{unit:"minute"}):b.m(e,r)},s:function(e,r,a){return r==="so"?a.ordinalNumber(e.getUTCSeconds(),{unit:"second"}):b.s(e,r)},S:function(e,r){return b.S(e,r)},X:function(e,r,a,n){var o=n._originalDate||e,i=o.getTimezoneOffset();if(i===0)return"Z";switch(r){case"X":return be(i);case"XXXX":case"XX":return M(i);case"XXXXX":case"XXX":default:return M(i,":")}},x:function(e,r,a,n){var o=n._originalDate||e,i=o.getTimezoneOffset();switch(r){case"x":return be(i);case"xxxx":case"xx":return M(i);case"xxxxx":case"xxx":default:return M(i,":")}},O:function(e,r,a,n){var o=n._originalDate||e,i=o.getTimezoneOffset();switch(r){case"O":case"OO":case"OOO":return"GMT"+ve(i,":");case"OOOO":default:return"GMT"+M(i,":")}},z:function(e,r,a,n){var o=n._originalDate||e,i=o.getTimezoneOffset();switch(r){case"z":case"zz":case"zzz":return"GMT"+ve(i,":");case"zzzz":default:return"GMT"+M(i,":")}},t:function(e,r,a,n){var o=n._originalDate||e,i=Math.floor(o.getTime()/1e3);return u(i,r.length)},T:function(e,r,a,n){var o=n._originalDate||e,i=o.getTime();return u(i,r.length)}};function ve(t,e){var r=t>0?"-":"+",a=Math.abs(t),n=Math.floor(a/60),o=a%60;if(o===0)return r+String(n);var i=e||"";return r+String(n)+i+u(o,2)}function be(t,e){if(t%60===0){var r=t>0?"-":"+";return r+u(Math.abs(t)/60,2)}return M(t,e)}function M(t,e){var r=e||"",a=t>0?"-":"+",n=Math.abs(t),o=u(Math.floor(n/60),2),i=u(n%60,2);return a+o+r+i}var we=at;var Te=function(e,r){switch(e){case"P":return r.date({width:"short"});case"PP":return r.date({width:"medium"});case"PPP":return r.date({width:"long"});case"PPPP":default:return r.date({width:"full"})}},Oe=function(e,r){switch(e){case"p":return r.time({width:"short"});case"pp":return r.time({width:"medium"});case"ppp":return r.time({width:"long"});case"pppp":default:return r.time({width:"full"})}},nt=function(e,r){var a=e.match(/(P+)(p+)?/)||[],n=a[1],o=a[2];if(!o)return Te(e,r);var i;switch(n){case"P":i=r.dateTime({width:"short"});break;case"PP":i=r.dateTime({width:"medium"});break;case"PPP":i=r.dateTime({width:"long"});break;case"PPPP":default:i=r.dateTime({width:"full"});break}return i.replace("{{date}}",Te(n,r)).replace("{{time}}",Oe(o,r))},ot={p:Oe,P:nt},Se=ot;var it=["D","DD"],st=["YY","YYYY"];function De(t){return it.indexOf(t)!==-1}function ke(t){return st.indexOf(t)!==-1}function ie(t,e,r){if(t==="YYYY")throw new RangeError("Use `yyyy` instead of `YYYY` (in `".concat(e,"`) for formatting years to the input `").concat(r,"`; see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md"));if(t==="YY")throw new RangeError("Use `yy` instead of `YY` (in `".concat(e,"`) for formatting years to the input `").concat(r,"`; see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md"));if(t==="D")throw new RangeError("Use `d` instead of `D` (in `".concat(e,"`) for formatting days of the month to the input `").concat(r,"`; see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md"));if(t==="DD")throw new RangeError("Use `dd` instead of `DD` (in `".concat(e,"`) for formatting days of the month to the input `").concat(r,"`; see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md"))}var ut={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"}},ft=function(e,r,a){var n,o=ut[e];return typeof o=="string"?n=o:r===1?n=o.one:n=o.other.replace("{{count}}",r.toString()),a!=null&&a.addSuffix?a.comparison&&a.comparison>0?"in "+n:n+" ago":n},Me=ft;function $(t){return function(){var e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},r=e.width?String(e.width):t.defaultWidth,a=t.formats[r]||t.formats[t.defaultWidth];return a}}var lt={full:"EEEE, MMMM do, y",long:"MMMM do, y",medium:"MMM d, y",short:"MM/dd/yyyy"},dt={full:"h:mm:ss a zzzz",long:"h:mm:ss a z",medium:"h:mm:ss a",short:"h:mm a"},mt={full:"{{date}} \'at\' {{time}}",long:"{{date}} \'at\' {{time}}",medium:"{{date}}, {{time}}",short:"{{date}}, {{time}}"},ct={date:$({formats:lt,defaultWidth:"full"}),time:$({formats:dt,defaultWidth:"full"}),dateTime:$({formats:mt,defaultWidth:"full"})},We=ct;var pt={lastWeek:"\'last\' eeee \'at\' p",yesterday:"\'yesterday at\' p",today:"\'today at\' p",tomorrow:"\'tomorrow at\' p",nextWeek:"eeee \'at\' p",other:"P"},gt=function(e,r,a,n){return pt[e]},Ce=gt;function W(t){return function(e,r){var a=r!=null&&r.context?String(r.context):"standalone",n;if(a==="formatting"&&t.formattingValues){var o=t.defaultFormattingWidth||t.defaultWidth,i=r!=null&&r.width?String(r.width):o;n=t.formattingValues[i]||t.formattingValues[o]}else{var s=t.defaultWidth,d=r!=null&&r.width?String(r.width):t.defaultWidth;n=t.values[d]||t.values[s]}var l=t.argumentCallback?t.argumentCallback(e):e;return n[l]}}var ht={narrow:["B","A"],abbreviated:["BC","AD"],wide:["Before Christ","Anno Domini"]},xt={narrow:["1","2","3","4"],abbreviated:["Q1","Q2","Q3","Q4"],wide:["1st quarter","2nd quarter","3rd quarter","4th quarter"]},yt={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"]},vt={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"]},bt={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"}},wt={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"}},Tt=function(e,r){var a=Number(e),n=a%100;if(n>20||n<10)switch(n%10){case 1:return a+"st";case 2:return a+"nd";case 3:return a+"rd"}return a+"th"},Ot={ordinalNumber:Tt,era:W({values:ht,defaultWidth:"wide"}),quarter:W({values:xt,defaultWidth:"wide",argumentCallback:function(e){return e-1}}),month:W({values:yt,defaultWidth:"wide"}),day:W({values:vt,defaultWidth:"wide"}),dayPeriod:W({values:bt,defaultWidth:"wide",formattingValues:wt,defaultFormattingWidth:"wide"})},Pe=Ot;function C(t){return function(e){var r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},a=r.width,n=a&&t.matchPatterns[a]||t.matchPatterns[t.defaultMatchWidth],o=e.match(n);if(!o)return null;var i=o[0],s=a&&t.parsePatterns[a]||t.parsePatterns[t.defaultParseWidth],d=Array.isArray(s)?Dt(s,function(c){return c.test(i)}):St(s,function(c){return c.test(i)}),l;l=t.valueCallback?t.valueCallback(d):d,l=r.valueCallback?r.valueCallback(l):l;var p=e.slice(i.length);return{value:l,rest:p}}}function St(t,e){for(var r in t)if(t.hasOwnProperty(r)&&e(t[r]))return r}function Dt(t,e){for(var r=0;r1&&arguments[1]!==void 0?arguments[1]:{},a=e.match(t.matchPattern);if(!a)return null;var n=a[0],o=e.match(t.parsePattern);if(!o)return null;var i=t.valueCallback?t.valueCallback(o[0]):o[0];i=r.valueCallback?r.valueCallback(i):i;var s=e.slice(n.length);return{value:i,rest:s}}}var kt=/^(\\d+)(th|st|nd|rd)?/i,Mt=/\\d+/i,Wt={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},Ct={any:[/^b/i,/^(a|c)/i]},Pt={narrow:/^[1234]/i,abbreviated:/^q[1234]/i,wide:/^[1234](th|st|nd|rd)? quarter/i},Ft={any:[/1/i,/2/i,/3/i,/4/i]},It={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},Yt={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]},Ut={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},Nt={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]},Et={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},At={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}},qt={ordinalNumber:se({matchPattern:kt,parsePattern:Mt,valueCallback:function(e){return parseInt(e,10)}}),era:C({matchPatterns:Wt,defaultMatchWidth:"wide",parsePatterns:Ct,defaultParseWidth:"any"}),quarter:C({matchPatterns:Pt,defaultMatchWidth:"wide",parsePatterns:Ft,defaultParseWidth:"any",valueCallback:function(e){return e+1}}),month:C({matchPatterns:It,defaultMatchWidth:"wide",parsePatterns:Yt,defaultParseWidth:"any"}),day:C({matchPatterns:Ut,defaultMatchWidth:"wide",parsePatterns:Nt,defaultParseWidth:"any"}),dayPeriod:C({matchPatterns:Et,defaultMatchWidth:"any",parsePatterns:At,defaultParseWidth:"any"})},Fe=qt;var _t={code:"en-US",formatDistance:Me,formatLong:We,formatRelative:Ce,localize:Pe,match:Fe,options:{weekStartsOn:0,firstWeekContainsDate:1}},Ie=_t;var Ye=Ie;var Lt=/[yYQqMLwIdDecihHKkms]o|(\\w)\\1*|\'\'|\'(\'\'|[^\'])+(\'|$)|./g,$t=/P+p+|P+|p+|\'\'|\'(\'\'|[^\'])+(\'|$)|./g,Qt=/^\'([^]*?)\'?$/,jt=/\'\'/g,Ht=/[a-zA-Z]/;function H(t,e,r){var a,n,o,i,s,d,l,p,c,h,g,v,N,D,E,R,B,G;f(2,arguments);var Ge=String(e),A=T(),q=(a=(n=r?.locale)!==null&&n!==void 0?n:A.locale)!==null&&a!==void 0?a:Ye,V=x((o=(i=(s=(d=r?.firstWeekContainsDate)!==null&&d!==void 0?d:r==null||(l=r.locale)===null||l===void 0||(p=l.options)===null||p===void 0?void 0:p.firstWeekContainsDate)!==null&&s!==void 0?s:A.firstWeekContainsDate)!==null&&i!==void 0?i:(c=A.locale)===null||c===void 0||(h=c.options)===null||h===void 0?void 0:h.firstWeekContainsDate)!==null&&o!==void 0?o:1);if(!(V>=1&&V<=7))throw new RangeError("firstWeekContainsDate must be between 1 and 7 inclusively");var X=x((g=(v=(N=(D=r?.weekStartsOn)!==null&&D!==void 0?D:r==null||(E=r.locale)===null||E===void 0||(R=E.options)===null||R===void 0?void 0:R.weekStartsOn)!==null&&N!==void 0?N:A.weekStartsOn)!==null&&v!==void 0?v:(B=A.locale)===null||B===void 0||(G=B.options)===null||G===void 0?void 0:G.weekStartsOn)!==null&&g!==void 0?g:0);if(!(X>=0&&X<=6))throw new RangeError("weekStartsOn must be between 0 and 6 inclusively");if(!q.localize)throw new RangeError("locale must contain localize property");if(!q.formatLong)throw new RangeError("locale must contain formatLong property");var Q=m(t);if(!Z(Q))throw new RangeError("Invalid time value");var Ve=z(Q),Xe=ee(Q,Ve),Je={firstWeekContainsDate:V,weekStartsOn:X,locale:q,_originalDate:Q},ze=Ge.match($t).map(function(y){var w=y[0];if(w==="p"||w==="P"){var j=Se[w];return j(y,q.formatLong)}return y}).join("").match(Lt).map(function(y){if(y==="\'\'")return"\'";var w=y[0];if(w==="\'")return Rt(y);var j=we[w];if(j)return!(r!=null&&r.useAdditionalWeekYearTokens)&&ke(y)&&ie(y,e,String(t)),!(r!=null&&r.useAdditionalDayOfYearTokens)&&De(y)&&ie(y,e,String(t)),j(Xe,y,q.localize,Je);if(w.match(Ht))throw new RangeError("Format string contains an unescaped latin alphabet character `"+w+"`");return y}).join("");return ze}function Rt(t){var e=t.match(Qt);return e?e[1].replace(jt,"\'"):t}var Ue=t=>[...new Set(t)];var ue=(t,e)=>{if(t instanceof Date)return"date";if(typeof t=="string"){if(/\\/\\/(\\S+?(?:jpe?g|png|gif|svg))/gi.test(t)||t.includes("unsplash"))return"image";if(/^\\d{4}-\\d{2}-\\d{2}$/.test(t))return"date";if(e=="tag"||e=="tags")return"tags-multi";if(/\\[\\[.*?\\]\\]/.test(t))return"link"}else{if(typeof t=="number")return"number";if(typeof t=="boolean")return"boolean";if(t)if(Array.isArray(t)||typeof t=="string"&&t.indexOf(",")>-1){let r=Array.isArray(t)?t:[];if(typeof t=="string"&&t.indexOf(",")>-1&&(r=P(t)),e=="tag"||e=="tags")return"tags-multi";if(r.length==1&&Array.isArray(r[0])&&r[0].length==1&&typeof r[0][0]=="string")return"link";let a=Ue(r.map(n=>ue(n,e)));return a.length==1&&a[0]=="link"?"link-multi":a.some(n=>n=="object")?"object-multi":"option-multi"}else{if(t.isLuxonDateTime)return"date";if(t.isLuxonDuration)return"duration";if(t.type=="file")return"link";if(typeof t=="object"&&!Array.isArray(t)&&t!==null)return"object"}else return"unknown"}return"text"};var Ne=t=>t.map(e=>e.replace(",","\\\\,")).join(", "),I=t=>JSON.stringify(t);var P=t=>t?.startsWith("[")?he(ye(t)):Bt(t),Bt=t=>(t?.replace("\\\\,",",")?.match(/(\\\\.|[^,])+/g)??[]).map(e=>e.trim()),le=(t,e)=>{switch(ue(e,t)){case"tags-multi":return e;case"object":case"object-multi":return JSON.stringify(e);case"number":return e.toString();case"boolean":return e?"true":"false";case"date":{if(e instanceof Date){let a=H(e,"yyyy-MM-dd");return typeof a=="string"?a:""}return typeof e!="string"?"":e}break;case"duration":return Ne(Object.keys(e.values).reduce((a,n)=>[...a,...e.values[n]>0?[e.values[n]+" "+n]:[]],[]));case"option-multi":case"link-multi":return typeof e=="string"?fe(e):I(e.map(a=>a?typeof a=="string"?fe(a):a.path?a.path:Array.isArray(e)&&a.length==1&&Array.isArray(a[0])&&a[0].length==1&&typeof a[0][0]=="string"?a[0][0]:JSON.stringify(a):""));case"link":return Array.isArray(e)&&e.length==1&&Array.isArray(e[0])&&e[0].length==1&&typeof e[0][0]=="string"?e[0][0]:typeof e=="string"?fe(e):e.path;case"text":case"tag":case"image":return e}return""};var ye=t=>{let e;try{e=JSON.parse(t)}catch{}return e};var fe=t=>{if(!t)return"";let e=/\\[\\[(.*?)\\]\\]/g.exec(t),r=e?.length>1?e[1].substring(0,xe("|",e[1])):t;return r||t};var Ee=(t,e)=>{let r=t?P(t):[],a=e?P(e):[];return a.every(n=>r.some(o=>o==n))&&r.every(n=>a.some(o=>o==n))},Y=(t,e)=>t==e,de=(t,e)=>(t??"").length==0,me=(t,e)=>(t??"").toLowerCase().includes((e??"").toLowerCase()),ce=(t,e)=>parseFloat(t)>parseFloat(e),pe=(t,e)=>parseInt(t){let r=isNaN(Date.parse(t))?new Date(parseInt(t)):new Date(t),a=isNaN(Date.parse(e))?new Date(parseInt(e)):new Date(e);return r.valueOf()>=a.valueOf()},qe=(t,e)=>{let r=isNaN(Date.parse(t))?new Date(parseInt(t)):new Date(t),a=isNaN(Date.parse(e))?new Date(parseInt(e)):new Date(e);return r.valueOf(){let r=t?P(t):[],a=e?P(e):[];return r.length==0?!1:a.some(n=>r.some(o=>o==n))},_e=(t,e)=>{if(!t)return!1;let r=new Date(`${t.toString().replace(".",":")}`),a=new Date(`${e}`);return r.getMonth()===a.getMonth()&&r.getDate()===a.getDate()},Le=t=>{if(!t)return!1;let e=new Date(`${t.toString()}T00:00`),r=new Date;return e.getMonth()===r.getMonth()&&e.getDate()===r.getDate()};var U={isNotEmpty:{type:["text","file","number","option","option-multi","link","link-multi","image"],fn:(t,e)=>!de(t,""),valueType:"none"},isEmpty:{type:["text","file","number","option","option-multi","link","link-multi","image"],fn:(t,e)=>de(t,""),valueType:"none"},include:{fn:(t,e)=>me(t,e),type:["text","file","link","image"],valueType:"text"},notInclude:{type:["text","file","link","image"],fn:(t,e)=>!me(t,e),valueType:"text"},is:{type:["text"],fn:(t,e)=>Y(t,e),valueType:"text"},isNot:{type:["text"],fn:(t,e)=>!Y(t,e),valueType:"text"},equal:{type:["number"],fn:(t,e)=>Y(t,e),valueType:"number"},isLink:{type:["link","context"],fn:(t,e)=>Y(t,e),valueType:"link"},isNotLink:{type:["link","context"],fn:(t,e)=>!Y(t,e),valueType:"link"},isGreatThan:{type:["number"],fn:(t,e)=>ce(t,e),valueType:"number"},isLessThan:{type:["number"],fn:(t,e)=>pe(t,e),valueType:"number"},isLessThanOrEqual:{type:["number"],fn:(t,e)=>!ce(t,e),valueType:"number"},isGreatThanOrEqual:{type:["number"],fn:(t,e)=>!pe(t,e),valueType:"number"},dateBefore:{type:["date"],fn:(t,e)=>qe(t,e),valueType:"date"},dateAfter:{type:["date"],fn:(t,e)=>Ae(t,e),valueType:"date"},isSameDate:{type:["date"],fn:(t,e)=>_e(t,e),valueType:"date"},isSameDateAsToday:{type:["date"],fn:(t,e)=>Le(t,e),valueType:"none"},isExactList:{type:["option","option-multi","link-multi","context-multi","tags-multi"],fn:(t,e)=>Ee(t,e),valueType:"list"},isAnyInList:{type:["option","context","link","option-multi","link-multi","context-multi","tags-multi"],fn:(t,e)=>ge(t,e),valueType:"list"},isNoneInList:{type:["option","context","link","option-multi","link-multi","context-multi","tags-multi"],fn:(t,e)=>!ge(t,e),valueType:"list"},isTrue:{type:["boolean"],fn:(t,e)=>t=="true",valueType:"none"},isFalse:{type:["boolean"],fn:(t,e)=>t!="true",valueType:"none"}};var Gt=(t,e,r)=>e.reduce((n,o)=>{let[i,s]=n,d=o.type=="context"?$e(s,o,r):o.type=="path"?je(s,o,r):o.type=="frontmatter"?Qe(s,o,r):He(s,o,r),l=s.filter(p=>!d.includes(p));return[[...i,...d],l]},[[],t])[0],Vt=(t,e,r)=>e.reduce((a,n)=>n.type=="context"?$e(a,n,r):n.type=="path"?je(a,n,r):n.type=="frontmatter"?Qe(a,n,r):He(a,n,r),t),$e=(t,e,r)=>{let a=U[e.fn];return!a||a.valueType!="none"&&e.value.length==0?[]:t.filter(n=>{let[o,i]=e.field.split("."),s=n.metadata?.property;if(!n.spaces?.includes(o)||!s||!s[i])return!1;let d=!0;if(a){let l=e.fType=="property"?r[e.value]:e.value;d=a.fn(le(i,s[i]),l)}return d})},Qe=(t,e,r)=>{let a=U[e.fn];return!a||a.valueType!="none"&&e.value.length==0?[]:t.filter(n=>{let o=n.metadata?.property;if(!o||o[e.field]===void 0)return!1;let i=!0;if(a){let s=e.fType=="property"?r[e.value]:e.value;i=a.fn(le(e.field,o[e.field]),s)}return i})},je=(t,e,r)=>{let a=U[e.fn];return!a||a.valueType!="none"&&e.value.length==0?[]:t.filter(n=>{let o="";e.field=="outlinks"?o=I(n.outlinks??[]):e.field=="inlinks"?o=I(n.inlinks??[]):e.field=="tags"&&(o=I(n.tags??[]));let i=!0;if(a){let s=e.fType=="property"?r[e.value]:e.value;i=a.fn(o,s)}return i})},He=(t,e,r)=>{let a=U[e.fn];return!a||a.valueType!="none"&&e.value.length==0?[]:t.filter(n=>{let o=!0;if(a){let i=e.fType=="property"?r[e.value]:e.value;o=a.fn(n.metadata?.[e.type]?.[e.field],i)}return o})},Re=(t,e,r)=>t.reduce((n,o)=>!n||o.filters.length==0?!1:o.type=="any"?Gt([e],o.filters,r).length>0:Vt([e],o.filters,r).length>0,!0);function Be(t){let{queries:e,pathsIndex:r,count:a}=t,n=[];for(let[o,i]of r)!i.hidden&&Re(e,i,{})&&n.push(i);return n.slice(0,a)}var Xt=self;Xt.onmessage=async t=>{let{payload:e,job:r}=t.data,a;r.type=="search"&&(a=Be(e));try{postMessage({job:r,result:a})}catch(n){console.log(n),postMessage({job:r,result:{$error:`Failed to run ${r.type} ${r.path}: ${n}`}})}};\n', { "name": "Superstate Search" }); +} + +// src/core/superstate/workers/search/search.ts +var Searcher = class { + constructor(numWorkers, cache2) { + this.numWorkers = numWorkers; + this.cache = cache2; + this.workers = []; + this.busy = []; + this.reloadQueue = []; + this.reloadSet = /* @__PURE__ */ new Set(); + this.callbacks = /* @__PURE__ */ new Map(); + for (let index2 = 0; index2 < numWorkers; index2++) { + const worker = new Worker3({ name: "Make.md Superstate Indexer " + (index2 + 1) }); + worker.onmessage = (evt) => this.finish(evt.data.job, evt.data.result, index2); + this.workers.push(worker); + this.busy.push(false); } - }))); -}; -var DefFilterGroup = (props) => { - const { - group, - selectGroupType, - addDefGroup, - selectField, - i: i4, - removeDefGroup - } = props; - return /* @__PURE__ */ import_react49.default.createElement("div", { - className: "mk-query-group" - }, /* @__PURE__ */ import_react49.default.createElement("div", { - className: "mk-filter-bar mk-query-filters" - }, props.children, /* @__PURE__ */ import_react49.default.createElement("div", { - className: "mk-filter-add", - onClick: (e5) => selectField(e5, i4, group?.filters.length ?? 0) - }, /* @__PURE__ */ import_react49.default.createElement("span", null, /* @__PURE__ */ import_react49.default.createElement("span", { - className: "mk-icon-xsmall", - dangerouslySetInnerHTML: { - __html: props.superstate.ui.getSticker("ui//plus") + } + run(jerb) { + const jobKey = stringifyJob(jerb); + const promise = new Promise((resolve2, reject) => { + if (this.callbacks.has(jobKey)) + this.callbacks.get(jobKey)?.push([resolve2, reject]); + else + this.callbacks.set(jobKey, [[resolve2, reject]]); + }); + if (this.reloadSet.has(jobKey)) + return promise; + this.reloadSet.add(jobKey); + const workerId = this.nextAvailableWorker(); + if (workerId !== void 0) { + this.send(jerb, workerId); + } else { + this.reloadQueue.push(jerb); } - }), i18n_default.buttons.addCondition))), props.removeable && /* @__PURE__ */ import_react49.default.createElement("div", { - className: "mk-filter-add", - onClick: (e5) => { - removeDefGroup(i4); - e5.stopPropagation(); + return promise; + } + finish(jerb, data2, index2) { + const jobKey = stringifyJob(jerb); + const calls = [].concat(this.callbacks.get(jobKey) ?? []); + this.reloadSet.delete(jobKey); + this.callbacks.delete(jobKey); + this.busy[index2] = false; + const job = this.reloadQueue.shift(); + if (job !== void 0) + this.send(job, index2); + if ("$error" in data2) { + for (const [_15, reject] of calls) + reject(data2["$error"]); + } else { + for (const [callback, _15] of calls) + callback(data2); } - }, /* @__PURE__ */ import_react49.default.createElement("span", null, /* @__PURE__ */ import_react49.default.createElement("span", { - className: "mk-icon-small", - dangerouslySetInnerHTML: { - __html: props.superstate.ui.getSticker("ui//close") + } + async send(job, workerId) { + if (job.type == "search") { + this.message(workerId, { + job, + payload: { + queries: job.payload.queries, + pathsIndex: this.cache.pathsIndex, + count: job.payload.count + } + }); + this.busy[workerId] = true; } - })))); + } + message(workerId, message) { + this.workers[workerId].postMessage( + message + ); + } + nextAvailableWorker() { + const index2 = this.busy.indexOf(false); + return index2 == -1 ? void 0 : index2; + } }; -// src/core/react/components/SpaceEditor/SpaceItems.tsx -var SpaceItems = (props) => { - const [metadata, setMetadata] = (0, import_react50.useState)( - props.space.metadata ?? {} - ); - const [smartSearch, setSmartSearch] = (0, import_react50.useState)(metadata?.filters?.length > 0); - const saveMetadata = (metadata2) => { - setMetadata(metadata2); - saveSpaceCache(props.superstate, props.space.space, metadata2); - }; - const saveQuery = (q2) => { - saveMetadata({ - ...metadata, - filters: q2 - }); - }; - const linkCaches = (0, import_react50.useMemo)( - () => (metadata?.links ?? []).map((f2) => props.superstate.pathsIndex.get(f2)).filter((f2) => f2), - [metadata] - ); - const directChildren = (0, import_react50.useMemo)(() => { - return [...props.superstate.spacesMap.getInverse(props.space.path)].map((f2) => props.superstate.pathsIndex.get(f2)).filter((f2) => f2.parent == props.space.path); - }, [props.space]); - const metadataProperties = props.superstate.allMetadata; - const allOptions = []; - Object.keys(metadataProperties).forEach((type) => { - metadataProperties[type].properties.forEach((field) => { - allOptions.push(field); - }); - }); - const sections = Object.keys(metadataProperties).map((f2) => { - return { - name: metadataProperties[f2].name, - value: f2 - }; - }); - return /* @__PURE__ */ import_react50.default.createElement(import_react50.default.Fragment, null, /* @__PURE__ */ import_react50.default.createElement("div", { - className: "mk-space-editor" - }, /* @__PURE__ */ import_react50.default.createElement("div", { - className: "mk-space-editor-header" - }, /* @__PURE__ */ import_react50.default.createElement("div", { - className: "mk-space-editor-header-title" - }, /* @__PURE__ */ import_react50.default.createElement("div", { - className: "mk-space-editor-title" - }, i18n_default.subViews.spaceItems), /* @__PURE__ */ import_react50.default.createElement("div", { - className: "mk-space-editor-description" - }, i18n_default.descriptions.spaceItems)), /* @__PURE__ */ import_react50.default.createElement("span", null), /* @__PURE__ */ import_react50.default.createElement("button", { - className: "mk-toolbar-button", - dangerouslySetInnerHTML: { - __html: props.superstate.ui.getSticker("ui//live") - }, - onClick: () => setSmartSearch((p) => !p) - }), /* @__PURE__ */ import_react50.default.createElement("button", { - className: "mk-button-new", - "aria-label": i18n_default.buttons.addItem, - onClick: (e5) => showLinkMenu( - e5, - props.superstate, - (link) => saveMetadata({ - ...metadata, - links: [...metadata.links ?? [], link] +// src/core/superstate/superstate.ts +var Superstate10 = class { + constructor(indexVersion, onChange, spaceManager, uiManager, commandsManager) { + this.indexVersion = indexVersion; + this.onChange = onChange; + this.loadouts = []; + this.kit = [ + buttonNode, + dividerNode, + progressNode, + callout, + toggleNode, + eventItem, + circularProgressNode, + previewNode, + linkNode, + imageListItem, + detailItem, + flowListItem, + cardListItem, + cardsListItem, + listItem, + listGroup, + columnGroup, + masonryGroup, + listView, + calendarView, + dateGroup, + tabsNode, + fieldNode, + gridGroup, + newItemNode, + ratingNode, + fieldsView, + rowGroup, + coverListItem, + columnView + ]; + this.eventsDispatcher = new EventDispatcher(); + const all2 = { + ...all, + createAdd: factory("add", [], () => function add4(a4, b2) { + return a4 + b2; }) - ), - dangerouslySetInnerHTML: { - __html: props.superstate.ui.getSticker("ui//plus") - } - })), /* @__PURE__ */ import_react50.default.createElement("div", { - className: "mk-space-editor-contents" - }, smartSearch && /* @__PURE__ */ import_react50.default.createElement("div", { - className: "mk-space-editor-smart" - }, /* @__PURE__ */ import_react50.default.createElement("span", null, i18n_default.subViews.smartSearch), metadata?.filters?.length > 0 && /* @__PURE__ */ import_react50.default.createElement(SpaceQuery, { - superstate: props.superstate, - filters: metadata.filters ?? [], - setFilters: saveQuery, - removeable: true, - fields: allOptions, - sections, - linkProps: props.space.propertyTypes - }), /* @__PURE__ */ import_react50.default.createElement("button", { - className: "mk-filter-add", - "aria-label": i18n_default.buttons.addSmartSearch, - onClick: (e5) => saveMetadata({ - ...metadata, - filters: [ - ...metadata.filters ?? [], - { - type: "any", - trueFalse: true, - filters: [] - } - ] - }) - }, /* @__PURE__ */ import_react50.default.createElement("div", { - className: "mk-icon-xsmall", - dangerouslySetInnerHTML: { - __html: props.superstate.ui.getSticker("ui//plus") + }; + const runContext = create(all2); + runContext.import(formulas, { override: true }); + this.formulaContext = runContext; + this.initialized = false; + this.spaceManager = spaceManager; + this.spaceManager.superstate = this; + this.ui = uiManager; + this.cli = commandsManager; + const spaceCommands = new SpacesCommandsAdapter(this.cli, this); + this.cli.superstate = this; + this.cli.terminals.splice(0, 0, spaceCommands); + this.cli.mainTerminal = spaceCommands; + this.allMetadata = {}; + this.api = new API(this); + this.pathsIndex = /* @__PURE__ */ new Map(); + this.spacesIndex = /* @__PURE__ */ new Map(); + this.contextsIndex = /* @__PURE__ */ new Map(); + this.framesIndex = /* @__PURE__ */ new Map(); + this.actionsIndex = /* @__PURE__ */ new Map(); + this.kitFrames = /* @__PURE__ */ new Map(); + this.kits = /* @__PURE__ */ new Map(); + this.actions = /* @__PURE__ */ new Map(); + this.templateCache = /* @__PURE__ */ new Map(); + this.waypoints = []; + this.spacesMap = new IndexMap(); + this.linksMap = new IndexMap(); + this.tagsMap = new IndexMap(); + this.iconsCache = /* @__PURE__ */ new Map(); + this.imagesCache = /* @__PURE__ */ new Map(); + this.contextStateQueue = Promise.resolve(); + this.vaultDBCache = []; + this.indexer = new Indexer(2, this); + this.searcher = new Searcher(1, this); + } + static create(indexVersion, onChange, spaceManager, uiManager, commandsManager) { + return new Superstate10(indexVersion, onChange, spaceManager, uiManager, commandsManager); + } + refreshMetadata() { + this.allMetadata = allMetadata(this); + } + async initializeIndex() { + await this.loadFromCache(); + } + addToContextStateQueue(operation) { + this.contextStateQueue = this.contextStateQueue.then(operation).catch(() => { + }); + } + async initialize() { + if (!this.persister) { + console.log("Cache Persister Not Found"); + return; } - }), i18n_default.buttons.addSmartSearch)), linkCaches.map((f2, i4) => /* @__PURE__ */ import_react50.default.createElement(PathCrumb, { - key: i4, - superstate: props.superstate, - path: f2.path - })), directChildren.map((f2, i4) => /* @__PURE__ */ import_react50.default.createElement(PathCrumb, { - key: i4, - superstate: props.superstate, - path: f2.path - }))))); -}; - -// src/core/react/components/SpaceEditor/SpaceTemplates.tsx -var import_react51 = __toESM(require_react()); -var TemplatesList = (props) => { - const { pathState } = (0, import_react51.useContext)(PathContext); - const { spaceState } = (0, import_react51.useContext)(SpaceContext); - const [templates, setTemplates] = import_react51.default.useState([]); - (0, import_react51.useEffect)(() => { - refreshData({ path: pathState.path }); - }, []); - const refreshData = (payload) => { - if (payload.path == pathState?.path) - setTemplates( - props.superstate.spacesIndex.get(spaceState.path)?.templates - ); - }; - (0, import_react51.useEffect)(() => { - props.superstate.eventsDispatcher.addListener( - "spaceStateUpdated", - refreshData + const start = Date.now(); + this.initializeActions(); + this.initializeWaypoints(); + this.initializeKits(); + this.initializeTemplates(); + if (this.settings.spacesEnabled) + await this.initializeSpaces(); + await this.initializeTags(); + await this.initializePaths(); + await this.initializeContexts(); + await this.initializeFrames(); + this.cleanContexts(); + this.refreshMetadata(); + this.dispatchEvent("superstateUpdated", null); + this.ui.notify(`Make.md - Superstate Loaded in ${(Date.now() - start) / 1e3} seconds`, "console"); + this.persister.cleanType("space"); + this.persister.cleanType("path"); + this.persister.cleanType("context"); + this.persister.cleanType("frame"); + } + async reloadSystemActions() { + const libraries = await this.spaceManager.readSystemCommands(); + libraries.forEach((f2) => this.actions.set(f2.name, f2.commands)); + this.dispatchEvent("actionStateUpdated", { path: "spaces://$actions" }); + } + async initializeActions() { + await this.reloadSystemActions(); + const promises = this.allSpaces().filter((f2) => f2.type != "default").map((f2) => f2.space).map( + (l2) => this.reloadActions(l2) ); - return () => { - props.superstate.eventsDispatcher.removeListener( - "spaceStateUpdated", - refreshData - ); - }; - }, [pathState]); - const newAction = (e5) => { - showLinkMenu(e5, props.superstate, (space2) => { - saveSpaceTemplate(props.superstate, pathState.path, space2); + await Promise.all(promises); + } + async initializeKits() { + const kits = await this.spaceManager.readAllKits(); + kits.forEach((f2) => this.kits.set(f2.id, f2)); + if (kits.length == 0) { + this.kits.set("default", { + id: "default", + name: "Default", + colors: {}, + frames: [] + }); + } + this.selectedKit = this.kits.get(this.settings.selectedKit) ?? this.kits.get("default"); + this.selectedKit.frames = [...this.selectedKit.frames, ...this.kit.map((f2) => rootToFrame(f2)).filter((f2) => !this.selectedKit.frames.some((g) => g.schema.id == f2.schema.id))]; + this.selectedKit.frames.forEach((v2) => { + const kitID = mdbSchemaToFrameSchema(v2.schema).def.id; + this.kitFrames.set(kitID, buildRootFromMDBFrame(this, v2, { ...defaultFrameEditorProps, screenType: this.ui.getScreenType() })); }); - }; - const showMenu2 = (e5, f2) => { - const offset2 = e5.target.getBoundingClientRect(); - const menuOptions = []; - menuOptions.push({ - name: "Set as Default", - icon: "ui//clipboard-pen", - onClick: () => setTemplateInSpace(props.superstate, pathState.path, f2) + this.dispatchEvent("frameStateUpdated", { path: `spaces://$kit` }); + } + async initializeTemplates() { + const allTemplates = await this.spaceManager.readAllTemplates(); + Object.keys(allTemplates).forEach((f2) => { + this.templateCache.set(f2, allTemplates[f2]); }); - props.superstate.ui.openMenu( - offset2, - defaultMenu(props.superstate.ui, menuOptions), - "bottom" - ); - }; - const editFormula = (e5) => { - const _props = { - superstate: props.superstate, - saveFormula: (value) => setTemplateNameInSpace(props.superstate, pathState.path, value), - formula: spaceState.metadata.templateName, - value: {}, - fields: [], - description: "Automatically set a template name using a formula", - path: pathState.path - }; - props.superstate.ui.openCustomMenu( - e5.target.getBoundingClientRect(), - /* @__PURE__ */ import_react51.default.createElement(FormulaEditor, { - ..._props - }), - { ..._props }, - "bottom" + } + async initializeSpaces() { + const allSpaces = [...this.spaceManager.allSpaces().values()]; + const promises = allSpaces.map((f2) => this.reloadSpace(f2, null, true)); + [...this.spacesIndex.keys()].filter((f2) => !allSpaces.some((g) => g.path == f2)).forEach((f2) => this.onSpaceDeleted(f2)); + await Promise.all(promises); + } + getSpaceItems(spacePath, filesOnly) { + const items = [...this.spacesMap.getInverse(spacePath)]; + const ranks = this.contextsIndex.get(spacePath)?.paths ?? []; + return items.map((f2, i4) => { + const pathCache = this.pathsIndex.get(f2); + return { + ...pathCache, + rank: ranks.indexOf(f2) + }; + }).filter((f2) => f2?.hidden != true && f2.path != spacePath); + } + async initializeFrames() { + await this.initializeTemplates(); + const promises = this.allSpaces().filter((f2) => f2.type != "default").map((f2) => f2.space).map( + (l2) => this.reloadFrames(l2).then((f2) => this.dispatchEvent("frameStateUpdated", { path: l2.path })) ); - }; - return /* @__PURE__ */ import_react51.default.createElement("div", { - className: "mk-actions-list" - }, /* @__PURE__ */ import_react51.default.createElement("div", { - className: "mk-space-editor-header" - }, /* @__PURE__ */ import_react51.default.createElement("div", null, /* @__PURE__ */ import_react51.default.createElement("div", { - className: "mk-space-editor-title" - }, i18n_default.subViews.spaceTemplates), /* @__PURE__ */ import_react51.default.createElement("div", { - className: "mk-space-editor-description" - }, i18n_default.descriptions.spaceTemplates)), /* @__PURE__ */ import_react51.default.createElement("span", null), /* @__PURE__ */ import_react51.default.createElement("button", { - className: "mk-toolbar-button", - "aria-label": i18n_default.labels.editFormula, - onClick: (e5) => editFormula(e5), - dangerouslySetInnerHTML: { - __html: props.superstate.ui.getSticker("ui//formula") + await Promise.all(promises); + } + async initializeContexts() { + await this.indexer.reload({ type: "contexts", path: "" }).then(async (r2) => { + const promises = [...r2.entries()].map(([path2, { cache: cache2, changed }]) => this.contextReloaded(path2, cache2, changed)); + await Promise.all(promises); + }); + } + async cleanContexts() { + this.contextsIndex.forEach((context) => { + const contextFiles = [...this.spacesMap.getInverse(context.path)]; + const removeFiles = context.tables?.[defaultContextSchemaID]?.rows.filter((f2) => !contextFiles.includes(f2[PathPropertyName])) ?? []; + if (removeFiles.length > 0) { + this.addToContextStateQueue(() => removePathsInContext(this.spaceManager, removeFiles.map((f2) => f2[PathPropertyName]), this.spacesIndex.get(context.path).space).then((f2) => this.reloadSpaceByPath(context.path))); + } + }); + this.spacesIndex.forEach((space2) => { + const removeFiles = [...this.spacesMap.getInverse(space2.path)]; + }); + } + async loadFromCache() { + this.dispatchEvent("superstateReindex", null); + if (this.settings.indexSVG) { + const allIcons = await this.persister.loadAll("icon"); + this.spaceManager.allPaths(["svg"]).forEach((s4) => { + const row2 = allIcons.find((f2) => f2.path == s4); + if (row2?.cache.length > 0) + this.iconsCache.set(s4, row2.cache); + }); } - }), /* @__PURE__ */ import_react51.default.createElement("button", { - className: "mk-button-new", - "aria-label": i18n_default.labels.newAction, - onClick: (e5) => newAction(e5), - dangerouslySetInnerHTML: { - __html: props.superstate.ui.getSticker("ui//plus") + const allPaths = await this.persister.loadAll("path"); + const allSpaces = await this.persister.loadAll("space"); + const allContexts = await this.persister.loadAll("context"); + const allFrames = await this.persister.loadAll("frame"); + allSpaces.forEach((s4) => { + const space2 = safelyParseJSON(s4.cache); + if (space2 && space2.type) { + this.spacesIndex.set(s4.path, space2); + } + }); + allContexts.forEach((s4) => { + const space2 = safelyParseJSON(s4.cache); + if (space2) { + this.contextsIndex.set(s4.path, space2); + } + }); + allFrames.forEach((s4) => { + const space2 = safelyParseJSON(s4.cache); + if (space2) { + this.framesIndex.set(s4.path, space2); + } + }); + allPaths.forEach((f2) => { + const cache2 = parsePathState(f2.cache); + this.pathsIndex.set(f2.path, cache2); + this.tagsMap.set(f2.path, new Set(cache2.tags)); + this.spacesMap.set(f2.path, new Set(cache2.spaces)); + this.linksMap.set(f2.path, new Set(cache2.outlinks)); + }); + this.dispatchEvent("superstateUpdated", null); + } + dispatchEvent(event, payload) { + this.eventsDispatcher.dispatchEvent(event, payload); + } + async initializeTags() { + const allTags = this.spaceManager.readTags().map((f2) => tagSpacePathFromTag(f2)); + const promises = [tagsSpacePath, ...allTags].map((l2) => this.reloadPath(l2, true)); + await Promise.all(promises); + } + async onSpaceDefinitionChanged(space2, oldDef) { + const currentPaths = this.spacesMap.getInverse(space2.path); + const newPaths = []; + if (space2.metadata?.links && !import_lodash12.default.isEqual(space2.metadata.links, oldDef?.links)) { + newPaths.push(...space2.metadata.links); } - })), /* @__PURE__ */ import_react51.default.createElement("div", { - className: "mk-space-editor-contents" - }, templates.map((f2, i4) => /* @__PURE__ */ import_react51.default.createElement("div", { - key: i4, - className: "mk-action", - onContextMenu: (e5) => showMenu2(e5, f2) - }, /* @__PURE__ */ import_react51.default.createElement("div", { - className: "mk-path" - }, /* @__PURE__ */ import_react51.default.createElement("div", { - className: "mk-path-icon", - dangerouslySetInnerHTML: { - __html: props.superstate.ui.getSticker("ui//clipboard-pen") + if (space2.metadata?.filters) { + const hasProps = space2.metadata.filters.some((f2) => f2.filters.some((g) => g.fType == "property")); + if (!import_lodash12.default.isEqual(space2.metadata?.filters, oldDef?.filters) || hasProps) { + for (const [k2, f2] of this.pathsIndex) { + if (!f2.hidden && pathByDef(space2.metadata?.filters, f2, space2.properties)) { + newPaths.push(k2); + } + } + } + } + const diff2 = [...import_lodash12.default.difference(newPaths, [...currentPaths]), ...import_lodash12.default.difference([...currentPaths], newPaths)]; + const cachedPromises = diff2.map((f2) => this.reloadPath(f2, true).then((g) => this.dispatchEvent("pathStateUpdated", { path: f2 }))); + await Promise.all(cachedPromises); + } + async initializeWaypoints() { + const allWaypoints = await this.spaceManager.readWaypoints(); + if (allWaypoints.length == 0 && this.settings.waypoints.length > 0) { + let newWaypoints = this.settings.waypoints.map((f2) => { + return { name: this.pathsIndex.get(f2)?.displayName, paths: [f2], sticker: f2 == "spaces://$tags" ? "ui//tags" : this.pathsIndex.get(f2)?.label?.sticker }; + }); + if (newWaypoints.length == 0) { + newWaypoints = [{ name: "Home", sticker: "ui//home", paths: ["/"] }]; + } + this.spaceManager.saveWaypoints(newWaypoints); + return; + } + this.waypoints = allWaypoints; + } + async initializePaths() { + this.dispatchEvent("superstateReindex", null); + const allFiles = this.spaceManager.allPaths(); + const start = Date.now(); + await this.indexer.reload({ type: "paths", path: "" }).then(async (r2) => { + for await (const [path2, { cache: cache2, changed }] of Object.entries(r2)) { + await this.pathReloaded(path2, cache2, changed, false); + } + }); + this.ui.notify(`Make.md - ${allFiles.length} Paths Cached in ${(Date.now() - start) / 1e3} seconds`, "console"); + const allPaths = uniq([...this.spaceManager.allSpaces().map((f2) => f2.path), ...allFiles]); + [...this.pathsIndex.keys()].filter((f2) => !allPaths.some((g) => g == f2)).forEach((f2) => this.onPathDeleted(f2)); + this.dispatchEvent("superstateUpdated", null); + } + async onTagRenamed(tag2, newTag) { + const oldPath = spacePathFromName(tag2); + const newSpaceInfo = fileSystemSpaceInfoFromTag(this.spaceManager, newTag); + await this.onSpaceRenamed(oldPath, newSpaceInfo); + await this.onPathRename(oldPath, newSpaceInfo.path); + this.dispatchEvent("spaceChanged", { path: oldPath, newPath: newSpaceInfo.path }); + const allContextsWithTag = []; + for (const [contextPath, spaceCache] of this.spacesIndex) { + const contextCache = this.contextsIndex.get(contextPath); + if (contextCache?.contexts.includes(tag2)) { + this.addToContextStateQueue(() => renameTagInContexts(this.spaceManager, tag2, newTag, allContextsWithTag)); + } + if (spaceCache.metadata?.contexts.includes(tag2)) { + saveSpaceCache(this, spaceCache.space, { ...spaceCache.metadata, contexts: spaceCache.metadata.contexts.map((f2) => f2 == tag2 ? newTag : f2) }); + } } - }), /* @__PURE__ */ import_react51.default.createElement("div", null, f2)), /* @__PURE__ */ import_react51.default.createElement("span", null), spaceState.metadata.template == f2 && /* @__PURE__ */ import_react51.default.createElement("div", { - className: "mk-path-icon", - "aria-label": "Default", - dangerouslySetInnerHTML: { - __html: props.superstate.ui.getSticker("ui//check") + this.dispatchEvent("spaceStateUpdated", { path: "spaces://$tags" }); + } + async onTagDeleted(tag2) { + this.tagsMap.getInverse(tag2).forEach((path2) => { + this.deleteTagInPath(tag2, path2); + }); + const spacePath = folderForTagSpace(tag2, this.settings); + await this.spaceManager.deletePath(spacePath); + this.onSpaceDeleted(tagSpacePathFromTag(tag2)); + for (const [contextPath, spaceCache] of this.spacesIndex) { + if (spaceCache.metadata?.contexts.includes(tag2)) { + saveSpaceCache(this, spaceCache.space, { ...spaceCache.metadata, contexts: spaceCache.metadata.contexts.filter((f2) => f2 != tag2) }); + } } - }), /* @__PURE__ */ import_react51.default.createElement("button", { - className: "mk-toolbar-button", - onClick: () => props.superstate.spaceManager.deleteTemplate(f2, spaceState.path), - dangerouslySetInnerHTML: { - __html: props.superstate.ui.getSticker("ui//trash") + const allContextsWithTag = []; + for (const [contextPath, contextCache] of this.contextsIndex) { + if (contextCache.contexts.includes(tag2)) { + allContextsWithTag.push(this.spaceManager.spaceInfoForPath(contextCache.path)); + } } - }))))); -}; - -// src/core/react/components/UI/Crumbs/ContextTableCrumb.tsx -var import_react52 = __toESM(require_react()); -var ContextTableCrumb = (props) => { - const { setDragNode } = (0, import_react52.useContext)(WindowContext); - const { spaceInfo } = (0, import_react52.useContext)(SpaceContext); - const dragId = spaceInfo.path + props.schema.id; - const { - attributes, - listeners, - setNodeRef: setDraggableNodeRef, - transform - } = useDraggable({ - id: dragId, - data: { - id: dragId, - type: "context", - space: spaceInfo?.path, - schema: props.schema.id + this.addToContextStateQueue(() => removeTagInContexts(this.spaceManager, tag2, allContextsWithTag)); + this.dispatchEvent("spaceStateUpdated", { path: "spaces://$tags" }); + } + async deleteTagInPath(tag2, path2) { + let oldMetadata; + if (this.pathsIndex.has(path2)) { + oldMetadata = this.pathsIndex.get(path2); } - }); - const ref2 = (0, import_react52.useRef)(null); - useDndMonitor({ - onDragStart: (e5) => { - if (e5.active.data.current.id == dragId) { - setDragNode( - /* @__PURE__ */ import_react52.default.createElement("div", { - dangerouslySetInnerHTML: { __html: ref2.current.innerHTML } - }) - ); - } + if (oldMetadata) { + const newMetadata = { + ...oldMetadata, + tags: oldMetadata.tags.filter((f2) => f2 != tag2), + spaces: oldMetadata.spaces.filter((f2) => f2 != tagSpacePathFromTag(tag2)) + }; + this.pathsIndex.set(path2, newMetadata); + this.tagsMap.set(path2, new Set(newMetadata.tags)); + this.spacesMap.set(path2, new Set(newMetadata.spaces)); + } else { + await this.reloadPath(path2); } - }); - return /* @__PURE__ */ import_react52.default.createElement("div", { - className: "mk-path", - onClick: (e5) => props.onClick(e5), - ref: (el) => { - setDraggableNodeRef(el); - ref2.current = el; - }, - onContextMenu: (e5) => props.onContextMenu(e5), - ...attributes, - ...listeners - }, /* @__PURE__ */ import_react52.default.createElement("div", { - className: "mk-path-icon", - dangerouslySetInnerHTML: { - __html: props.superstate.ui.getSticker( - props.schema.primary == "true" ? "ui//layout-list" : "ui//table" - ) + this.onPathReloaded(path2); + this.dispatchEvent("pathStateUpdated", { path: path2 }); + } + onMetadataChange(path2) { + if (!this.pathsIndex.has(path2)) { + return; } - }), props.schema.name); -}; - -// src/core/react/components/SpaceEditor/TableList.tsx -var import_react53 = __toESM(require_react()); -var TableList = (props) => { - const { pathState } = (0, import_react53.useContext)(PathContext); - const { spaceState } = (0, import_react53.useContext)(SpaceContext); - const [tables, setTables] = (0, import_react53.useState)([]); - (0, import_react53.useEffect)(() => { - refreshData({ path: pathState.path }); - }, []); - const refreshData = (payload) => { - if (payload.path == pathState?.path) - setTables( - (props.superstate.contextsIndex.get(pathState?.path)?.schemas ?? []).filter((f2) => f2.primary != "true") - ); - }; - (0, import_react53.useEffect)(() => { - props.superstate.eventsDispatcher.addListener( - "contextStateUpdated", - refreshData - ); - return () => { - props.superstate.eventsDispatcher.removeListener( - "contextStateUpdated", - refreshData - ); - }; - }, [pathState]); - const newTable = (e5) => { - props.superstate.ui.openModal( - i18n_default.labels.newTable, - (_props) => /* @__PURE__ */ import_react53.default.createElement(InputModal, { - value: "", - saveLabel: i18n_default.buttons.save, - hide: _props.hide, - saveValue: (value) => { - props.superstate.spaceManager.tablesForSpace(spaceState.path).then((schemas) => { - if (schemas) { - const newSchema = { - id: uniqueNameFromString( - sanitizeTableName(value), - schemas.map((g) => g.id) - ), - name: value, - type: "db" - }; - return props.superstate.spaceManager.createTable(spaceState.path, newSchema).then((f2) => { - return props.superstate.spaceManager.addSpaceProperty( - spaceState.path, - { ...defaultTableFields[0], schemaId: newSchema.id } - ); - }); - } - }); + this.reloadPath(path2).then( + (f2) => { + const pathState = this.pathsIndex.get(path2); + const spaceState = this.spacesIndex.get(path2); + if (spaceState) { + this.reloadSpace(spaceState.space).then((f3) => this.onSpaceDefinitionChanged(f3, spaceState.metadata)); } - }) + const allContextsWithFile = pathState.spaces.map((f3) => this.spacesIndex.get(f3)?.space).filter((f3) => f3); + this.addToContextStateQueue(() => updateContextWithProperties(this, path2, allContextsWithFile).then(() => { + allContextsWithFile.forEach((f3) => { + this.dispatchEvent("contextStateUpdated", { path: f3.path }); + }); + })); + this.dispatchEvent("pathStateUpdated", { path: path2 }); + } ); - }; - const viewContextMenu = (e5, _schema) => { - const menuOptions = []; - menuOptions.push({ - name: i18n_default.menu.copyEmbedLink, - icon: "ui//link", - onClick: (e6) => { - navigator.clipboard.writeText( - contextEmbedStringFromContext(spaceState, _schema.id) - ); + } + reloadSpaceByPath(path2, metadata) { + return this.reloadSpace(this.spaceManager.spaceInfoForPath(path2), metadata); + } + async onPathRename(oldPath, newPath) { + const newFilePath = newPath; + const oldFileCache = this.pathsIndex.get(oldPath); + const oldSpaces = oldFileCache?.spaces ?? []; + if (oldFileCache) { + this.spacesMap.delete(oldPath); + this.spacesMap.deleteInverse(oldPath); + this.linksMap.delete(oldPath); + this.linksMap.deleteInverse(oldPath); + this.pathsIndex.delete(oldPath); + const allContextsWithPath = oldSpaces.map((f2) => this.spacesIndex.get(f2)).filter((f2) => f2); + await renamePathInContexts(this.spaceManager, oldPath, newFilePath, allContextsWithPath.map((f2) => f2.space)); + for (const space2 of allContextsWithPath) { + if (space2.metadata?.links?.includes(oldPath)) { + this.addToContextStateQueue(() => saveSpaceMetadataValue(this, space2.path, "links", space2.metadata.links.map((f2) => f2 == oldPath ? newPath : f2))); + } + await this.reloadContext(space2.space); + } + const allContextsWithLink = []; + for (const [contextPath, contextCache] of this.contextsIndex) { + if (contextCache.outlinks.includes(oldPath)) { + allContextsWithLink.push(this.spacesIndex.get(contextCache.path).space); + } } + this.addToContextStateQueue(() => renameLinkInContexts(this.spaceManager, oldPath, newFilePath, allContextsWithLink).then((f2) => Promise.all(allContextsWithLink.map((c3) => this.reloadContext(c3))))); + } + if (this.settings.waypoints.includes(oldPath)) { + this.settings.waypoints = this.settings.waypoints.map((f2) => f2 == oldPath ? newPath : f2); + this.saveSettings(); + this.dispatchEvent("settingsChanged", null); + } + await this.reloadPath(newPath, true); + const changedSpaces = uniq([...this.spacesMap.get(newPath) ?? [], ...oldSpaces]); + const cachedPromises = changedSpaces.map((f2) => this.reloadContext(this.spacesIndex.get(f2)?.space)); + await Promise.all(cachedPromises); + changedSpaces.forEach((f2) => this.dispatchEvent("spaceStateUpdated", { path: f2 })); + this.dispatchEvent("pathChanged", { path: oldPath, newPath }); + this.ui.viewsByPath(oldPath).forEach((view) => { + view.openPath(newPath); }); - menuOptions.push({ - name: i18n_default.menu.moveFile, - icon: "ui//move", - onClick: (e6) => { - showSpacesMenu(e6, props.superstate, (space2) => { - const table = props.superstate.contextsIndex.get(spaceState.path).tables?.[_schema.id]; - table.schema.id = uniqueNameFromString( - sanitizeTableName(table.schema.id), - Object.keys(props.superstate.contextsIndex.get(space2).tables) - ); - table.cols = table.cols.map((f2) => ({ - ...f2, - schemaId: table.schema.id - })); - props.superstate.spaceManager.createTable(space2, table.schema).then((f2) => props.superstate.spaceManager.saveTable(space2, table)); - }); + } + async onPathCreated(path2) { + await this.reloadPath(path2, true); + const parent = getParentPathFromString(path2); + if (this.spacesIndex.has(parent) && this.spacesIndex.get(parent).defPath == path2) { + await this.reloadSpace(this.spacesIndex.get(parent).space); + } + this.dispatchEvent("pathCreated", { path: path2 }); + } + onPathDeleted(path2) { + this.spacesMap.delete(path2); + this.linksMap.delete(path2); + this.linksMap.deleteInverse(path2); + this.persister.remove(path2, "path"); + const fileCache = this.pathsIndex.get(path2); + if (!fileCache) { + return; + } + const allContextsWithFile = (fileCache.spaces ?? []).map((f2) => this.spacesIndex.get(f2)?.space).filter((f2) => f2); + this.addToContextStateQueue(() => removePathInContexts(this.spaceManager, path2, allContextsWithFile).then((f2) => allContextsWithFile.forEach((c3) => this.reloadContext(c3)))); + const allContextsWithLink = []; + for (const [contextPath, contextCache] of this.contextsIndex) { + if (contextCache.outlinks.includes(path2) && this.spacesIndex.has(contextCache.path)) { + allContextsWithLink.push(this.spacesIndex.get(contextCache.path).space); } + } + this.addToContextStateQueue(() => removeLinkInContexts(this.spaceManager, path2, allContextsWithLink).then((f2) => allContextsWithFile.forEach((c3) => this.reloadContext(c3)))); + (fileCache.spaces ?? []).forEach((f2) => { + this.dispatchEvent("spaceStateUpdated", { path: f2 }); }); - menuOptions.push({ - name: i18n_default.menu.duplicate, - icon: "ui//copy", - onClick: (e6) => { - props.superstate.ui.openModal( - "Duplicate Table", - (_props) => /* @__PURE__ */ import_react53.default.createElement(InputModal, { - value: "", - hide: _props.hide, - saveLabel: "Save", - saveValue: (value) => { - const table = props.superstate.contextsIndex.get( - spaceState.path - ).tables?.[_schema.id]; - table.schema.id = uniqueNameFromString( - sanitizeTableName(value), - Object.keys( - props.superstate.contextsIndex.get(spaceState.path).tables - ) - ); - table.cols = table.cols.map((f2) => ({ - ...f2, - schemaId: table.schema.id - })); - props.superstate.spaceManager.createTable(spaceState.path, table.schema).then( - (f2) => props.superstate.spaceManager.saveTable( - spaceState.path, - table - ) - ); - } - }) - ); + this.pathsIndex.delete(path2); + this.dispatchEvent("pathDeleted", { path: path2 }); + } + async onSpaceRenamed(oldPath, newSpaceInfo) { + if (this.spacesIndex.has(oldPath)) { + const oldmetadata = this.spacesIndex.get(oldPath).metadata; + this.spacesIndex.set(newSpaceInfo.path, { + ...this.spacesIndex.get(oldPath), + path: newSpaceInfo.path, + defPath: newSpaceInfo.defPath, + name: newSpaceInfo.name, + space: newSpaceInfo + }); + this.spacesMap.rename(oldPath, newSpaceInfo.path); + this.spacesMap.renameInverse(oldPath, newSpaceInfo.path); + this.spacesIndex.delete(oldPath); + this.contextsIndex.delete(oldPath); + this.framesIndex.delete(oldPath); + this.actionsIndex.delete(oldPath); + await this.reloadSpace(newSpaceInfo, oldmetadata).then((f2) => this.onSpaceDefinitionChanged(f2, oldmetadata)); + await this.reloadContext(newSpaceInfo); + await this.reloadActions(newSpaceInfo); + await this.reloadFrames(newSpaceInfo).then((f2) => this.dispatchEvent("frameStateUpdated", { path: newSpaceInfo.path })); + } + } + onSpaceDeleted(space2) { + if (this.spacesIndex.has(space2)) { + this.spacesIndex.delete(space2); + this.contextsIndex.delete(space2); + this.framesIndex.delete(space2); + } + this.spacesMap.delete(space2); + this.spacesMap.deleteInverse(space2); + this.persister.remove(space2, "space"); + this.dispatchEvent("spaceDeleted", { path: space2 }); + } + async reloadActions(space2) { + if (!space2) + return false; + this.spaceManager.commandsForSpace(space2.path).then((r2) => { + this.actionsIndex.set(space2.path, r2); + this.dispatchEvent("actionStateUpdated", { path: space2.path }); + }); + } + async reloadFrames(space2) { + if (!space2) + return false; + return this.indexer.reload({ type: "frames", path: space2.path }).then((r2) => { + const { changed, cache: cache2 } = r2; + if (!changed) { + return false; } + this.framesIndex.set(space2.path, cache2); + this.persister.store(space2.path, JSON.stringify(cache2), "frame"); + return true; }); - menuOptions.push({ - name: i18n_default.buttons.renameView, - icon: "ui//edit", - onClick: (e6) => { - props.superstate.ui.openModal( - i18n_default.labels.renameView, - (_props) => /* @__PURE__ */ import_react53.default.createElement(InputModal, { - value: _schema.name, - saveLabel: i18n_default.labels.renameView, - hide: _props.hide, - saveValue: (value) => { - props.superstate.spaceManager.saveTableSchema( - pathState.path, - _schema.id, - () => ({ - ..._schema, - name: value - }) - ); + } + async reloadContextByPath(path2) { + return this.reloadContext(this.spaceManager.spaceInfoForPath(path2)); + } + async reloadContext(space2) { + if (!space2) + return false; + return this.indexer.reload({ type: "context", path: space2.path }).then((r2) => { + return this.contextReloaded(space2.path, r2.cache, r2.changed); + }); + } + async contextReloaded(path2, cache2, changed) { + if (!changed) { + return false; + } + this.contextsIndex.set(path2, cache2); + if (cache2.dbExists) { + if (this.settings.syncFormulaToFrontmatter) { + const allRows = cache2.tables?.[defaultContextSchemaID]?.rows ?? []; + const allColumns = cache2.tables?.[defaultContextSchemaID]?.cols ?? []; + const updatedValues = allRows.filter((f2) => { + const path3 = f2[PathPropertyName]; + const pathCache = this.pathsIndex.get(path3); + if (!pathCache) { + return false; + } + if (pathCache.type == "file" && pathCache.subtype != "md") + return false; + return allColumns.reduce((acc, col, i4) => { + if (acc) + return acc; + if (col.type != "fileprop" || col.primary == "true") + return acc; + if (f2[col.name]?.length > 0 && pathCache.metadata?.property?.[col.name] != f2[col.name]) + return true; + return acc; + }, false); + }); + if (updatedValues.length > 0) { + updatedValues.forEach((f2) => saveProperties(this, f2[PathPropertyName], allColumns.reduce((acc, col, i4) => { + if (col.type == "fileprop" && col.primary != "true") { + return { ...acc, [col.name]: f2[col.name] }; } - }) - ); + return acc; + }, {}))); + } + } + const contextPaths = cache2.tables?.[defaultContextSchemaID]?.rows.map((f2) => f2[PathPropertyName]) ?? []; + const missingPaths = cache2.paths.filter((f2) => !contextPaths.includes(f2)); + const removedPaths = contextPaths.filter((f2) => !cache2.paths.includes(f2)); + if (missingPaths.length > 0) { + this.addToContextStateQueue(() => insertContextItems(this.spaceManager, missingPaths, path2)); + } + if (removedPaths.length > 0) { + this.addToContextStateQueue(() => removePathsInContext(this.spaceManager, removedPaths, cache2.space)); + } + } + this.persister.store(path2, JSON.stringify(cache2), "context"); + this.dispatchEvent("contextStateUpdated", { path: path2 }); + return true; + } + allSpaces(ordered) { + if (ordered) { + return orderArrayByArrayWithKey([...this.spacesIndex.values()], this.spaceOrder(), "path"); + } + return [...this.spacesIndex.values()]; + } + spaceOrder() { + return [...this.settings.waypoints]; + } + allFrames() { + return [...this.framesIndex.values()].filter((f2) => f2).flatMap((f2) => f2.schemas.filter((f3) => f3.type == "frame").map((s4) => ({ schema: s4, path: f2.path }))); + } + async updateSpaceMetadata(spacePath, metadata) { + const space2 = this.spacesIndex.get(spacePath); + const oldDef = space2?.metadata; + if (!space2) { + return this.reloadSpaceByPath(spacePath); + } + let spaceDefChanged = false; + const spaceSort = metadata?.sort ?? { field: "rank", asc: true, group: true }; + const sortable = spaceSort.field == "rank"; + if (!import_lodash12.default.isEqual(space2.metadata.links, metadata.links) || !import_lodash12.default.isEqual(space2.metadata.filters, metadata.filters)) { + spaceDefChanged = true; + } + const newSpaceCache = { + ...space2, + metadata, + contexts: metadata?.contexts ?? [], + sortable + }; + this.spacesIndex.set(spacePath, newSpaceCache); + if (spaceDefChanged) { + await this.onSpaceDefinitionChanged(newSpaceCache, oldDef); + } + this.dispatchEvent("spaceStateUpdated", { path: space2.path }); + return newSpaceCache; + } + async reloadSpace(space2, spaceMetadata, initialized = true) { + if (!space2) + return; + const metadata = spaceMetadata ?? await this.spaceManager.spaceDefForSpace(space2.path); + let pathState = this.pathsIndex.get(space2.path); + const type = this.spaceManager.spaceTypeByString(this.spaceManager.uriByString(space2.path)); + if (type == "default" || type == "tag") { + metadata.filters = []; + metadata.links = []; + } + const propertyTypes = []; + let properties3 = {}; + const frame = this.framesIndex.get(space2.path); + if (frame) { + const frameProps = frame.frames[mainFrameID]?.cols ?? []; + propertyTypes.push(...frameProps); + } else { + const frameProps = await this.spaceManager.readFrame(space2.path, mainFrameID).then((f2) => f2?.cols ?? []); + propertyTypes.push(...frameProps); + } + if (propertyTypes.length > 0) { + if (!pathState) { + const pathCache = this.spaceManager.readPathCache(space2.defPath); + pathState = { + path: space2.path, + name: space2.name, + tags: [], + spaces: [], + outlinks: [], + hidden: false, + metadata: pathCache?.metadata, + type: "space", + subtype: type, + displayName: space2.name, + label: pathCache?.label + }; + } + properties3 = await this.spaceManager.readProperties(space2.defPath).then((f2) => linkContextRow(this.formulaContext, this.pathsIndex, f2, propertyTypes, pathState)); + } + [...this.spacesMap.get(space2.path)].map((f2) => this.contextsIndex.get(f2)).forEach((f2) => { + if (f2) { + const contextProps = f2.tables?.[defaultContextSchemaID]?.cols ?? []; + propertyTypes.push(...contextProps); + properties3 = { ...properties3, ...f2.tables?.[defaultContextSchemaID]?.rows.find((g) => g[PathPropertyName] == space2.path) ?? {} }; } }); - menuOptions.push({ - name: i18n_default.buttons.delete, - icon: "ui//trash", - onClick: (e6) => { - props.superstate.spaceManager.deleteTable(pathState.path, _schema.id); + const spaceSort = metadata?.sort ?? { field: "rank", asc: true, group: true }; + const sortable = spaceSort.field == "rank" || !spaceSort; + const contexts = metadata?.contexts ?? []; + const dependencies314 = uniq((metadata.filters ?? []).flatMap((f2) => f2.filters).flatMap((f2) => f2.type == "context" ? [f2.field.split(".")[0]] : f2.type == "path" && f2.field == "space" ? parseMultiString(f2.value) : [])); + if (type == "tag" && this.settings.autoAddContextsToSubtags) { + const parentTags = getAllParentTags(space2.name); + contexts.push(...parentTags); + } + const templates = await this.spaceManager.readTemplates(space2.path); + const cache2 = { + name: space2.name, + space: space2, + path: space2.path, + defPath: space2.defPath, + type, + templates, + contexts: contexts.map((f2) => ensureTag(f2)), + metadata, + dependencies: dependencies314, + sortable, + properties: properties3, + propertyTypes + }; + this.spacesIndex.set(space2.path, cache2); + this.persister.store(space2.path, JSON.stringify(cache2), "space"); + cache2.metadata?.links?.forEach((f2) => { + if (pathIsSpace(this, f2)) { + this.spacesMap.set(f2, /* @__PURE__ */ new Set([...this.spacesMap.get(f2), space2.path])); } }); - props.superstate.ui.openMenu( - e5.target.getBoundingClientRect(), - defaultMenu(props.superstate.ui, menuOptions) - ); - }; - return /* @__PURE__ */ import_react53.default.createElement("div", { - className: "mk-space-editor" - }, /* @__PURE__ */ import_react53.default.createElement("div", { - className: "mk-space-editor-header" - }, /* @__PURE__ */ import_react53.default.createElement("div", { - className: "mk-space-editor-header-title" - }, /* @__PURE__ */ import_react53.default.createElement("div", { - className: "mk-space-editor-title" - }, i18n_default.subViews.spaceLists), /* @__PURE__ */ import_react53.default.createElement("div", { - className: "mk-space-editor-description" - }, i18n_default.descriptions.spaceLists)), /* @__PURE__ */ import_react53.default.createElement("span", null), /* @__PURE__ */ import_react53.default.createElement("button", { - className: "mk-button-new", - "aria-label": i18n_default.labels.newTable, - onClick: (e5) => newTable(e5), - dangerouslySetInnerHTML: { - __html: props.superstate.ui.getSticker("ui//plus") + if (initialized) { + this.dispatchEvent("spaceStateUpdated", { path: space2.path }); + return cache2; } - })), /* @__PURE__ */ import_react53.default.createElement("div", { - className: "mk-space-editor-contents" - }, tables.map((f2, i4) => /* @__PURE__ */ import_react53.default.createElement(ContextTableCrumb, { - key: i4, - superstate: props.superstate, - schema: f2, - onClick: (e5) => { - props.hide(); - props.superstate.ui.openPath( - contextPathForSpace(spaceState, f2.id), - e5.metaKey + } + async pathReloaded(path2, cache2, changed, force) { + this.pathsIndex.set(path2, cache2); + await this.onPathReloaded(path2); + if (cache2.subtype == "image" || cache2.metadata?.file?.extension == "svg") { + this.imagesCache.set(cache2.metadata.file.filename, path2); + } + if (!changed && !force) { + return false; + } + this.tagsMap.set(path2, new Set(cache2.tags)); + this.linksMap.set(path2, new Set(cache2.outlinks)); + if (!import_lodash12.default.isEqual(cache2.spaces, Array.from(this.spacesMap.get(path2)))) { + this.spacesMap.set(path2, new Set(cache2.spaces)); + const promises = cache2.tags.map((f2) => this.spacesIndex.has(tagSpacePathFromTag(f2)) ? null : fileSystemSpaceInfoFromTag(this.spaceManager, f2)).filter((f2) => f2).map( + async (f2) => { + await this.reloadSpace(f2); + this.reloadContext(f2); + await this.reloadPath(f2.path); + return; + } ); - }, - onContextMenu: (e5) => { - viewContextMenu(e5, f2); + const allPromises = Promise.all(promises); + allPromises.then((f2) => { + this.dispatchEvent("spaceStateUpdated", { path: "spaces://$tags" }); + }); } - })))); + if (force) { + const allContextsWithFile = cache2.spaces.map((f2) => this.spacesIndex.get(f2)?.space).filter((f2) => f2); + this.addToContextStateQueue(() => updateContextWithProperties(this, path2, allContextsWithFile).then((g) => { + allContextsWithFile.forEach((f2) => { + this.reloadContext(f2); + this.dispatchEvent("spaceStateUpdated", { path: f2.path }); + }); + })); + } + if (cache2.metadata?.file?.extension == "svg" && this.settings.indexSVG) { + this.spaceManager.readPath(path2).then((f2) => { + this.iconsCache.set(path2, f2); + this.persister.store(path2, f2, "icon"); + }); + } + } + async reloadPath(path2, force) { + if (!path2) + return false; + return this.indexer.reload({ type: "path", path: path2 }).then(async (r2) => { + await this.pathReloaded(path2, r2.cache, r2.changed, force); + return true; + }); + } + async onPathReloaded(path2) { + let pathState; + if (this.pathsIndex.has(path2)) { + pathState = this.pathsIndex.get(path2); + } + if (!pathState) { + return false; + } + await this.persister.store(path2, serializePathState(pathState), "path"); + } }; -// src/core/react/components/SpaceEditor/SpaceEditor.tsx -var SpaceEditor = (props) => { - const [tab, setTab] = (0, import_react54.useState)( - props.space?.type == "tag" ? Math.max(1, props.tab) : props.tab - ); - return /* @__PURE__ */ import_react54.default.createElement("div", { - className: "mk-space-editor-container" - }, /* @__PURE__ */ import_react54.default.createElement("div", { - className: "mk-tab-group" - }, props.space?.type != "tag" && /* @__PURE__ */ import_react54.default.createElement("div", { - "aria-label": i18n_default.subViews.spaceItems, - onClick: () => setTab(0), - className: `mk-tab ${tab == 0 ? "mk-active" : ""}`, - dangerouslySetInnerHTML: { - __html: props.superstate.ui.getSticker("ui//file-stack") +// src/core/middleware/filesystem.ts +var FilesystemMiddleware = class { + constructor() { + this.filesystems = []; + this.filetypes = []; + this.eventDispatch = new EventDispatcher(); + } + static create() { + return new FilesystemMiddleware(); + } + resolvePath(path2, source) { + return this.primary.resolvePath(path2, source); + } + keysForCacheType(cacheType) { + return this.primary.keysForCacheType(cacheType); + } + allTags() { + return this.primary.readAllTags(); + } + fileFragmentChanged(file) { + this.eventDispatch.dispatchEvent("onFileFragmentChanged", { file }); + } + initiateFileSystemAdapter(adapter, primary) { + adapter.initiate(this); + if (primary) { + this.primary = adapter; } - }), /* @__PURE__ */ import_react54.default.createElement("div", { - "aria-label": i18n_default.subViews.spaceContext, - onClick: () => setTab(1), - className: `mk-tab ${tab == 1 ? "mk-active" : ""}`, - dangerouslySetInnerHTML: { - __html: props.superstate.ui.getSticker("ui//list") + this.filesystems.push(adapter); + } + initiateFiletypeAdapter(adapter) { + adapter.initiate(this); + this.filetypes.push(adapter); + } + filetypeAdaptersForFile(file) { + if (!file) + return []; + return this.filetypes.filter((f2) => f2.supportedFileTypes.includes(file.extension)); + } + filetypeAdaptersForFileFragments(file, fragmentType) { + return this.filetypeAdaptersForFile(file).filter((f2) => f2.contentTypes ? f2.contentTypes(file).includes(fragmentType) : false); + } + getFileCacheTypeByRefString(file, refString) { + const adapters = this.filetypeAdaptersForFile(file); + return adapters.reduce((p, c3) => { + if (p) + return p; + return c3.getCacheTypeByRefString(file, refString); + }, null); + } + allCaches() { + return this.primary.cache; + } + allFiles() { + return this.primary.allFiles(); + } + resourcePathForPath(path2) { + return this.adapterForPath(path2).resourcePathForPath(path2); + } + parentPathForPath(path2) { + return this.adapterForPath(path2).parentPathForPath(path2); + } + async createFileCache(path2) { + const file = await this.getFile(path2); + for (const adapter of this.filetypeAdaptersForFile(file)) { + if (adapter.parseCache) + await adapter.parseCache(file, false); } - }), /* @__PURE__ */ import_react54.default.createElement("div", { - "aria-label": i18n_default.subViews.spaceLists, - onClick: () => setTab(2), - className: `mk-tab ${tab == 2 ? "mk-active" : ""}`, - dangerouslySetInnerHTML: { - __html: props.superstate.ui.getSticker("ui//layout-list") + } + getFileCache(path2) { + return this.adapterForPath(path2).getFileCache(path2); + } + getFileContent(file, contentType, contentId) { + const adapters = this.filetypeAdaptersForFile(file).filter((f2) => f2.contentTypes(file).includes(contentType)); + if (adapters.length >= 1) { + return adapters[0].readContent(file, contentType, contentId); } - }), /* @__PURE__ */ import_react54.default.createElement("div", { - "aria-label": i18n_default.subViews.spaceActions, - onClick: () => setTab(3), - className: `mk-tab ${tab == 3 ? "mk-active" : ""}`, - dangerouslySetInnerHTML: { - __html: props.superstate.ui.getSticker("ui//mouse-pointer-click") + } + updateFileCache(path2, cache2, refresh) { + this.adapterForPath(path2).updateFileCache(path2, cache2, refresh); + } + readFileFragments(file, fragmentType, query) { + const adapters = this.filetypeAdaptersForFileFragments(file, fragmentType); + if (adapters.length >= 1) { + return adapters[0].readContent(file, fragmentType, query); } - }), /* @__PURE__ */ import_react54.default.createElement("div", { - "aria-label": i18n_default.subViews.spaceTemplates, - onClick: () => setTab(4), - className: `mk-tab ${tab == 4 ? "mk-active" : ""}`, - dangerouslySetInnerHTML: { - __html: props.superstate.ui.getSticker("ui//clipboard-pen") + } + async newFile(parent, name317, type, content3) { + const adapter = this.filetypes.find((f2) => f2.supportedFileTypes.includes(type)); + if (adapter) + return adapter.newFile(parent, name317, type, content3); + } + newFileFragment(file, fragmentType, name317, content3, options) { + const adapters = this.filetypeAdaptersForFileFragments(file, fragmentType); + if (adapters.length >= 1) { + return adapters[0].newContent(file, fragmentType, name317, content3, options); } - })), /* @__PURE__ */ import_react54.default.createElement(PathProvider, { - superstate: props.superstate, - path: props.space.path, - readMode: false - }, /* @__PURE__ */ import_react54.default.createElement(SpaceProvider, { - superstate: props.superstate - }, tab == 0 ? /* @__PURE__ */ import_react54.default.createElement(SpaceItems, { - superstate: props.superstate, - space: props.space - }) : tab == 1 ? /* @__PURE__ */ import_react54.default.createElement(FramesMDBProvider, { - superstate: props.superstate - }, /* @__PURE__ */ import_react54.default.createElement(ContextEditorProvider, { - superstate: props.superstate - }, /* @__PURE__ */ import_react54.default.createElement(SpacePropertyEditorContext, { - superstate: props.superstate - }))) : tab == 2 ? /* @__PURE__ */ import_react54.default.createElement(TableList, { - superstate: props.superstate, - hide: props.close - }) : tab == 3 ? /* @__PURE__ */ import_react54.default.createElement(ActionsList, { - superstate: props.superstate, - close: props.close - }) : tab == 4 ? /* @__PURE__ */ import_react54.default.createElement(TemplatesList, { - superstate: props.superstate, - close: props.close - }) : /* @__PURE__ */ import_react54.default.createElement(import_react54.default.Fragment, null)))); + } + saveFileLabel(file, key2, value) { + const adapters = this.filetypeAdaptersForFileFragments(file, "label"); + if (adapters.length >= 1) { + return adapters[0].saveContent(file, "label", key2, () => value); + } else { + return this.primary.updateFileLabel(file.path, key2, value); + } + } + saveFileFragment(file, fragmentType, fragmentId, saveContent) { + const adapters = this.filetypeAdaptersForFileFragments(file, fragmentType); + if (adapters.length >= 1) { + return adapters[0].saveContent(file, fragmentType, fragmentId, saveContent); + } + return false; + } + deleteFileFragment(file, fragmentType, fragmentId) { + const adapters = this.filetypeAdaptersForFileFragments(file, fragmentType); + if (adapters.length >= 1) { + return adapters[0].deleteContent(file, fragmentType, fragmentId); + } + } + onCreate(file) { + this.eventDispatch.dispatchEvent("onCreate", { file }); + } + onModify(file) { + this.eventDispatch.dispatchEvent("onModify", { file }); + } + onRename(file, oldPath) { + this.eventDispatch.dispatchEvent("onRename", { file, oldPath }); + } + onDelete(file) { + this.eventDispatch.dispatchEvent("onDelete", { file }); + } + adapterForPath(path2) { + return this.primary; + } + async getRoot() { + return this.adapterForPath().getRoot(); + } + async copyFile(path2, folder, newName) { + return this.adapterForPath(path2).copyFile(path2, folder, newName); + } + async writeTextToFile(path2, content3) { + return this.adapterForPath(path2).writeTextToFile(path2, content3); + } + async readTextFromFile(path2) { + return this.adapterForPath(path2).readTextFromFile(path2); + } + async writeBinaryToFile(path2, buffer) { + return this.adapterForPath(path2).writeBinaryToFile(path2, buffer); + } + async readBinaryToFile(path2) { + return this.adapterForPath(path2).readBinaryToFile(path2); + } + async renameFile(path2, newPath) { + return this.adapterForPath(path2).renameFile(path2, newPath); + } + async createFolder(path2) { + return this.adapterForPath(path2).createFolder(path2); + } + async childrenForFolder(path2, type) { + return this.adapterForPath(path2).childrenForFolder(path2, type); + } + async fileExists(path2) { + return this.adapterForPath(path2).fileExists(path2); + } + async getFile(path2, source) { + return this.adapterForPath(path2).getFile(path2, source); + } + async deleteFile(path2) { + return this.adapterForPath(path2).deleteFile(path2); + } + async addTagToFile(path2, tag2) { + return this.adapterForPath(path2).addTagToFile(path2, tag2); + } + async renameTagForFile(path2, oldTag, newTag) { + return this.adapterForPath(path2).renameTagForFile(path2, oldTag, newTag); + } + async removeTagFromFile(path2, tag2) { + return this.adapterForPath(path2).removeTagFromFile(path2, tag2); + } + filesForTag(tag2) { + return this.primary.filesForTag(tag2); + } }; -var SpaceEditor_default = SpaceEditor; -// src/core/react/components/UI/Modals/ContextEditor.tsx -var openSpaceEditorModal = (superstate, space2, tab) => { - superstate.ui.openModal( - space2.name, - (props) => /* @__PURE__ */ import_react55.default.createElement(SpaceEditor_default, { - superstate, - space: space2, - tab, - close: () => { - props.hide(); +// src/core/spaceManager/filesystemAdapter/filesystemAdapter.ts +var defaultTemplatesFolder = ".space/templates"; +var defaultKitsFolder = ".space/kits"; +var defaultActionsFolder = ".space/actions"; +var defaultWaypointsFile = ".space/waypoints.json"; +var defaultSpaceFolder = ".space"; +var FilesystemSpaceAdapter = class { + constructor(fileSystem) { + this.fileSystem = fileSystem; + this.schemes = ["spaces", "vault"]; + this.onCreate = async (payload) => { + if (payload.file.isFolder) { + this.spaceManager.onSpaceCreated(payload.file.path); + } else { + this.spaceManager.onPathCreated(payload.file.path); } - }), - "mk-space-editor-modal" - ); -}; -var SpacePropertyEditorContext = (props) => { - const { spaceState: spaceCache } = (0, import_react55.useContext)(SpaceContext); - const { - predicate, - savePredicate, - tableData, - sortedColumns, - hideColumn, - delColumn, - saveColumn - } = (0, import_react55.useContext)(ContextEditorContext); - const columns = (0, import_react55.useMemo)(() => { - return (tableData?.cols ?? []).sort( - (a4, b2) => (predicate?.colsOrder ?? []).findIndex((x2) => x2 == a4.name) - (predicate?.colsOrder ?? []).findIndex((x2) => x2 == b2.name) - ); - }, [tableData, predicate]); - const saveContexts = (contexts) => { - saveSpaceMetadataValue( - props.superstate, - spaceCache.path, - "contexts", - contexts - ); - }; - return /* @__PURE__ */ import_react55.default.createElement(SpacePropertyEditor, { - superstate: props.superstate, - colsOrder: predicate?.colsOrder ?? [], - setColumnOrder: (cols) => savePredicate({ colsOrder: cols }), - colsHidden: predicate?.colsHidden ?? [], - columns, - contexts: spaceCache?.contexts ?? [], - saveContexts, - hideColumn, - delColumn, - saveColumn - }); -}; - -// src/core/react/components/UI/Menus/navigator/spaceContextMenu.tsx -var showSpaceContextMenu = (superstate, path2, e5, activePath, parentSpace, onClose) => { - const space2 = superstate.spacesIndex.get(path2.path); - if (!space2) - return; - const menuOptions = []; - menuOptions.push({ - name: "New", - type: 6 /* Submenu */, - onSubmenu: (offset2) => { - return showSpaceAddMenu(superstate, offset2, space2); - }, - icon: "ui//plus" - }); - if (space2.type == "folder") { - menuOptions.push({ - name: i18n_default.buttons.addIntoSpace, - icon: "ui//pin", - onClick: (e6) => { - showLinkMenu(e6, superstate, (link) => { - pinPathToSpaceAtIndex(superstate, space2, link); - }); + }; + this.onDelete = (payload) => { + if (!payload.file) + return; + if (!payload.file.isFolder && payload.file.extension != "mdb") { + this.spaceManager.onPathDeleted(payload.file.path); + } else if (payload.file.isFolder) { + this.spaceManager.onSpaceDeleted(payload.file.path); + } + }; + this.onRename = (payload) => { + if (!payload.file) + return; + if (!payload.file.isFolder && payload.file.extension != "mdb") { + this.spaceManager.onPathChanged(payload.file.path, payload.oldPath); + } else if (payload.file.isFolder) { + this.spaceManager.onSpaceRenamed(payload.file.path, payload.oldPath); + } + }; + this.authorities = ["vault"]; + fileSystem.eventDispatch.addListener("onCreate", this.onCreate, 0, this); + fileSystem.eventDispatch.addListener("onRename", this.onRename, 0, this); + fileSystem.eventDispatch.addListener("onDelete", this.onDelete, 0, this); + fileSystem.eventDispatch.addListener("onCacheUpdated", this.onMetadataChange, 0, this); + } + initiateAdapter(manager) { + this.spaceManager = manager; + } + async readTemplates(path2) { + return (await this.childrenForPath(`${path2}/.space/templates`)).filter((f2) => !f2.startsWith(".")).map((f2) => f2.split("/").pop()); + } + async saveTemplate(path2, space2) { + return this.copyPath(path2, `${space2}/.space/templates`); + } + deleteTemplate(path2, space2) { + return this.deletePath(`${space2}/.space/templates/${path2}`); + } + async readWaypoints() { + if (!await this.fileSystem.fileExists(defaultSpaceFolder)) { + await this.fileSystem.createFolder(defaultSpaceFolder); + } + if (!await this.fileSystem.fileExists(defaultWaypointsFile)) { + return []; + } + return this.fileSystem.readTextFromFile(defaultWaypointsFile).then((f2) => ensureArray(safelyParseJSON(f2))); + } + async saveWaypoints(waypoints) { + if (!await this.fileSystem.fileExists(defaultSpaceFolder)) { + await this.fileSystem.createFolder(defaultSpaceFolder); + } + return this.fileSystem.writeTextToFile(defaultWaypointsFile, JSON.stringify(waypoints)); + } + async readTemplate(name317) { + const g = `${defaultTemplatesFolder}/${name317}`; + if (await this.fileSystem.fileExists(g)) { + return this.fileSystem.readFileFragments({ + path: g + "/.space/views.mdb", + name: "views", + filename: "views.mdb", + parent: g, + isFolder: false, + extension: "mdb" + }, "mdbTables"); + } + } + async readAllKits() { + const strings = (await this.childrenForPath(defaultKitsFolder)).map((f2) => f2.split("/").pop()); + const kits = Promise.all(strings.map(async (f2) => { + const frames = await this.readKitFrames(f2); + return { + id: f2, + name: f2, + colors: {}, + frames: Object.values(frames ?? {}) + }; + })); + return kits; + } + async readAllTemplates() { + const strings = (await this.childrenForPath(defaultTemplatesFolder)).map((f2) => f2.split("/").pop()); + const templates = {}; + for (const string4 of strings) { + const template2 = await this.readTemplate(string4); + if (template2) { + templates[string4] = template2; } - }); + } + return templates; } - menuOptions.push(menuSeparator); - if (space2.type != "default") { - menuOptions.push({ - name: i18n_default.labels.renameSection, - icon: "ui//edit", - onClick: (e6) => { - openSpaceEditorModal(superstate, space2, 0); - } - }); + async readKitFrames(name317) { + return this.fileSystem.readFileFragments({ + path: `${defaultKitsFolder}/${name317}/kit.mdb`, + name: "kit", + filename: "kit.mdb", + parent: `${defaultKitsFolder}/${name317}`, + isFolder: false, + extension: "mdb" + }, "mdbTables"); } - if (onClose) { - menuOptions.push({ - name: i18n_default.menu.closeSpace, - icon: "ui//close", - onClick: (e6) => { - onClose(); - } - }); + async saveFrameKit(frames, name317) { + const mdbFile = { + path: `${defaultKitsFolder}/${name317}/kit.mdb`, + name: "kit", + filename: "kit.mdb", + parent: `${defaultKitsFolder}/${name317}`, + isFolder: false, + extension: "mdb" + }; + await this.fileSystem.saveFileFragment(mdbFile, "schema", frames.schema.id, () => frames.schema); + this.fileSystem.saveFileFragment(mdbFile, "mdbFrame", frames.schema.id, () => frames); } - menuOptions.push(menuSeparator); - if (space2.type == "folder") { - menuOptions.push({ - name: i18n_default.buttons.addToSpace, - icon: "ui//pin", - onClick: (e6) => { - showSpacesMenu( - e6, - superstate, - (link) => { - const spaceCache = superstate.spacesIndex.get(link); - if (spaceCache) - addPathToSpaceAtIndex(superstate, spaceCache, space2.path, -1); - }, - true - ); - } - }); - menuOptions.push(menuSeparator); + async saveSpaceTemplate(frames, name317) { + let templateName = name317; + if (await this.fileSystem.fileExists(defaultTemplatesFolder)) { + const paths = await this.childrenForPath(`${defaultTemplatesFolder}/${name317}`); + templateName = uniqueNameFromString(templateName, paths); + } + await this.fileSystem.newFile(`${defaultTemplatesFolder}/${templateName}/.space`, "view", "mdb", frames); } - const parentSpaceCache = superstate.spacesIndex.get(parentSpace); - if (parentSpaceCache && (parentSpaceCache.type == "folder" || parentSpaceCache.type == "vault")) { - menuOptions.push({ - name: "Save as Template", - icon: "ui//clipboard-add", - onClick: (e6) => { - saveSpaceTemplate(superstate, space2.path, parentSpace); - } - }); - if (parentSpace != path2.parent) { - const spaceCache = superstate.spacesIndex.get(parentSpace); - if (spaceCache) { - menuOptions.push({ - name: i18n_default.menu.removeFromSpace, - icon: "ui//pin-off", - onClick: (e6) => { - removePathsFromSpace(superstate, spaceCache.path, [space2.path]); - } - }); + async onMetadataChange(payload) { + if (!payload.path) + return; + for (const space2 of this.allSpaces()) { + if (space2.defPath == payload.path) { + this.spaceManager.onPathPropertyChanged(space2.path); + return; } } + this.spaceManager.onPathPropertyChanged(payload.path); } - menuOptions.push(menuSeparator); - if (superstate.settings.spacesStickers) { - menuOptions.push({ - name: i18n_default.menu.changeColor, - icon: "ui//palette", - type: 6 /* Submenu */, - onSubmenu: (offset2) => { - return showColorPickerMenu( - superstate, - offset2, - "", - (value) => savePathColor(superstate, space2.path, value) - ); - } - }); - menuOptions.push({ - name: i18n_default.buttons.changeIcon, - icon: "ui//sticker", - onClick: (e6) => { - superstate.ui.openPalette((_props) => /* @__PURE__ */ import_react56.default.createElement(StickerModal_default, { - ui: superstate.ui, - hide: _props.hide, - selectedSticker: (emoji) => savePathSticker(superstate, space2.path, emoji) - })); - } - }); - menuOptions.push({ - name: i18n_default.buttons.removeIcon, - icon: "ui//file-minus", - onClick: (e6) => { - removePathIcon(superstate, space2.path); - } - }); + uriByPath(path2) { + return this.spaceManager.uriByString(path2); } - if (space2.metadata?.sort) { - menuOptions.push(menuSeparator); - menuOptions.push({ - name: i18n_default.menu.sortBy, - icon: "ui//sort-desc", - type: 6 /* Submenu */, - onSubmenu: (offset2) => { - const sortOptions = []; - sortOptions.push({ - name: i18n_default.menu.groupSpaces, - icon: "ui//arrow-up-down", - value: space2.metadata.sort.group == true, - type: 3 /* Radio */, - onClick: (e6) => { - updateSpaceSort(superstate, space2.path, { - field: space2.metadata.sort.field, - asc: space2.metadata.sort.asc, - group: !space2.metadata.sort.group - }); - } - }); - sortOptions.push(menuSeparator); - const rankSortOption = { - field: "rank", - asc: true, - group: space2.metadata.sort.group - }; - sortOptions.push({ - name: i18n_default.menu.customSort, - icon: "ui//arrow-up-down", - value: space2.metadata.sort.field == rankSortOption.field && space2.metadata.sort.asc == rankSortOption.asc, - type: 3 /* Radio */, - onClick: (e6) => { - updateSpaceSort(superstate, space2.path, rankSortOption); - } - }); - sortOptions.push(menuSeparator); - const nameSortOption = { - field: "name", - asc: true, - group: space2.metadata.sort.group - }; - sortOptions.push({ - name: i18n_default.menu.fileNameSortAlphaAsc, - icon: "ui//arrow-up-down", - value: space2.metadata.sort.field == nameSortOption.field && space2.metadata.sort.asc == nameSortOption.asc, - type: 3 /* Radio */, - onClick: (e6) => { - updateSpaceSort(superstate, space2.path, nameSortOption); - } - }); - const nameSortOptionDesc = { - field: "name", - asc: false, - group: space2.metadata.sort.group - }; - sortOptions.push({ - name: i18n_default.menu.fileNameSortAlphaDesc, - icon: "ui//arrow-up-down", - value: space2.metadata.sort.field == nameSortOptionDesc.field && space2.metadata.sort.asc == nameSortOptionDesc.asc, - type: 3 /* Radio */, - onClick: (e6) => { - updateSpaceSort(superstate, space2.path, nameSortOptionDesc); - } - }); - sortOptions.push(menuSeparator); - const numberSortOption = { - field: "number", - asc: true, - group: space2.metadata.sort.group - }; - sortOptions.push({ - name: i18n_default.menu.fileNameSortNumericalAsc, - icon: "ui//arrow-up-down", - value: space2.metadata.sort.field == numberSortOption.field && space2.metadata.sort.asc == numberSortOption.asc, - type: 3 /* Radio */, - onClick: (e6) => { - updateSpaceSort(superstate, space2.path, numberSortOption); - } - }); - const numberSortOptionDesc = { - field: "number", - asc: false, - group: space2.metadata.sort.group - }; - sortOptions.push({ - name: i18n_default.menu.fileNameSortNumericalDesc, - icon: "ui//arrow-up-down", - value: space2.metadata.sort.field == numberSortOptionDesc.field && space2.metadata.sort.asc == numberSortOptionDesc.asc, - type: 3 /* Radio */, - onClick: (e6) => { - updateSpaceSort(superstate, space2.path, numberSortOptionDesc); - } - }); - sortOptions.push(menuSeparator); - const createdTimeSortOption = { - field: "ctime", - asc: false, - group: space2.metadata.sort.group - }; - sortOptions.push({ - name: i18n_default.menu.createdTimeSortAsc, - icon: "ui//arrow-up-down", - value: space2.metadata.sort.field == createdTimeSortOption.field && space2.metadata.sort.asc == createdTimeSortOption.asc, - type: 3 /* Radio */, - onClick: (e6) => { - updateSpaceSort(superstate, space2.path, createdTimeSortOption); - } - }); - const createdTimeSortOptionDesc = { - field: "ctime", - asc: true, - group: space2.metadata.sort.group + allPaths(type) { + return [...this.fileSystem.allFiles().filter((f2) => type ? type.some((g) => g == "folder" ? f2.isFolder : f2.extension == g) : true).map((g) => g.path)]; + } + async pathExists(path2) { + return this.fileSystem.fileExists(path2); + } + async createItemAtPath(parent, type, name317, content3) { + const parentURI = await this.getPathInfo(parent); + if (!parentURI?.isFolder) { + const file = await this.fileSystem.getFile(parent); + if (!file) + return null; + return this.fileSystem.newFileFragment(file, type, name317, content3)?.then((f2) => file.path); + } + return this.fileSystem.newFile(parent, name317, type, content3).then((f2) => f2?.path); + } + async renamePath(oldPath, path2) { + const uri = this.uriByPath(oldPath); + const newUri = this.uriByPath(path2); + const file = await this.fileSystem.getFile(uri.path); + if (uri.refStr) { + const refType = await this.fileSystem.getFileCacheTypeByRefString(file, uri.refStr); + return await this.fileSystem.saveFileFragment(file, refType, uri.refStr, () => newUri.refStr); + } + return await this.fileSystem.renameFile(oldPath, path2); + } + async deletePath(path2) { + const uri = this.uriByPath(path2); + if (uri.refStr) { + const file = await this.fileSystem.getFile(uri.path); + const refType = await this.fileSystem.getFileCacheTypeByRefString(file, uri.refStr); + return this.fileSystem.deleteFileFragment(file, refType, uri.refStr); + } + return this.fileSystem.deleteFile(path2); + } + async getPathInfo(path2) { + const uri = this.uriByPath(path2); + const file = await this.fileSystem.getFile(uri.path); + if (uri.refStr) { + const type = this.fileSystem.getFileCacheTypeByRefString(file, uri.refStr); + } + return file; + } + keysForCacheType(path2) { + return this.fileSystem.keysForCacheType(path2); + } + readPathCache(path2) { + const uri = this.uriByPath(path2); + if (uri.scheme == "spaces") { + if (path2.startsWith(tagsSpacePath)) { + return { + file: null, + metadata: null, + label: { + name: "Tags", + sticker: "", + color: "" + }, + type: "space", + parent: "", + tags: [] }; - sortOptions.push({ - name: i18n_default.menu.createdTimeSortDesc, - icon: "ui//arrow-up-down", - value: space2.metadata.sort.field == createdTimeSortOptionDesc.field && space2.metadata.sort.asc == createdTimeSortOptionDesc.asc, - type: 3 /* Radio */, - onClick: (e6) => { - updateSpaceSort(superstate, space2.path, createdTimeSortOptionDesc); - } - }); - sortOptions.push(menuSeparator); - const sizeSortOption = { - field: "size", - asc: false, - group: space2.metadata.sort.group + } + if (uri.authority.charAt(0) == "#") { + return { + file: null, + metadata: null, + label: { + name: uri.authority, + sticker: "", + color: "" + }, + type: "space", + parent: "", + tags: [] }; - sortOptions.push({ - name: i18n_default.menu.sizeSortAsc, - icon: "ui//arrow-up-down", - value: space2.metadata.sort.field == sizeSortOption.field && space2.metadata.sort.asc == sizeSortOption.asc, - type: 3 /* Radio */, - onClick: (e6) => { - updateSpaceSort(superstate, space2.path, sizeSortOption); - } - }); - const sizeSortOptionDesc = { - field: "size", - asc: true, - group: space2.metadata.sort.group + } else { + return { + file: null, + metadata: null, + label: { + name: "Tags", + sticker: "", + color: "" + }, + type: "space", + parent: "", + tags: [] }; - sortOptions.push({ - name: i18n_default.menu.sizeSortDesc, - icon: "ui//arrow-up-down", - value: space2.metadata.sort.field == sizeSortOptionDesc.field && space2.metadata.sort.asc == sizeSortOptionDesc.asc, - type: 3 /* Radio */, - onClick: (e6) => { - updateSpaceSort(superstate, space2.path, sizeSortOptionDesc); - } - }); - return superstate.ui.openMenu( - offset2, - defaultMenu(superstate.ui, sortOptions) - ); } - }); + } + return this.fileSystem.getFileCache(path2); } - if (space2.type != "default") { - menuOptions.push(menuSeparator); - menuOptions.push({ - name: i18n_default.menu.rename, - icon: "ui//edit", - onClick: (e6) => { - superstate.ui.openModal( - i18n_default.labels.rename, - (_props) => /* @__PURE__ */ import_react56.default.createElement(InputModal, { - saveLabel: i18n_default.buttons.rename, - value: space2.type == "tag" ? stringFromTag(space2.name) : space2.name, - hide: _props.hide, - saveValue: (v2) => renamePathByName(superstate, space2.path, v2) - }) - ); - } - }); + async readPath(path2) { + const uri = this.uriByPath(path2); + const file = await this.fileSystem.getFile(uri.path); + if (uri.refStr) { + const fragmentType = this.fileSystem.getFileCacheTypeByRefString(file, uri.refStr); + this.fileSystem.getFileContent(file, fragmentType, uri.refStr); + } + return this.fileSystem.readTextFromFile(path2); } - menuOptions.push({ - name: i18n_default.menu.duplicate, - icon: "ui//documents", - onClick: (e6) => { - superstate.spaceManager.copyPath(path2.path, `${path2.parent}`); + async copyPath(path2, newPath, newName) { + const uri = this.uriByPath(path2); + const file = await this.fileSystem.getFile(uri.path); + return this.fileSystem.copyFile(file.path, newPath, newName); + } + async writeToPath(path2, content3, binary) { + const uri = this.uriByPath(path2); + const file = await this.fileSystem.getFile(uri.path); + if (uri.refStr) { + const fragmentType = this.fileSystem.getFileCacheTypeByRefString(file, uri.refStr); + this.fileSystem.saveFileFragment(file, fragmentType, uri.refStr, () => content3); } - }); - if (space2.type == "folder") { - menuOptions.push({ - name: i18n_default.menu.moveFile, - icon: "ui//paper-plane", - onClick: (e6) => { - showSpacesMenu(e6, superstate, (link) => { - superstate.spaceManager.renameSpace( - space2.path, - movePath(space2.path, link) - ); - }); - } - }); + if (binary) { + return this.fileSystem.writeBinaryToFile(path2, content3); + } + return this.fileSystem.writeTextToFile(path2, content3); } - menuOptions.push(menuSeparator); - if (!isTouchScreen(superstate.ui)) { - menuOptions.push({ - name: i18n_default.menu.revealInDefault, - icon: "ui//arrow-up-right", - onClick: (e6) => { - superstate.ui.openPath( - space2.type == "folder" ? space2.path : `${superstate.settings.spacesFolder}/${space2.name}`, - "system" - ); - } - }); + async childrenForPath(path2, type) { + if (await this.fileSystem.fileExists(path2)) + return this.fileSystem.childrenForFolder(path2, type); + return []; } - menuOptions.push(menuSeparator); - if (space2.type == "folder") { - menuOptions.push({ - name: i18n_default.menu.hide, - icon: "ui//eye-off", - onClick: (e6) => { - hidePath(superstate, space2.path); - } - }); + parentPathForPath(path2) { + return this.fileSystem.parentPathForPath(path2); } - if (space2.type == "folder" || space2.type == "tag") - menuOptions.push({ - name: i18n_default.menu.delete, - icon: "ui//trash", - onClick: (e6) => { - superstate.ui.openModal( - i18n_default.labels.deleteSpace, - (_props) => /* @__PURE__ */ import_react56.default.createElement(ConfirmationModal, { - hide: _props.hide, - confirmAction: () => removeSpace(superstate, space2.path), - confirmLabel: i18n_default.buttons.delete, - message: i18n_default.descriptions.deleteSpace - }) - ); + async readFrame(path2, schema) { + const mdbFile = await this.fileSystem.getFile(this.spaceInfoForPath(path2).framePath); + if (!mdbFile) { + const defaultTemplate2 = this.defaultFrame(); + if (Object.keys(defaultTemplate2).some((f2) => f2 == schema)) { + const defaultTable = defaultTemplate2[schema]; + return defaultTable; } - }); - superstate.ui.openMenu( - e5.target.getBoundingClientRect(), - defaultMenu(superstate.ui, menuOptions) - ); - return false; -}; - -// src/core/utils/ui/selection.ts -var selectNextIndex = (currIndex, array) => { - if (!currIndex && array.length > 0) - return array[0]; - const pos = array.indexOf(currIndex); - if (pos < array.length - 1) - return array[pos + 1]; - return currIndex; -}; -var selectPrevIndex = (currIndex, array) => { - const pos = array.indexOf(currIndex); - if (pos > 0) - return array[pos - 1]; - return array[0]; -}; -var selectRange = (currSel, newSel, array) => { - const lastIndex = array.findIndex((f2) => f2 == currSel); - const newIndex = array.findIndex((f2) => f2 == newSel); - if (lastIndex < newIndex) { - return array.filter((f2, i4) => i4 > lastIndex && i4 <= newIndex); + } + return this.fileSystem.readFileFragments(mdbFile, "mdbTable", schema); } - return array.filter((f2, i4) => i4 < lastIndex && i4 >= newIndex); -}; - -// src/core/react/components/SpaceView/Contexts/TableView/TableView.tsx -var import_lodash12 = __toESM(require_lodash()); - -// src/core/react/components/SpaceView/Contexts/DataTypeView/DataTypeView.tsx -var import_react76 = __toESM(require_react()); - -// src/core/react/components/SpaceView/Contexts/DataTypeView/BooleanCell.tsx -var import_react57 = __toESM(require_react()); -var BooleanCell = (props) => { - const { initialValue, saveValue } = props; - const [value, setValue] = import_react57.default.useState(initialValue == "true"); - const onChange = () => { - if (props.editMode == 0 /* EditModeReadOnly */) { - return; + async readAllFrames(path2) { + const mdbFile = await this.fileSystem.getFile(this.spaceInfoForPath(path2).framePath); + if (!mdbFile) { + return this.defaultFrame(); } - setValue(!value); - saveValue(!value ? "true" : "false"); - }; - (0, import_react57.useEffect)(() => { - if (props.editMode == 4 /* EditModeActive */) { - setValue(!value); - saveValue(!value ? "true" : "false"); - props.setEditMode(null); + return this.fileSystem.readFileFragments(mdbFile, "mdbTables"); + } + async readTable(path2, schema) { + const spaceInfo = this.spaceInfoForPath(path2); + const mdbFile = await this.fileSystem.getFile(spaceInfo.dbPath); + if (!mdbFile && schema == defaultContextDBSchema.id) { + const defaultTable = defaultTableDataForContext(this.spaceManager.superstate, spaceInfo); + return defaultTable; } - }, [props.editMode]); - import_react57.default.useEffect(() => { - setValue(initialValue == "true"); - }, [initialValue]); - if (props.editMode < 2 /* EditModeView */) { - return /* @__PURE__ */ import_react57.default.createElement("div", { - className: "mk-cell-boolean" - }, /* @__PURE__ */ import_react57.default.createElement("input", { - type: "checkbox", - checked: value, - onChange - })); + return this.fileSystem.readFileFragments(mdbFile, "mdbTable", schema); } - return /* @__PURE__ */ import_react57.default.createElement("div", { - className: "mk-cell-boolean" - }, /* @__PURE__ */ import_react57.default.createElement("input", { - type: "checkbox", - checked: value, - onChange - })); -}; - -// src/core/react/components/SpaceView/Contexts/DataTypeView/ColorCell.tsx -var import_react58 = __toESM(require_react()); -var ColorCell = (props) => { - const showMenu2 = (e5) => { - const handleChangeComplete = (color2) => { - props.saveValue(color2); - }; - const offset2 = e5.target.getBoundingClientRect(); - showColorPickerMenu( - props.superstate, - offset2, - props.initialValue, - handleChangeComplete - ); - }; - return /* @__PURE__ */ import_react58.default.createElement("div", null, /* @__PURE__ */ import_react58.default.createElement("div", { - className: "mk-setter-color", - onClick: (e5) => showMenu2(e5), - style: { - backgroundColor: props.initialValue, - width: 30, - height: 30 + async spaceInitiated(path2) { + const spaceInfo = this.spaceInfoForPath(path2); + const mdbFile = await this.fileSystem.getFile(spaceInfo.dbPath); + if (mdbFile) + return true; + return false; + } + async tablesForSpace(path2) { + const spaceInfo = this.spaceInfoForPath(path2); + const mdbFile = await this.fileSystem.getFile(spaceInfo.dbPath); + if (!mdbFile) { + return defaultContextTable.rows; } - })); -}; - -// src/core/react/components/SpaceView/Contexts/DataTypeView/ContextCell.tsx -var import_react60 = __toESM(require_react()); - -// src/core/react/components/SpaceView/Contexts/DataTypeView/OptionCell.tsx -var import_lodash11 = __toESM(require_lodash()); -var import_react59 = __toESM(require_react()); -var OptionCell = (props) => { - const parsedValue = (0, import_react59.useMemo)( - () => parseFieldValue( - props.propertyValue, - "option", - props.superstate, - props.source - ), - [props.propertyValue, props.source] - ); - const serializeValue = (newOptions, value2) => { - return JSON.stringify({ - ...value2, - options: newOptions.map((f2) => ({ - name: f2.name, - value: f2.value, - color: f2.color - })) - }); - }; - const parseOptions = (_options, values2, editMode, editable) => { - return [ - ...(_options ?? []).filter((f2) => f2.value).map((t5) => ({ - ...t5, - color: editable ? t5.color?.length > 0 ? t5.color : "var(--mk-color-none)" : void 0, - removeable: editable ? editMode >= 2 /* EditModeView */ : false - })) ?? [], - ...values2.map((f2) => { - return { - name: f2, - value: f2, - color: editable ? "var(--mk-color-none)" : void 0, - removeable: editable ? editMode >= 2 /* EditModeView */ : false - }; - }) - ].filter(onlyUniqueProp("value")).filter((f2) => f2.value.length > 0); - }; - const parseValues = (value2, multi) => { - return (multi ? parseMultiString(value2) ?? [] : [value2]).filter( - (f2) => f2 && f2.length > 0 - ); - }; - const [options, setOptions] = (0, import_react59.useState)( - parseOptions( - parsedValue.options ?? [], - parseValues(props.initialValue, props.multi), - props.editMode, - parsedValue.source ? false : true - ) - ); - const [value, setValue] = (0, import_react59.useState)( - parseValues(props.initialValue, props.multi) - ); - (0, import_react59.useEffect)(() => { - setValue(parseValues(props.initialValue, props.multi)); - }, [props.initialValue, props.multi]); - (0, import_react59.useEffect)(() => { - setOptions( - parseOptions( - parsedValue.options ?? [], - value, - props.editMode, - parsedValue.source ? false : true - ) - ); - }, [parsedValue, value, props.editMode]); - const removeValue = (v2) => { - if (props.multi) { - const newValues = value.filter((f2) => f2 != v2); - setValue(newValues); - props.saveValue(serializeMultiString(newValues)); - } else { - setValue([]); - props.saveValue(""); + return this.fileSystem.readFileFragments(mdbFile, "schemas", null); + } + defaultDBTablesForContext(spaceInfo) { + const table = defaultTableDataForContext(this.spaceManager.superstate, spaceInfo); + const defaultFields = defaultFieldsForContext(spaceInfo); + const defaultTable = defaultTablesForContext(spaceInfo); + return { + ...defaultTable, + m_fields: { + uniques: defaultFields.uniques, + cols: defaultFields.cols, + rows: [...defaultFields.rows ?? [], ...table.cols] + }, + [table.schema.id]: { + uniques: table.cols.filter((c3) => c3.unique == "true").map((c3) => c3.name), + cols: table.cols.map((c3) => c3.name), + rows: table.rows + } + }; + } + defaultFrame() { + if (this.spaceManager.superstate.settings.defaultSpaceTemplate.length > 0 && this.spaceManager.superstate.templateCache.has(this.spaceManager.superstate.settings.defaultSpaceTemplate)) { + return this.spaceManager.superstate.templateCache.get(this.spaceManager.superstate.settings.defaultSpaceTemplate); } - }; - const removeOption = (option) => { - const newOptions = options.filter((f2) => f2.value != option); - const newValues = value.filter((f2) => f2 != option); - setOptions(newOptions); - setValue(newValues); - if (props.multi) { - props.saveOptions( - serializeValue(newOptions, parsedValue), - serializeMultiString(newValues) - ); - } else { - props.saveOptions( - serializeValue(newOptions, parsedValue), - serializeMultiDisplayString(newValues) - ); + return DefaultMDBTables; + } + async createDefaultTable(path2) { + const spaceInfo = this.spaceInfoForPath(path2); + const dbPath = this.spaceInfoForPath(path2).dbPath; + const extension = dbPath.split(".").pop(); + const folder = dbPath.split("/").slice(0, -1).join("/"); + const filename = dbPath.split("/").pop().split(".")[0]; + return this.fileSystem.newFile(folder, filename, extension, this.defaultDBTablesForContext(spaceInfo)); + } + async createDefaultFrames(path2) { + const defaultSpaceTemplate = this.defaultFrame(); + const dbField = { + ...mdbFrameToDBTables(defaultSpaceTemplate), + m_schema: defaultFramesTable + }; + const dbPath = this.spaceInfoForPath(path2).framePath; + const extension = dbPath.split(".").pop(); + const folder = dbPath.split("/").slice(0, -1).join("/"); + const filename = dbPath.split("/").pop().split(".")[0]; + return this.fileSystem.newFile(folder, filename, extension, dbField); + } + async createTable(path2, schema) { + let mdbFile = await this.fileSystem.getFile(this.spaceInfoForPath(path2).dbPath); + if (!mdbFile) { + mdbFile = await this.createDefaultTable(path2); } - }; - const savePropValue = (options2, value2) => { - if (props.multi) { - props.saveOptions( - serializeValue(options2, parsedValue), - serializeMultiString(value2) - ); - } else { - props.saveOptions( - serializeValue(options2, parsedValue), - serializeMultiDisplayString(value2) - ); + return this.fileSystem.newFileFragment(mdbFile, "schema", schema.id, schema); + } + async saveTableSchema(path2, schemaId, saveSchema) { + let mdbFile = await this.fileSystem.getFile(this.spaceInfoForPath(path2).dbPath); + if (!mdbFile) { + mdbFile = await this.createDefaultTable(path2); } - }; - const saveOptions = (_options, _value) => { - const newOptions = (0, import_lodash11.uniq)([..._options, ..._value]).filter((f2) => f2.length > 0).map( - (t5) => options.find((f2) => f2.value == t5) ?? { - name: t5, - value: t5 - } - ); - if (!props.multi) { - if (props.editMode >= 2 /* EditModeView */) { - setOptions(newOptions); + return this.fileSystem.saveFileFragment(mdbFile, "schema", schemaId, saveSchema); + } + async saveTable(path2, table, force) { + let mdbFile = await this.fileSystem.getFile(this.spaceInfoForPath(path2).dbPath); + if (!mdbFile) { + if (force) { + mdbFile = await this.createDefaultTable(path2); + } else { + return false; } - setValue(_value); - savePropValue(newOptions, _value); - } else { - const newValues = (0, import_lodash11.uniq)([...value, _value[0]]); - if (props.editMode >= 2 /* EditModeView */) - setOptions(newOptions); - setValue(newValues); - savePropValue(newOptions, newValues); } - }; - const saveOption = (option, newValue) => { - const newOptions = options.map((t5) => t5.value == option ? newValue : t5); - const newValues = value; - setOptions(newOptions); - setValue(newValues); - savePropValue(newOptions, newValues); - }; - const showOptionMenu = (e5, optionValue) => { - const option = options.find((f2) => f2.value == optionValue); - const menuOptions = []; - menuOptions.push( - menuInput( - option.value, - (value2) => saveOption(option.value, { ...option, value: value2 }) - ) - ); - menuOptions.push(menuSeparator); - menuOptions.push({ - name: "None", - color: "var(--mk-color-none)", - onClick: () => { - saveOption(option.value, { ...option, color: "" }); + return this.fileSystem.saveFileFragment(mdbFile, "mdbTable", table.schema.id, () => table); + } + async deleteTable(path2, name317) { + const mdbFile = await this.fileSystem.getFile(this.spaceInfoForPath(path2).dbPath); + return this.fileSystem.deleteFileFragment(mdbFile, "schema", name317); + } + async readAllTables(path2) { + const spaceInfo = this.spaceInfoForPath(path2); + const mdbFile = await this.fileSystem.getFile(spaceInfo.dbPath); + if (!mdbFile) { + const defaultTable = defaultTableDataForContext(this.spaceManager.superstate, spaceInfo); + return { + [defaultTable.schema.id]: defaultTable + }; + } + return this.fileSystem.readFileFragments(mdbFile, "mdbTables", null); + } + async framesForSpace(path2) { + const mdbFile = await this.fileSystem.getFile(this.spaceInfoForPath(path2).framePath); + if (!mdbFile) { + const frames = this.defaultFrame(); + return Object.values(frames).map((f2) => f2.schema); + } + return this.fileSystem.readFileFragments(mdbFile, "schemas", null); + } + async createFrame(path2, schema) { + let mdbFile = await this.fileSystem.getFile(this.spaceInfoForPath(path2).framePath); + if (!mdbFile) { + mdbFile = await this.createDefaultFrames(path2); + } + return this.fileSystem.newFileFragment(mdbFile, "schema", schema.id, schema); + } + async deleteFrame(path2, name317) { + const mdbFile = await this.fileSystem.getFile(this.spaceInfoForPath(path2).framePath); + return this.fileSystem.deleteFileFragment(mdbFile, "schema", name317); + } + async saveFrameSchema(path2, schemaId, saveSchema) { + let mdbFile = await this.fileSystem.getFile(this.spaceInfoForPath(path2).framePath); + if (!mdbFile) { + mdbFile = await this.createDefaultFrames(path2); + } + return this.fileSystem.saveFileFragment(mdbFile, "schema", schemaId, saveSchema); + } + async saveFrame(path2, frame) { + let mdbFile = await this.fileSystem.getFile(this.spaceInfoForPath(path2).framePath); + if (!mdbFile) { + mdbFile = await this.createDefaultFrames(path2); + } + return this.fileSystem.saveFileFragment(mdbFile, "mdbFrame", frame.schema.id, () => frame); + } + async createDefaultCommands(path2) { + const dbField = { + m_fields: { + uniques: fieldSchema.uniques, + cols: fieldSchema.cols, + rows: [] + }, + m_schema: { + uniques: [], + cols: ["id", "name", "type", "def", "predicate", "primary"], + rows: [] } - }); - colors.forEach((f2) => { - menuOptions.push({ - name: f2[0], - value: f2[1], - color: `${f2[1]}`, - onClick: () => { - saveOption(option.value, { ...option, color: f2[1] }); - } - }); - }); - props.superstate.ui.openMenu( - e5.target.getBoundingClientRect(), - defaultMenu(props.superstate.ui, menuOptions) - ); - }; - const menuProps = () => ({ - multi: false, - editable: props.editMode >= 2 /* EditModeView */, - ui: props.superstate.ui, - value, - options: !props.multi ? [{ name: i18n_default.menu.none, value: "" }, ...options] : options, - saveOptions, - removeOption: props.editMode >= 2 /* EditModeView */ && removeOption, - onMoreOption: props.editMode >= 2 /* EditModeView */ && showOptionMenu, - placeholder: i18n_default.labels.optionItemSelectPlaceholder, - searchable: true, - showAll: true, - onHide: () => props.setEditMode(null) - }); - return /* @__PURE__ */ import_react59.default.createElement(OptionCellBase, { - superstate: props.superstate, - baseClass: "mk-cell-option", - value, - menuProps, - multi: props.multi, - removeValue, - selectLabel: props.compactMode ? props.property.name : i18n_default.labels.select, - editMode: props.editMode, - labelElement: (_props) => { - const color2 = options.find((f2) => f2.value == _props.value)?.color ?? "var(--mk-color-none)"; - return /* @__PURE__ */ import_react59.default.createElement("div", { - className: "mk-cell-option-item", - style: { - background: `${color2}`, - color: color2 == "var(--mk-color-none)" ? "inherit" : "var(--mk-color-white)" - } - }, _props.value, _props.children); + }; + const dbPath = this.spaceInfoForPath(path2).commandsPath; + const extension = dbPath.split(".").pop(); + const folder = dbPath.split("/").slice(0, -1).join("/"); + const filename = dbPath.split("/").pop().split(".")[0]; + return this.fileSystem.newFile(folder, filename, extension, dbField); + } + async commandsForSpace(path2) { + const mdbFile = await this.fileSystem.getFile(this.spaceInfoForPath(path2).commandsPath); + if (!mdbFile) { + return []; } - }); -}; -var OptionCellBase = (props) => { - const { value, menuProps } = props; - const menuRef = (0, import_react59.useRef)(null); - (0, import_react59.useEffect)(() => { - if (props.editMode == 4 /* EditModeActive */) { - if (!menuRef.current) - showMenu2(); + return this.fileSystem.readFileFragments(mdbFile, "mdbCommands", null); + } + async runCommand(path2, name317, args) { + const mdbFile = await this.fileSystem.getFile(this.spaceInfoForPath(path2).commandsPath); + if (!mdbFile) { + return { result: null, error: "No commands file found" }; } - }, [props.editMode]); - const ref2 = (0, import_react59.useRef)(null); - const showMenu2 = () => { - if (menuRef.current) { - menuRef.current.hide(); - menuRef.current = null; - return; + const command = await this.fileSystem.readFileFragments(mdbFile, "mdbCommand", name317); + if (!command) { + return { result: null, error: "No command found" }; } - const offset2 = ref2.current.getBoundingClientRect(); - menuRef.current = props.superstate.ui.openMenu( - offset2, - menuProps(), - "bottom", - () => menuRef.current = null - ); - }; - const editable = props.editMode > 1 /* EditModeNone */; - return /* @__PURE__ */ import_react59.default.createElement("div", { - className: props.baseClass, - ref: ref2 - }, value.length > 0 ? value.map((o2, i4) => /* @__PURE__ */ import_react59.default.createElement(import_react59.default.Fragment, { - key: i4 - }, props.labelElement && /* @__PURE__ */ import_react59.default.createElement(props.labelElement, { - value: o2 - }, editable ? !props.multi && value.length > 0 ? /* @__PURE__ */ import_react59.default.createElement(import_react59.default.Fragment, null, /* @__PURE__ */ import_react59.default.createElement("span", null), /* @__PURE__ */ import_react59.default.createElement("div", { - onClick: (e5) => { - e5.stopPropagation(); - showMenu2(); - }, - className: "mk-cell-option-select mk-icon-xxsmall mk-icon-rotated", - dangerouslySetInnerHTML: { - __html: props.superstate.ui.getSticker( - "ui//collapse-solid" - ) + let result; + let error; + try { + if (command.schema.type == "script") + result = executeCode(command.code, args); + if (command.schema.type == "formula") + result = runFormulaWithContext(this.spaceManager.superstate.formulaContext, this.spaceManager.superstate.pathsIndex, command.code, command.fields.reduce((p, c3) => ({ ...p, [c3.name]: c3 }), {}), args, this.spaceManager.superstate.pathsIndex.get(path2)); + } catch (e5) { + error = e5; + } + return { result, error }; + } + async createCommand(path2, schema) { + let mdbFile = await this.fileSystem.getFile(this.spaceInfoForPath(path2).commandsPath); + if (!mdbFile) { + mdbFile = await this.createDefaultCommands(path2); + } + return this.fileSystem.newFileFragment(mdbFile, "schema", schema.id, schema); + } + async readSystemCommands() { + const strings = (await this.childrenForPath(defaultActionsFolder, "folder")).map((f2) => f2.split("/").pop()); + const kits = Promise.all(strings.map(async (f2) => { + const frames = await this.readLibraryCommands(f2); + return { + name: f2, + commands: Object.values(frames ?? {}) + }; + })); + return kits; + } + async readLibraryCommands(name317) { + return this.fileSystem.readFileFragments({ + path: `${defaultActionsFolder}/${name317}/commands.mdb`, + name: "commands", + filename: "commands.mdb", + parent: `${defaultKitsFolder}/${name317}`, + isFolder: false, + extension: "mdb" + }, "mdbCommands"); + } + async saveSystemCommand(lib, command) { + const mdbFile = { + path: `${defaultActionsFolder}/${lib}/commands.mdb`, + name: "commands", + filename: "commands.mdb", + parent: `${defaultActionsFolder}/${lib}`, + isFolder: false, + extension: "mdb" + }; + if (command) { + await this.fileSystem.saveFileFragment(mdbFile, "schema", command.schema.id, () => command.schema); + await this.fileSystem.saveFileFragment(mdbFile, "mdbCommand", command.schema.id, () => command); + } else { + const dbField = { + m_fields: { + uniques: fieldSchema.uniques, + cols: fieldSchema.cols, + rows: [] + }, + m_schema: { + uniques: [], + cols: ["id", "name", "type", "def", "predicate", "primary"], + rows: [] + } + }; + const dbPath = mdbFile.path; + const extension = dbPath.split(".").pop(); + const folder = dbPath.split("/").slice(0, -1).join("/"); + const filename = dbPath.split("/").pop().split(".")[0]; + await this.fileSystem.newFile(folder, filename, extension, dbField); } - })) : props.multi ? /* @__PURE__ */ import_react59.default.createElement("div", { - className: "mk-cell-option-remove mk-icon-xxsmall", - onClick: (e5) => { - e5.stopPropagation(); - props.removeValue(o2); - }, - dangerouslySetInnerHTML: { - __html: props.superstate.ui.getSticker("ui//close") + } + async deleteCommand(path2, name317) { + const mdbFile = await this.fileSystem.getFile(this.spaceInfoForPath(path2).commandsPath); + return this.fileSystem.deleteFileFragment(mdbFile, "mdbCommand", name317); + } + async saveCommand(path2, schemaId, saveCommand) { + let mdbFile = await this.fileSystem.getFile(this.spaceInfoForPath(path2).commandsPath); + if (!mdbFile) { + mdbFile = await this.createDefaultCommands(path2); } - }) : null : null))) : editable && !props.multi ? /* @__PURE__ */ import_react59.default.createElement("div", { - className: "mk-cell-option-item", - onClick: (e5) => { - showMenu2(); + return this.fileSystem.saveFileFragment(mdbFile, "mdbCommand", schemaId, saveCommand); + } + async contextForSpace(path2) { + const mdbFile = await this.fileSystem.getFile(this.spaceInfoForPath(path2).dbPath); + if (!mdbFile) { + return defaultTableDataForContext(this.spaceManager.superstate, this.spaceInfoForPath(path2)); } - }, /* @__PURE__ */ import_react59.default.createElement("div", { - className: "mk-cell-empty" - }, props.selectLabel), /* @__PURE__ */ import_react59.default.createElement("div", { - className: "mk-cell-option-select mk-icon-xxsmall mk-icon-rotated", - dangerouslySetInnerHTML: { - __html: props.superstate.ui.getSticker("ui//collapse-solid") + return this.fileSystem.readFileFragments(mdbFile, "mdbTable", defaultContextSchemaID); + } + async addSpaceProperty(path2, property) { + const mdbFile = await this.fileSystem.getFile(this.spaceInfoForPath(path2)?.dbPath); + if (!mdbFile) { + await this.createDefaultTable(path2); } - })) : props.editMode == 0 /* EditModeReadOnly */ ? /* @__PURE__ */ import_react59.default.createElement("div", { - className: "mk-cell-option-item mk-cell-empty" - }, /* @__PURE__ */ import_react59.default.createElement("div", null, i18n_default.menu.none)) : /* @__PURE__ */ import_react59.default.createElement(import_react59.default.Fragment, null), editable && props.multi ? /* @__PURE__ */ import_react59.default.createElement("div", { - onClick: (e5) => editable && showMenu2(), - className: "mk-cell-option-new mk-icon-small", - dangerouslySetInnerHTML: { - __html: props.superstate.ui.getSticker("ui//plus") + return this.fileSystem.newFileFragment(mdbFile, "field", property.name, property); + } + async deleteSpaceProperty(path2, property) { + const mdbFile = await this.fileSystem.getFile(this.spaceInfoForPath(path2).dbPath); + return this.fileSystem.deleteFileFragment(mdbFile, "field", property); + } + async saveSpaceProperty(path2, property, oldProperty) { + const mdbFile = await this.fileSystem.getFile(this.spaceInfoForPath(path2).dbPath); + if (!mdbFile) { + await this.createDefaultTable(path2); + } + return this.fileSystem.saveFileFragment(mdbFile, "field", oldProperty, (prev) => ({ ...prev, ...property })); + } + async addProperty(path2, property) { + const file = await this.fileSystem.getFile(path2); + this.fileSystem.newFileFragment(file, "property", property.name, property); + } + async saveProperties(path2, properties3) { + const file = await this.fileSystem.getFile(path2); + this.fileSystem.saveFileFragment(file, "property", null, (prev) => ({ ...prev, ...properties3 })); + } + async readLabel(path2) { + return this.fileSystem.getFileCache(path2).label; + } + async saveLabel(path2, label, value) { + const file = await this.fileSystem.getFile(path2); + this.fileSystem.saveFileLabel(file, label, value); + } + async renameProperty(path2, property, newProperty) { + const file = await this.fileSystem.getFile(path2); + this.fileSystem.saveFileFragment(file, "property", null, (prev) => { + const { [property]: value, ...properties3 } = prev; + if (!value) + return prev; + return { ...properties3, [newProperty]: value }; + }); + } + async readProperties(path2) { + const file = await this.fileSystem.getFile(path2); + return this.fileSystem.readFileFragments(file, "property", null); + } + async deleteProperty(path2, property) { + const file = await this.fileSystem.getFile(path2); + this.fileSystem.deleteFileFragment(file, "property", property); + } + allSpaces() { + const tagSpace = this.spaceManager.spaceInfoForPath(tagsSpacePath); + const getAllTagContextFiles = () => this.readTags().map((f2) => fileSystemSpaceInfoFromTag(this.spaceManager, tagPathToTag(f2))) ?? []; + const getAllFolderContextFiles = () => { + const folders = this.allPaths(["folder"]).filter((f2) => !f2.startsWith(this.spaceManager.superstate.settings.spacesFolder + "/#")); + return folders.map((f2) => fileSystemSpaceInfoFromFolder(this.spaceManager, f2)); + }; + const allTagSpaces = this.spaceManager.superstate.settings.enableDefaultSpaces ? getAllTagContextFiles() : []; + const allFolders = getAllFolderContextFiles(); + return [tagSpace, ...allTagSpaces, ...allFolders]; + } + readTags() { + return this.fileSystem.allTags(); + } + spaceInfoForPath(path2) { + return fileSystemSpaceInfoByPath(this.spaceManager, path2); + } + allCaches() { + return this.fileSystem.allCaches(); + } + async spaceDefForSpace(path2) { + const space2 = this.spaceInfoForPath(path2); + if (!space2) + return null; + const defFile = await this.fileSystem.getFile(space2.defPath); + const metaCache = defFile ? this.fileSystem.getFileCache(defFile.path)?.frontmatter : null; + const spaceDef = metaCache ?? {}; + return parseSpaceMetadata(spaceDef, this.spaceManager.superstate.settings); + } + async createSpace(name317, parentPath, definition) { + const spaceInfo = this.spaceInfoForPath(parentPath); + const newPath = spaceInfo.folderPath == "/" ? name317 : spaceInfo.folderPath + "/" + name317; + await this.fileSystem.createFolder(newPath); + if (Object.keys(definition ?? {}).length > 0) + return this.saveSpace(newPath, () => definition); + } + async saveSpace(path2, definitionFn, properties3) { + const metadata = definitionFn(await this.spaceDefForSpace(path2)) ?? {}; + const spaceInfo = this.spaceInfoForPath(path2); + let file = await this.fileSystem.getFile(spaceInfo.defPath); + if (!file) { + file = await this.fileSystem.newFile(spaceInfo.folderPath, spaceInfo.name, "md"); } - }) : /* @__PURE__ */ import_react59.default.createElement(import_react59.default.Fragment, null)); + await this.fileSystem.saveFileFragment(file, "frontmatter", null, (frontmatter) => ({ + ...frontmatter, + [spaceFilterKey(this.spaceManager.superstate.settings)]: metadata.filters, + [spaceContextsKey(this.spaceManager.superstate.settings)]: metadata.contexts, + [spaceLinksKey(this.spaceManager.superstate.settings)]: metadata.links, + [spaceSortKey(this.spaceManager.superstate.settings)]: metadata.sort, + [spaceTemplateKey(this.spaceManager.superstate.settings)]: metadata.template, + [spaceTemplateNameKey(this.spaceManager.superstate.settings)]: metadata.templateName, + ...properties3 ?? {} + })); + return; + } + renameSpace(oldPath, newPath) { + const spaceInfo = this.spaceInfoForPath(oldPath); + const newSpaceInfo = this.spaceInfoForPath(newPath); + this.fileSystem.renameFile(spaceInfo.folderPath, newSpaceInfo.folderPath).then((f2) => this.fileSystem.renameFile(movePath(spaceInfo.defPath, newSpaceInfo.path), newSpaceInfo.defPath)); + } + deleteSpace(path2) { + const spaceCache = this.spaceInfoForPath(path2); + const spaceInfo = fileSystemSpaceInfoFromTag(this.spaceManager, spaceCache.name); + this.fileSystem.deleteFile(spaceInfo.folderPath); + } + childrenForSpace(path2) { + return this.fileSystem.allFiles().filter((f2) => f2.parent == path2).map((f2) => f2.path); + } + addTag(path2, tag2) { + this.fileSystem.addTagToFile(path2, tag2); + } + renameTag(path2, tag2, newTag) { + this.fileSystem.renameTagForFile(path2, tag2, newTag); + } + deleteTag(path2, tag2) { + this.fileSystem.removeTagFromFile(path2, tag2); + } + pathsForTag(tag2) { + return this.fileSystem.filesForTag(tag2); + } + resolvePath(path2, source) { + return this.fileSystem.resolvePath(path2, source); + } }; -// src/core/react/components/SpaceView/Contexts/DataTypeView/ContextCell.tsx -var ContextCell = (props) => { - const { spaceState } = (0, import_react60.useContext)(SpaceContext); - const fieldValue = (0, import_react60.useMemo)( - () => parseFieldValue(props.propertyValue, "context", props.superstate), - [props.propertyValue] - ); - const spacePath = (0, import_react60.useMemo)( - () => fieldValue ? props.superstate.spaceManager.resolvePath( - fieldValue.space, - spaceState?.path - ) : null, - [fieldValue.space, spaceState] - ); - const parseValue = (v2, multi) => (multi ? parseMultiString(v2) ?? [] : [v2]).filter((f2) => f2); - const [propValues, setPropValues] = (0, import_react60.useState)( - props.superstate.contextsIndex.get(spacePath)?.spaceMap[fieldValue.spaceField]?.[props.path] ?? [] - ); - (0, import_react60.useEffect)(() => { - setPropValues( - props.superstate.contextsIndex.get(spacePath)?.spaceMap[fieldValue.spaceField]?.[props.path] ?? [] - ); - }, [spacePath, fieldValue]); - const options = [...props.superstate.spacesMap.getInverse(spacePath)].map((f2) => props.superstate.pathsIndex.get(f2)).filter((f2) => f2).map((f2) => ({ - name: f2.name, - icon: f2.label.sticker, - description: f2.path, - value: f2.path - })); - const [value, setValue] = (0, import_react60.useState)( - parseValue(props.initialValue, props.multi) - ); - const allValues = (0, import_react60.useMemo)( - () => uniq([...value, ...propValues]), - [value, propValues] - ); - const saveValue = (_values) => { - if (props.multi) { - props.saveValue(serializeMultiString(_values)); - } else { - props.saveValue(serializeMultiDisplayString(_values)); +// src/core/react/components/UI/Menus/menu/SelectMenu.tsx +var import_react79 = __toESM(require_react()); + +// node_modules/fuse.js/dist/fuse.mjs +function isArray4(value) { + return !Array.isArray ? getTag(value) === "[object Array]" : Array.isArray(value); +} +var INFINITY = 1 / 0; +function baseToString(value) { + if (typeof value == "string") { + return value; + } + let result = value + ""; + return result == "0" && 1 / value == -INFINITY ? "-0" : result; +} +function toString3(value) { + return value == null ? "" : baseToString(value); +} +function isString4(value) { + return typeof value === "string"; +} +function isNumber3(value) { + return typeof value === "number"; +} +function isBoolean2(value) { + return value === true || value === false || isObjectLike(value) && getTag(value) == "[object Boolean]"; +} +function isObject2(value) { + return typeof value === "object"; +} +function isObjectLike(value) { + return isObject2(value) && value !== null; +} +function isDefined(value) { + return value !== void 0 && value !== null; +} +function isBlank(value) { + return !value.trim().length; +} +function getTag(value) { + return value == null ? value === void 0 ? "[object Undefined]" : "[object Null]" : Object.prototype.toString.call(value); +} +var INCORRECT_INDEX_TYPE = "Incorrect 'index' type"; +var LOGICAL_SEARCH_INVALID_QUERY_FOR_KEY = (key2) => `Invalid value for key ${key2}`; +var PATTERN_LENGTH_TOO_LARGE = (max5) => `Pattern length exceeds max of ${max5}.`; +var MISSING_KEY_PROPERTY = (name317) => `Missing ${name317} property in key`; +var INVALID_KEY_WEIGHT_VALUE = (key2) => `Property 'weight' in key '${key2}' must be a positive integer`; +var hasOwn2 = Object.prototype.hasOwnProperty; +var KeyStore = class { + constructor(keys) { + this._keys = []; + this._keyMap = {}; + let totalWeight = 0; + keys.forEach((key2) => { + let obj = createKey(key2); + this._keys.push(obj); + this._keyMap[obj.id] = obj; + totalWeight += obj.weight; + }); + this._keys.forEach((key2) => { + key2.weight /= totalWeight; + }); + } + get(keyId) { + return this._keyMap[keyId]; + } + keys() { + return this._keys; + } + toJSON() { + return JSON.stringify(this._keys); + } +}; +function createKey(key2) { + let path2 = null; + let id3 = null; + let src = null; + let weight = 1; + let getFn = null; + if (isString4(key2) || isArray4(key2)) { + src = key2; + path2 = createKeyPath(key2); + id3 = createKeyId(key2); + } else { + if (!hasOwn2.call(key2, "name")) { + throw new Error(MISSING_KEY_PROPERTY("name")); } - }; - const removeValue = (v2) => { - if (propValues.includes(v2)) { - const newPropValues = propValues.filter((f2) => f2 != v2); - setPropValues(newPropValues); - updateContextValue( - props.superstate.spaceManager, - props.superstate.spacesIndex.get(spacePath).space, - v2, - fieldValue.spaceField, - props.path, - deletePropertyMultiValue - ); - } else { - const newValues = value.filter((f2) => f2 != v2); - setValue(newValues); - saveValue(newValues.map((f2) => f2)); + const name317 = key2.name; + src = name317; + if (hasOwn2.call(key2, "weight")) { + weight = key2.weight; + if (weight <= 0) { + throw new Error(INVALID_KEY_WEIGHT_VALUE(name317)); + } } - }; - (0, import_react60.useEffect)(() => { - setValue(parseValue(props.initialValue, props.multi)); - }, [props.initialValue, props.multi]); - const saveOptions = (_options, _value) => { - insertContextItems(props.superstate.spaceManager, _value, spacePath); - if (!props.multi) { - setValue(_value); - saveValue(_value); + path2 = createKeyPath(name317); + id3 = createKeyId(name317); + getFn = key2.getFn; + } + return { path: path2, id: id3, weight, src, getFn }; +} +function createKeyPath(key2) { + return isArray4(key2) ? key2 : key2.split("."); +} +function createKeyId(key2) { + return isArray4(key2) ? key2.join(".") : key2; +} +function get(obj, path2) { + let list = []; + let arr = false; + const deepGet = (obj2, path3, index2) => { + if (!isDefined(obj2)) { + return; + } + if (!path3[index2]) { + list.push(obj2); } else { - const newValue = _value[0]; - if (newValue) { - const newValues = [...value, newValue]; - setValue(newValues); - saveValue(newValues); + let key2 = path3[index2]; + const value = obj2[key2]; + if (!isDefined(value)) { + return; + } + if (index2 === path3.length - 1 && (isString4(value) || isNumber3(value) || isBoolean2(value))) { + list.push(toString3(value)); + } else if (isArray4(value)) { + arr = true; + for (let i4 = 0, len = value.length; i4 < len; i4 += 1) { + deepGet(value[i4], path3, index2 + 1); + } + } else if (path3.length) { + deepGet(value, path3, index2 + 1); } } }; - const menuProps = () => { - const _options = !props.multi ? [{ name: i18n_default.menu.none, value: "" }, ...options] : options; - return { - ui: props.superstate.ui, - multi: false, - editable: true, - value: allValues.map((f2) => f2.path), - options: _options, - saveOptions, - placeholder: i18n_default.labels.contextItemSelectPlaceholder, - searchable: true, - showAll: true, - onHide: () => props.setEditMode(null) - }; - }; - return /* @__PURE__ */ import_react60.default.createElement(OptionCellBase, { - baseClass: "mk-cell-context", - superstate: props.superstate, - menuProps, - removeValue, - selectLabel: props.compactMode ? props.property.name : i18n_default.labels.select, - labelElement: (_props) => /* @__PURE__ */ import_react60.default.createElement(PathCrumb, { - superstate: props.superstate, - path: _props.value, - source: spaceState?.path - }, _props.children), - value: allValues, - multi: props.multi, - editMode: props.editMode - }); + deepGet(obj, isString4(path2) ? path2.split(".") : path2, 0); + return arr ? list : list[0]; +} +var MatchOptions = { + includeMatches: false, + findAllMatches: false, + minMatchCharLength: 1 }; - -// src/core/react/components/SpaceView/Contexts/DataTypeView/DateCell.tsx -var import_classnames = __toESM(require_classnames()); -var import_react61 = __toESM(require_react()); -var DateCell = (props) => { - const [value, setValue] = (0, import_react61.useState)(props.initialValue); - (0, import_react61.useEffect)(() => { - setValue(props.initialValue); - }, [props.initialValue]); - const date = (0, import_react61.useMemo)(() => { - const dateTime = parseDate2(value); - if (!isValidDate(dateTime)) { - return null; - } - return dateTime; - }, [value]); - const saveValue = (date2) => { - const newValue = formatDate(props.superstate, date2, "yyyy-MM-dd"); - props.saveValue(newValue); - setValue(newValue); - props.setEditMode(null); - }; - const menuRef = (0, import_react61.useRef)(null); - const ref2 = (0, import_react61.useRef)(null); - (0, import_react61.useEffect)(() => { - if (props.editMode == 4 /* EditModeActive */) { - if (ref2.current) { - showPicker(); - ref2.current.focus(); - } - } - }, [props.editMode]); - const showPicker = (0, import_react61.useCallback)( - (e5) => { - if (props.editMode <= 1 /* EditModeNone */) { - return; +var BasicOptions = { + isCaseSensitive: false, + includeScore: false, + keys: [], + shouldSort: true, + sortFn: (a4, b2) => a4.score === b2.score ? a4.idx < b2.idx ? -1 : 1 : a4.score < b2.score ? -1 : 1 +}; +var FuzzyOptions = { + location: 0, + threshold: 0.6, + distance: 100 +}; +var AdvancedOptions = { + useExtendedSearch: false, + getFn: get, + ignoreLocation: false, + ignoreFieldNorm: false, + fieldNormWeight: 1 +}; +var Config = { + ...BasicOptions, + ...MatchOptions, + ...FuzzyOptions, + ...AdvancedOptions +}; +var SPACE = /[^ ]+/g; +function norm2(weight = 1, mantissa = 3) { + const cache2 = /* @__PURE__ */ new Map(); + const m4 = Math.pow(10, mantissa); + return { + get(value) { + const numTokens = value.match(SPACE).length; + if (cache2.has(numTokens)) { + return cache2.get(numTokens); } - const offset2 = e5 ? e5.target.getBoundingClientRect() : ref2.current.getBoundingClientRect(); - menuRef.current = showDatePickerMenu( - props.superstate.ui, - offset2, - date, - saveValue, - 0 /* None */, - null, - "bottom" - ); + const norm3 = 1 / Math.pow(numTokens, 0.5 * weight); + const n3 = parseFloat(Math.round(norm3 * m4) / m4); + cache2.set(numTokens, n3); + return n3; }, - [date] - ); - const onKeyDown = (e5) => { - e5.stopPropagation(); - if (e5.key == "Enter" || e5.key == "Escape") { - e5.target.blur(); - saveValue(date); - menuRef.current.hide(); + clear() { + cache2.clear(); } }; - const format8 = (0, import_react61.useMemo)( - () => safelyParseJSON(props.propertyValue)?.format, - [props.propertyValue] - ); - const isEmpty = !(value?.length > 0); - return /* @__PURE__ */ import_react61.default.createElement("div", { - className: "mk-cell-date", - onClick: (e5) => !value && showPicker(e5) - }, /* @__PURE__ */ import_react61.default.createElement("div", { - className: (0, import_classnames.default)( - "mk-cell-date-item", - isEmpty && "mk-cell-date-new" - ) - }, /* @__PURE__ */ import_react61.default.createElement("div", { - className: "mk-icon-xsmall", - dangerouslySetInnerHTML: { - __html: props.superstate.ui.getSticker("ui//calendar") +} +var FuseIndex = class { + constructor({ + getFn = Config.getFn, + fieldNormWeight = Config.fieldNormWeight + } = {}) { + this.norm = norm2(fieldNormWeight, 3); + this.getFn = getFn; + this.isCreated = false; + this.setIndexRecords(); + } + setSources(docs = []) { + this.docs = docs; + } + setIndexRecords(records = []) { + this.records = records; + } + setKeys(keys = []) { + this.keys = keys; + this._keysMap = {}; + keys.forEach((key2, idx) => { + this._keysMap[key2.id] = idx; + }); + } + create() { + if (this.isCreated || !this.docs.length) { + return; } - }), isEmpty && "Select", props.editMode == 4 /* EditModeActive */ ? /* @__PURE__ */ import_react61.default.createElement("input", { - onClick: (e5) => e5.stopPropagation(), - className: "mk-cell-text", - ref: ref2, - type: "text", - value, - onChange: (e5) => setValue(e5.target.value), - onMouseDown: () => showPicker(), - onKeyDown - }) : /* @__PURE__ */ import_react61.default.createElement("div", { - className: "mk-cell-date-value", - onClick: (e5) => showPicker(e5) - }, date ? formatDate( - props.superstate, - date, - format8?.length > 0 ? format8 : null - ) : value))); -}; - -// src/core/react/components/SpaceView/Contexts/DataTypeView/IconCell.tsx -var import_react62 = __toESM(require_react()); -var IconCell = (props) => { - const value = (0, import_react62.useMemo)( - () => props.multi ? parseMultiString(props.initialValue) ?? [] : [props.initialValue], - [props.initialValue] - ); - const ref2 = (0, import_react62.useRef)(null); - (0, import_react62.useEffect)(() => { - if (props.editMode == 4 /* EditModeActive */) { - ref2?.current?.focus(); + this.isCreated = true; + if (isString4(this.docs[0])) { + this.docs.forEach((doc, docIndex) => { + this._addString(doc, docIndex); + }); + } else { + this.docs.forEach((doc, docIndex) => { + this._addObject(doc, docIndex); + }); } - }, [props.editMode]); - const triggerStickerMenu = (e5) => { - props.superstate.ui.openPalette((_props) => /* @__PURE__ */ import_react62.default.createElement(StickerModal_default, { - ui: props.superstate.ui, - hide: _props.hide, - selectedSticker: (emoji) => props.saveValue(emoji) - })); - }; - return /* @__PURE__ */ import_react62.default.createElement("div", { - className: "mk-cell-icon" - }, value.map( - (v2, i4) => v2?.length > 0 ? /* @__PURE__ */ import_react62.default.createElement("div", { - className: "mk-cell-clickable", - key: i4, - "aria-label": i18n_default.buttons.changeIcon, - dangerouslySetInnerHTML: { - __html: props.superstate.ui.getSticker(v2) - }, - onClick: (e5) => triggerStickerMenu(e5) - }) : /* @__PURE__ */ import_react62.default.createElement("div", { - key: i4, - className: "mk-cell-placeholder", - onClick: (e5) => triggerStickerMenu(e5) - }, i18n_default.labels.selectIcon) - )); -}; - -// src/core/react/components/UI/Modals/ImageModal.tsx -var import_react63 = __toESM(require_react()); - -// src/utils/regex.ts -var urlRegex = /https?:\/\/(www\.)?[-a-zA-Z0-9@:%._\+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b([-a-zA-Z0-9()@:%_\+.~#?&//=]*)/gi; - -// src/core/react/components/UI/Modals/ImageModal.tsx -var ImageModal = (props) => { - const [query, setQuery] = (0, import_react63.useState)(""); - const [allImages, setAllImages] = (0, import_react63.useState)([]); - const [images, setImages] = (0, import_react63.useState)([]); - const [selectedImage, setSelectedImage] = (0, import_react63.useState)(null); - (0, import_react63.useEffect)(() => { - const _allImages = []; - _allImages.push( - ...[...props.superstate.pathsIndex.values()].filter((f2) => f2.subtype == "image").map((f2) => ({ path: f2.path, thumnail: f2.label.thumbnail })) - ); - setAllImages(_allImages); - setImages(_allImages); - }, []); - (0, import_react63.useEffect)(() => { - query.match(urlRegex) ? setImages([{ path: query, thumnail: query }]) : setImages(allImages.filter((f2) => f2.path.includes(query))); - }, [query, allImages]); - const handleInputChange = (event) => { - setQuery(event.target.value); - }; - const handleKeyDown = (event) => { - const currentIndex = images.findIndex((f2) => f2.path == selectedImage); - if (event.key === "ArrowUp" && currentIndex > 0) { - setSelectedImage(images[currentIndex - 1].path); - } else if (event.key === "ArrowDown" && currentIndex < images.length - 1) { - setSelectedImage(images[currentIndex + 1].path); - } else if (event.key === "Enter") { - props.selectedPath(selectedImage); - props.hide(); + this.norm.clear(); + } + add(doc) { + const idx = this.size(); + if (isString4(doc)) { + this._addString(doc, idx); + } else { + this._addObject(doc, idx); } - }; - const ref2 = (0, import_react63.useRef)(null); - (0, import_react63.useEffect)(() => { - if (ref2.current) { - ref2.current.focus(); + } + removeAt(idx) { + this.records.splice(idx, 1); + for (let i4 = idx, len = this.size(); i4 < len; i4 += 1) { + this.records[i4].i -= 1; } - }, [ref2.current]); - return /* @__PURE__ */ import_react63.default.createElement(import_react63.default.Fragment, null, /* @__PURE__ */ import_react63.default.createElement("input", { - onKeyDown: handleKeyDown, - value: query, - ref: ref2, - onChange: handleInputChange, - className: "mk-input mk-input-large mk-border-bottom" - }), /* @__PURE__ */ import_react63.default.createElement("div", { - className: "mk-layout-masonry mk-padding-12 mk-layout-scroll" - }, images.map((image) => /* @__PURE__ */ import_react63.default.createElement("img", { - key: image.path, - src: props.superstate.ui.getUIPath(image.thumnail), - className: selectedImage === image.path ? "mk-selected" : "", - onClick: () => { - props.selectedPath(image.path); - props.hide(); + } + getValueForItemAtKeyId(item, keyId) { + return item[this._keysMap[keyId]]; + } + size() { + return this.records.length; + } + _addString(doc, docIndex) { + if (!isDefined(doc) || isBlank(doc)) { + return; } - })))); + let record = { + v: doc, + i: docIndex, + n: this.norm.get(doc) + }; + this.records.push(record); + } + _addObject(doc, docIndex) { + let record = { i: docIndex, $: {} }; + this.keys.forEach((key2, keyIndex) => { + let value = key2.getFn ? key2.getFn(doc) : this.getFn(doc, key2.path); + if (!isDefined(value)) { + return; + } + if (isArray4(value)) { + let subRecords = []; + const stack = [{ nestedArrIndex: -1, value }]; + while (stack.length) { + const { nestedArrIndex, value: value2 } = stack.pop(); + if (!isDefined(value2)) { + continue; + } + if (isString4(value2) && !isBlank(value2)) { + let subRecord = { + v: value2, + i: nestedArrIndex, + n: this.norm.get(value2) + }; + subRecords.push(subRecord); + } else if (isArray4(value2)) { + value2.forEach((item, k2) => { + stack.push({ + nestedArrIndex: k2, + value: item + }); + }); + } else + ; + } + record.$[keyIndex] = subRecords; + } else if (isString4(value) && !isBlank(value)) { + let subRecord = { + v: value, + n: this.norm.get(value) + }; + record.$[keyIndex] = subRecord; + } + }); + this.records.push(record); + } + toJSON() { + return { + keys: this.keys, + records: this.records + }; + } }; -var ImageModal_default = ImageModal; - -// src/core/react/components/SpaceView/Contexts/DataTypeView/ImageCell.tsx -var import_react64 = __toESM(require_react()); -var ImageCell = (props) => { - const { initialValue, multi } = props; - const [value, setValue] = import_react64.default.useState( - parseMultiString(initialValue) - ); - const menuRef = (0, import_react64.useRef)(null); - const sourcePaths = (0, import_react64.useMemo)(() => { - if (value?.length > 0) { - return value.map((f2) => props.superstate.ui.getUIPath(f2)); +function createIndex2(keys, docs, { getFn = Config.getFn, fieldNormWeight = Config.fieldNormWeight } = {}) { + const myIndex = new FuseIndex({ getFn, fieldNormWeight }); + myIndex.setKeys(keys.map(createKey)); + myIndex.setSources(docs); + myIndex.create(); + return myIndex; +} +function parseIndex(data2, { getFn = Config.getFn, fieldNormWeight = Config.fieldNormWeight } = {}) { + const { keys, records } = data2; + const myIndex = new FuseIndex({ getFn, fieldNormWeight }); + myIndex.setKeys(keys); + myIndex.setIndexRecords(records); + return myIndex; +} +function computeScore$1(pattern, { + errors = 0, + currentLocation = 0, + expectedLocation = 0, + distance: distance2 = Config.distance, + ignoreLocation = Config.ignoreLocation +} = {}) { + const accuracy = errors / pattern.length; + if (ignoreLocation) { + return accuracy; + } + const proximity = Math.abs(expectedLocation - currentLocation); + if (!distance2) { + return proximity ? 1 : accuracy; + } + return accuracy + proximity / distance2; +} +function convertMaskToIndices(matchmask = [], minMatchCharLength = Config.minMatchCharLength) { + let indices = []; + let start = -1; + let end = -1; + let i4 = 0; + for (let len = matchmask.length; i4 < len; i4 += 1) { + let match2 = matchmask[i4]; + if (match2 && start === -1) { + start = i4; + } else if (!match2 && start !== -1) { + end = i4 - 1; + if (end - start + 1 >= minMatchCharLength) { + indices.push([start, end]); + } + start = -1; } - return []; - }, [value]); - import_react64.default.useEffect(() => { - setValue(parseMultiString(initialValue)); - }, [initialValue]); - const deleteValue = (index2) => { - if (multi) { - const newValue = [...value]; - newValue.splice(index2, 1); - setValue(newValue); - props.saveValue(serializeMultiString(newValue)); - } else { - props.saveValue(""); + } + if (matchmask[i4 - 1] && i4 - start >= minMatchCharLength) { + indices.push([start, i4 - 1]); + } + return indices; +} +var MAX_BITS = 32; +function search(text2, pattern, patternAlphabet, { + location = Config.location, + distance: distance2 = Config.distance, + threshold = Config.threshold, + findAllMatches = Config.findAllMatches, + minMatchCharLength = Config.minMatchCharLength, + includeMatches = Config.includeMatches, + ignoreLocation = Config.ignoreLocation +} = {}) { + if (pattern.length > MAX_BITS) { + throw new Error(PATTERN_LENGTH_TOO_LARGE(MAX_BITS)); + } + const patternLen = pattern.length; + const textLen = text2.length; + const expectedLocation = Math.max(0, Math.min(location, textLen)); + let currentThreshold = threshold; + let bestLocation = expectedLocation; + const computeMatches = minMatchCharLength > 1 || includeMatches; + const matchMask = computeMatches ? Array(textLen) : []; + let index2; + while ((index2 = text2.indexOf(pattern, bestLocation)) > -1) { + let score = computeScore$1(pattern, { + currentLocation: index2, + expectedLocation, + distance: distance2, + ignoreLocation + }); + currentThreshold = Math.min(score, currentThreshold); + bestLocation = index2 + patternLen; + if (computeMatches) { + let i4 = 0; + while (i4 < patternLen) { + matchMask[index2 + i4] = 1; + i4 += 1; + } } - }; - const saveValue = (index2, image) => { - if (props.multi) { - if (index2 == -1) { - props.saveValue(serializeMultiString([...value, image])); + } + bestLocation = -1; + let lastBitArr = []; + let finalScore = 1; + let binMax = patternLen + textLen; + const mask = 1 << patternLen - 1; + for (let i4 = 0; i4 < patternLen; i4 += 1) { + let binMin = 0; + let binMid = binMax; + while (binMin < binMid) { + const score2 = computeScore$1(pattern, { + errors: i4, + currentLocation: expectedLocation + binMid, + expectedLocation, + distance: distance2, + ignoreLocation + }); + if (score2 <= currentThreshold) { + binMin = binMid; } else { - props.saveValue( - serializeMultiString(value.map((f2, i4) => i4 == index2 ? image : f2)) - ); + binMax = binMid; } - } else { - props.saveValue(image); - } - }; - const showModal2 = (index2) => { - props.superstate.ui.openPalette((_props) => /* @__PURE__ */ import_react64.default.createElement(ImageModal_default, { - superstate: props.superstate, - hide: _props.hide, - selectedPath: (image) => saveValue(index2, image) - })); - props.setEditMode(null); - }; - return /* @__PURE__ */ import_react64.default.createElement("div", { - className: "mk-cell-image" - }, sourcePaths.map((f2, i4) => /* @__PURE__ */ import_react64.default.createElement("div", { - key: i4, - className: "mk-cell-image-item" - }, /* @__PURE__ */ import_react64.default.createElement("img", { - onClick: (e5) => props.superstate.ui.openPath( - initialValue, - e5.metaKey ? "tab" : false - ), - src: f2 - }), props.editMode > 1 /* EditModeNone */ ? /* @__PURE__ */ import_react64.default.createElement("div", { - className: "mk-image-selector" - }, /* @__PURE__ */ import_react64.default.createElement("div", { - onClick: () => showModal2(i4), - className: "mk-hover-button mk-icon-xsmall", - dangerouslySetInnerHTML: { - __html: props.superstate.ui.getSticker("ui//edit") + binMid = Math.floor((binMax - binMin) / 2 + binMin); } - }), /* @__PURE__ */ import_react64.default.createElement("div", { - onClick: () => deleteValue(i4), - className: "mk-hover-button mk-icon-xsmall", - dangerouslySetInnerHTML: { - __html: props.superstate.ui.getSticker("ui//close") + binMax = binMid; + let start = Math.max(1, expectedLocation - binMid + 1); + let finish = findAllMatches ? textLen : Math.min(expectedLocation + binMid, textLen) + patternLen; + let bitArr = Array(finish + 2); + bitArr[finish + 1] = (1 << i4) - 1; + for (let j = finish; j >= start; j -= 1) { + let currentLocation = j - 1; + let charMatch = patternAlphabet[text2.charAt(currentLocation)]; + if (computeMatches) { + matchMask[currentLocation] = +!!charMatch; + } + bitArr[j] = (bitArr[j + 1] << 1 | 1) & charMatch; + if (i4) { + bitArr[j] |= (lastBitArr[j + 1] | lastBitArr[j]) << 1 | 1 | lastBitArr[j + 1]; + } + if (bitArr[j] & mask) { + finalScore = computeScore$1(pattern, { + errors: i4, + currentLocation, + expectedLocation, + distance: distance2, + ignoreLocation + }); + if (finalScore <= currentThreshold) { + currentThreshold = finalScore; + bestLocation = currentLocation; + if (bestLocation <= expectedLocation) { + break; + } + start = Math.max(1, 2 * expectedLocation - bestLocation); + } + } } - })) : /* @__PURE__ */ import_react64.default.createElement(import_react64.default.Fragment, null))), props.editMode > 1 /* EditModeNone */ ? props.multi ? /* @__PURE__ */ import_react64.default.createElement("div", { - onClick: (e5) => showModal2(-1), - className: "mk-cell-option-new mk-icon-small", - dangerouslySetInnerHTML: { - __html: props.superstate.ui.getSticker("ui//plus") + const score = computeScore$1(pattern, { + errors: i4 + 1, + currentLocation: expectedLocation, + expectedLocation, + distance: distance2, + ignoreLocation + }); + if (score > currentThreshold) { + break; } - }) : value.length == 0 ? /* @__PURE__ */ import_react64.default.createElement("div", { - onClick: () => showModal2(-1), - className: "mk-cell-clickable" - }, "Select") : null : /* @__PURE__ */ import_react64.default.createElement(import_react64.default.Fragment, null)); -}; - -// src/core/react/components/SpaceView/Contexts/DataTypeView/LinkCell.tsx -var import_react65 = __toESM(require_react()); -var LinkCell = (props) => { - const parseValue = (v2) => props.multi ? parseMultiString(v2) ?? [] : [v2].filter((f2) => f2); - (0, import_react65.useEffect)(() => { - setValue(parseValue(props.initialValue)); - }, [props.initialValue]); - const [value, setValue] = (0, import_react65.useState)(parseValue(props.initialValue)); - const removeValue = (v2) => { - const newValues = value.filter((f2) => f2 != v2); - setValue(newValues); - saveValue(newValues); + lastBitArr = bitArr; + } + const result = { + isMatch: bestLocation >= 0, + score: Math.max(1e-3, finalScore) }; - const saveValue = (_values) => { - if (props.multi) { - props.saveValue(serializeMultiString(_values)); + if (computeMatches) { + const indices = convertMaskToIndices(matchMask, minMatchCharLength); + if (!indices.length) { + result.isMatch = false; + } else if (includeMatches) { + result.indices = indices; + } + } + return result; +} +function createPatternAlphabet(pattern) { + let mask = {}; + for (let i4 = 0, len = pattern.length; i4 < len; i4 += 1) { + const char = pattern.charAt(i4); + mask[char] = (mask[char] || 0) | 1 << len - i4 - 1; + } + return mask; +} +var BitapSearch = class { + constructor(pattern, { + location = Config.location, + threshold = Config.threshold, + distance: distance2 = Config.distance, + includeMatches = Config.includeMatches, + findAllMatches = Config.findAllMatches, + minMatchCharLength = Config.minMatchCharLength, + isCaseSensitive = Config.isCaseSensitive, + ignoreLocation = Config.ignoreLocation + } = {}) { + this.options = { + location, + threshold, + distance: distance2, + includeMatches, + findAllMatches, + minMatchCharLength, + isCaseSensitive, + ignoreLocation + }; + this.pattern = isCaseSensitive ? pattern : pattern.toLowerCase(); + this.chunks = []; + if (!this.pattern.length) { + return; + } + const addChunk = (pattern2, startIndex) => { + this.chunks.push({ + pattern: pattern2, + alphabet: createPatternAlphabet(pattern2), + startIndex + }); + }; + const len = this.pattern.length; + if (len > MAX_BITS) { + let i4 = 0; + const remainder = len % MAX_BITS; + const end = len - remainder; + while (i4 < end) { + addChunk(this.pattern.substr(i4, MAX_BITS), i4); + i4 += MAX_BITS; + } + if (remainder) { + const startIndex = len - MAX_BITS; + addChunk(this.pattern.substr(startIndex), startIndex); + } } else { - props.saveValue(serializeMultiDisplayString(_values)); + addChunk(this.pattern, 0); } - }; - const saveOptions = (_15, _value) => { - if (!props.multi) { - setValue(_value); - saveValue(_value); - } else { - const newValue = _value[0]; - if (newValue) { - const newValues = uniq([...value, newValue]); - setValue(newValues); - saveValue(newValues); + } + searchIn(text2) { + const { isCaseSensitive, includeMatches } = this.options; + if (!isCaseSensitive) { + text2 = text2.toLowerCase(); + } + if (this.pattern === text2) { + let result2 = { + isMatch: true, + score: 0 + }; + if (includeMatches) { + result2.indices = [[0, text2.length - 1]]; } + return result2; } - }; - const menuProps = () => { - const options = [...props.superstate.pathsIndex.values()].filter((f2) => !f2.hidden).map((f2) => ({ - name: f2.name, - value: f2.path, - description: f2.path - })); - const _options = !props.multi ? [{ name: i18n_default.menu.none, value: "" }, ...options] : options; - return { - ui: props.superstate.ui, - multi: false, - editable: true, - value: value.map((f2) => f2), - options: _options, - saveOptions, - placeholder: i18n_default.labels.linkItemSelectPlaceholder, - detail: true, - searchable: true + const { + location, + distance: distance2, + threshold, + findAllMatches, + minMatchCharLength, + ignoreLocation + } = this.options; + let allIndices = []; + let totalScore = 0; + let hasMatches = false; + this.chunks.forEach(({ pattern, alphabet, startIndex }) => { + const { isMatch: isMatch2, score, indices } = search(text2, pattern, alphabet, { + location: location + startIndex, + distance: distance2, + threshold, + findAllMatches, + minMatchCharLength, + includeMatches, + ignoreLocation + }); + if (isMatch2) { + hasMatches = true; + } + totalScore += score; + if (isMatch2 && indices) { + allIndices = [...allIndices, ...indices]; + } + }); + let result = { + isMatch: hasMatches, + score: hasMatches ? totalScore / this.chunks.length : 1 }; - }; - const openLink = async (o2) => { - const pathExists = await props.superstate.spaceManager.pathExists(o2); - if (pathExists) { - props.superstate.ui.openPath(o2, false); - } else { - await props.superstate.spaceManager.createItemAtPath("/", "md", o2); - props.superstate.ui.openPath(o2, false); + if (hasMatches && includeMatches) { + result.indices = allIndices; } - }; - return /* @__PURE__ */ import_react65.default.createElement(OptionCellBase, { - superstate: props.superstate, - baseClass: "mk-cell-link", - removeValue, - selectLabel: props.compactMode ? props.property.name : i18n_default.labels.select, - menuProps, - labelElement: (_props) => /* @__PURE__ */ import_react65.default.createElement(PathCrumb, { - superstate: props.superstate, - path: _props.value - }, _props.children), - value, - multi: props.multi, - editMode: props.editMode - }); + return result; + } }; - -// src/core/react/components/SpaceView/Contexts/DataTypeView/LookUpCell.tsx -var import_react66 = __toESM(require_react()); -var LookUpCell = (props) => { - const initialValue = ensureString(props.initialValue); - const parsedValue = (0, import_react66.useMemo)( - () => parseFieldValue(props.propertyValue, "fileprop", props.superstate), - [props.propertyValue] - ); - const saveParsedValue = (field, value) => { - props.saveOptions(JSON.stringify({ ...parsedValue, [field]: value }), ""); - }; - const editFormula = (e5) => { - const _props = { - superstate: props.superstate, - saveFormula: (value) => saveParsedValue("value", value), - formula: parsedValue.value, - value: props.row, - fields: props.columns, - path: props.path +var BaseMatch = class { + constructor(pattern) { + this.pattern = pattern; + } + static isMultiMatch(pattern) { + return getMatch(pattern, this.multiRegex); + } + static isSingleMatch(pattern) { + return getMatch(pattern, this.singleRegex); + } + search() { + } +}; +function getMatch(pattern, exp3) { + const matches = pattern.match(exp3); + return matches ? matches[1] : null; +} +var ExactMatch = class extends BaseMatch { + constructor(pattern) { + super(pattern); + } + static get type() { + return "exact"; + } + static get multiRegex() { + return /^="(.*)"$/; + } + static get singleRegex() { + return /^=(.*)$/; + } + search(text2) { + const isMatch2 = text2 === this.pattern; + return { + isMatch: isMatch2, + score: isMatch2 ? 0 : 1, + indices: [0, this.pattern.length - 1] }; - props.superstate.ui.openCustomMenu( - e5.target.getBoundingClientRect(), - /* @__PURE__ */ import_react66.default.createElement(FormulaEditor, { - ..._props - }), - { ..._props }, - "bottom" - ); - }; - return parsedValue.type == "image" ? /* @__PURE__ */ import_react66.default.createElement(ImageCell, { - ...props, - editMode: 0 /* EditModeReadOnly */, - multi: false - }) : parsedValue.type == "icon" ? /* @__PURE__ */ import_react66.default.createElement(IconCell, { - ...props, - multi: false, - editMode: 0 /* EditModeReadOnly */ - }) : parsedValue.type == "link" ? /* @__PURE__ */ import_react66.default.createElement(LinkCell, { - ...props, - multi: false, - editMode: 0 /* EditModeReadOnly */ - }) : /* @__PURE__ */ import_react66.default.createElement("div", { - className: "mk-cell-fileprop", - onClick: (e5) => editFormula(e5) - }, initialValue); + } }; - -// src/core/react/components/SpaceView/Contexts/DataTypeView/NumberCell.tsx -var import_react67 = __toESM(require_react()); -var NumberCell = (props) => { - const { initialValue, saveValue } = props; - const [value, setValue] = import_react67.default.useState(initialValue); - const ref2 = (0, import_react67.useRef)(null); - const onBlur = () => { - if (initialValue != value) - saveValue(value); - }; - const onKeyDown = (e5) => { - e5.stopPropagation(); - if (e5.key == "Enter") { - e5.target.blur(); - props.setEditMode(null); - } - if (e5.key == "Escape") { - setValue(initialValue); - e5.target.blur(); - props.setEditMode(null); - } - }; - import_react67.default.useEffect(() => { - setValue(initialValue); - }, [initialValue]); - (0, import_react67.useEffect)(() => { - if (props.editMode == 4 /* EditModeActive */) { - ref2?.current?.focus(); - } - }, [props.editMode]); - return props.editMode > 2 /* EditModeView */ ? /* @__PURE__ */ import_react67.default.createElement("input", { - className: "mk-cell-text", - type: "number", - ref: ref2, - value: value ?? "", - onChange: (e5) => setValue(e5.target.value), - onKeyDown, - onBlur - }) : /* @__PURE__ */ import_react67.default.createElement("div", { - className: "mk-cell-number" - }, value); +var InverseExactMatch = class extends BaseMatch { + constructor(pattern) { + super(pattern); + } + static get type() { + return "inverse-exact"; + } + static get multiRegex() { + return /^!"(.*)"$/; + } + static get singleRegex() { + return /^!(.*)$/; + } + search(text2) { + const index2 = text2.indexOf(this.pattern); + const isMatch2 = index2 === -1; + return { + isMatch: isMatch2, + score: isMatch2 ? 0 : 1, + indices: [0, text2.length - 1] + }; + } }; - -// src/core/react/components/SpaceView/Contexts/DataTypeView/ObjectCell.tsx -var import_react68 = __toESM(require_react()); -var import_react_dom4 = __toESM(require_react_dom()); -var ObjectEditor = (props) => { - const { value, saveValue, saveType } = props; - const allProperties = [ - ...Object.keys(props.type ?? {}).map((f2) => { - return { - name: f2, - type: props.type[f2].type, - value: JSON.stringify(props.type[f2].value) - }; - }), - ...Object.keys(value).filter((f2) => !Object.keys(props.type ?? {}).includes(f2)).map((f2) => { - return { - name: f2, - type: "text" - }; - }) - ]; - const saveKey = (key2, newKey) => { - if (key2 != newKey) - saveValue({ - ...value, - [newKey]: value[key2], - [key2]: void 0 - }); - }; - const saveVal = (key2, val) => { - saveValue({ - ...value, - [key2]: val +var PrefixExactMatch = class extends BaseMatch { + constructor(pattern) { + super(pattern); + } + static get type() { + return "prefix-exact"; + } + static get multiRegex() { + return /^\^"(.*)"$/; + } + static get singleRegex() { + return /^\^(.*)$/; + } + search(text2) { + const isMatch2 = text2.startsWith(this.pattern); + return { + isMatch: isMatch2, + score: isMatch2 ? 0 : 1, + indices: [0, this.pattern.length - 1] + }; + } +}; +var InversePrefixExactMatch = class extends BaseMatch { + constructor(pattern) { + super(pattern); + } + static get type() { + return "inverse-prefix-exact"; + } + static get multiRegex() { + return /^!\^"(.*)"$/; + } + static get singleRegex() { + return /^!\^(.*)$/; + } + search(text2) { + const isMatch2 = !text2.startsWith(this.pattern); + return { + isMatch: isMatch2, + score: isMatch2 ? 0 : 1, + indices: [0, text2.length - 1] + }; + } +}; +var SuffixExactMatch = class extends BaseMatch { + constructor(pattern) { + super(pattern); + } + static get type() { + return "suffix-exact"; + } + static get multiRegex() { + return /^"(.*)"\$$/; + } + static get singleRegex() { + return /^(.*)\$$/; + } + search(text2) { + const isMatch2 = text2.endsWith(this.pattern); + return { + isMatch: isMatch2, + score: isMatch2 ? 0 : 1, + indices: [text2.length - this.pattern.length, text2.length - 1] + }; + } +}; +var InverseSuffixExactMatch = class extends BaseMatch { + constructor(pattern) { + super(pattern); + } + static get type() { + return "inverse-suffix-exact"; + } + static get multiRegex() { + return /^!"(.*)"\$$/; + } + static get singleRegex() { + return /^!(.*)\$$/; + } + search(text2) { + const isMatch2 = !text2.endsWith(this.pattern); + return { + isMatch: isMatch2, + score: isMatch2 ? 0 : 1, + indices: [0, text2.length - 1] + }; + } +}; +var FuzzyMatch = class extends BaseMatch { + constructor(pattern, { + location = Config.location, + threshold = Config.threshold, + distance: distance2 = Config.distance, + includeMatches = Config.includeMatches, + findAllMatches = Config.findAllMatches, + minMatchCharLength = Config.minMatchCharLength, + isCaseSensitive = Config.isCaseSensitive, + ignoreLocation = Config.ignoreLocation + } = {}) { + super(pattern); + this._bitapSearch = new BitapSearch(pattern, { + location, + threshold, + distance: distance2, + includeMatches, + findAllMatches, + minMatchCharLength, + isCaseSensitive, + ignoreLocation }); - }; - const showPropertyMenu2 = (e5, field) => { - if (props.editMode <= 3 /* EditModeValueOnly */) { - return; + } + static get type() { + return "fuzzy"; + } + static get multiRegex() { + return /^"(.*)"$/; + } + static get singleRegex() { + return /^(.*)$/; + } + search(text2) { + return this._bitapSearch.searchIn(text2); + } +}; +var IncludeMatch = class extends BaseMatch { + constructor(pattern) { + super(pattern); + } + static get type() { + return "include"; + } + static get multiRegex() { + return /^'"(.*)"$/; + } + static get singleRegex() { + return /^'(.*)$/; + } + search(text2) { + let location = 0; + let index2; + const indices = []; + const patternLen = this.pattern.length; + while ((index2 = text2.indexOf(this.pattern, location)) > -1) { + location = index2 + patternLen; + indices.push([index2, location - 1]); } - const offset2 = e5.target.getBoundingClientRect(); - const menuOptions = []; - menuOptions.push({ - name: i18n_default.menu.rename, - icon: "ui//edit", - onClick: (e6) => { - props.superstate.ui.openModal( - i18n_default.labels.rename, - (props2) => /* @__PURE__ */ import_react68.default.createElement(InputModal, { - value: field, - saveLabel: i18n_default.labels.rename, - hide: props2.hide, - saveValue: (value2) => { - saveKey(field, value2); - props2.hide(); - } - }) - ); + const isMatch2 = !!indices.length; + return { + isMatch: isMatch2, + score: isMatch2 ? 0 : 1, + indices + }; + } +}; +var searchers = [ + ExactMatch, + IncludeMatch, + PrefixExactMatch, + InversePrefixExactMatch, + InverseSuffixExactMatch, + SuffixExactMatch, + InverseExactMatch, + FuzzyMatch +]; +var searchersLen = searchers.length; +var SPACE_RE = / +(?=(?:[^\"]*\"[^\"]*\")*[^\"]*$)/; +var OR_TOKEN = "|"; +function parseQuery(pattern, options = {}) { + return pattern.split(OR_TOKEN).map((item) => { + let query = item.trim().split(SPACE_RE).filter((item2) => item2 && !!item2.trim()); + let results = []; + for (let i4 = 0, len = query.length; i4 < len; i4 += 1) { + const queryItem = query[i4]; + let found = false; + let idx = -1; + while (!found && ++idx < searchersLen) { + const searcher = searchers[idx]; + let token = searcher.isMultiMatch(queryItem); + if (token) { + results.push(new searcher(token, options)); + found = true; + } } - }); - menuOptions.push({ - name: i18n_default.buttons.delete, - icon: "ui//trash", - onClick: (e6) => { - props.saveType( - Object.keys(props.type ?? {}).reduce((p, c3) => { - if (c3 != field) - return { ...p, [c3]: props.type[c3] }; - return p; - }, {}), - Object.keys(value).reduce((p, c3) => { - if (c3 != field) - return { ...p, [c3]: value[c3] }; - return p; - }, {}) - ); + if (found) { + continue; } - }); - props.superstate.ui.openMenu( - offset2, - defaultMenu(props.superstate.ui, menuOptions) - ); - }; - const saveFieldValue = (field, fieldValue, value2) => { - const val = parseObject(value2, field.type == "object-multi"); - if (propertyIsObjectType(field)) { - const parsedValue = parseFieldValue(fieldValue, field.type); - const newType = { - ...props.type, - [field.name]: { - type: field.type, - label: field.name, - value: parsedValue + idx = -1; + while (++idx < searchersLen) { + const searcher = searchers[idx]; + let token = searcher.isSingleMatch(queryItem); + if (token) { + results.push(new searcher(token, options)); + break; } + } + } + return results; + }); +} +var MultiMatchSet = /* @__PURE__ */ new Set([FuzzyMatch.type, IncludeMatch.type]); +var ExtendedSearch = class { + constructor(pattern, { + isCaseSensitive = Config.isCaseSensitive, + includeMatches = Config.includeMatches, + minMatchCharLength = Config.minMatchCharLength, + ignoreLocation = Config.ignoreLocation, + findAllMatches = Config.findAllMatches, + location = Config.location, + threshold = Config.threshold, + distance: distance2 = Config.distance + } = {}) { + this.query = null; + this.options = { + isCaseSensitive, + includeMatches, + minMatchCharLength, + findAllMatches, + ignoreLocation, + location, + threshold, + distance: distance2 + }; + this.pattern = isCaseSensitive ? pattern : pattern.toLowerCase(); + this.query = parseQuery(this.pattern, this.options); + } + static condition(_15, options) { + return options.useExtendedSearch; + } + searchIn(text2) { + const query = this.query; + if (!query) { + return { + isMatch: false, + score: 1 }; - saveType(newType, val); } - }; - return /* @__PURE__ */ import_react68.default.createElement("div", { - className: "mk-cell-object-group" - }, props.draggable && /* @__PURE__ */ import_react68.default.createElement("div", { - className: "mk-cell-object-group-header", - onClick: (e5) => { - props.showDragMenu(e5); + const { includeMatches, isCaseSensitive } = this.options; + text2 = isCaseSensitive ? text2 : text2.toLowerCase(); + let numMatches = 0; + let allIndices = []; + let totalScore = 0; + for (let i4 = 0, qLen = query.length; i4 < qLen; i4 += 1) { + const searchers2 = query[i4]; + allIndices.length = 0; + numMatches = 0; + for (let j = 0, pLen = searchers2.length; j < pLen; j += 1) { + const searcher = searchers2[j]; + const { isMatch: isMatch2, indices, score } = searcher.search(text2); + if (isMatch2) { + numMatches += 1; + totalScore += score; + if (includeMatches) { + const type = searcher.constructor.type; + if (MultiMatchSet.has(type)) { + allIndices = [...allIndices, ...indices]; + } else { + allIndices.push(indices); + } + } + } else { + totalScore = 0; + numMatches = 0; + allIndices.length = 0; + break; + } + } + if (numMatches) { + let result = { + isMatch: true, + score: totalScore / numMatches + }; + if (includeMatches) { + result.indices = allIndices; + } + return result; + } } - }, props.typeName ?? "Object"), /* @__PURE__ */ import_react68.default.createElement("div", { - className: "mk-cell-object" - }, allProperties.map((f2, i4) => /* @__PURE__ */ import_react68.default.createElement(DataPropertyView, { - key: i4, - initialValue: value[f2.name] ?? "", - superstate: props.superstate, - updateValue: (v2) => saveVal(f2.name, v2), - updateFieldValue: (fv, v2) => saveFieldValue(f2, fv, v2), - propertyMenu: (e5) => showPropertyMenu2(e5, f2.name), - row: value, - columns: allProperties, - source: null, - compactMode: props.compactMode, - column: f2, - editMode: 5 /* EditModeAlways */ - })))); + return { + isMatch: false, + score: 1 + }; + } }; -var ObjectCell = (props) => { - const parsedValue = parseFieldValue( - props.propertyValue, - "object", - props.superstate - ); - const type = parsedValue.type; - const { initialValue, superstate } = props; - const value = (0, import_react68.useMemo)( - () => parseObject(initialValue, props.multi), - [initialValue, props.multi] - ); - const saveType = (newType, _value) => { - if (props.multi) { - const newValues = value.map((f2) => ({ - ...Object.keys(newType).reduce((p, c3) => { - if (f2[c3]) - return { ...p, [c3]: f2[c3] }; - return p; - }, {}) - })); - props.savePropValue( - JSON.stringify({ ...parsedValue, type: newType }), - JSON.stringify(newValues) - ); - } else { - props.savePropValue( - JSON.stringify({ ...parsedValue, type: newType }), - JSON.stringify(_value) - ); +var registeredSearchers = []; +function register(...args) { + registeredSearchers.push(...args); +} +function createSearcher(pattern, options) { + for (let i4 = 0, len = registeredSearchers.length; i4 < len; i4 += 1) { + let searcherClass = registeredSearchers[i4]; + if (searcherClass.condition(pattern, options)) { + return new searcherClass(pattern, options); } - }; - const saveValue = (newValue) => { - props.saveValue(JSON.stringify(newValue)); - }; - const insertMultiValue = (index2) => { - const item = Object.keys(type).reduce((p, c3) => ({ ...p, [c3]: "" }), {}); - props.saveValue( - JSON.stringify([...value.slice(0, index2), item, ...value.slice(index2)]) - ); - }; - const saveMultiValue = (newValue, index2) => { - if (index2 >= value.length) { - props.saveValue(JSON.stringify([...value, newValue])); - return; + } + return new BitapSearch(pattern, options); +} +var LogicalOperator = { + AND: "$and", + OR: "$or" +}; +var KeyType = { + PATH: "$path", + PATTERN: "$val" +}; +var isExpression = (query) => !!(query[LogicalOperator.AND] || query[LogicalOperator.OR]); +var isPath = (query) => !!query[KeyType.PATH]; +var isLeaf = (query) => !isArray4(query) && isObject2(query) && !isExpression(query); +var convertToExplicit = (query) => ({ + [LogicalOperator.AND]: Object.keys(query).map((key2) => ({ + [key2]: query[key2] + })) +}); +function parse6(query, options, { auto = true } = {}) { + const next = (query2) => { + let keys = Object.keys(query2); + const isQueryPath = isPath(query2); + if (!isQueryPath && keys.length > 1 && !isExpression(query2)) { + return next(convertToExplicit(query2)); } - props.saveValue( - JSON.stringify( - value.map( - (f2, i4) => i4 == index2 ? newValue : f2 - ) - ) - ); - }; - const deleteMultiValue = (index2) => { - props.saveValue( - JSON.stringify( - value.filter((f2, i4) => i4 != index2) - ) - ); - }; - const newKey = (key2) => { - if (key2) - saveValue({ - ...value, - [key2]: "" - }); - }; - const showPropertyMultiMenu = (e5, index2) => { - const offset2 = e5.target.getBoundingClientRect(); - const menuOptions = []; - menuOptions.push({ - name: i18n_default.menu.insertAbove, - onClick: (e6) => { - insertMultiValue(index2); + if (isLeaf(query2)) { + const key2 = isQueryPath ? query2[KeyType.PATH] : keys[0]; + const pattern = isQueryPath ? query2[KeyType.PATTERN] : query2[key2]; + if (!isString4(pattern)) { + throw new Error(LOGICAL_SEARCH_INVALID_QUERY_FOR_KEY(key2)); } - }); - menuOptions.push({ - name: i18n_default.menu.insertBelow, - onClick: (e6) => { - insertMultiValue(index2 + 1); + const obj = { + keyId: createKeyId(key2), + pattern + }; + if (auto) { + obj.searcher = createSearcher(pattern, options); } - }); - menuOptions.push(menuSeparator); - if (index2 > 0) - menuOptions.push({ - name: i18n_default.menu.moveUp, - onClick: (e6) => { - props.saveValue( - JSON.stringify( - arrayMove(value, index2, index2 - 1) - ) - ); - } - }); - if (index2 < value.length - 1) - menuOptions.push({ - name: i18n_default.menu.moveDown, - onClick: (e6) => { - props.saveValue( - JSON.stringify( - arrayMove(value, index2, index2 + 1) - ) - ); - } - }); - menuOptions.push(menuSeparator); - menuOptions.push({ - name: i18n_default.buttons.delete, - icon: "ui//trash", - onClick: (e6) => { - deleteMultiValue(index2); + return obj; + } + let node = { + children: [], + operator: keys[0] + }; + keys.forEach((key2) => { + const value = query2[key2]; + if (isArray4(value)) { + value.forEach((item) => { + node.children.push(next(item)); + }); } }); - props.superstate.ui.openMenu( - offset2, - defaultMenu(props.superstate.ui, menuOptions) - ); - }; - const [dragProperty, setDragProperty] = (0, import_react68.useState)(-1); - const [hoverNode, setHoverNode] = (0, import_react68.useState)(-1); - const resetState = () => { - setHoverNode(-1); - setDragProperty(-1); + return node; }; - useDndMonitor({ - onDragStart({ active }) { - if (active.data.current.type == "object") - setDragProperty(active.data.current.id); - }, - onDragOver({ active, over }) { - const overId = over?.data.current.id; - if (active.data.current.type == "object") { - if (overId) - setHoverNode(overId); - } - }, - onDragCancel() { - resetState(); - }, - onDragEnd({ active, over }) { - if (!active || hoverNode != -1) { - resetState(); - return; - } - props.saveValue( - JSON.stringify( - arrayMove(value, dragProperty, hoverNode) - ) + if (!isExpression(query)) { + query = convertToExplicit(query); + } + return next(query); +} +function computeScore(results, { ignoreFieldNorm = Config.ignoreFieldNorm }) { + results.forEach((result) => { + let totalScore = 1; + result.matches.forEach(({ key: key2, norm: norm3, score }) => { + const weight = key2 ? key2.weight : null; + totalScore *= Math.pow( + score === 0 && weight ? Number.EPSILON : score, + (weight || 1) * (ignoreFieldNorm ? 1 : norm3) ); - resetState(); - } + }); + result.score = totalScore; }); - const menuRef = (0, import_react68.useRef)(); - (0, import_react68.useEffect)(() => { - if (menuRef.current) { - menuRef.current.update(props); - } - }, [props]); - return !props.compactMode ? props.multi ? /* @__PURE__ */ import_react68.default.createElement("div", { - className: "mk-cell-object-multi" - }, value.map((f2, i4) => /* @__PURE__ */ import_react68.default.createElement(ObjectEditor, { - key: i4, - superstate, - value: f2, - compactMode: props.compactMode, - row: props.row, - typeName: parsedValue.typeName, - columns: props.columns, - type, - saveValue: (newValue) => saveMultiValue(newValue, i4), - saveType, - editMode: props.editMode, - draggable: true, - index: i4, - showDragMenu: (e5) => showPropertyMultiMenu(e5, i4) - })), dragProperty != -1 && (0, import_react_dom4.createPortal)( - /* @__PURE__ */ import_react68.default.createElement(DragOverlay, { - dropAnimation: null, - zIndex: 1600 - }, /* @__PURE__ */ import_react68.default.createElement(ObjectEditor, { - superstate, - value: value[dragProperty], - typeName: parsedValue.typeName, - compactMode: props.compactMode, - row: props.row, - columns: props.columns, - type, - saveValue: null, - saveType: null, - editMode: props.editMode, - draggable: false - })), - document.body - )) : /* @__PURE__ */ import_react68.default.createElement(ObjectEditor, { - superstate, - value, - typeName: parsedValue.typeName, - compactMode: props.compactMode, - row: props.row, - columns: props.columns, - type, - saveValue, - saveType, - editMode: props.editMode, - draggable: false - }) : /* @__PURE__ */ import_react68.default.createElement("div", { - className: "mk-cell-object" - }, /* @__PURE__ */ import_react68.default.createElement("div", { - className: "mk-cell-clickable", - onClick: (e5) => { - menuRef.current = superstate.ui.openCustomMenu( - e5.currentTarget.getBoundingClientRect(), - /* @__PURE__ */ import_react68.default.createElement(ObjectEditorModal, { - ...props - }), - props - ); - } - }, /* @__PURE__ */ import_react68.default.createElement("div", { - className: "mk-icon-xsmall", - dangerouslySetInnerHTML: { - __html: props.superstate.ui.getSticker("ui//edit") +} +function transformMatches(result, data2) { + const matches = result.matches; + data2.matches = []; + if (!isDefined(matches)) { + return; + } + matches.forEach((match2) => { + if (!isDefined(match2.indices) || !match2.indices.length) { + return; } - }), `${i18n_default.menu.edit} ${props.property.name}`)); -}; -var ObjectEditorModal = (props) => { - const [value, setValue] = (0, import_react68.useState)(props.initialValue); - const [fieldValue, setFieldValue] = (0, import_react68.useState)(props.property.value); - const saveValue = (value2) => { - setValue(value2); - props.saveValue(value2); - }; - const savePropValue = (propValue, value2) => { - setValue(value2); - setFieldValue(propValue); - props.savePropValue(propValue, value2); - }; - const saveType = (newType, _value) => { - const parsedValue = parseFieldValue(fieldValue, props.property.type); - const newValue = parseObject(value, props.property.type == "object-multi"); - if (props.property.type == "object-multi") { - savePropValue( - JSON.stringify({ ...parsedValue, type: newType }), - JSON.stringify(newValue) - ); - } else { - savePropValue( - JSON.stringify({ ...parsedValue, type: newType }), - JSON.stringify(_value) - ); + const { indices, value } = match2; + let obj = { + indices, + value + }; + if (match2.key) { + obj.key = match2.key.src; } - }; - const newProperty = (e5) => { - const offset2 = e5.target.getBoundingClientRect(); - const type = parseFieldValue(fieldValue, props.property.type)?.type; - const _value = parseObject(value, props.property.type == "object-multi"); - showNewPropertyMenu( - props.superstate, - offset2, - [], - [], - (source, field) => { - saveType( - { - ...type ?? {}, - [field.name]: { type: field.type, label: field.name } - }, - { - ..._value, - [field.name]: "" - } - ); - }, - null, - null, - true, - false - ); - }; - const insertMultiValue = (index2) => { - const val = parseObject(value, props.property.type == "object-multi"); - const type = parseFieldValue(fieldValue, props.property.type)?.type; - const item = Object.keys(type).reduce((p, c3) => ({ ...p, [c3]: "" }), {}); - saveValue( - JSON.stringify([...val.slice(0, index2), item, ...val.slice(index2)]) - ); - }; - return /* @__PURE__ */ import_react68.default.createElement("div", { - className: "mk-editor-frame-properties" - }, /* @__PURE__ */ import_react68.default.createElement("div", { - className: "mk-editor-actions-name" - }, /* @__PURE__ */ import_react68.default.createElement("div", { - className: "mk-editor-actions-name-icon" - }, /* @__PURE__ */ import_react68.default.createElement("div", { - className: "mk-icon-small", - dangerouslySetInnerHTML: { - __html: props.superstate.ui.getSticker("ui//list") + if (match2.idx > -1) { + obj.refIndex = match2.idx; } - })), /* @__PURE__ */ import_react68.default.createElement("div", { - className: "mk-editor-actions-name-text" - }, i18n_default.labels.editObject), /* @__PURE__ */ import_react68.default.createElement("span", null), /* @__PURE__ */ import_react68.default.createElement("div", { - className: "mk-icon-small mk-inline-button", - dangerouslySetInnerHTML: { - __html: props.superstate.ui.getSticker("ui//close") - }, - onClick: () => props.hide() - })), /* @__PURE__ */ import_react68.default.createElement(ObjectCell, { - ...props, - initialValue: value, - compactMode: false, - propertyValue: fieldValue, - saveValue: (v2) => { - saveValue(v2); - }, - savePropValue: (v2, p) => { - savePropValue(v2, p); - }, - editMode: 5 /* EditModeAlways */ - }), /* @__PURE__ */ import_react68.default.createElement("div", { - className: "mk-cell-object-options" - }, /* @__PURE__ */ import_react68.default.createElement("button", { - onClick: (e5) => newProperty(e5), - className: "mk-inline-button" - }, /* @__PURE__ */ import_react68.default.createElement("div", { - className: "mk-icon-xsmall", - dangerouslySetInnerHTML: { - __html: props.superstate.ui.getSticker("ui//plus") + data2.matches.push(obj); + }); +} +function transformScore(result, data2) { + data2.score = result.score; +} +function format7(results, docs, { + includeMatches = Config.includeMatches, + includeScore = Config.includeScore +} = {}) { + const transformers = []; + if (includeMatches) + transformers.push(transformMatches); + if (includeScore) + transformers.push(transformScore); + return results.map((result) => { + const { idx } = result; + const data2 = { + item: docs[idx], + refIndex: idx + }; + if (transformers.length) { + transformers.forEach((transformer) => { + transformer(result, data2); + }); } - }), i18n_default.labels.propertyFileProp), props.property.type == "object-multi" && /* @__PURE__ */ import_react68.default.createElement("button", { - onClick: (e5) => insertMultiValue(0), - className: "mk-inline-button" - }, /* @__PURE__ */ import_react68.default.createElement("div", { - className: "mk-icon-xsmall", - dangerouslySetInnerHTML: { - __html: props.superstate.ui.getSticker("ui//insert") + return data2; + }); +} +var Fuse = class { + constructor(docs, options = {}, index2) { + this.options = { ...Config, ...options }; + if (this.options.useExtendedSearch && false) { + throw new Error(EXTENDED_SEARCH_UNAVAILABLE); } - }), "Object"))); -}; - -// src/core/react/components/SpaceView/Contexts/DataTypeView/PathCell.tsx -var import_react69 = __toESM(require_react()); -var PathCell = (props) => { - const fileOrCleanPath = (f2) => { - if (!f2) - return { - path: "" - }; - const resolvedPath = props.superstate.spaceManager.resolvePath( - f2, - props.folder - ); - const pathState = props.superstate.pathsIndex.get(resolvedPath); - return pathState ? { path: f2, pathState } : { path: f2 }; - }; - const value = (0, import_react69.useMemo)( - () => (props.multi ? parseMultiString(props.initialValue) ?? [] : [props.initialValue]).map((f2) => fileOrCleanPath(f2)), - [props.initialValue] - ); - const ref2 = (0, import_react69.useRef)(null); - const onKeyDown = (e5) => { - e5.stopPropagation(); - e5.key == "Enter" && e5.target.blur(); - }; - const pathExists = async (name317) => { - if (!name317) - return false; - return await props.superstate.spaceManager.pathExists(name317) ? true : false; - }; - const onBlur = async () => { - if (!ref2.current) - return; - if (await pathExists(ref2.current?.value)) { - props.superstate.ui.notify(i18n_default.notice.fileExists); - } else { - props.saveValue(ref2.current.value); - props.setEditMode(null); + this._keyStore = new KeyStore(this.options.keys); + this.setCollection(docs, index2); + } + setCollection(docs, index2) { + this._docs = docs; + if (index2 && !(index2 instanceof FuseIndex)) { + throw new Error(INCORRECT_INDEX_TYPE); } - }; - const newPath = async (file) => { - const pathName = file.path.replace(/\//g, "").replace(/\./g, ""); - const path2 = `${props.folder}/${pathName}.md`; - if (pathName.length == 0) { + this._myIndex = index2 || createIndex2(this.options.keys, this._docs, { + getFn: this.options.getFn, + fieldNormWeight: this.options.fieldNormWeight + }); + } + add(doc) { + if (!isDefined(doc)) { return; } - if (await pathExists(path2)) { - props.superstate.ui.notify(i18n_default.notice.fileExists); - } else { - await props.superstate.spaceManager.createItemAtPath( - props.folder, - "md", - pathName - ); + this._docs.push(doc); + this._myIndex.add(doc); + } + remove(predicate = () => false) { + const results = []; + for (let i4 = 0, len = this._docs.length; i4 < len; i4 += 1) { + const doc = this._docs[i4]; + if (predicate(doc, i4)) { + this.removeAt(i4); + i4 -= 1; + len -= 1; + results.push(doc); + } } - }; - const deleteRow = () => { - props.deleteRow(); - }; - (0, import_react69.useEffect)(() => { - if (props.editMode == 4 /* EditModeActive */) { - ref2?.current?.focus(); + return results; + } + removeAt(idx) { + this._docs.splice(idx, 1); + this._myIndex.removeAt(idx); + } + getIndex() { + return this._myIndex; + } + search(query, { limit = -1 } = {}) { + const { + includeMatches, + includeScore, + shouldSort, + sortFn, + ignoreFieldNorm + } = this.options; + let results = isString4(query) ? isString4(this._docs[0]) ? this._searchStringList(query) : this._searchObjectList(query) : this._searchLogical(query); + computeScore(results, { ignoreFieldNorm }); + if (shouldSort) { + results.sort(sortFn); } - }, [props.editMode]); - return /* @__PURE__ */ import_react69.default.createElement("div", { - className: "mk-cell-file" - }, value.map((v2, i4) => { - if (props.editMode == 0 /* EditModeReadOnly */) { - if (v2.pathState) { - return /* @__PURE__ */ import_react69.default.createElement("div", { - key: i4, - className: "mk-cell-file-title" - }, v2 && v2.pathState ? v2.pathState.name : "", v2.pathState.type == "file" && v2.pathState.subtype != "md" && /* @__PURE__ */ import_react69.default.createElement("span", { - className: "nav-file-tag" - }, v2.pathState.metadata.file.extension), /* @__PURE__ */ import_react69.default.createElement("button", { - "aria-label": i18n_default.buttons.toggleFlow, - className: "mk-cell-file-flow mk-inline-button", - dangerouslySetInnerHTML: { - __html: props.superstate.ui.getSticker("ui//flow-hover") - }, - onClick: (e5) => { - if (props.openFlow) { - props.openFlow(e5); - e5.stopPropagation(); + if (isNumber3(limit) && limit > -1) { + results = results.slice(0, limit); + } + return format7(results, this._docs, { + includeMatches, + includeScore + }); + } + _searchStringList(query) { + const searcher = createSearcher(query, this.options); + const { records } = this._myIndex; + const results = []; + records.forEach(({ v: text2, i: idx, n: norm3 }) => { + if (!isDefined(text2)) { + return; + } + const { isMatch: isMatch2, score, indices } = searcher.searchIn(text2); + if (isMatch2) { + results.push({ + item: text2, + idx, + matches: [{ score, value: text2, norm: norm3, indices }] + }); + } + }); + return results; + } + _searchLogical(query) { + const expression = parse6(query, this.options); + const evaluate2 = (node, item, idx) => { + if (!node.children) { + const { keyId, searcher } = node; + const matches = this._findMatches({ + key: this._keyStore.get(keyId), + value: this._myIndex.getValueForItemAtKeyId(item, keyId), + searcher + }); + if (matches && matches.length) { + return [ + { + idx, + item, + matches } + ]; + } + return []; + } + const res = []; + for (let i4 = 0, len = node.children.length; i4 < len; i4 += 1) { + const child = node.children[i4]; + const result = evaluate2(child, item, idx); + if (result.length) { + res.push(...result); + } else if (node.operator === LogicalOperator.AND) { + return []; + } + } + return res; + }; + const records = this._myIndex.records; + const resultMap = {}; + const results = []; + records.forEach(({ $: item, i: idx }) => { + if (isDefined(item)) { + let expResults = evaluate2(expression, item, idx); + if (expResults.length) { + if (!resultMap[idx]) { + resultMap[idx] = { idx, item, matches: [] }; + results.push(resultMap[idx]); } - })); - } else { - return /* @__PURE__ */ import_react69.default.createElement("div", { - key: i4, - className: "mk-cell-file-title" - }, v2.path); + expResults.forEach(({ matches }) => { + resultMap[idx].matches.push(...matches); + }); + } } + }); + return results; + } + _searchObjectList(query) { + const searcher = createSearcher(query, this.options); + const { keys, records } = this._myIndex; + const results = []; + records.forEach(({ $: item, i: idx }) => { + if (!isDefined(item)) { + return; + } + let matches = []; + keys.forEach((key2, keyIndex) => { + matches.push( + ...this._findMatches({ + key: key2, + value: item[keyIndex], + searcher + }) + ); + }); + if (matches.length) { + results.push({ + idx, + item, + matches + }); + } + }); + return results; + } + _findMatches({ key: key2, value, searcher }) { + if (!isDefined(value)) { + return []; } - if (v2.pathState) { - return /* @__PURE__ */ import_react69.default.createElement("div", { - className: "mk-cell-file-item", - key: i4 - }, /* @__PURE__ */ import_react69.default.createElement(PathCrumb, { - superstate: props.superstate, - path: v2.pathState.path - })); - } - return /* @__PURE__ */ import_react69.default.createElement("div", { - className: "mk-cell-file-item", - key: i4 - }, /* @__PURE__ */ import_react69.default.createElement("div", { - className: "mk-path-icon" - }, /* @__PURE__ */ import_react69.default.createElement("button", { - onClick: (e5) => newPath(v2), - dangerouslySetInnerHTML: { - __html: props.superstate.ui.getSticker("ui//new-file") + let matches = []; + if (isArray4(value)) { + value.forEach(({ v: text2, i: idx, n: norm3 }) => { + if (!isDefined(text2)) { + return; + } + const { isMatch: isMatch2, score, indices } = searcher.searchIn(text2); + if (isMatch2) { + matches.push({ + score, + key: key2, + value: text2, + idx, + norm: norm3, + indices + }); + } + }); + } else { + const { v: text2, n: norm3 } = value; + const { isMatch: isMatch2, score, indices } = searcher.searchIn(text2); + if (isMatch2) { + matches.push({ score, key: key2, value: text2, norm: norm3, indices }); } - })), props.editMode > 2 /* EditModeView */ ? /* @__PURE__ */ import_react69.default.createElement("input", { - className: "mk-cell-file-name", - type: "text", - placeholder: i18n_default.buttons.newNote, - ref: ref2, - defaultValue: v2.path, - onKeyDown, - onBlur - }) : /* @__PURE__ */ import_react69.default.createElement("div", { - className: "mk-cell-file-name" - }, v2.path)); - })); + } + return matches; + } }; +Fuse.version = "7.0.0"; +Fuse.createIndex = createIndex2; +Fuse.parseIndex = parseIndex; +Fuse.config = Config; +{ + Fuse.parseQuery = parse6; +} +{ + register(ExtendedSearch); +} -// src/core/react/components/SpaceView/Contexts/DataTypeView/PropertySelectCell.tsx -var import_react70 = __toESM(require_react()); -var PropertySelectCell = (props) => { - const [value, setValue] = (0, import_react70.useState)( - parseLinkedPropertyToValue(props.initialValue) - ); - const saveOptions = (_15, _value) => { - setValue(parseLinkedPropertyToValue(_value[0])); - props.saveValue(_value[0]); - }; - const menuProps = () => { - const options = (props.columns ?? []).map((f2) => ({ - name: f2.name, - description: f2.table, - value: f2.table == "" ? `$root['props']['${f2.name}']` : `$contexts['${f2.table}']['${f2.name}']` - })); - return { - ui: props.superstate.ui, - multi: false, - editable: true, - value: value ? [value] : [], - options, - saveOptions, - placeholder: i18n_default.labels.linkItemSelectPlaceholder, - detail: true, - searchable: true +// src/core/react/components/UI/Menus/menu/SelectMenuComponent.tsx +var import_react78 = __toESM(require_react()); + +// src/core/react/components/UI/Menus/menu/SelectMenuInput.tsx +var import_react75 = __toESM(require_react()); +var SIZER_STYLES = { + position: "absolute", + width: 0, + height: 0, + visibility: "hidden", + overflow: "scroll", + whiteSpace: "pre" +}; +var STYLE_PROPS = [ + "fontSize", + "fontFamily", + "fontWeight", + "fontStyle", + "letterSpacing", + "textTransform" +]; +var SelectMenuSearch = (0, import_react75.forwardRef)( + (props, input) => { + const { classNames: classNames13, inputAttributes, inputEventHandlers, index: index2 } = props; + const sizer = (0, import_react75.useRef)(null); + const [inputWidth, setInputWidth] = (0, import_react75.useState)(null); + const [query, setQuery] = (0, import_react75.useState)(""); + const [placeholderText, setPlaceholderText] = (0, import_react75.useState)(""); + (0, import_react75.useEffect)(() => { + copyInputStyles(); + updateInputWidth(); + setTimeout(() => { + input.current?.focus(); + }, 50); + }, []); + (0, import_react75.useEffect)(() => { + if (query !== props.query || placeholderText !== props.placeholderText) { + setQuery(props.query); + setPlaceholderText(props.placeholderText); + updateInputWidth(); + } + }, [props.query, props.placeholderText]); + const copyInputStyles = () => { + const inputStyle = window.getComputedStyle(input.current); + STYLE_PROPS.forEach((prop2) => { + sizer.current.style[prop2] = inputStyle[prop2]; + }); }; - }; - return /* @__PURE__ */ import_react70.default.createElement(OptionCellBase, { - superstate: props.superstate, - removeValue: null, - baseClass: "mk-cell-link", - selectLabel: props.compactMode ? props.property.name : i18n_default.labels.select, - menuProps, - labelElement: (_props) => /* @__PURE__ */ import_react70.default.createElement("div", null, _props.value), - value: value ? [value] : [], - multi: false, - editMode: props.editMode - }); + const updateInputWidth = () => { + const _inputWidth = Math.ceil(sizer.current.scrollWidth) + 2; + if (_inputWidth !== inputWidth) { + setInputWidth(_inputWidth); + } + }; + return /* @__PURE__ */ import_react75.default.createElement("div", { + className: classNames13.searchWrapper + }, /* @__PURE__ */ import_react75.default.createElement("input", { + ...inputAttributes, + ...inputEventHandlers, + ref: input, + value: query, + placeholder: placeholderText, + className: classNames13.searchInput, + role: "combobox", + style: { width: "100%" }, + onClick: (e5) => e5.stopPropagation() + }), /* @__PURE__ */ import_react75.default.createElement("div", { + ref: sizer, + style: SIZER_STYLES + }, query || placeholderText)); + } +); +var SelectMenuInput_default = SelectMenuSearch; +SelectMenuSearch.displayName = "SelectMenuSearch"; + +// src/core/react/components/UI/Menus/menu/SelectMenuPill.tsx +var import_react76 = __toESM(require_react()); +var SelectMenuPillComponent = (props) => { + return /* @__PURE__ */ import_react76.default.createElement("button", { + type: "button", + className: props.classNames.selectedTag, + onClick: props.onDelete + }, /* @__PURE__ */ import_react76.default.createElement("span", { + className: props.classNames.selectedTagName + }, props.tag.name)); }; +var SelectMenuPill_default = SelectMenuPillComponent; -// src/core/react/components/SpaceView/Contexts/DataTypeView/SpaceCell.tsx -var import_react71 = __toESM(require_react()); -var SpaceCell = (props) => { - const openLink = async () => { - props.superstate.ui.openPath(props.initialValue, false); - }; - const menuRef = (0, import_react71.useRef)(null); - const spaceObject = contextPathFromPath(props.superstate, props.initialValue); - const ref2 = (0, import_react71.useRef)(null); - const menuProps = () => ({ - multi: false, - ui: props.superstate.ui, - editable: true, - value: [props.initialValue], - options: props.superstate.allSpaces().map((f2) => ({ - name: f2.name, - value: f2.path, - description: f2.name - })), - saveOptions: (_15, value) => props.saveValue(value[0]), - removeOption: () => { +// src/core/react/components/UI/Menus/menu/SelectMenuSuggestions.tsx +var import_react77 = __toESM(require_react()); +function markIt(name317, query) { + const regexp = matchAny(query); + return name317?.replace(regexp, "$&"); +} +var SelectMenuSuggestionsComponent = (props) => { + const ref2 = (0, import_react77.useRef)(null); + (0, import_react77.useEffect)(() => { + if (props.active) { + ref2?.current?.scrollIntoViewIfNeeded(); + } + }, [props.active]); + return /* @__PURE__ */ import_react77.default.createElement(import_react77.default.Fragment, null, props.item.icon && /* @__PURE__ */ import_react77.default.createElement(Sticker, { + ui: props.ui, + sticker: props.item.icon + }), /* @__PURE__ */ import_react77.default.createElement("div", { + ref: ref2, + className: "mk-menu-options-inner" + }, props.item.onToggle && /* @__PURE__ */ import_react77.default.createElement("div", null, "Toggle"), /* @__PURE__ */ import_react77.default.createElement("span", { + style: props.item.color?.length > 0 ? { + background: props.item.color, + padding: "2px 4px", + borderRadius: "4px", + color: props.item.color == "var(--mk-color-none)" ? "inherit" : "var(--mk-color-white)" + } : {}, + dangerouslySetInnerHTML: { + __html: markIt(props.item.name, props.query) + } + }), props.item.description && /* @__PURE__ */ import_react77.default.createElement("span", { + "aria-label": props.item.description, + className: "mk-menu-options-description", + dangerouslySetInnerHTML: { + __html: markIt(props.item.description, props.query) + } + })), props.item.type == 1 /* Disclosure */ && /* @__PURE__ */ import_react77.default.createElement("span", null, props.item.value), props.item.type == 3 /* Radio */ && props.item.value && /* @__PURE__ */ import_react77.default.createElement("div", { + className: "mk-icon-small", + dangerouslySetInnerHTML: { + __html: props.ui.getSticker("ui//check") + } + }), props.item.onMoreOptions || props.onMoreOption && props.item.removeable ? /* @__PURE__ */ import_react77.default.createElement("div", { + onClick: (e5) => { + e5.stopPropagation(); + e5.preventDefault(); + props.item.onMoreOptions ? props.item.onMoreOptions(e5) : props.onMoreOption(e5, props.item.value); }, - placeholder: i18n_default.labels.optionItemSelectPlaceholder, - searchable: true, - showAll: true, - onHide: () => props.setEditMode(null) - }); - const menuSchemaProps = () => ({ - multi: false, - ui: props.superstate.ui, - editable: true, - value: [spaceObject.schema], - options: props.superstate.contextsIndex.get(spaceObject.space).schemas.map((f2) => ({ - name: f2.name, - value: f2.id, - description: f2.name - })), - saveOptions: (_15, value) => props.saveValue(`${spaceObject?.space}/#^${value[0]}`), - removeOption: () => { + className: "mk-icon-small", + dangerouslySetInnerHTML: { + __html: props.ui.getSticker("ui//options") + } + }) : null, props.item.removeable && props.onDeleteOption && /* @__PURE__ */ import_react77.default.createElement("div", { + onClick: (e5) => { + e5.stopPropagation(); + e5.preventDefault(); + props.onDeleteOption(props.item.value); }, - placeholder: i18n_default.labels.optionItemSelectPlaceholder, - searchable: true, - showAll: true, - onHide: () => props.setEditMode(null) - }); - const showMenu2 = () => { - const offset2 = ref2.current.getBoundingClientRect(); - menuRef.current = props.superstate.ui.openMenu(offset2, menuProps()); - }; - const showSchemaMenu = () => { - const offset2 = ref2.current.getBoundingClientRect(); - menuRef.current = props.superstate.ui.openMenu(offset2, menuSchemaProps()); - }; - return /* @__PURE__ */ import_react71.default.createElement("div", { - ref: ref2, - className: "mk-cell-space" - }, /* @__PURE__ */ import_react71.default.createElement("div", { - className: "mk-cell-option-item" - }, /* @__PURE__ */ import_react71.default.createElement("div", { - onClick: () => openLink() - }, spaceObject?.space), props.editMode > 2 /* EditModeView */ && /* @__PURE__ */ import_react71.default.createElement(import_react71.default.Fragment, null, /* @__PURE__ */ import_react71.default.createElement("span", null), /* @__PURE__ */ import_react71.default.createElement("div", { - onClick: (e5) => showMenu2(), - className: "mk-cell-option-select mk-icon-xxsmall mk-icon-rotated", + className: "mk-icon-small", dangerouslySetInnerHTML: { - __html: props.superstate.ui.getSticker("ui//collapse-solid") + __html: props.ui.getSticker("ui//close") } - }))), props.isTable && /* @__PURE__ */ import_react71.default.createElement("div", { - className: "mk-cell-option-item" - }, /* @__PURE__ */ import_react71.default.createElement("div", { - onClick: () => openLink() - }, spaceObject?.schemaName), spaceObject?.space && /* @__PURE__ */ import_react71.default.createElement("div", { - onClick: (e5) => showSchemaMenu(), - className: "mk-cell-option-select mk-icon-xxsmall mk-icon-rotated", + }), props.item.type == 6 /* Submenu */ && /* @__PURE__ */ import_react77.default.createElement("div", { + className: "mk-icon-small", dangerouslySetInnerHTML: { - __html: props.superstate.ui.getSticker("ui//collapse-solid") + __html: props.ui.getSticker("ui//chevron-right") } - }))); -}; - -// src/core/react/components/SpaceView/Contexts/DataTypeView/SuperCell.tsx -var import_react73 = __toESM(require_react()); - -// src/core/react/components/SpaceView/Contexts/DataTypeView/SuperCell/ParameterSetter.tsx -var import_react72 = __toESM(require_react()); -var ParameterSetter = (props) => { - const [value, setValue] = (0, import_react72.useState)(props.value); - const saveValue = (key2, val) => { - setValue({ ...value, [key2]: val }); - props.saveValue(key2, val); - }; - const stackedProperty = (field) => { - return field.type.startsWith("object") || field.type == "super"; - }; - return /* @__PURE__ */ import_react72.default.createElement("div", { - className: "mk-cell-object" - }, props.command.fields.map((field, i4) => { - const isStacked = stackedProperty(field); - return /* @__PURE__ */ import_react72.default.createElement(DataPropertyView, { - key: i4, - superstate: props.superstate, - initialValue: !field.type.startsWith("object") ? removeQuotes(value?.[field.name]) : value?.[field.name], - compactMode: false, - updateFieldValue: (fv, f2) => { - saveValue( - field.name, - !field.type.startsWith("object") ? wrapQuotes(f2) : f2 - ); - }, - updateValue: (value2) => { - saveValue( - field.name, - !field.type.startsWith("object") ? wrapQuotes(value2) : value2 - ); - }, - column: { ...field, table: "" }, - editMode: 5 /* EditModeAlways */, - columns: props.command.fields - }); })); }; - -// src/core/react/components/SpaceView/Contexts/DataTypeView/SuperCell.tsx -var SuperCell = (props) => { - const command = (0, import_react73.useMemo)(() => { - const parsedValue = parseFieldValue( - props.propertyValue, - "super", - props.superstate - ); - const superPropertyName = parsedValue.dynamic ? props.row?.[parsedValue.field] : parsedValue.field; - return props.superstate.cli.commandForAction(superPropertyName); - }, [props.propertyValue, props.row]); - const parseValue = (value2) => { - if (!value2) - return null; - let parsedValue; - try { - parsedValue = JSON.parse(value2); - parsedValue = Object.keys(parsedValue).reduce((p, c3) => { - if (typeof parsedValue[c3] === "object") { - return { ...p, [c3]: JSON.stringify(parsedValue[c3]) }; - } - if (typeof parsedValue[c3] === "string") { - return { ...p, [c3]: wrapQuotes(parsedValue[c3]) }; - } - return { ...p, [c3]: parsedValue[c3] }; - }, {}); - } catch (e5) { - console.log(e5); - return null; - } - return parsedValue; - }; - const [value, setValue] = (0, import_react73.useState)( - parseValue(unwrapParanthesis(props.initialValue)) - ); - (0, import_react73.useEffect)(() => { - setValue(parseValue(unwrapParanthesis(props.initialValue))); - }, [props.initialValue]); - const specialStringify = (obj) => { - return `{${Object.keys(obj ?? {}).map((key2) => `"${key2}": ${obj[key2]}`).join(",")}}`; - }; - const saveValue = (key2, val) => { - setValue({ ...value, [key2]: val }); - const newValue = wrapParanthesis( - specialStringify({ ...value, [key2]: val }) - ); - props.saveValue(newValue); - }; - const editParameters = (e5) => { - const rect = e5.currentTarget.getBoundingClientRect(); - const _props = { - superstate: props.superstate, - command, - value, - saveValue - }; - props.superstate.ui.openCustomMenu( - rect, - /* @__PURE__ */ import_react73.default.createElement(ParameterSetter, { - ..._props - }), - _props, - "bottom" - ); - }; - return /* @__PURE__ */ import_react73.default.createElement(import_react73.default.Fragment, null, command && (props.compactMode ? /* @__PURE__ */ import_react73.default.createElement("div", { - className: "mk-cell-super", - onClick: (e5) => editParameters(e5) - }, "Edit Parameters") : /* @__PURE__ */ import_react73.default.createElement(ParameterSetter, { - superstate: props.superstate, - command, - value, - saveValue - }))); -}; - -// src/core/react/components/SpaceView/Contexts/DataTypeView/TagCell.tsx -var import_react74 = __toESM(require_react()); -var TagCell = (props) => { - const [value, setValue] = (0, import_react74.useState)([]); - (0, import_react74.useEffect)(() => { - setValue([...props.superstate.tagsMap.get(props.path) ?? []]); - }, []); - (0, import_react74.useEffect)(() => { - const updateValue2 = (payload) => { - if (payload.path == props.path) - setValue([...props.superstate.tagsMap.get(props.path) ?? []]); - }; - props.superstate.eventsDispatcher.addListener( - "pathStateUpdated", - updateValue2 - ); - return () => { - props.superstate.eventsDispatcher.removeListener( - "pathStateUpdated", - updateValue2 - ); - }; - }, [props.path]); - const removeValue = (v2) => { - deleteTagFromPath(props.superstate, props.path, v2); - }; - const saveOptions = (_options, _value) => { - const newValue = _value[0]; - addTagToPath(props.superstate, props.path, newValue); - }; - const menuProps = () => { - const options = props.superstate.spaceManager.readTags().map((f2) => ({ - name: f2, - value: f2 - })); - return { - ui: props.superstate.ui, - multi: false, - editable: true, - value, - options, - saveOptions, - placeholder: i18n_default.labels.tagItemSelectPlaceholder, - searchable: true, - showAll: true, - onHide: () => props.setEditMode(null) - }; - }; - return /* @__PURE__ */ import_react74.default.createElement(OptionCellBase, { - superstate: props.superstate, - baseClass: "mk-cell-tags", - removeValue, - menuProps, - selectLabel: props.compactMode ? props.property.name : i18n_default.labels.select, +var SelectMenuInput = (props) => { + const [value, setValue] = (0, import_react77.useState)(props.value); + return /* @__PURE__ */ import_react77.default.createElement("input", { + type: "text", value, - multi: true, - editMode: props.editMode, - labelElement: (_props) => /* @__PURE__ */ import_react74.default.createElement("div", { - className: "mk-cell-tags-label" - }, _props.value, _props.children) - }); -}; - -// src/core/react/components/SpaceView/Contexts/DataTypeView/TextCell.tsx -var import_react75 = __toESM(require_react()); -var TextCell = (props) => { - const { initialValue, saveValue } = props; - const ref2 = (0, import_react75.useRef)(null); - const onBlur = (e5) => { - const value = e5.currentTarget.innerText; - if (initialValue != value) - saveValue(value); - }; - const onKeyDown = (e5) => { - e5.stopPropagation(); - if (e5.key == "Enter") { - if (!e5.shiftKey) { - e5.target.blur(); - props.setEditMode(null); - } - } - if (e5.key == "Escape") { - ref2.current.innerText = initialValue; - e5.target.blur(); - props.setEditMode(null); - } - }; - (0, import_react75.useEffect)(() => { - if (props.editMode == 4 /* EditModeActive */) { - if (ref2?.current) { - const sel = window.getSelection(); - sel.selectAllChildren(ref2.current); - sel.collapseToEnd(); + onKeyDown: (e5) => { + if (e5.key == "Enter") { + props.setValue(value); } - } - }, [props.editMode]); - return props.editMode > 2 /* EditModeView */ ? /* @__PURE__ */ import_react75.default.createElement("div", { + }, + onMouseDown: (e5) => e5.stopPropagation(), onClick: (e5) => e5.stopPropagation(), - className: "mk-cell-text", - ref: ref2, - "data-ph": props.compactMode ? props.property.name : "Empty", - onKeyDown, - onBlur, - contentEditable: true, - dangerouslySetInnerHTML: { __html: initialValue } - }) : /* @__PURE__ */ import_react75.default.createElement("div", { - className: "mk-cell-text" - }, initialValue); -}; - -// src/core/react/components/SpaceView/Contexts/DataTypeView/DataTypeView.tsx -var DataTypeView = (props) => { - const { initialValue, column: column2, row: row2 } = props; - const saveValue = (value) => { - props.updateValue(value); - }; - const saveFieldValue = (fieldValue, value) => { - if (props.editMode > 0 /* EditModeReadOnly */ && props.updateFieldValue) { - props.updateFieldValue(fieldValue, value); - } else { - props.updateValue(value); - } - }; - const viewProps = { - initialValue, - saveValue, - editMode: props.editMode, - setEditMode: props.setEditMode ?? (() => { - }), - superstate: props.superstate, - propertyValue: column2.value, - path: props.source ?? row2?.[PathPropertyName], - property: column2, - compactMode: props.compactMode - }; - const fieldType = fieldTypeForType(column2.type, column2.name); - if (!fieldType) { - return /* @__PURE__ */ import_react76.default.createElement(import_react76.default.Fragment, null); - } - if (fieldType.type == "file") { - if (props.compactMode) { - return /* @__PURE__ */ import_react76.default.createElement(LinkCell, { - ...viewProps, - multi: false, - source: props.source - }); - } - return /* @__PURE__ */ import_react76.default.createElement(PathCell, { - ...viewProps, - multi: fieldType.multiType == column2.type - }); - } else if (fieldType.type == "icon") { - return /* @__PURE__ */ import_react76.default.createElement(IconCell, { - ...viewProps, - multi: fieldType.multiType == column2.type - }); - } else if (fieldType.type == "boolean") { - return /* @__PURE__ */ import_react76.default.createElement(BooleanCell, { - ...viewProps, - column: column2 - }); - } else if (fieldType.type == "option") { - return /* @__PURE__ */ import_react76.default.createElement(OptionCell, { - ...viewProps, - multi: fieldType.multiType == column2.type, - saveOptions: saveFieldValue, - source: props.source - }); - } else if (fieldType.type == "date") { - return /* @__PURE__ */ import_react76.default.createElement(DateCell, { - ...viewProps - }); - } else if (fieldType.type == "context") { - return /* @__PURE__ */ import_react76.default.createElement(ContextCell, { - ...viewProps, - multi: fieldType.multiType == column2.type, - source: props.source - }); - } else if (fieldType.type == "fileprop") { - return /* @__PURE__ */ import_react76.default.createElement(LookUpCell, { - ...viewProps, - row: props.row, - columns: props.columns, - saveOptions: saveFieldValue - }); - } else if (fieldType.type == "number") { - return /* @__PURE__ */ import_react76.default.createElement(NumberCell, { - ...viewProps - }); - } else if (fieldType.type == "link") { - return /* @__PURE__ */ import_react76.default.createElement(LinkCell, { - ...viewProps, - multi: fieldType.multiType == column2.type, - source: props.source - }); - } else if (fieldType.type == "tags-multi") { - return /* @__PURE__ */ import_react76.default.createElement(TagCell, { - ...viewProps - }); - } else if (fieldType.type == "image") { - return /* @__PURE__ */ import_react76.default.createElement(ImageCell, { - ...viewProps, - multi: fieldType.multiType == column2.type - }); - } else if (fieldType.type == "object") { - return /* @__PURE__ */ import_react76.default.createElement(ObjectCell, { - ...viewProps, - multi: fieldType.multiType == column2.type, - savePropValue: saveFieldValue, - columns: props.columns, - row: props.row, - compactMode: props.compactMode - }); - } else if (fieldType.type == "color") { - return /* @__PURE__ */ import_react76.default.createElement(ColorCell, { - ...viewProps - }); - } else if (fieldType.type == "space") { - return /* @__PURE__ */ import_react76.default.createElement(SpaceCell, { - ...viewProps, - isTable: false - }); - } else if (fieldType.type == "table") { - return /* @__PURE__ */ import_react76.default.createElement(SpaceCell, { - ...viewProps, - isTable: true - }); - } else if (fieldType.type == "super") { - return /* @__PURE__ */ import_react76.default.createElement(SuperCell, { - ...viewProps, - row: row2, - columns: props.columns, - compactMode: props.compactMode, - source: props.source - }); - } else if (fieldType.type == "input") { - return /* @__PURE__ */ import_react76.default.createElement(PropertySelectCell, { - ...viewProps, - columns: props.columns - }); - } - return /* @__PURE__ */ import_react76.default.createElement(TextCell, { - ...viewProps + onFocus: (e5) => { + e5.stopPropagation(); + }, + onChange: (e5) => setValue(e5.target.value), + onBlur: (e5) => props.setValue(value) }); }; - -// src/core/react/components/SpaceView/Contexts/TableView/TableView.tsx -var TableView = (props) => { - const { - spaceInfo, - readMode, - spaceState: spaceCache - } = (0, import_react77.useContext)(SpaceContext); - const { - tableData, - dbSchema, - contextTable, - saveDB, - selectedRows, - selectRows, - sortedColumns: cols, - filteredData: data2, - predicate, - savePredicate, - updateFieldValue, - updateValue: updateValue2 - } = (0, import_react77.useContext)(ContextEditorContext); - const [pagination, setPagination] = import_react77.default.useState({ - pageIndex: 0, - pageSize: 10 +var SelectMenuSuggestions = (props) => { + const options = props.options.map((item, index2) => { + const key2 = `${props.id}-${index2}`; + const className = item.type == -1 /* Separator */ ? "mk-menu-separator" : item.type == 2 /* Input */ ? "mk-menu-input" : item.type == 5 /* Custom */ ? "mk-menu-custom" : `mk-menu-option ${props.index === index2 && props.classNames.suggestionActive} ${item.disabled && props.classNames.suggestionDisabled}`; + return /* @__PURE__ */ import_react77.default.createElement("div", { + ref: (ref2) => { + if (props.refs?.current) + props.refs.current[index2] = ref2; + }, + onMouseDown: (e5) => { + if (!props.isDisclosureMenu) + e5.stopPropagation(); + e5.preventDefault(); + }, + onClick: (e5) => { + if (item.onSubmenu && props.openSubmenu) { + const el = props.refs?.current[index2].getBoundingClientRect(); + props.openSubmenu(item.onSubmenu(el)); + } else if (item.onClick) { + item.onClick(e5); + if (item.type != 6 /* Submenu */ && item.type != 1 /* Disclosure */) { + props.hide(); + } + } else { + if (item.type == null || item.type == 0 /* Option */ || item.type == 1 /* Disclosure */) { + props.selectOption(item, { + ctrlKey: e5.ctrlKey, + metaKey: e5.metaKey, + altKey: e5.altKey, + shiftKey: e5.shiftKey, + doubleClick: e5.detail == 2 + }); + if (!props.isDisclosureMenu) + e5.stopPropagation(); + } + } + }, + id: key2, + key: key2, + className + }, item.type == -1 /* Separator */ ? /* @__PURE__ */ import_react77.default.createElement(import_react77.default.Fragment, null) : item.type == -2 /* Section */ ? /* @__PURE__ */ import_react77.default.createElement("div", { + className: "mk-menu-options-section" + }, item.name) : item.type == 2 /* Input */ ? /* @__PURE__ */ import_react77.default.createElement(SelectMenuInput, { + value: item.value, + setValue: item.onValueChange + }) : item.type == 5 /* Custom */ ? /* @__PURE__ */ import_react77.default.createElement(item.fragment, { + hide: props.hide + }) : /* @__PURE__ */ import_react77.default.createElement(SelectMenuSuggestionsComponent, { + ui: props.ui, + item, + query: props.query, + active: index2 == props.index, + onMoreOption: props.moreOption, + onDeleteOption: props.deleteOption + })); }); - const [activeId, setActiveId] = (0, import_react77.useState)(null); - const [lastSelectedIndex, setLastSelectedIndex] = (0, import_react77.useState)(null); - const [selectedColumn, setSelectedColumn] = (0, import_react77.useState)(null); - const [currentEdit, setCurrentEdit] = (0, import_react77.useState)(null); - const [overId, setOverId] = (0, import_react77.useState)(null); - const [openFlows, setOpenFlows] = (0, import_react77.useState)([]); - const [colsSize, setColsSize] = (0, import_react77.useState)({}); - const ref2 = (0, import_react77.useRef)(null); - const primaryCol = cols.find((f2) => f2.primary == "true"); - (0, import_react77.useEffect)(() => { - setColsSize({ ...predicate?.colsSize ?? {}, "+": 30 }); - }, [predicate]); - (0, import_react77.useEffect)(() => { - setCurrentEdit(null); - }, [selectedColumn, lastSelectedIndex]); - const saveColsSize = (colSize) => { - const newColSize = colSize(colsSize); - setColsSize(newColSize); - debouncedSavePredicate(newColSize); - }; - const debouncedSavePredicate = (0, import_react77.useCallback)( - (0, import_lodash12.debounce)( - (nextValue) => savePredicate({ - colsSize: nextValue - }), - 1e3 - ), - [predicate] - ); - const newRow = (name317, index2, data3) => { - if (dbSchema?.id == defaultContextSchemaID) { - newPathInSpace(props.superstate, spaceCache, "md", name317, true); - } else { - saveDB( - createNewRow( - tableData, - primaryCol ? { [primaryCol.name]: name317 ?? "", ...data3 ?? {} } : data3 ?? {}, - index2 - ) - ); - } - }; - const deleteRow = (rowIndex) => { - const row2 = tableData.rows.find((f2, i4) => i4 == rowIndex); - if (row2) { - if (dbSchema.primary == "true") - deletePath(props.superstate, row2[PathPropertyName]); - saveDB({ - ...tableData, - rows: tableData.rows.filter((f2, i4) => i4 != rowIndex) - }); - } - }; - const toggleFlow = (path2) => { - setOpenFlows( - (f2) => f2.find((p) => p == path2) ? f2.filter((p) => p != path2) : uniq([...f2, path2]) - ); - }; - const selectItem = (modifier, index2) => { - if (modifier.metaKey) { - props.superstate.ui.openPath( - tableData.rows[parseInt(index2)][PathPropertyName], - false - ); - return; + return /* @__PURE__ */ import_react77.default.createElement("div", { + className: "mk-menu-suggestions" + }, options, props.query && props.allowNew && /* @__PURE__ */ import_react77.default.createElement("div", { + className: "mk-menu-option", + onMouseDown: (e5) => e5.preventDefault(), + onClick: (e5) => props.selectOption( + { name: props.query, value: props.query }, + { + ctrlKey: e5.ctrlKey, + metaKey: e5.metaKey, + altKey: e5.altKey, + shiftKey: e5.shiftKey + } + ) + }, /* @__PURE__ */ import_react77.default.createElement("div", { + className: "mk-sticker", + dangerouslySetInnerHTML: { + __html: props.ui.getSticker("ui//plus") } - if (modifier.ctrlKey) { - selectedRows.some((f2) => f2 == index2) ? selectRows( - null, - selectedRows.filter((f2) => f2 != index2) - ) : selectRows(index2, uniq([...selectedRows, index2])); - } else if (modifier.shiftKey) { - selectRows( - index2, - uniq([ - ...selectedRows, - ...selectRange( - lastSelectedIndex, - index2, - data2.map((f2) => f2._index) - ) - ]) - ); + }), /* @__PURE__ */ import_react77.default.createElement("div", { + className: "mk-menu-options-inner" + }, props.addKeyword ?? "Add", " ", props.query))); +}; +var SelectMenuSuggestions_default = SelectMenuSuggestions; + +// src/core/react/components/UI/Menus/menu/concerns/focusNextElement.js +function focusNextElement(scope, currentTarget) { + const interactiveEls = scope.querySelectorAll("a,button,input"); + const currentEl = Array.prototype.findIndex.call( + interactiveEls, + (element) => element === currentTarget + ); + const nextEl = interactiveEls[currentEl - 1] || interactiveEls[currentEl + 1]; + if (nextEl) { + nextEl.focus(); + } +} + +// src/core/react/components/UI/Menus/menu/SelectMenuComponent.tsx +var KEYS = { + ENTER: "Enter", + TAB: "Tab", + BACKSPACE: "Backspace", + UP_ARROW: "ArrowUp", + UP_ARROW_COMPAT: "Up", + DOWN_ARROW: "ArrowDown", + DOWN_ARROW_COMPAT: "Down" +}; +var CLASS_NAMES = { + root: "mk-menu-container", + rootFocused: "mk-focused", + selected: "mk-menu-input-wrapper", + selectedTagWrapper: "mk-menu-selected-tag-wrapper", + selectedTag: "mk-menu-selected-tag", + selectedTagName: "mk-menu-selected-tag-name", + search: "mk-menu-search", + searchWrapper: "mk-menu-search-container", + searchInput: "mk-menu-search-input", + suggestions: "mk-menu-suggestions", + suggestionActive: "mk-active", + suggestionDisabled: "mk-disabled" +}; +var defaultProps = { + ui: null, + id: "SelectMenu", + tags: [], + hide: () => null, + suggestionsOnly: false, + placeholderText: i18n_default.labels.optionItemSelectPlaceholder, + noSuggestionsText: null, + newTagText: null, + suggestions: [], + suggestionsFilter: defaultSuggestionsFilter, + suggestionsTransform: null, + classNames: CLASS_NAMES, + delimiters: [KEYS.ENTER], + minQueryLength: 2, + maxSuggestionsLength: 8, + inputAttributes: {} +}; +var findMatchIndex = (options, query) => { + return options.findIndex((option) => matchExact(query).test(option.name)); +}; +var pressDelimiter = (props, query, index2, options, addTag2, modifiers) => { + if (query.length >= props.minQueryLength) { + const match2 = findMatchIndex(options, query); + const _index = index2 === -1 ? match2 : index2; + const tag2 = _index > -1 ? options[_index] : null; + if (tag2) { + addTag2(tag2, modifiers); } else { - selectRows(index2, [index2]); + addTag2({ name: query, value: query }, modifiers); } - setLastSelectedIndex(index2); + } +}; +function defaultSuggestionsFilter(item, query) { + const regexp = matchAny(query); + return regexp.test(item.name); +} +function getOptions2(props, query, section) { + let options; + let suggestions = props.suggestions; + if (section.length > 0) { + suggestions = props.suggestions.filter((f2) => f2.section == section); + } + const fuseOptions = { + threshold: 0, + ignoreLocation: true, + keys: ["name", "value"] }; - const onKeyDown = (e5) => { - const setCellValue = (value) => { - if (selectedColumn) { - const columnTuple = selectedColumn.split("#"); - updateValue2( - columnTuple[0], - value, - columnTuple[1] ?? "", - parseInt(lastSelectedIndex), - "" - ); + const fuse = new Fuse(suggestions, fuseOptions); + options = query.length == 0 ? suggestions : fuse.search(query).map((result) => result.item); + options = options.slice(0, props.maxSuggestionsLength); + if (props.newTagText && findMatchIndex(options, query) === -1) { + options.push({ id: 0, name: query, value: query }); + } else if (props.noSuggestionsText && options.length === 0) { + options.push({ + id: 0, + name: props.noSuggestionsText, + value: "", + disabled: true + }); + } + return options; +} +var SelectMenuComponent = import_react78.default.forwardRef( + (_props, ref2) => { + const props = { ...defaultProps, ..._props }; + const [options, setOptions] = (0, import_react78.useState)([]); + const refs = (0, import_react78.useRef)([]); + const sections = (0, import_react78.useMemo)(() => { + if (!props.showSections) + return []; + return [ + { + name: "All", + value: "" + }, + ...props.sections ?? uniq(props.suggestions.map((f2) => f2.section)).filter((f2) => f2) + ]; + }, [props.showSections, props.sections, props.suggestions]); + const inputRef = (0, import_react78.useRef)(null); + const [section, setSection] = (0, import_react78.useState)(""); + const [query, setQuery] = (0, import_react78.useState)(""); + const [focused, setFocused] = (0, import_react78.useState)(false); + const [index2, setIndex] = (0, import_react78.useState)(0); + const onComposition = (0, import_react78.useRef)(false); + (0, import_react78.useEffect)(() => { + if (ref2) { + ref2.current = () => { + if (!focused) { + inputRef?.current?.focus(); + setFocused(true); + return false; + } + return true; + }; + } + }, [focused]); + (0, import_react78.useEffect)(() => { + if (query.length == 0 && props.defaultSuggestions) { + setOptions(props.defaultSuggestions); + return; + } + setOptions(getOptions2(props, query, section)); + }, [query, props.defaultSuggestions, section, props.suggestions]); + const container = (0, import_react78.useRef)(null); + const onInput = (e5) => { + if (e5.type === "compositionstart") { + onComposition.current = true; + return; + } + if (e5.type === "compositionend") { + onComposition.current = false; + } + if (onComposition.current) { + return; + } + const _query = e5.target.value; + if (props.onInput) { + props.onInput(_query); + } + if (_query.length === query.length + 1 && props.delimiters.indexOf(query.slice(-1)) > -1) { + pressDelimiter(props, query, index2, options, addTag2, {}); + } else if (_query !== query) { + setQuery(_query); } }; - const clearCell = () => { - setCellValue(""); + const onKeyDown = (e5) => { + if (props.delimiters.indexOf(e5.key) > -1) { + if (query || index2 > -1) { + e5.preventDefault(); + } + pressDelimiter(props, query, index2, options, addTag2, { + ctrlKey: e5.ctrlKey, + metaKey: e5.metaKey, + altKey: e5.altKey, + shiftKey: e5.shiftKey + }); + } + if (e5.key == "Escape") { + return; + } + if (e5.key === KEYS.TAB) { + pressTabKey(e5); + } + if (e5.key === KEYS.BACKSPACE) { + pressBackspaceKey(); + } + if (e5.key === KEYS.UP_ARROW || e5.key === KEYS.UP_ARROW_COMPAT) { + pressUpKey(e5); + } + if (e5.key === KEYS.DOWN_ARROW || e5.key === KEYS.DOWN_ARROW_COMPAT) { + pressDownKey(e5); + } + e5.stopPropagation(); }; - const copyCell = () => { - navigator.clipboard.writeText( - tableData.rows[parseInt(lastSelectedIndex)][selectedColumn] - ); + const onBlur = () => { + setFocused(false); + if (props.onBlur) { + props.onBlur(); + } }; - const nextRow = () => { - const newIndex = selectNextIndex( - lastSelectedIndex, - data2.map((f2) => f2._index) - ); - selectRows(newIndex, [newIndex]); - setLastSelectedIndex(newIndex); + const onFocus = () => { + setFocused(true); + if (props.onFocus) { + props.onFocus(); + } }; - const lastRow = () => { - const newIndex = selectPrevIndex( - lastSelectedIndex, - data2.map((f2) => f2._index) - ); - selectRows(newIndex, [newIndex]); - setLastSelectedIndex(newIndex); + const onDeleteTag = (index3, event) => { + if (container.current) { + focusNextElement(container.current, event.currentTarget); + } + deleteTag(index3); }; - if (e5.key == "c" && e5.metaKey) { - copyCell(); - } - if (e5.key == "x" && e5.metaKey) { - copyCell(); - clearCell(); - } - if (e5.key == "v" && e5.metaKey) { - navigator.clipboard.readText().then((f2) => setCellValue(f2)); - } - if (e5.key == "Escape") { - selectRows(null, []); - setLastSelectedIndex(null); - } - if (e5.key == "Backspace" || e5.key == "Delete") { - clearCell(); - } - if (e5.key == "Enter") { - if (selectedColumn && lastSelectedIndex) { - if (e5.shiftKey) { - newRow("", parseInt(lastSelectedIndex) + 1); - nextRow(); - } else { - setCurrentEdit([selectedColumn, lastSelectedIndex]); - e5.preventDefault(); - e5.stopPropagation(); - } + const addTag2 = (tag2, modifiers) => { + if (tag2.disabled) { + return; } - return; - } - if (e5.key == "ArrowDown") { - nextRow(); + if (props.onValidate && !props.onValidate(tag2)) { + return; + } + props.onAddition(tag2, modifiers); + clearInput(); + }; + const deleteTag = (i4) => { + props.onDelete(i4); + }; + const clearInput = () => { + setQuery(""); + setIndex(-1); + }; + const clearSelectedIndex = () => { + setIndex(-1); + }; + const pressUpKey = (e5) => { e5.preventDefault(); - } - if (e5.key == "ArrowUp") { - lastRow(); + const size2 = options.length - 1; + const newIndex = index2 <= 0 ? size2 : index2 - 1; + if (options[newIndex].disabled) { + setIndex(newIndex <= 0 ? size2 : newIndex - 1); + } else { + setIndex(newIndex); + } + }; + const pressDownKey = (e5) => { e5.preventDefault(); + const size2 = options.length - 1; + const newIndex = index2 >= size2 ? 0 : index2 + 1; + if (options[newIndex].disabled) { + setIndex(newIndex >= size2 ? 0 : newIndex + 1); + } else { + setIndex(newIndex); + } + }; + function pressBackspaceKey() { + if (!query.length) { + deleteTag(props.tags.length - 1); + } } - if (e5.key == "ArrowLeft") { - const newIndex = selectPrevIndex( - selectedColumn, - columns.map((f2) => f2.accessorKey).filter((f2) => f2 != "+") - ); - setSelectedColumn(newIndex); - } - if (e5.key == "ArrowRight") { - const newIndex = selectNextIndex( - selectedColumn, - columns.map((f2) => f2.accessorKey).filter((f2) => f2 != "+") - ); - setSelectedColumn(newIndex); - } - }; - const columns = (0, import_react77.useMemo)( - () => [ - ...cols.map((f2) => { - return { - header: f2.name, - accessorKey: f2.name + f2.table, - meta: { - table: f2.table, - editable: f2.name != PathPropertyName, - schemaId: dbSchema?.id - }, - cell: ({ - getValue, - row: { index: index2 }, - column: { colId }, - cell, - table: table2 - }) => { - const initialValue = getValue(); - const rowIndex = parseInt(data2[index2]["_index"]); - const tableIndex = parseInt(data2[index2]["_index"]); - const saveValue = (value) => { - setCurrentEdit(null); - if (initialValue != value) - table2.options.meta?.updateData( - f2.name, - value, - f2.table, - rowIndex - ); - }; - const saveFieldValue = (fieldValue, value) => { - table2.options.meta?.updateFieldValue( - f2.name, - fieldValue, - value, - f2.table, - rowIndex - ); - }; - const editMode = readMode ? 0 /* EditModeReadOnly */ : !cell.getIsGrouped() ? isTouchScreen(props.superstate.ui) ? 5 /* EditModeAlways */ : currentEdit && currentEdit[0] == f2.name + f2.table && currentEdit[1] == tableIndex.toString() ? 4 /* EditModeActive */ : 2 /* EditModeView */ : 0 /* EditModeReadOnly */; - const cellProps = { - compactMode: true, - initialValue, - updateValue: saveValue, - updateFieldValue: saveFieldValue, - superstate: props.superstate, - setEditMode: setCurrentEdit, - column: f2, - editMode, - row: data2[index2], - contextTable, - source: data2[index2][PathPropertyName] - }; - const fieldType = fieldTypeForType(f2.type, f2.name); - if (!fieldType) { - return /* @__PURE__ */ import_react77.default.createElement(import_react77.default.Fragment, null, initialValue); + function pressTabKey(e5) { + if (props.showSections) { + e5.preventDefault(); + e5.stopPropagation(); + setSection((p) => { + const sectionIndex = sections.findIndex((g) => g.value == p); + if (e5.shiftKey) { + if (sectionIndex == 0) { + return p; } - return /* @__PURE__ */ import_react77.default.createElement(DataTypeView, { - ...cellProps - }); + if (props.onSelectSection) { + props.onSelectSection(sections[sectionIndex - 1].value); + } + return sections[sectionIndex - 1].value; } - }; - }) ?? [], - ...readMode ? [] : [ - { - header: "+", - meta: { schemaId: dbSchema?.id }, - accessorKey: "+", - size: 20, - cell: () => /* @__PURE__ */ import_react77.default.createElement(import_react77.default.Fragment, null) - } - ] - ], - [cols, data2, currentEdit, predicate, dbSchema, contextTable] - ); - const groupBy2 = (0, import_react77.useMemo)( - () => predicate?.groupBy?.length > 0 && cols.find((f2) => f2.name + f2.table == predicate.groupBy[0]) ? predicate.groupBy : [], - [predicate, cols] - ); - const table = useReactTable({ - data: data2, - columns, - columnResizeMode: "onChange", - state: { - columnVisibility: predicate?.colsHidden.reduce( - (p, c3) => ({ ...p, [c3]: false }), - {} - ), - columnOrder: predicate?.colsOrder, - columnSizing: { - ...columns.reduce((p, c3) => ({ ...p, [c3.accessorKey]: 150 }), {}), - ...colsSize - }, - grouping: groupBy2, - expanded: true, - pagination - }, - onColumnSizingChange: saveColsSize, - getCoreRowModel: getCoreRowModel(), - getExpandedRowModel: getExpandedRowModel(), - getGroupedRowModel: getGroupedRowModel(), - getPaginationRowModel: getPaginationRowModel(), - onPaginationChange: setPagination, - meta: { - updateData: updateValue2, - updateFieldValue - } - }); - const sensors = useSensors( - useSensor(MouseSensor, { - activationConstraint: { - distance: 10 - } - }), - useSensor(TouchSensor, { - activationConstraint: { - delay: 250, - tolerance: 5 + if (sectionIndex == sections.length - 1) { + return p; + } + if (props.onSelectSection) { + props.onSelectSection(sections[sectionIndex + 1].value); + } + return sections[sectionIndex + 1].value; + }); } - }) - ); - const measuring = { - droppable: { - strategy: MeasuringStrategy.Always } - }; - function handleDragStart(event) { - const { - active: { id: activeId2 } - } = event; - setActiveId(activeId2); - setOverId(overId); - document.body.style.setProperty("cursor", "grabbing"); - } - function handleDragOver({ over }) { - const overId2 = over?.id; - if (overId2) { - setOverId(over?.id ?? null); + const focusInput = () => { + inputRef.current.focus(); + }; + const inputEventHandlers = { + onChange: onInput, + onBlur, + onFocus, + onInput: () => { + }, + onKeyDown, + onCompositionEnd: onInput, + onCompositionStart: onInput + }; + (0, import_react78.useEffect)(() => { + props.ui.inputManager.on("keydown", onKeyDown); + return () => { + props.ui.inputManager.off("keydown", onKeyDown); + }; + }, [options, index2]); + const expanded = focused && query.length >= props.minQueryLength; + const classNames13 = Object.assign({}, CLASS_NAMES, props.classNames); + if (props.wrapperClass) { + classNames13.root = `${classNames13.root} ${props.wrapperClass}`; } + const rootClassNames = [classNames13.root]; + focused && rootClassNames.push(classNames13.rootFocused); + const submenuRef = (0, import_react78.useRef)(null); + const openSubmenu = (menu) => { + if (submenuRef.current) { + submenuRef.current.hide(); + } + submenuRef.current = menu; + }; + return /* @__PURE__ */ import_react78.default.createElement("div", { + ref: container, + className: rootClassNames.join(" "), + style: !props.suggestionsOnly ? { + "--mk-menu-max-height": "200px" + } : {} + }, !props.suggestionsOnly ? /* @__PURE__ */ import_react78.default.createElement("div", { + className: classNames13.selected, + "aria-relevant": "additions removals", + "aria-live": "polite" + }, props.tags.length > 0 && /* @__PURE__ */ import_react78.default.createElement("div", { + className: classNames13.selectedTagWrapper + }, props.tags.map((tag2, i4) => /* @__PURE__ */ import_react78.default.createElement(SelectMenuPill_default, { + key: i4, + tag: tag2, + classNames: classNames13, + onDelete: (e5) => onDeleteTag(i4, e5) + }))), /* @__PURE__ */ import_react78.default.createElement("div", { + className: classNames13.search + }, /* @__PURE__ */ import_react78.default.createElement(SelectMenuInput_default, { + ui: props.ui, + ref: inputRef, + query, + index: index2, + id: props.id, + classNames: classNames13, + inputAttributes: props.inputAttributes, + inputEventHandlers, + expanded, + placeholderText: props.placeholderText + }))) : null, props.showSections ? /* @__PURE__ */ import_react78.default.createElement("div", { + className: "mk-menu-sections" + }, sections.map((f2, i4) => /* @__PURE__ */ import_react78.default.createElement("div", { + key: i4, + onClick: (e5) => { + e5.stopPropagation(); + setSection(f2.value); + }, + className: `${section == f2.value ? "is-active" : ""} mk-menu-section` + }, f2.name == "" ? i18n_default.labels.all : f2.name))) : /* @__PURE__ */ import_react78.default.createElement(import_react78.default.Fragment, null), options.length || props.allowNew ? /* @__PURE__ */ import_react78.default.createElement(SelectMenuSuggestions_default, { + ui: props.ui, + hide: () => { + props.hide(); + }, + addKeyword: props.addKeyword, + refs, + options, + query, + setIndex, + index: index2, + id: props.id, + classNames: classNames13, + expanded, + selectOption: addTag2, + allowNew: props.allowNew, + moreOption: props.onMoreOption, + deleteOption: props.onDeleteOption, + isDisclosureMenu: props.isDisclosure, + openSubmenu + }) : null, props.previewComponent); } - const saveFilter = (filter4) => { - savePredicate({ - filters: [ - ...(predicate?.filters ?? []).filter((s4) => s4.field != filter4.field), - filter4 - ] +); +SelectMenuComponent.displayName = "SelectMenuComponent"; +var SelectMenuComponent_default = SelectMenuComponent; + +// src/core/react/components/UI/Menus/menu/SelectMenu.tsx +var SelectMenu = import_react79.default.forwardRef( + (props, ref2) => { + const initialOptions = props.options.map((o2, i4) => { + return { + ...o2, + id: i4 + 1 + }; }); - }; - const selectCell = (e5, index2, column2) => { - if (isTouchScreen(props.superstate.ui) || column2 == "+") - return; - selectItem( - { - ctrlKey: e5.ctrlKey, - metaKey: e5.metaKey, - altKey: e5.altKey, - shiftKey: e5.shiftKey - }, - data2[index2]["_index"] + (0, import_react79.useEffect)(() => { + setSuggestions( + props.options.map((o2, i4) => { + return { + ...o2, + id: i4 + 1 + }; + }) + ); + }, [props.options]); + const [suggestions, setSuggestions] = (0, import_react79.useState)(initialOptions); + const [tags3, setTags] = (0, import_react79.useState)( + props.value.map( + (v2) => initialOptions.find((f2) => f2.value == v2) ?? { + id: 0, + name: v2, + value: v2 + } + ) ); - setSelectedColumn(column2); - if (e5.detail === 1) { - } else if (e5.detail === 2) { - setCurrentEdit([column2, data2[index2]["_index"]]); - } - }; - const showContextMenu = (e5, index2) => { - e5.preventDefault(); - if (dbSchema.primary == "true") { - const row2 = tableData.rows.find((f2, i4) => i4 == index2); - if (row2) { - if (props.superstate.spacesIndex.has(row2[PathPropertyName])) { - const pathState = props.superstate.pathsIndex.get( - row2[PathPropertyName] + const onDelete = (0, import_react79.useCallback)( + (tagIndex) => { + const newTags = tags3.filter((_15, i4) => i4 !== tagIndex); + setTags(newTags); + if (props.saveOptions) + props.saveOptions( + suggestions.map((f2) => f2.value), + newTags.map((f2) => f2.value), + false ); - if (pathState) - showSpaceContextMenu( - props.superstate, - pathState, - e5, - "", - spaceCache.path - ); - return; + }, + [suggestions, tags3, props] + ); + const onDeleteOption = (0, import_react79.useCallback)( + (removeTag) => { + const newSuggestions = suggestions.filter((f2) => f2.value != removeTag); + const newTags = tags3.filter((f2) => f2.value != removeTag); + setSuggestions(newSuggestions); + setTags(newTags); + if (props.removeOption) + props.removeOption(removeTag); + props.hide(); + }, + [tags3, suggestions, props] + ); + const onAddition = (0, import_react79.useCallback)( + (newTag, modifiers) => { + let tag2 = newTag; + let newSuggestions = suggestions; + let newTags = tags3; + if (!suggestions.find((s4) => s4.value == newTag.value)) { + tag2 = { + id: suggestions.length + 1, + name: newTag.name, + value: newTag.value ?? newTag.name + }; + newSuggestions = [...suggestions, tag2]; + setSuggestions(newSuggestions); } - if (spaceCache) - showPathContextMenu( - props.superstate, - row2[PathPropertyName], - spaceCache.path, - e5.target.getBoundingClientRect() + if (props.multi) { + if (!tags3.find((t5) => t5.value == tag2.value)) { + newTags = [...tags3, tag2]; + setTags(newTags); + } + } else { + newTags = [tag2]; + setTags(newTags); + } + if (props.saveOptions) + props.saveOptions( + newSuggestions.map((f2) => f2.value), + newTags.map((f2) => f2.value), + true ); - return; - } - } - const menuOptions = []; - menuOptions.push({ - name: i18n_default.menu.deleteRow, - icon: "ui//trash", - onClick: (e6) => { - deleteRow(index2); - } - }); - props.superstate.ui.openMenu( - e5.target.getBoundingClientRect(), - defaultMenu(props.superstate.ui, menuOptions) + if (!props.multi && newTag.type != 1 /* Disclosure */) { + props.hide(); + } + }, + [tags3, suggestions] ); - }; - function handleDragEnd({ active, over }) { - resetState(); - const currentCols = predicate?.colsOrder ?? []; - savePredicate({ - colsOrder: arrayMove( - currentCols, - currentCols.findIndex((f2) => f2 == activeId), - currentCols.findIndex((f2) => f2 == overId) - ) + const onValidation = (0, import_react79.useCallback)( + (newTag) => { + if (!props.editable && !suggestions.find((s4) => s4.value == newTag.value)) { + return false; + } + if (newTag.name.length == 0) { + return false; + } + return true; + }, + [suggestions] + ); + return /* @__PURE__ */ import_react79.default.createElement(SelectMenuComponent_default, { + tags: props.multi ? tags3 : [], + suggestions, + ui: props.ui, + ref: ref2, + addKeyword: props.addKeyword, + hide: props.hide, + onDelete, + wrapperClass: props.wrapperClass, + onMoreOption: props.onMoreOption, + onDeleteOption, + onAddition, + onValidate: onValidation, + onSelectSection: props.onSelectSection, + defaultSuggestions: props.defaultOptions, + placeholderText: props.placeholder ?? "", + minQueryLength: 0, + onHover: props.onHover, + showSections: props.showSections, + sections: props.sections, + maxSuggestionsLength: props.showAll ? Math.min(50, props.options.length) : 25, + suggestionsOnly: !props.searchable && !props.editable, + allowNew: props.editable, + previewComponent: props.previewComponent, + isDisclosure: props.isDisclosure }); } - function handleDragCancel() { - resetState(); - } - function resetState() { - setOverId(null); - setActiveId(null); - document.body.style.setProperty("cursor", ""); - } - return /* @__PURE__ */ import_react77.default.createElement(DndContext, { - sensors, - collisionDetection: closestCenter, - measuring, - onDragStart: handleDragStart, - onDragOver: handleDragOver, - onDragEnd: handleDragEnd, - onDragCancel: handleDragCancel - }, /* @__PURE__ */ import_react77.default.createElement("div", { - className: "mk-table", - ref: ref2, - tabIndex: 1, - onKeyDown - }, /* @__PURE__ */ import_react77.default.createElement("table", { - ...{} - }, /* @__PURE__ */ import_react77.default.createElement("thead", null, table.getHeaderGroups().map((headerGroup) => /* @__PURE__ */ import_react77.default.createElement("tr", { - key: headerGroup.id - }, /* @__PURE__ */ import_react77.default.createElement("th", null), headerGroup.headers.map((header) => /* @__PURE__ */ import_react77.default.createElement("th", { - className: "mk-th", - key: header.id, - style: { - minWidth: header.column.getIsGrouped() ? "0px" : colsSize[header.column.columnDef.accessorKey] ?? "150px", - maxWidth: header.column.getIsGrouped() ? "0px" : colsSize[header.column.columnDef.accessorKey] ?? "150px" - } - }, header.isPlaceholder ? null : header.column.columnDef.header != "+" ? header.column.getIsGrouped() ? /* @__PURE__ */ import_react77.default.createElement(import_react77.default.Fragment, null) : /* @__PURE__ */ import_react77.default.createElement(ColumnHeader, { - superstate: props.superstate, - editable: header.column.columnDef.meta.editable, - column: cols.find( - (f2) => f2.name == header.column.columnDef.header && f2.table == header.column.columnDef.meta.table - ) - }) : /* @__PURE__ */ import_react77.default.createElement(ColumnHeader, { - superstate: props.superstate, - isNew: true, - editable: true, - column: { - name: "", - schemaId: header.column.columnDef.meta.schemaId, - type: "text", - table: "" - } - }), /* @__PURE__ */ import_react77.default.createElement("div", { - ...{ - onMouseDown: header.getResizeHandler(), - onTouchStart: header.getResizeHandler(), - className: `mk-resizer ${header.column.getIsResizing() ? "isResizing" : ""}` - } - })))))), /* @__PURE__ */ import_react77.default.createElement("tbody", null, table.getRowModel().rows.map((row2) => /* @__PURE__ */ import_react77.default.createElement("tr", { - className: selectedRows?.some( - (f2) => f2 == data2[row2.index]["_index"] - ) ? "mk-active" : void 0, - onContextMenu: (e5) => { - const rowIndex = parseInt( - data2[row2.index]["_index"] - ); - showContextMenu(e5, rowIndex); - }, - key: row2.id - }, /* @__PURE__ */ import_react77.default.createElement("td", null), row2.getVisibleCells().map( - (cell, i4) => cell.getIsGrouped() ? /* @__PURE__ */ import_react77.default.createElement("td", { - key: i4, - className: "mk-td-group", - colSpan: cols.length + (readMode ? 0 : 1) - }, /* @__PURE__ */ import_react77.default.createElement("div", { - ...{ - onClick: row2.getToggleExpandedHandler(), - style: { - display: "flex", - alignItems: "center", - cursor: "normal" - } - } - }, flexRender( - cell.column.columnDef.cell, - cell.getContext() - ), " ", "(", row2.subRows.length, ")")) : cell.getIsAggregated() ? /* @__PURE__ */ import_react77.default.createElement(import_react77.default.Fragment, { - key: i4 - }, flexRender( - cell.column.columnDef.aggregatedCell ?? cell.column.columnDef.cell, - cell.getContext() - )) : /* @__PURE__ */ import_react77.default.createElement("td", { - onClick: (e5) => selectCell( - e5, - cell.row.index, - cell.column.columnDef.accessorKey - ), - className: `${cell.column.columnDef.accessorKey == selectedColumn ? "mk-selected-cell " : ""} mk-td ${cell.getIsPlaceholder() ? "mk-td-empty" : ""}`, - key: cell.id, - style: { - minWidth: cell.getIsPlaceholder() ? "0px" : colsSize[cell.column.columnDef.accessorKey] ?? "50px" - } - }, cell.getIsPlaceholder() ? null : flexRender( - cell.column.columnDef.cell, - cell.getContext() - )) - )))), /* @__PURE__ */ import_react77.default.createElement("tfoot", null, table.getCanNextPage() && /* @__PURE__ */ import_react77.default.createElement("tr", null, /* @__PURE__ */ import_react77.default.createElement("th", { - className: "mk-row-new", - colSpan: cols.length + (readMode ? 1 : 2), - onClick: () => table.setPageSize(pagination.pageSize + 25) - }, "Load More")), !readMode ? /* @__PURE__ */ import_react77.default.createElement("tr", null, /* @__PURE__ */ import_react77.default.createElement("th", { - className: "mk-row-new", - colSpan: cols.length + (readMode ? 1 : 2), - "data-placeholder": i18n_default.hintText.newItem, - onKeyPress: (e5) => { - if (e5.key == "Enter") { - newRow(e5.currentTarget.innerText); - e5.currentTarget.innerText = ""; - e5.currentTarget.blur(); - } - }, - contentEditable: true - })) : /* @__PURE__ */ import_react77.default.createElement(import_react77.default.Fragment, null))), (0, import_react_dom5.createPortal)( - /* @__PURE__ */ import_react77.default.createElement(DragOverlay, { - dropAnimation: null, - zIndex: 1600 - }, activeId ? /* @__PURE__ */ import_react77.default.createElement(ColumnHeader, { - superstate: props.superstate, - editable: false, - column: { - name: activeId, - schemaId: tableData.schema.id, - type: "text", - table: "" - } - }) : null), - document.body - ))); -}; +); +SelectMenu.displayName = "SelectMenu"; +var SelectMenu_default = SelectMenu; -// src/core/react/components/SpaceView/Contexts/DataTypeView/DataPropertyView.tsx -var DataPropertyView = (props) => { - const isObjectType = (0, import_react78.useMemo)( - () => propertyIsObjectType(props.column), - [props.column] - ); - const parsedValue = parseFieldValue( - props.column.value, - props.column.type, - props.superstate - ); - const saveType = (newType, _value) => { - const value = parseObject( - props.initialValue ?? "", - props.column.type == "object-multi" +// src/core/react/components/Explorer/Explorer.tsx +var import_react84 = __toESM(require_react()); + +// src/core/react/components/PathView/NoteView.tsx +var import_react80 = __toESM(require_react()); +var NoteView = (0, import_react80.forwardRef)((props, ref2) => { + const flowRef = (0, import_react80.useRef)(null); + const [existsPas, setExistsPas] = (0, import_react80.useState)(false); + const [loaded, setLoaded] = (0, import_react80.useState)(false); + const loadPath = async (force) => { + const div2 = flowRef.current; + const path2 = props.superstate.spaceManager.uriByString( + props.path, + props.source ); - if (props.column.type == "object-multi") { - props.updateFieldValue( - JSON.stringify({ ...parsedValue, type: newType }), - JSON.stringify(value) - ); + const properties3 = props.properties; + const pathState = props.superstate.pathsIndex.get(path2.path); + const filePath = pathState?.type == "space" ? props.superstate.spacesIndex.get(props.path)?.defPath : pathState?.path; + if (!filePath) { + if (!force) { + setExistsPas(true); + setLoaded(false); + return; + } else { + const parent = props.superstate.spaceManager.parentPathForPath( + path2.path + ); + if (!parent) + return; + const newPath = await props.superstate.spaceManager.createItemAtPath( + parent, + "md", + pathToString(props.path) + ); + setExistsPas(false); + await props.superstate.ui.openPath(newPath, false, div2, properties3); + } } else { - props.updateFieldValue( - JSON.stringify({ ...parsedValue, type: newType }), - JSON.stringify(_value) - ); + setExistsPas(false); + props.superstate.ui.openPath(filePath, false, div2, properties3); } + setLoaded(true); }; - const newProperty = (e5) => { - const offset2 = e5.target.getBoundingClientRect(); - const type = parseFieldValue(props.column.value, props.column.type)?.type; - const value = parseObject( - props.initialValue ?? "", - props.column.type == "object-multi" - ); - showNewPropertyMenu( - props.superstate, - offset2, - [], - [], - (source, field) => { - saveType( - { - ...type ?? {}, - [field.name]: { type: field.type, label: field.name } - }, - { - ...value, - [field.name]: "" - } - ); - }, - null, - null, - true, - false - ); - }; - const insertMultiValue = (index2) => { - const type = parseFieldValue(props.column.value, props.column.type)?.type; - const value = parseObject( - props.initialValue ?? "", - props.column.type == "object-multi" - ); - const item = Object.keys(type).reduce((p, c3) => ({ ...p, [c3]: "" }), {}); - props.updateValue( - JSON.stringify([...value.slice(0, index2), item, ...value.slice(index2)]) - ); - }; - return /* @__PURE__ */ import_react78.default.createElement(import_react78.default.Fragment, null, /* @__PURE__ */ import_react78.default.createElement("div", { - className: "mk-path-context-row" - }, /* @__PURE__ */ import_react78.default.createElement(PropertyField, { - superstate: props.superstate, - path: props.path, - property: props.column, - onClick: (e5) => props.propertyMenu && props.propertyMenu(e5), - contexts: props.contexts, - draggable: props.draggable - }), /* @__PURE__ */ import_react78.default.createElement("div", { - className: "mk-path-context-value" - }, isObjectType ? !props.compactMode && /* @__PURE__ */ import_react78.default.createElement("div", { - className: "mk-cell-object-options" - }, props.editMode > 3 /* EditModeValueOnly */ && /* @__PURE__ */ import_react78.default.createElement("button", { - onClick: (e5) => newProperty(e5), - className: "mk-inline-button" - }, /* @__PURE__ */ import_react78.default.createElement("div", { - className: "mk-icon-xsmall", - dangerouslySetInnerHTML: { - __html: props.superstate.ui.getSticker("ui//plus") - } - }), i18n_default.labels.propertyFileProp), props.column.type == "object-multi" && /* @__PURE__ */ import_react78.default.createElement("button", { - onClick: (e5) => insertMultiValue(0), - className: "mk-inline-button" - }, /* @__PURE__ */ import_react78.default.createElement("div", { - className: "mk-icon-xsmall", - dangerouslySetInnerHTML: { - __html: props.superstate.ui.getSticker("ui//insert") - } - }), parsedValue?.typeName ?? "Object")) : /* @__PURE__ */ import_react78.default.createElement(DataTypeView, { - ...props - })), props.linkProp && /* @__PURE__ */ import_react78.default.createElement(import_react78.default.Fragment, null, /* @__PURE__ */ import_react78.default.createElement("span", null), /* @__PURE__ */ import_react78.default.createElement("div", { - className: "mk-icon-small", - style: { height: "24px" }, - onClick: (e5) => props.linkProp(e5), - dangerouslySetInnerHTML: { - __html: props.superstate.ui.getSticker("ui//plug") + const toggleFlow = () => { + if (props.load) { + loadPath(); + } else { + if (flowRef?.current) + flowRef.current.innerHTML = ""; } - }))), isObjectType && !props.compactMode && /* @__PURE__ */ import_react78.default.createElement("div", { - className: "mk-path-context-row", - style: { marginLeft: "30px" } - }, /* @__PURE__ */ import_react78.default.createElement(DataTypeView, { - ...props - }))); -}; + }; + (0, import_react80.useEffect)(() => { + toggleFlow(); + }, [props.load, props.path]); + return /* @__PURE__ */ import_react80.default.createElement(import_react80.default.Fragment, null, /* @__PURE__ */ import_react80.default.createElement("div", { + className: `${props.classname ?? ""} mk-flowspace-editor`, + ref: flowRef, + onClick: (e5) => e5.stopPropagation() + }), existsPas ? /* @__PURE__ */ import_react80.default.createElement("div", { + onClick: () => loadPath(true), + className: "mk-placeholder", + style: { color: "var(--mk-ui-text-tertiary)" } + }, i18n_default.labels.notePlaceholder.replace( + "${1}", + pathToString(props.path) + )) : /* @__PURE__ */ import_react80.default.createElement(import_react80.default.Fragment, null)); +}); +NoteView.displayName = "FlowView"; + +// src/core/react/components/Explorer/ContextPropertiesView.tsx +var import_react83 = __toESM(require_react()); // src/core/react/components/Explorer/PathContextList.tsx +var import_react81 = __toESM(require_react()); var PathContextList = (props) => { - const { pathState } = (0, import_react79.useContext)(PathContext); - const [cols, setCols] = (0, import_react79.useState)([]); - (0, import_react79.useEffect)(() => { + const { pathState } = (0, import_react81.useContext)(PathContext); + const [cols, setCols] = (0, import_react81.useState)([]); + (0, import_react81.useEffect)(() => { reloadProperties(); }, [pathState]); - (0, import_react79.useEffect)(() => { + (0, import_react81.useEffect)(() => { const contextUpdated = (payload) => { const spaces2 = [ ...props.superstate.spacesMap.get(pathState?.path) ?? [] @@ -115303,7 +115561,7 @@ var PathContextList = (props) => { editable: true }); }; - return /* @__PURE__ */ import_react79.default.createElement(import_react79.default.Fragment, null, cols.map((f2, i4) => /* @__PURE__ */ import_react79.default.createElement(DataPropertyView, { + return /* @__PURE__ */ import_react81.default.createElement(import_react81.default.Fragment, null, cols.map((f2, i4) => /* @__PURE__ */ import_react81.default.createElement(DataPropertyView, { key: i4, superstate: props.superstate, initialValue: f2.value, @@ -115357,14 +115615,14 @@ var showPropertiesMenu = (superstate, rect, property, deleteProperty2, syncPrope }; // src/core/react/components/Explorer/PropertiesView.tsx -var import_react80 = __toESM(require_react()); +var import_react82 = __toESM(require_react()); var PropertiesView = (props) => { - const { pathState } = (0, import_react80.useContext)(PathContext); - const [values2, setValues] = (0, import_react80.useState)({}); - const [cols, setCols] = (0, import_react80.useState)([]); - const [excludeKeys, setExcludeKeys] = (0, import_react80.useState)([]); - const { tableData, saveProperty, delProperty, saveFrame } = (0, import_react80.useContext)(FramesMDBContext); - const { newProperty: newPropertyInFrame } = (0, import_react80.useContext)(FramesMDBContext); + const { pathState } = (0, import_react82.useContext)(PathContext); + const [values2, setValues] = (0, import_react82.useState)({}); + const [cols, setCols] = (0, import_react82.useState)([]); + const [excludeKeys, setExcludeKeys] = (0, import_react82.useState)([]); + const { tableData, saveProperty, delProperty, saveFrame } = (0, import_react82.useContext)(FramesMDBContext); + const { newProperty: newPropertyInFrame } = (0, import_react82.useContext)(FramesMDBContext); const saveField = (source, field) => { if (source == "$fm") { if (pathState.type == "space" && newPropertyInFrame) { @@ -115440,7 +115698,7 @@ var PropertiesView = (props) => { refreshData(); } }; - (0, import_react80.useEffect)(() => { + (0, import_react82.useEffect)(() => { refreshData(); props.superstate.eventsDispatcher.addListener( "contextStateUpdated", @@ -115549,8 +115807,8 @@ var PropertiesView = (props) => { })) }); }; - const [dragProperty, setDragProperty] = (0, import_react80.useState)(null); - const [hoverNode, setHoverNode] = (0, import_react80.useState)(null); + const [dragProperty, setDragProperty] = (0, import_react82.useState)(null); + const [hoverNode, setHoverNode] = (0, import_react82.useState)(null); const resetState = () => { setHoverNode(null); setDragProperty(null); @@ -115619,9 +115877,9 @@ var PropertiesView = (props) => { ); }; const propertiessuperstate = props.superstate.settings.hideFrontmatter; - return !propertiessuperstate || props.force ? /* @__PURE__ */ import_react80.default.createElement("div", { + return !propertiessuperstate || props.force ? /* @__PURE__ */ import_react82.default.createElement("div", { className: "mk-path-context-properties" - }, cols.map((f2, i4) => /* @__PURE__ */ import_react80.default.createElement(DataPropertyView, { + }, cols.map((f2, i4) => /* @__PURE__ */ import_react82.default.createElement(DataPropertyView, { key: i4, path: pathState.path, propertyMenu: (e5) => showMenu2(e5, f2), @@ -115639,34 +115897,34 @@ var PropertiesView = (props) => { }), contextTable: {}, source: pathState.path - })), /* @__PURE__ */ import_react80.default.createElement("button", { + })), /* @__PURE__ */ import_react82.default.createElement("button", { className: "mk-inline-button", onClick: (e5) => newProperty(e5) - }, /* @__PURE__ */ import_react80.default.createElement("div", { + }, /* @__PURE__ */ import_react82.default.createElement("div", { className: "mk-icon-xsmall", dangerouslySetInnerHTML: { __html: props.superstate.ui.getSticker("ui//plus") } - }), i18n_default.labels.newProperty)) : excludeKeys.length > 0 ? /* @__PURE__ */ import_react80.default.createElement("style", null, `${excludeKeys.map((f2) => `.metadata-property[data-property-key="${f2}"]`).join(", ")} + }), i18n_default.labels.newProperty)) : excludeKeys.length > 0 ? /* @__PURE__ */ import_react82.default.createElement("style", null, `${excludeKeys.map((f2) => `.metadata-property[data-property-key="${f2}"]`).join(", ")} { display: none; - }`) : /* @__PURE__ */ import_react80.default.createElement(import_react80.default.Fragment, null); + }`) : /* @__PURE__ */ import_react82.default.createElement(import_react82.default.Fragment, null); }; // src/core/react/components/Explorer/ContextPropertiesView.tsx var ContextPropertiesView = (props) => { - const { pathState } = (0, import_react81.useContext)(PathContext); - const spaces2 = (0, import_react81.useMemo)( + const { pathState } = (0, import_react83.useContext)(PathContext); + const spaces2 = (0, import_react83.useMemo)( () => [...props.superstate.spacesMap.get(pathState?.path) ?? []].map((f2) => props.superstate.spacesIndex.get(f2)?.space).filter((f2) => f2), [pathState] ); - return /* @__PURE__ */ import_react81.default.createElement("div", { + return /* @__PURE__ */ import_react83.default.createElement("div", { className: "mk-path-context-properties" - }, /* @__PURE__ */ import_react81.default.createElement(PathContextList, { + }, /* @__PURE__ */ import_react83.default.createElement(PathContextList, { superstate: props.superstate, color: "var(--tag-background)", path: pathState.path - }), pathState?.path ? /* @__PURE__ */ import_react81.default.createElement(PropertiesView, { + }), pathState?.path ? /* @__PURE__ */ import_react83.default.createElement(PropertiesView, { superstate: props.superstate, spaces: spaces2.map((f2) => f2.path), force: true, @@ -115675,7 +115933,7 @@ var ContextPropertiesView = (props) => { ...FMSpaceKeys(props.superstate.settings) ], editable: props.editable - }) : /* @__PURE__ */ import_react81.default.createElement(import_react81.default.Fragment, null)); + }) : /* @__PURE__ */ import_react83.default.createElement(import_react83.default.Fragment, null)); }; // src/core/react/components/Explorer/Explorer.tsx @@ -115802,11 +116060,11 @@ var flattenTree = (superstate, node, openNodes, depth, index2) => { return items; }; var Explorer = (props) => { - const [selectedPath, setSelectedPath] = (0, import_react82.useState)(null); + const [selectedPath, setSelectedPath] = (0, import_react84.useState)(null); const changeSelectedPath = (path2) => { setSelectedPath(path2); }; - (0, import_react82.useEffect)(() => { + (0, import_react84.useEffect)(() => { props.superstate.ui.eventsDispatch.addListener( "activePathChanged", changeSelectedPath @@ -115818,18 +116076,18 @@ var Explorer = (props) => { ); }; }, []); - return /* @__PURE__ */ import_react82.default.createElement(PathProvider, { + return /* @__PURE__ */ import_react84.default.createElement(PathProvider, { superstate: props.superstate, path: selectedPath, readMode: false - }, /* @__PURE__ */ import_react82.default.createElement(PathContextView, { + }, /* @__PURE__ */ import_react84.default.createElement(PathContextView, { superstate: props.superstate })); }; var PathContextView = (props) => { - const [openNodes, setOpenNodes] = (0, import_react82.useState)([]); - const { pathState } = (0, import_react82.useContext)(PathContext); - const flattenedTree = (0, import_react82.useMemo)( + const [openNodes, setOpenNodes] = (0, import_react84.useState)([]); + const { pathState } = (0, import_react84.useContext)(PathContext); + const flattenedTree = (0, import_react84.useMemo)( () => pathState ? flattenTree( props.superstate, { @@ -115849,60 +116107,60 @@ var PathContextView = (props) => { ) : [], [pathState, openNodes] ); - (0, import_react82.useEffect)(() => { + (0, import_react84.useEffect)(() => { pathState && setOpenNodes([pathState.path]); }, [pathState]); - return /* @__PURE__ */ import_react82.default.createElement("div", { + return /* @__PURE__ */ import_react84.default.createElement("div", { className: "mk-path-context" - }, pathState ? /* @__PURE__ */ import_react82.default.createElement(import_react82.default.Fragment, null, flattenedTree.map((f2, i4) => /* @__PURE__ */ import_react82.default.createElement("div", { + }, pathState ? /* @__PURE__ */ import_react84.default.createElement(import_react84.default.Fragment, null, flattenedTree.map((f2, i4) => /* @__PURE__ */ import_react84.default.createElement("div", { key: f2.id, className: "mk-tree-wrapper", style: { marginLeft: f2.depth * 8 } - }, !f2.isLeafNode ? /* @__PURE__ */ import_react82.default.createElement(CollapseToggle, { + }, !f2.isLeafNode ? /* @__PURE__ */ import_react84.default.createElement(CollapseToggle, { superstate: props.superstate, collapsed: !openNodes.some((g) => g == f2.id), onToggle: (collapsed) => setOpenNodes( (p) => p.some((g) => g == f2.id) ? p.filter((o2) => o2 != f2.id) : [...p, f2.id] ) - }) : /* @__PURE__ */ import_react82.default.createElement(import_react82.default.Fragment, null), f2.type == "metadata" ? f2.subType == "flow" ? /* @__PURE__ */ import_react82.default.createElement(ExplorerFlowRow, { + }) : /* @__PURE__ */ import_react84.default.createElement(import_react84.default.Fragment, null), f2.type == "metadata" ? f2.subType == "flow" ? /* @__PURE__ */ import_react84.default.createElement(ExplorerFlowRow, { path: f2.path, source: f2.parentPath, superstate: props.superstate - }) : f2.subType == "properties" ? /* @__PURE__ */ import_react82.default.createElement(ExplorerContextRow, { + }) : f2.subType == "properties" ? /* @__PURE__ */ import_react84.default.createElement(ExplorerContextRow, { superstate: props.superstate, node: f2 - }) : /* @__PURE__ */ import_react82.default.createElement("div", { + }) : /* @__PURE__ */ import_react84.default.createElement("div", { className: "mk-path-context-row" - }, /* @__PURE__ */ import_react82.default.createElement("div", { + }, /* @__PURE__ */ import_react84.default.createElement("div", { className: "mk-path-context-field" - }, /* @__PURE__ */ import_react82.default.createElement("div", { + }, /* @__PURE__ */ import_react84.default.createElement("div", { className: "mk-path-context-field-icon", dangerouslySetInnerHTML: { __html: props.superstate.ui.getSticker(f2.sticker) } - }), /* @__PURE__ */ import_react82.default.createElement("div", { + }), /* @__PURE__ */ import_react84.default.createElement("div", { className: "mk-path-context-field-key" - }, f2.label))) : /* @__PURE__ */ import_react82.default.createElement("div", { + }, f2.label))) : /* @__PURE__ */ import_react84.default.createElement("div", { className: "mk-path-context-row" - }, /* @__PURE__ */ import_react82.default.createElement("div", { + }, /* @__PURE__ */ import_react84.default.createElement("div", { className: "mk-path-context-field" - }, /* @__PURE__ */ import_react82.default.createElement("div", { + }, /* @__PURE__ */ import_react84.default.createElement("div", { className: "mk-path-context-field-icon", dangerouslySetInnerHTML: { __html: props.superstate.ui.getSticker(f2.sticker) } - }), /* @__PURE__ */ import_react82.default.createElement("div", { + }), /* @__PURE__ */ import_react84.default.createElement("div", { className: "mk-path-context-field-key" - }, f2.label)))))) : /* @__PURE__ */ import_react82.default.createElement(import_react82.default.Fragment, null)); + }, f2.label)))))) : /* @__PURE__ */ import_react84.default.createElement(import_react84.default.Fragment, null)); }; var ExplorerFlowRow = (props) => { - const path2 = (0, import_react82.useMemo)(() => { + const path2 = (0, import_react84.useMemo)(() => { const spaceCache = props.superstate.spacesIndex.get(props.path); if (spaceCache) return spaceCache.space.defPath; return props.path; }, [props.path]); - const [block, setBlock] = (0, import_react82.useState)([null, null]); + const [block, setBlock] = (0, import_react84.useState)([null, null]); const refreshBlock = (path3) => { const fCache = props.superstate.pathsIndex.get(path3); const link = [ @@ -115930,15 +116188,15 @@ var ExplorerFlowRow = (props) => { } } }; - (0, import_react82.useEffect)(() => { + (0, import_react84.useEffect)(() => { refreshBlock(path2); }, []); - (0, import_react82.useEffect)(() => { + (0, import_react84.useEffect)(() => { refreshBlock(path2); }, [path2]); - return /* @__PURE__ */ import_react82.default.createElement(import_react82.default.Fragment, null, /* @__PURE__ */ import_react82.default.createElement("div", { + return /* @__PURE__ */ import_react84.default.createElement(import_react84.default.Fragment, null, /* @__PURE__ */ import_react84.default.createElement("div", { className: "mk-path-context-backlink" - }, /* @__PURE__ */ import_react82.default.createElement(NoteView, { + }, /* @__PURE__ */ import_react84.default.createElement(NoteView, { load: true, superstate: props.superstate, path: path2, @@ -115951,29 +116209,29 @@ var ExplorerFlowRow = (props) => { }; var ExplorerContextRow = (props) => { const { node, superstate } = props; - const [spaceCache, setSpaceCache] = (0, import_react82.useState)( + const [spaceCache, setSpaceCache] = (0, import_react84.useState)( superstate.spacesIndex.get(node.path) ); - return /* @__PURE__ */ import_react82.default.createElement(ContextPropertiesView, { + return /* @__PURE__ */ import_react84.default.createElement(ContextPropertiesView, { superstate: props.superstate, editable: true }); }; // src/core/react/components/MDBView/MDBViewer.tsx -var import_react153 = __toESM(require_react()); +var import_react155 = __toESM(require_react()); // src/core/react/context/FrameSelectionContext.tsx -var import_react86 = __toESM(require_react()); +var import_react88 = __toESM(require_react()); // src/core/react/context/FrameInstanceContext.tsx var import_lodash14 = __toESM(require_lodash()); -var import_react85 = __toESM(require_react()); +var import_react87 = __toESM(require_react()); // src/core/react/context/FrameEditorRootContext.tsx var import_lodash13 = __toESM(require_lodash()); -var import_react83 = __toESM(require_react()); -var FramesEditorRootContext = (0, import_react83.createContext)({ +var import_react85 = __toESM(require_react()); +var FramesEditorRootContext = (0, import_react85.createContext)({ root: null, nodes: [], properties: [], @@ -115994,17 +116252,17 @@ var FramesEditorRootContext = (0, import_react83.createContext)({ setLastCreatedId: () => null }); var FrameEditorProvider = (props) => { - const { spaceInfo } = (0, import_react83.useContext)(SpaceContext); - const [selectedSlide, setSelectedSlide] = (0, import_react83.useState)(null); - const [lastCreatedId, setLastCreatedId] = (0, import_react83.useState)(null); + const { spaceInfo } = (0, import_react85.useContext)(SpaceContext); + const [selectedSlide, setSelectedSlide] = (0, import_react85.useState)(null); + const [lastCreatedId, setLastCreatedId] = (0, import_react85.useState)(null); const { frameSchema, saveFrame, frameSchemas: schemas, tableData, getMDBData - } = (0, import_react83.useContext)(FramesMDBContext); - const nodes = (0, import_react83.useMemo)(() => { + } = (0, import_react85.useContext)(FramesMDBContext); + const nodes = (0, import_react85.useMemo)(() => { if (!frameSchema) return []; const frames = tableData?.rows.map( @@ -116026,8 +116284,8 @@ var FrameEditorProvider = (props) => { } return [...frames, _root]; }, [tableData, frameSchema]); - const [root, setRoot] = (0, import_react83.useState)(null); - const frameProperties = (0, import_react83.useMemo)(() => { + const [root, setRoot] = (0, import_react85.useState)(null); + const frameProperties = (0, import_react85.useMemo)(() => { const hiddenFields = [ ...FMMetadataKeys(props.superstate.settings), ...FMSpaceKeys(props.superstate.settings) @@ -116069,7 +116327,7 @@ var FrameEditorProvider = (props) => { initiateRoot(); } }; - (0, import_react83.useEffect)(() => { + (0, import_react85.useEffect)(() => { props.superstate.eventsDispatcher.addListener( "frameStateUpdated", refreshFrame @@ -116081,7 +116339,7 @@ var FrameEditorProvider = (props) => { ); }; }, [spaceInfo]); - (0, import_react83.useEffect)(() => { + (0, import_react85.useEffect)(() => { initiateRoot(); }, [frameSchema, nodes, tableData, props.editMode]); const updateNode = (_node, state) => { @@ -116340,7 +116598,7 @@ var FrameEditorProvider = (props) => { }); }; const properties3 = tableData?.cols ?? []; - return /* @__PURE__ */ import_react83.default.createElement(FramesEditorRootContext.Provider, { + return /* @__PURE__ */ import_react85.default.createElement(FramesEditorRootContext.Provider, { value: { root, nodes, @@ -116365,13 +116623,13 @@ var FrameEditorProvider = (props) => { }; // src/core/react/context/FrameRootContext.tsx -var import_react84 = __toESM(require_react()); -var FrameRootContext = import_react84.default.createContext({ +var import_react86 = __toESM(require_react()); +var FrameRootContext = import_react86.default.createContext({ root: null, path: null }); var FrameRootProvider = (props) => { - const [root, setRoot] = (0, import_react84.useState)(null); + const [root, setRoot] = (0, import_react86.useState)(null); const refreshFrame = (payload) => { if (payload.path != props.path.path && props.path.authority != "$kit") { return; @@ -116391,7 +116649,7 @@ var FrameRootProvider = (props) => { ) ); }; - (0, import_react84.useEffect)(() => { + (0, import_react86.useEffect)(() => { props.superstate.eventsDispatcher.addListener( "frameStateUpdated", refreshFrame @@ -116404,7 +116662,7 @@ var FrameRootProvider = (props) => { ); }; }, [props.path]); - return /* @__PURE__ */ import_react84.default.createElement(FrameRootContext.Provider, { + return /* @__PURE__ */ import_react86.default.createElement(FrameRootContext.Provider, { value: { root, path: props.path.fullPath @@ -116413,7 +116671,7 @@ var FrameRootProvider = (props) => { }; // src/core/react/context/FrameInstanceContext.tsx -var FrameInstanceContext = (0, import_react85.createContext)({ +var FrameInstanceContext = (0, import_react87.createContext)({ id: "", hoverNode: { id: null, node: "", direction: null }, setHoverNode: (node) => null, @@ -116425,33 +116683,34 @@ var FrameInstanceContext = (0, import_react85.createContext)({ linkedProps: [] }); var FrameInstanceProvider = (props) => { - const [hoverNode, setHoverNode] = (0, import_react85.useState)(null); - const [instance, setInstance] = (0, import_react85.useState)({ + const [hoverNode, setHoverNode] = (0, import_react87.useState)(null); + const [instance, setInstance] = (0, import_react87.useState)({ state: {}, id: null, root: null, exec: null, - slides: {} + slides: {}, + contexts: {} }); - const [rootProps, setRootProps] = (0, import_react85.useState)(props.props); - (0, import_react85.useEffect)(() => { + const [rootProps, setRootProps] = (0, import_react87.useState)(props.props); + (0, import_react87.useEffect)(() => { setRootProps((p) => { if (import_lodash14.default.isEqual(p, props.props)) return p; return props.props; }); }, [props.props]); - const { selectedSlide: _selectedSlide } = (0, import_react85.useContext)(FramesEditorRootContext); + const { selectedSlide: _selectedSlide } = (0, import_react87.useContext)(FramesEditorRootContext); const selectedSlide = props.editable ? _selectedSlide : null; - const { root: editableRoot } = (0, import_react85.useContext)(FramesEditorRootContext); - const { root: nonEditableRoot, path: path2 } = (0, import_react85.useContext)(FrameRootContext); - const root = (0, import_react85.useMemo)( + const { root: editableRoot } = (0, import_react87.useContext)(FramesEditorRootContext); + const { root: nonEditableRoot, path: path2 } = (0, import_react87.useContext)(FrameRootContext); + const root = (0, import_react87.useMemo)( () => props.editable ? editableRoot : nonEditableRoot, [props.editable, editableRoot, nonEditableRoot] ); - const activeRunID = (0, import_react85.useRef)(null); - const currentRoot = (0, import_react85.useRef)(null); - const linkedProps = (0, import_react85.useMemo)(() => { + const activeRunID = (0, import_react87.useRef)(null); + const currentRoot = (0, import_react87.useRef)(null); + const linkedProps = (0, import_react87.useMemo)(() => { return Object.keys(props.propSetters || {}); }, [props.propSetters]); const saveState = (newState, instance2) => { @@ -116483,7 +116742,7 @@ var FrameInstanceProvider = (props) => { }); }); }; - (0, import_react85.useEffect)(() => { + (0, import_react87.useEffect)(() => { if (instance?.root && props.propSetters) stateChangedForProps( Object.keys(props.propSetters), @@ -116494,13 +116753,13 @@ var FrameInstanceProvider = (props) => { props.propSetters[f2](instance.state[instance.root.id].props[f2]); }); }, [instance]); - const selectableNodeBounds = (0, import_react85.useRef)({}); + const selectableNodeBounds = (0, import_react87.useRef)({}); const fastSaveState = (newState) => { setInstance((p) => { return { ...p, state: newState }; }); }; - (0, import_react85.useEffect)( + (0, import_react87.useEffect)( () => () => { activeRunID.current = null; }, @@ -116536,14 +116795,14 @@ var FrameInstanceProvider = (props) => { }); } }; - (0, import_react85.useEffect)(() => { - if (instance.root && !executableChanged(root, instance.root)) { + (0, import_react87.useEffect)(() => { + if (instance.root && !executableChanged(root, instance.root) && (0, import_lodash14.isEqual)(props.contexts, instance.contexts)) { saveState({ [instance.root.id]: { props: rootProps } }, instance); } else { runRoot(); } }, [rootProps, root, props.contexts]); - return /* @__PURE__ */ import_react85.default.createElement(FrameInstanceContext.Provider, { + return /* @__PURE__ */ import_react87.default.createElement(FrameInstanceContext.Provider, { value: { id: props.id, linkedProps, @@ -116559,7 +116818,7 @@ var FrameInstanceProvider = (props) => { }; // src/core/react/context/FrameSelectionContext.tsx -var FrameSelectionContext = (0, import_react86.createContext)({ +var FrameSelectionContext = (0, import_react88.createContext)({ selectable: false, selected: false, selection: [], @@ -116576,18 +116835,18 @@ var FrameSelectionProvider = (props) => { selection: parentSelection, selectionMode: parentSelectionMode, setIsParentToSelection: setParentSelectable - } = (0, import_react86.useContext)(FrameSelectionContext); - const selected = (0, import_react86.useMemo)(() => { + } = (0, import_react88.useContext)(FrameSelectionContext); + const selected = (0, import_react88.useMemo)(() => { return parentSelection.includes(props.id) || props.selected; }, [parentSelection, props.id, props.selected]); - const selectionMode = (0, import_react86.useMemo)( + const selectionMode = (0, import_react88.useMemo)( () => props.editMode ?? 0 /* Read */, [props.editMode] ); - const { instance } = (0, import_react86.useContext)(FrameInstanceContext); - const [selection2, setSelection] = (0, import_react86.useState)([]); - const [isParentToSelection, setIsParentToSelection] = (0, import_react86.useState)(false); - const selectable = (0, import_react86.useMemo)(() => { + const { instance } = (0, import_react88.useContext)(FrameInstanceContext); + const [selection2, setSelection] = (0, import_react88.useState)([]); + const [isParentToSelection, setIsParentToSelection] = (0, import_react88.useState)(false); + const selectable = (0, import_react88.useMemo)(() => { if (selection2.length > 0) return true; if (isParentToSelection) @@ -116600,7 +116859,7 @@ var FrameSelectionProvider = (props) => { } return false; }, [selected, selectionMode, selection2, isParentToSelection]); - (0, import_react86.useEffect)(() => { + (0, import_react88.useEffect)(() => { const reset2 = (id3) => { if (id3 != props.id) { setSelection([]); @@ -116650,7 +116909,7 @@ var FrameSelectionProvider = (props) => { return; setSelection((prev) => prev.filter((f2) => f2 != id3)); }; - return /* @__PURE__ */ import_react86.default.createElement(FrameSelectionContext.Provider, { + return /* @__PURE__ */ import_react88.default.createElement(FrameSelectionContext.Provider, { value: { selectable, selected, @@ -116668,11 +116927,11 @@ var FrameSelectionProvider = (props) => { // src/core/react/components/SpaceView/Contexts/ContextListContainer.tsx var import_lodash19 = __toESM(require_lodash()); -var import_react152 = __toESM(require_react()); +var import_react154 = __toESM(require_react()); // src/core/react/components/SpaceView/Contexts/ContextBuilder/ContextListInstance.tsx var import_lodash18 = __toESM(require_lodash()); -var import_react149 = __toESM(require_react()); +var import_react151 = __toESM(require_react()); // src/core/utils/frames/editor/dropFrame.ts var shouldDeleteColumn = (nodeParent) => { @@ -116797,7 +117056,7 @@ var dropFrame = (_activeNode, overNode, root, nodes, direction) => { }; // src/core/react/components/SpaceView/Frames/ViewNodes/FrameEditorInstance.tsx -var import_react148 = __toESM(require_react()); +var import_react150 = __toESM(require_react()); // src/core/react/components/SpaceView/Frames/EditorNodes/FrameEditorNodeView.tsx var import_classnames10 = __toESM(require_classnames()); @@ -116827,28 +117086,28 @@ var parseStylesToClass = (styles2) => { }; // src/core/react/components/SpaceView/Frames/EditorNodes/FrameEditorNodeView.tsx -var import_react147 = __toESM(require_react()); +var import_react149 = __toESM(require_react()); var import_react_dom11 = __toESM(require_react_dom()); // src/core/react/components/SpaceView/Frames/FrameNodeEditor/FrameMultiNodeEditor.tsx -var import_react87 = __toESM(require_react()); +var import_react89 = __toESM(require_react()); var FrameMultiNodeEditor = (props) => { - const { groupNodes, saveNodes, nodes } = (0, import_react87.useContext)(FramesEditorRootContext); - const { selection: selection2, select } = (0, import_react87.useContext)(FrameSelectionContext); + const { groupNodes, saveNodes, nodes } = (0, import_react89.useContext)(FramesEditorRootContext); + const { selection: selection2, select } = (0, import_react89.useContext)(FrameSelectionContext); const selectedNodes = selection2.map((f2) => nodes.find((n3) => n3.id == f2)).filter((f2) => f2); - return /* @__PURE__ */ import_react87.default.createElement("div", { + return /* @__PURE__ */ import_react89.default.createElement("div", { className: "mk-editor-frame-node-selector", style: { pointerEvents: "auto" }, onClick: (e5) => e5.stopPropagation() - }, /* @__PURE__ */ import_react87.default.createElement("div", { + }, /* @__PURE__ */ import_react89.default.createElement("div", { className: "mk-mark" - }, /* @__PURE__ */ import_react87.default.createElement("div", { + }, /* @__PURE__ */ import_react89.default.createElement("div", { dangerouslySetInnerHTML: { __html: props.superstate.ui.getSticker("ui//copy-check") } - }), i18n_default.labels.itemsSelected.replace("${1}", selection2.length.toString())), /* @__PURE__ */ import_react87.default.createElement("div", { + }), i18n_default.labels.itemsSelected.replace("${1}", selection2.length.toString())), /* @__PURE__ */ import_react89.default.createElement("div", { className: "mk-divider" - }), /* @__PURE__ */ import_react87.default.createElement("div", { + }), /* @__PURE__ */ import_react89.default.createElement("div", { "aria-label": i18n_default.editor.createVerticalSection, className: "mk-mark", dangerouslySetInnerHTML: { @@ -116858,16 +117117,16 @@ var FrameMultiNodeEditor = (props) => { layoutAlign: `"left"`, gap: `"8px"` }) - }), /* @__PURE__ */ import_react87.default.createElement("div", { + }), /* @__PURE__ */ import_react89.default.createElement("div", { "aria-label": i18n_default.editor.createHorizontalSection, className: "mk-mark", dangerouslySetInnerHTML: { __html: props.superstate.ui.getSticker("ui//columns") }, onClick: () => groupNodes(selectedNodes, { layout: `"row"`, gap: `"8px"` }) - }), /* @__PURE__ */ import_react87.default.createElement("div", { + }), /* @__PURE__ */ import_react89.default.createElement("div", { className: "mk-divider" - }), /* @__PURE__ */ import_react87.default.createElement("div", { + }), /* @__PURE__ */ import_react89.default.createElement("div", { className: "mk-mark", "aria-label": i18n_default.menu.delete, onClick: () => saveNodes([], selectedNodes), @@ -116878,28 +117137,122 @@ var FrameMultiNodeEditor = (props) => { }; // src/core/react/components/SpaceView/Frames/FrameNodeEditor/FrameNodeEditor.tsx -var import_react103 = __toESM(require_react()); +var import_react105 = __toESM(require_react()); // src/core/utils/contexts/inlineTable.ts -var createInlineTable = async (superstate, path2, schema) => { - let tableName = "Table"; +var predicateForViewType = (type) => { + if (type == "table") { + return { + view: "table", + listView: "", + listGroup: "", + listItem: "" + }; + } + if (type == "flow") { + return { + view: "list", + listView: "spaces://$kit/#*listView", + listGroup: "spaces://$kit/#*listGroup", + listItem: "spaces://$kit/#*flowListItem" + }; + } + if (type == "list") { + return { + view: "list", + listView: "spaces://$kit/#*listView", + listGroup: "spaces://$kit/#*listGroup", + listItem: "spaces://$kit/#*rowItem" + }; + } + if (type == "details") { + return { + view: "list", + listView: "spaces://$kit/#*listView", + listGroup: "spaces://$kit/#*listGroup", + listItem: "spaces://$kit/#*detailItem" + }; + } + if (type == "board") { + return { + view: "list", + listView: "spaces://$kit/#*columnView", + listGroup: "spaces://$kit/#*columnGroup", + listItem: "spaces://$kit/#*cardListItem" + }; + } + if (type == "cards") { + return { + view: "list", + listView: "spaces://$kit/#*listView", + listGroup: "spaces://$kit/#*gridGroup", + listItem: "spaces://$kit/#*cardsListItem" + }; + } + if (type == "catalog") { + return { + view: "list", + listView: "spaces://$kit/#*listView", + listGroup: "spaces://$kit/#*rowGroup", + listItem: "spaces://$kit/#*coverListItem" + }; + } + if (type == "gallery") { + return { + view: "list", + listView: "spaces://$kit/#*listView", + listGroup: "spaces://$kit/#*masonryGroup", + listItem: "spaces://$kit/#*imageListItem" + }; + } + if (type == "calendar") { + return { + view: "list", + listView: "spaces://$kit/#*calendarView", + listGroup: "spaces://$kit/#*dateGroup", + listItem: "spaces://$kit/#*eventItem" + }; + } +}; +var createInlineTable = async (superstate, path2, type) => { + let tableName = type == "board" ? "Board" : "Table"; const schemas = await superstate.spaceManager.tablesForSpace(path2); if (schemas) { tableName = uniqueNameFromString( - schema ?? "Table", + tableName, schemas.map((f2) => f2.id) ); } - await superstate.spaceManager.createTable(path2, { + const viewID = await superstate.spaceManager.createTable(path2, { id: tableName, name: tableName, type: "db" }).then( - (f2) => { - return superstate.spaceManager.addSpaceProperty(path2, { ...defaultTableFields[0], schemaId: tableName }); + (f2) => superstate.spaceManager.addSpaceProperty(path2, { ...defaultTableFields[0], schemaId: tableName }) + ).then( + async (f2) => { + const schemaTable = await superstate.spaceManager.framesForSpace(path2); + const schema = { + id: uniqueNameFromString( + tableName, + schemaTable?.map((f3) => f3.id) ?? [] + ), + name: tableName, + type: "view", + predicate: JSON.stringify({ + ...defaultPredicate, + ...type ? predicateForViewType(type) : { view: "table" } + }), + def: JSON.stringify({ + db: tableName, + icon: type == "board" ? "ui//square-kanban" : "ui//table" + }) + }; + await superstate.spaceManager.createFrame(path2, schema); + return schema.id; } ); - return tableName; + return viewID; }; // src/core/react/components/UI/Menus/frames/newFrameMenu.tsx @@ -116990,7 +117343,7 @@ var showNewFrameMenu = (rect, superstate, space2, addNode, options = { searchabl const table = await createInlineTable(superstate, space2.path); addNode({ ...contextNode.node, - props: { value: wrapQuotes(`${space2.path}/#^${table}`) } + props: { value: wrapQuotes(`${space2.path}/#*${table}`) } }); } else if (item.value == "link") { } @@ -117019,7 +117372,7 @@ var showNewFrameMenu = (rect, superstate, space2, addNode, options = { searchabl }; // src/core/react/components/SpaceView/Frames/Setters/ColorSetter.tsx -var import_react88 = __toESM(require_react()); +var import_react90 = __toESM(require_react()); var ColorSetter = (props) => { const showColorMenu = (e5, prop2) => { const handleChangeComplete = (color2) => { @@ -117033,7 +117386,7 @@ var ColorSetter = (props) => { handleChangeComplete ); }; - return /* @__PURE__ */ import_react88.default.createElement("div", { + return /* @__PURE__ */ import_react90.default.createElement("div", { className: "mk-color", style: { background: props.value @@ -117045,11 +117398,11 @@ var ColorSetter = (props) => { }; // src/core/react/components/SpaceView/Frames/FrameNodeEditor/Submenus/ContentSubmenu.tsx -var import_react91 = __toESM(require_react()); +var import_react93 = __toESM(require_react()); // src/core/react/components/SpaceView/Frames/Setters/StepSetter.tsx var import_lodash15 = __toESM(require_lodash()); -var import_react89 = __toESM(require_react()); +var import_react91 = __toESM(require_react()); function countDecimals(value) { if (Math.floor(value) === value) return 0; @@ -117063,19 +117416,19 @@ function InputDrag({ onInput, ...props }) { - const [value, setValue] = (0, import_react89.useState)(props.value); - const [modifier, setModifier] = (0, import_react89.useState)(""); - const startValue = (0, import_react89.useRef)(0); - const inputRef = (0, import_react89.useRef)(null); + const [value, setValue] = (0, import_react91.useState)(props.value); + const [modifier, setModifier] = (0, import_react91.useState)(""); + const startValue = (0, import_react91.useRef)(0); + const inputRef = (0, import_react91.useRef)(null); const step = props.step ? +props.step : 1; - const modifiers = (0, import_react89.useMemo)( + const modifiers = (0, import_react91.useMemo)( () => ({ shiftKey: 0.1, ..._modifiers }), [_modifiers] ); - const [, setStartPos] = (0, import_react89.useState)([0, 0]); + const [, setStartPos] = (0, import_react91.useState)([0, 0]); const style = { cursor: "ew-resize", ..._style }; const handleChange = (e5) => { const newValue = e5.target.value; @@ -117088,7 +117441,7 @@ function InputDrag({ const handleDragEnd = (0, import_lodash15.debounce)((newValue) => { onChange?.(newValue, inputRef.current); }, 200); - const handleInput = (0, import_react89.useCallback)( + const handleInput = (0, import_react91.useCallback)( (newValue) => { requestAnimationFrame(() => { onInput?.(newValue, inputRef.current); @@ -117097,7 +117450,7 @@ function InputDrag({ }, [handleDragEnd, onInput] ); - const handleMove = (0, import_react89.useCallback)( + const handleMove = (0, import_react91.useCallback)( (e5) => { setStartPos((pos) => { const { clientX: x2, clientY: y22 } = e5; @@ -117126,11 +117479,11 @@ function InputDrag({ }, [modifier, props.max, props.min, step, handleInput, modifiers] ); - const handleMoveEnd = (0, import_react89.useCallback)(() => { + const handleMoveEnd = (0, import_react91.useCallback)(() => { document.removeEventListener("mousemove", handleMove); document.removeEventListener("mouseup", handleMoveEnd); }, [handleMove]); - const handleDown = (0, import_react89.useCallback)( + const handleDown = (0, import_react91.useCallback)( (e5) => { let _startValue = +value; if (isNaN(_startValue)) { @@ -117157,11 +117510,11 @@ function InputDrag({ const handleKeyUp = () => { setModifier(""); }; - (0, import_react89.useEffect)(() => { + (0, import_react91.useEffect)(() => { if (props.value !== value && typeof props.value === "number") setValue(props.value); }, [props.value]); - (0, import_react89.useEffect)(() => { + (0, import_react91.useEffect)(() => { document.addEventListener("keydown", handleKeyDown); document.addEventListener("keyup", handleKeyUp); return () => { @@ -117171,7 +117524,7 @@ function InputDrag({ document.removeEventListener("keyup", handleKeyUp); }; }, []); - return /* @__PURE__ */ import_react89.default.createElement("input", { + return /* @__PURE__ */ import_react91.default.createElement("input", { placeholder: "auto", type: "number", ...props, @@ -117206,9 +117559,9 @@ var StepSetter = (props) => { defaultMenu(props.superstate.ui, menuOptions) ); }; - return /* @__PURE__ */ import_react89.default.createElement("div", { + return /* @__PURE__ */ import_react91.default.createElement("div", { className: "mk-setter-step" - }, /* @__PURE__ */ import_react89.default.createElement("span", null, props.name), /* @__PURE__ */ import_react89.default.createElement(InputDrag, { + }, /* @__PURE__ */ import_react91.default.createElement("span", null, props.name), /* @__PURE__ */ import_react91.default.createElement(InputDrag, { min: props.min, max: props.max, value: numericValue, @@ -117222,21 +117575,21 @@ var StepSetter = (props) => { onChange: (value) => { props.setValue(wrapQuotes(`${value.toString() + unit2}`)); } - }), /* @__PURE__ */ import_react89.default.createElement("span", { + }), /* @__PURE__ */ import_react91.default.createElement("span", { onClick: (e5) => showUnitMenu(e5) }, unit2)); }; // src/core/react/components/SpaceView/Frames/FrameNodeEditor/Submenus/AlignmentSubmenu.tsx -var import_react90 = __toESM(require_react()); +var import_react92 = __toESM(require_react()); var AlignmentEditor = (props) => { const directions2 = ["nw", "n", "ne", "w", "m", "e", "sw", "s", "se"]; - const [layoutAlign, setLayoutAlign] = (0, import_react90.useState)( + const [layoutAlign, setLayoutAlign] = (0, import_react92.useState)( props.state?.styles?.layoutAlign ); - return /* @__PURE__ */ import_react90.default.createElement("div", { + return /* @__PURE__ */ import_react92.default.createElement("div", { className: "mk-editor-alignment-menu" - }, directions2.map((d4) => /* @__PURE__ */ import_react90.default.createElement("div", { + }, directions2.map((d4) => /* @__PURE__ */ import_react92.default.createElement("div", { className: `mk-editor-alignment-selector ${layoutAlign == d4 && "mk-active"}`, key: "d", onClick: () => { @@ -117248,11 +117601,11 @@ var AlignmentEditor = (props) => { // src/core/react/components/SpaceView/Frames/FrameNodeEditor/Submenus/ContentSubmenu.tsx var ContentSubmenu = (props) => { - const { spaceInfo } = (0, import_react91.useContext)(SpaceContext); - const { addNode } = (0, import_react91.useContext)(FramesEditorRootContext); - const { select } = (0, import_react91.useContext)(FrameSelectionContext); + const { spaceInfo } = (0, import_react93.useContext)(SpaceContext); + const { addNode } = (0, import_react93.useContext)(FramesEditorRootContext); + const { select } = (0, import_react93.useContext)(FrameSelectionContext); const { selectedNode, saveStyleValue } = props; - return /* @__PURE__ */ import_react91.default.createElement(import_react91.default.Fragment, null, /* @__PURE__ */ import_react91.default.createElement("div", { + return /* @__PURE__ */ import_react93.default.createElement(import_react93.default.Fragment, null, /* @__PURE__ */ import_react93.default.createElement("div", { className: "mk-editor-frame-node-button-primary", dangerouslySetInnerHTML: { __html: props.superstate.ui.getSticker("ui//plus") @@ -117268,7 +117621,7 @@ var ContentSubmenu = (props) => { ); e5.stopPropagation(); } - }), /* @__PURE__ */ import_react91.default.createElement(ToggleSetter, { + }), /* @__PURE__ */ import_react93.default.createElement(ToggleSetter, { icon: "ui//arrow-right", superstate: props.superstate, name: i18n_default.editor.rows, @@ -117276,7 +117629,7 @@ var ContentSubmenu = (props) => { setValue: (value) => saveStyleValue("layout", value), onValue: "'row'", defaultValue: "'row'" - }), /* @__PURE__ */ import_react91.default.createElement(ToggleSetter, { + }), /* @__PURE__ */ import_react93.default.createElement(ToggleSetter, { icon: "ui//arrow-down", superstate: props.superstate, name: i18n_default.editor.columns, @@ -117284,7 +117637,7 @@ var ContentSubmenu = (props) => { setValue: (value) => saveStyleValue("layout", value), onValue: "'column'", defaultValue: "'column'" - }), /* @__PURE__ */ import_react91.default.createElement(ToggleSetter, { + }), /* @__PURE__ */ import_react93.default.createElement(ToggleSetter, { icon: "ui//layout-dashboard", superstate: props.superstate, name: i18n_default.editor.gallery, @@ -117292,14 +117645,14 @@ var ContentSubmenu = (props) => { setValue: (value) => saveStyleValue("layout", value), onValue: "'masonry'", defaultValue: "'masonry'" - }), /* @__PURE__ */ import_react91.default.createElement("div", { + }), /* @__PURE__ */ import_react93.default.createElement("div", { className: "mk-divider" - }), props.state.styles?.["layout"] == "row" || props.state.styles?.["layout"] == "column" ? /* @__PURE__ */ import_react91.default.createElement(import_react91.default.Fragment, null, /* @__PURE__ */ import_react91.default.createElement("div", { + }), props.state.styles?.["layout"] == "row" || props.state.styles?.["layout"] == "column" ? /* @__PURE__ */ import_react93.default.createElement(import_react93.default.Fragment, null, /* @__PURE__ */ import_react93.default.createElement("div", { className: "mk-editor-frame-node-button", onClick: (e5) => { props.superstate.ui.openCustomMenu( e5.target.getBoundingClientRect(), - /* @__PURE__ */ import_react91.default.createElement(AlignmentEditor, { + /* @__PURE__ */ import_react93.default.createElement(AlignmentEditor, { ...props }), { ...props } @@ -117308,7 +117661,7 @@ var ContentSubmenu = (props) => { dangerouslySetInnerHTML: { __html: props.superstate.ui.getSticker("ui//grid") } - }), /* @__PURE__ */ import_react91.default.createElement("div", { + }), /* @__PURE__ */ import_react93.default.createElement("div", { className: "mk-editor-frame-node-button", onClick: (e5) => { e5.preventDefault(); @@ -117321,13 +117674,13 @@ var ContentSubmenu = (props) => { dangerouslySetInnerHTML: { __html: props.superstate.ui.getSticker("ui//wrap-text") } - }), /* @__PURE__ */ import_react91.default.createElement(StepSetter, { + }), /* @__PURE__ */ import_react93.default.createElement(StepSetter, { superstate: props.superstate, name: i18n_default.editor.gap, value: selectedNode.styles?.["gap"], setValue: (value) => saveStyleValue("gap", value), units: ["px"] - })) : /* @__PURE__ */ import_react91.default.createElement(import_react91.default.Fragment, null, /* @__PURE__ */ import_react91.default.createElement(StepSetter, { + })) : /* @__PURE__ */ import_react93.default.createElement(import_react93.default.Fragment, null, /* @__PURE__ */ import_react93.default.createElement(StepSetter, { superstate: props.superstate, name: i18n_default.editor.columns, value: selectedNode.styles?.["columnCount"], @@ -117338,24 +117691,24 @@ var ContentSubmenu = (props) => { }; // src/core/react/components/SpaceView/Frames/FrameNodeEditor/Submenus/LayoutSubmenu.tsx -var import_react96 = __toESM(require_react()); +var import_react98 = __toESM(require_react()); // src/core/react/components/SpaceView/Frames/FrameNodeEditor/Submenus/SizeSubmenu.tsx -var import_react92 = __toESM(require_react()); +var import_react94 = __toESM(require_react()); var SizeSubmenu = (props) => { const { selectedNode, saveStyleValue } = props; - return /* @__PURE__ */ import_react92.default.createElement(import_react92.default.Fragment, null, /* @__PURE__ */ import_react92.default.createElement("div", { + return /* @__PURE__ */ import_react94.default.createElement(import_react94.default.Fragment, null, /* @__PURE__ */ import_react94.default.createElement("div", { className: "mk-divider" - }), /* @__PURE__ */ import_react92.default.createElement(StepSetter, { + }), /* @__PURE__ */ import_react94.default.createElement(StepSetter, { superstate: props.superstate, name: i18n_default.editor.width, min: 0, value: selectedNode.styles?.["width"], setValue: (value) => saveStyleValue("width", value), units: ["px", "%", "em"] - }), /* @__PURE__ */ import_react92.default.createElement("div", { + }), /* @__PURE__ */ import_react94.default.createElement("div", { className: "mk-divider" - }), /* @__PURE__ */ import_react92.default.createElement(StepSetter, { + }), /* @__PURE__ */ import_react94.default.createElement(StepSetter, { superstate: props.superstate, name: i18n_default.editor.height, min: 0, @@ -117366,31 +117719,31 @@ var SizeSubmenu = (props) => { }; // src/core/react/components/SpaceView/Frames/FrameNodeEditor/Submenus/SpacingSubmenu.tsx -var import_react95 = __toESM(require_react()); +var import_react97 = __toESM(require_react()); // src/core/react/components/SpaceView/Frames/FrameNodeEditor/Submenus/MarginSubmenu.tsx -var import_react93 = __toESM(require_react()); +var import_react95 = __toESM(require_react()); var MarginSubmenu = (props) => { const { selectedNode, saveStyleValue } = props; - return /* @__PURE__ */ import_react93.default.createElement(import_react93.default.Fragment, null, /* @__PURE__ */ import_react93.default.createElement(StepSetter, { + return /* @__PURE__ */ import_react95.default.createElement(import_react95.default.Fragment, null, /* @__PURE__ */ import_react95.default.createElement(StepSetter, { superstate: props.superstate, name: i18n_default.editor.marginLeft, value: selectedNode.styles?.["marginLeft"], setValue: (value) => saveStyleValue("marginLeft", value), units: ["px", "em"] - }), /* @__PURE__ */ import_react93.default.createElement(StepSetter, { + }), /* @__PURE__ */ import_react95.default.createElement(StepSetter, { superstate: props.superstate, name: i18n_default.editor.marginTop, value: selectedNode.styles?.["marginTop"], setValue: (value) => saveStyleValue("marginTop", value), units: ["px", "em"] - }), /* @__PURE__ */ import_react93.default.createElement(StepSetter, { + }), /* @__PURE__ */ import_react95.default.createElement(StepSetter, { superstate: props.superstate, name: i18n_default.editor.marginRight, value: selectedNode.styles?.["marginRight"], setValue: (value) => saveStyleValue("marginRight", value), units: ["px", "em"] - }), /* @__PURE__ */ import_react93.default.createElement(StepSetter, { + }), /* @__PURE__ */ import_react95.default.createElement(StepSetter, { superstate: props.superstate, name: i18n_default.editor.marginBottom, value: selectedNode.styles?.["marginBottom"], @@ -117400,30 +117753,30 @@ var MarginSubmenu = (props) => { }; // src/core/react/components/SpaceView/Frames/FrameNodeEditor/Submenus/PaddingSubmenu.tsx -var import_react94 = __toESM(require_react()); +var import_react96 = __toESM(require_react()); var PaddingSubmenu = (props) => { const { selectedNode, saveStyleValue } = props; - return /* @__PURE__ */ import_react94.default.createElement(import_react94.default.Fragment, null, /* @__PURE__ */ import_react94.default.createElement(StepSetter, { + return /* @__PURE__ */ import_react96.default.createElement(import_react96.default.Fragment, null, /* @__PURE__ */ import_react96.default.createElement(StepSetter, { superstate: props.superstate, name: i18n_default.editor.paddingLeft, value: selectedNode.styles?.["paddingLeft"], setValue: (value) => saveStyleValue("paddingLeft", value), units: ["px", "em"] - }), /* @__PURE__ */ import_react94.default.createElement(StepSetter, { + }), /* @__PURE__ */ import_react96.default.createElement(StepSetter, { superstate: props.superstate, name: i18n_default.editor.paddingTop, min: 0, value: selectedNode.styles?.["paddingTop"], setValue: (value) => saveStyleValue("paddingTop", value), units: ["px", "em"] - }), /* @__PURE__ */ import_react94.default.createElement(StepSetter, { + }), /* @__PURE__ */ import_react96.default.createElement(StepSetter, { superstate: props.superstate, name: i18n_default.editor.paddingRight, min: 0, value: selectedNode.styles?.["paddingRight"], setValue: (value) => saveStyleValue("paddingRight", value), units: ["px", "em"] - }), /* @__PURE__ */ import_react94.default.createElement(StepSetter, { + }), /* @__PURE__ */ import_react96.default.createElement(StepSetter, { superstate: props.superstate, name: i18n_default.editor.paddingBottom, min: 0, @@ -117440,7 +117793,7 @@ var SpacingSubmenu = (props) => { const offset2 = e5.target.getBoundingClientRect(); return props.superstate.ui.openCustomMenu( offset2, - /* @__PURE__ */ import_react95.default.createElement(PaddingSubmenu, { + /* @__PURE__ */ import_react97.default.createElement(PaddingSubmenu, { ...props }), props @@ -117450,33 +117803,33 @@ var SpacingSubmenu = (props) => { const offset2 = e5.target.getBoundingClientRect(); return props.superstate.ui.openCustomMenu( offset2, - /* @__PURE__ */ import_react95.default.createElement(MarginSubmenu, { + /* @__PURE__ */ import_react97.default.createElement(MarginSubmenu, { ...props }), props ); }; - return /* @__PURE__ */ import_react95.default.createElement(import_react95.default.Fragment, null, /* @__PURE__ */ import_react95.default.createElement(StepSetter, { + return /* @__PURE__ */ import_react97.default.createElement(import_react97.default.Fragment, null, /* @__PURE__ */ import_react97.default.createElement(StepSetter, { superstate: props.superstate, name: i18n_default.editor.margin, value: selectedNode.styles?.["margin"], setValue: (value) => saveStyleValue("margin", value), units: ["px", "em"] - }), /* @__PURE__ */ import_react95.default.createElement("div", { + }), /* @__PURE__ */ import_react97.default.createElement("div", { dangerouslySetInnerHTML: { __html: props.superstate.ui.getSticker("ui//plus") }, onClick: (e5) => { showMarginMenu(e5); } - }), /* @__PURE__ */ import_react95.default.createElement(StepSetter, { + }), /* @__PURE__ */ import_react97.default.createElement(StepSetter, { superstate: props.superstate, name: i18n_default.editor.padding, min: 0, value: selectedNode.styles?.["padding"], setValue: (value) => saveStyleValue("padding", value), units: ["px", "em"] - }), /* @__PURE__ */ import_react95.default.createElement("div", { + }), /* @__PURE__ */ import_react97.default.createElement("div", { dangerouslySetInnerHTML: { __html: props.superstate.ui.getSticker("ui//plus") }, @@ -117519,22 +117872,22 @@ var LayoutSubmenu = (props) => { defaultMenu(props.superstate.ui, menuOptions) ); }; - return /* @__PURE__ */ import_react96.default.createElement(import_react96.default.Fragment, null, /* @__PURE__ */ import_react96.default.createElement("div", { + return /* @__PURE__ */ import_react98.default.createElement(import_react98.default.Fragment, null, /* @__PURE__ */ import_react98.default.createElement("div", { className: "mk-divider" - }), /* @__PURE__ */ import_react96.default.createElement(SpacingSubmenu, { + }), /* @__PURE__ */ import_react98.default.createElement(SpacingSubmenu, { ...props - }), /* @__PURE__ */ import_react96.default.createElement(SizeSubmenu, { + }), /* @__PURE__ */ import_react98.default.createElement(SizeSubmenu, { ...props - }), /* @__PURE__ */ import_react96.default.createElement("div", { + }), /* @__PURE__ */ import_react98.default.createElement("div", { className: "mk-divider" })); }; // src/core/react/components/SpaceView/Frames/FrameNodeEditor/Submenus/ModeSubmenu.tsx -var import_react97 = __toESM(require_react()); +var import_react99 = __toESM(require_react()); var ModeSubmenu = (props) => { const { selectedNode, saveStyleValue } = props; - return /* @__PURE__ */ import_react97.default.createElement(import_react97.default.Fragment, null, /* @__PURE__ */ import_react97.default.createElement(ToggleSetter, { + return /* @__PURE__ */ import_react99.default.createElement(import_react99.default.Fragment, null, /* @__PURE__ */ import_react99.default.createElement(ToggleSetter, { superstate: props.superstate, name: i18n_default.editor.minimize, value: selectedNode.styles?.["--mk-min-mode"], @@ -117547,7 +117900,7 @@ var ModeSubmenu = (props) => { // src/core/react/components/SpaceView/Frames/FrameNodeEditor/Submenus/PropertiesSubmenu.tsx var import_classnames2 = __toESM(require_classnames()); -var import_react98 = __toESM(require_react()); +var import_react100 = __toESM(require_react()); var PropertiesSubmenu = (props) => { const { selectedNode, @@ -117747,33 +118100,33 @@ var PropertiesSubmenu = (props) => { const stackedProperty = (field) => { return field.type.startsWith("object") || field.type == "super"; }; - return /* @__PURE__ */ import_react98.default.createElement("div", { + return /* @__PURE__ */ import_react100.default.createElement("div", { className: "mk-editor-frame-properties" - }, /* @__PURE__ */ import_react98.default.createElement("div", { + }, /* @__PURE__ */ import_react100.default.createElement("div", { className: "mk-editor-actions-name" - }, /* @__PURE__ */ import_react98.default.createElement("div", { + }, /* @__PURE__ */ import_react100.default.createElement("div", { className: "mk-editor-actions-name-icon" - }, /* @__PURE__ */ import_react98.default.createElement("div", { + }, /* @__PURE__ */ import_react100.default.createElement("div", { className: "mk-icon-small", dangerouslySetInnerHTML: { __html: props.superstate.ui.getSticker("ui//list") } - })), /* @__PURE__ */ import_react98.default.createElement("div", { + })), /* @__PURE__ */ import_react100.default.createElement("div", { className: "mk-editor-actions-name-text" - }, i18n_default.buttons.editProperty), /* @__PURE__ */ import_react98.default.createElement("span", null), /* @__PURE__ */ import_react98.default.createElement("div", { + }, i18n_default.buttons.editProperty), /* @__PURE__ */ import_react100.default.createElement("span", null), /* @__PURE__ */ import_react100.default.createElement("div", { className: "mk-icon-small mk-inline-button", dangerouslySetInnerHTML: { __html: props.superstate.ui.getSticker("ui//close") }, onClick: () => props.hide() - })), /* @__PURE__ */ import_react98.default.createElement("div", { + })), /* @__PURE__ */ import_react100.default.createElement("div", { className: "mk-props-contexts" }, fields.map((f2, i4) => { const isStaticProperty = f2.type.startsWith("object") ? objectIsConst(frameProps?.[f2.name], f2.type) : f2.type == "super" || stringIsConst(frameProps?.[f2.name]); const isStacked = stackedProperty(f2); - return /* @__PURE__ */ import_react98.default.createElement(import_react98.default.Fragment, { + return /* @__PURE__ */ import_react100.default.createElement(import_react100.default.Fragment, { key: i4 - }, isStaticProperty ? /* @__PURE__ */ import_react98.default.createElement(DataPropertyView, { + }, isStaticProperty ? /* @__PURE__ */ import_react100.default.createElement(DataPropertyView, { initialValue: valueForField(f2, frameProps?.[f2.name]), column: f2, compactMode: false, @@ -117790,12 +118143,12 @@ var PropertiesSubmenu = (props) => { linkProp: (e5) => showPropsMenu(e5, f2), source: pathState.path, columns: frameProperties - }) : /* @__PURE__ */ import_react98.default.createElement("div", { + }) : /* @__PURE__ */ import_react100.default.createElement("div", { className: (0, import_classnames2.default)( "mk-path-context-row", isStacked && "mk-path-context-stacked" ) - }, f2.type == "input" ? /* @__PURE__ */ import_react98.default.createElement(PropertySelectCell, { + }, f2.type == "input" ? /* @__PURE__ */ import_react100.default.createElement(PropertySelectCell, { initialValue: frameProps?.[f2.name], superstate: props.superstate, compactMode: true, @@ -117803,16 +118156,16 @@ var PropertiesSubmenu = (props) => { editMode: 3 /* EditModeValueOnly */, saveValue: (value) => savePropValue(f2.name, wrapQuotes(value)), columns: frameProperties - }) : /* @__PURE__ */ import_react98.default.createElement(import_react98.default.Fragment, null, /* @__PURE__ */ import_react98.default.createElement(PropertyField, { + }) : /* @__PURE__ */ import_react100.default.createElement(import_react100.default.Fragment, null, /* @__PURE__ */ import_react100.default.createElement(PropertyField, { path: pathState.path, superstate: props.superstate, property: f2, draggable: true - }), /* @__PURE__ */ import_react98.default.createElement("div", { + }), /* @__PURE__ */ import_react100.default.createElement("div", { className: "mk-active" - }, /* @__PURE__ */ import_react98.default.createElement("div", { + }, /* @__PURE__ */ import_react100.default.createElement("div", { "aria-label": i18n_default.editor.linkedProperty - }, parseLinkedPropertyToValue(frameProps?.[f2.name])))), /* @__PURE__ */ import_react98.default.createElement("span", null), !isStacked && /* @__PURE__ */ import_react98.default.createElement("div", { + }, parseLinkedPropertyToValue(frameProps?.[f2.name])))), /* @__PURE__ */ import_react100.default.createElement("span", null), !isStacked && /* @__PURE__ */ import_react100.default.createElement("div", { "aria-label": i18n_default.editor.linkProperty, className: "mk-icon-small mk-inline-button", onClick: (e5) => showPropsMenu(e5, f2), @@ -117824,10 +118177,10 @@ var PropertiesSubmenu = (props) => { }; // src/core/react/components/SpaceView/Frames/FrameNodeEditor/Submenus/StyleSubmenu.tsx -var import_react101 = __toESM(require_react()); +var import_react103 = __toESM(require_react()); // src/core/react/components/SpaceView/Frames/FrameNodeEditor/Submenus/BorderSubmenu.tsx -var import_react99 = __toESM(require_react()); +var import_react101 = __toESM(require_react()); var BorderSubmenu = (props) => { const { selectedNode, saveStyleValue } = props; const showOutlineStyleMenu = (e5) => { @@ -117878,22 +118231,22 @@ var BorderSubmenu = (props) => { handleChangeComplete ); }; - return /* @__PURE__ */ import_react99.default.createElement(import_react99.default.Fragment, null, /* @__PURE__ */ import_react99.default.createElement("div", { + return /* @__PURE__ */ import_react101.default.createElement(import_react101.default.Fragment, null, /* @__PURE__ */ import_react101.default.createElement("div", { className: "mk-divider" - }), /* @__PURE__ */ import_react99.default.createElement("div", { + }), /* @__PURE__ */ import_react101.default.createElement("div", { className: "mk-editor-frame-node-button", onClick: (e5) => showOutlineStyleMenu(e5) - }, /* @__PURE__ */ import_react99.default.createElement("div", { + }, /* @__PURE__ */ import_react101.default.createElement("div", { dangerouslySetInnerHTML: { __html: props.superstate.ui.getSticker("ui//case-sensitive") } - }), props.state.styles?.["outlineStyle"] ?? i18n_default.labels.none), /* @__PURE__ */ import_react99.default.createElement(StepSetter, { + }), props.state.styles?.["outlineStyle"] ?? i18n_default.labels.none), /* @__PURE__ */ import_react101.default.createElement(StepSetter, { superstate: props.superstate, name: i18n_default.editor.size, value: props.state.styles?.["outlineWidth"], setValue: (value) => saveStyleValue("outlineWidth", value), units: ["px", "em"] - }), /* @__PURE__ */ import_react99.default.createElement("div", { + }), /* @__PURE__ */ import_react101.default.createElement("div", { onClick: (e5) => { showColorMenu(e5, "outlineColor"); }, @@ -117905,7 +118258,7 @@ var BorderSubmenu = (props) => { }; // src/core/react/components/SpaceView/Frames/FrameNodeEditor/Submenus/ShadowSubmenu.tsx -var import_react100 = __toESM(require_react()); +var import_react102 = __toESM(require_react()); var ShadowSubmenu = (props) => { const { selectedNode, saveStyleValue } = props; const showColorMenu = (e5, prop2) => { @@ -117921,7 +118274,7 @@ var ShadowSubmenu = (props) => { handleChangeComplete ); }; - return /* @__PURE__ */ import_react100.default.createElement(import_react100.default.Fragment, null, /* @__PURE__ */ import_react100.default.createElement("div", { + return /* @__PURE__ */ import_react102.default.createElement(import_react102.default.Fragment, null, /* @__PURE__ */ import_react102.default.createElement("div", { className: "mk-editor-frame-node-button", onMouseDown: () => { props.exitMenu(); @@ -117929,35 +118282,35 @@ var ShadowSubmenu = (props) => { dangerouslySetInnerHTML: { __html: props.superstate.ui.getSticker("ui//close") } - }), /* @__PURE__ */ import_react100.default.createElement("div", { + }), /* @__PURE__ */ import_react102.default.createElement("div", { className: "mk-divider" - }), /* @__PURE__ */ import_react100.default.createElement(StepSetter, { + }), /* @__PURE__ */ import_react102.default.createElement(StepSetter, { superstate: props.superstate, name: "X", value: selectedNode.styles?.["--shadow-x"], setValue: (value) => saveStyleValue("--shadow-x", value), units: ["px", "em"] - }), /* @__PURE__ */ import_react100.default.createElement(StepSetter, { + }), /* @__PURE__ */ import_react102.default.createElement(StepSetter, { superstate: props.superstate, name: "Y", value: selectedNode.styles?.["--shadow-y"], setValue: (value) => saveStyleValue("--shadow-y", value), units: ["px", "em"] - }), /* @__PURE__ */ import_react100.default.createElement(StepSetter, { + }), /* @__PURE__ */ import_react102.default.createElement(StepSetter, { superstate: props.superstate, name: i18n_default.editor.shadowBlur, value: selectedNode.styles?.["--shadow-blur"], setValue: (value) => saveStyleValue("--shadow-blur", value), units: ["px", "em"] - }), /* @__PURE__ */ import_react100.default.createElement(StepSetter, { + }), /* @__PURE__ */ import_react102.default.createElement(StepSetter, { superstate: props.superstate, name: i18n_default.editor.shadowSpread, value: selectedNode.styles?.["--shadow-spread"], setValue: (value) => saveStyleValue("--shadow-spread", value), units: ["px", "em"] - }), /* @__PURE__ */ import_react100.default.createElement("div", { + }), /* @__PURE__ */ import_react102.default.createElement("div", { className: "mk-divider" - }), /* @__PURE__ */ import_react100.default.createElement("div", { + }), /* @__PURE__ */ import_react102.default.createElement("div", { onClick: (e5) => { showColorMenu(e5, "--shadow-color"); }, @@ -117965,7 +118318,7 @@ var ShadowSubmenu = (props) => { style: { background: removeQuotes(selectedNode.styles?.["--shadow-color"]) } - }), /* @__PURE__ */ import_react100.default.createElement(StepSetter, { + }), /* @__PURE__ */ import_react102.default.createElement(StepSetter, { superstate: props.superstate, name: i18n_default.editor.opacity, value: selectedNode.styles?.["--shadow-alpha"], @@ -117994,21 +118347,21 @@ var StyleSubmenu = (props) => { const offset2 = e5.target.getBoundingClientRect(); return props.superstate.ui.openCustomMenu( offset2, - /* @__PURE__ */ import_react101.default.createElement(ShadowSubmenu, { + /* @__PURE__ */ import_react103.default.createElement(ShadowSubmenu, { ...props }), props ); }; - return /* @__PURE__ */ import_react101.default.createElement(import_react101.default.Fragment, null, /* @__PURE__ */ import_react101.default.createElement("div", { + return /* @__PURE__ */ import_react103.default.createElement(import_react103.default.Fragment, null, /* @__PURE__ */ import_react103.default.createElement("div", { className: "mk-color", onClick: (e5) => showColorMenu(e5, "background"), style: { background: removeQuotes(props.selectedNode.styles?.["background"]) } - }), /* @__PURE__ */ import_react101.default.createElement(BorderSubmenu, { + }), /* @__PURE__ */ import_react103.default.createElement(BorderSubmenu, { ...props - }), /* @__PURE__ */ import_react101.default.createElement(StepSetter, { + }), /* @__PURE__ */ import_react103.default.createElement(StepSetter, { superstate: props.superstate, name: i18n_default.editor.opacity, min: 0, @@ -118037,7 +118390,7 @@ function listFonts() { } // src/core/react/components/SpaceView/Frames/FrameNodeEditor/Submenus/TextSubmenu.tsx -var import_react102 = __toESM(require_react()); +var import_react104 = __toESM(require_react()); var TextSubmenu = (props) => { const { selectedNode, saveStyleValue } = props; const showFontMenu = (e5) => { @@ -118074,22 +118427,22 @@ var TextSubmenu = (props) => { handleChangeComplete ); }; - return /* @__PURE__ */ import_react102.default.createElement(import_react102.default.Fragment, null, /* @__PURE__ */ import_react102.default.createElement("div", { + return /* @__PURE__ */ import_react104.default.createElement(import_react104.default.Fragment, null, /* @__PURE__ */ import_react104.default.createElement("div", { className: "mk-editor-frame-node-button", onClick: (e5) => showFontMenu(e5) - }, /* @__PURE__ */ import_react102.default.createElement("div", { + }, /* @__PURE__ */ import_react104.default.createElement("div", { dangerouslySetInnerHTML: { __html: props.superstate.ui.getSticker("ui//type") } - }), selectedNode.styles?.["--font-text"]), /* @__PURE__ */ import_react102.default.createElement("div", { + }), selectedNode.styles?.["--font-text"]), /* @__PURE__ */ import_react104.default.createElement("div", { className: "mk-divider" - }), /* @__PURE__ */ import_react102.default.createElement(StepSetter, { + }), /* @__PURE__ */ import_react104.default.createElement(StepSetter, { superstate: props.superstate, name: i18n_default.editor.size, value: selectedNode.styles?.["--font-text-size"], setValue: (value) => saveStyleValue("--font-text-size", value), units: ["px", "em"] - }), /* @__PURE__ */ import_react102.default.createElement(ToggleSetter, { + }), /* @__PURE__ */ import_react104.default.createElement(ToggleSetter, { superstate: props.superstate, name: i18n_default.editor.bold, value: selectedNode.styles?.["--font-text-weight"], @@ -118097,7 +118450,7 @@ var TextSubmenu = (props) => { onValue: "'bold'", icon: "ui//bold", setValue: (value) => saveStyleValue("--font-text-weight", value) - }), /* @__PURE__ */ import_react102.default.createElement(ToggleSetter, { + }), /* @__PURE__ */ import_react104.default.createElement(ToggleSetter, { superstate: props.superstate, name: i18n_default.editor.italic, value: selectedNode.styles?.["--font-text-style"], @@ -118105,7 +118458,7 @@ var TextSubmenu = (props) => { onValue: "'italic'", icon: "ui//italic", setValue: (value) => saveStyleValue("--font-text-style", value) - }), /* @__PURE__ */ import_react102.default.createElement(ToggleSetter, { + }), /* @__PURE__ */ import_react104.default.createElement(ToggleSetter, { superstate: props.superstate, name: i18n_default.editor.underline, value: selectedNode.styles?.["--font-text-decoration"], @@ -118113,13 +118466,13 @@ var TextSubmenu = (props) => { onValue: "'underline'", icon: "ui//underline", setValue: (value) => saveStyleValue("--font-text-decoration", value) - }), /* @__PURE__ */ import_react102.default.createElement(ColorSetter, { + }), /* @__PURE__ */ import_react104.default.createElement(ColorSetter, { superstate: props.superstate, value: removeQuotes(selectedNode.styles?.["--font-text-color"]), setValue: (value) => saveStyleValue("--font-text-color", `'${value}'`) - }), /* @__PURE__ */ import_react102.default.createElement("div", { + }), /* @__PURE__ */ import_react104.default.createElement("div", { className: "mk-divider" - }), /* @__PURE__ */ import_react102.default.createElement(ToggleSetter, { + }), /* @__PURE__ */ import_react104.default.createElement(ToggleSetter, { superstate: props.superstate, name: i18n_default.editor.alignLeft, value: selectedNode.styles?.["textAlign"], @@ -118127,7 +118480,7 @@ var TextSubmenu = (props) => { onValue: "'left'", icon: "ui//align-left", setValue: (value) => saveStyleValue("textAlign", value) - }), /* @__PURE__ */ import_react102.default.createElement(ToggleSetter, { + }), /* @__PURE__ */ import_react104.default.createElement(ToggleSetter, { superstate: props.superstate, name: i18n_default.editor.alignCenter, value: selectedNode.styles?.["textAlign"], @@ -118135,7 +118488,7 @@ var TextSubmenu = (props) => { onValue: "'center'", icon: "ui//align-center", setValue: (value) => saveStyleValue("textAlign", value) - }), /* @__PURE__ */ import_react102.default.createElement(ToggleSetter, { + }), /* @__PURE__ */ import_react104.default.createElement(ToggleSetter, { superstate: props.superstate, name: i18n_default.editor.alignRight, value: selectedNode.styles?.["textAlign"], @@ -118143,7 +118496,7 @@ var TextSubmenu = (props) => { onValue: "'right'", icon: "ui//align-right", setValue: (value) => saveStyleValue("textAlign", value) - }), /* @__PURE__ */ import_react102.default.createElement(ToggleSetter, { + }), /* @__PURE__ */ import_react104.default.createElement(ToggleSetter, { superstate: props.superstate, name: i18n_default.editor.alignJustify, value: selectedNode.styles?.["textAlign"], @@ -118151,9 +118504,9 @@ var TextSubmenu = (props) => { onValue: "'justify'", icon: "ui//align-justify", setValue: (value) => saveStyleValue("textAlign", value) - }), /* @__PURE__ */ import_react102.default.createElement("div", { + }), /* @__PURE__ */ import_react104.default.createElement("div", { className: "mk-divider" - }), /* @__PURE__ */ import_react102.default.createElement(StepSetter, { + }), /* @__PURE__ */ import_react104.default.createElement(StepSetter, { superstate: props.superstate, name: i18n_default.editor.numberOfLines, value: selectedNode.styles?.["--line-count"], @@ -118164,13 +118517,13 @@ var TextSubmenu = (props) => { // src/core/react/components/SpaceView/Frames/FrameNodeEditor/FrameNodeEditor.tsx var FrameNodeEditor = (props) => { - const { pathState } = (0, import_react103.useContext)(PathContext); + const { pathState } = (0, import_react105.useContext)(PathContext); const { deleteFrame, duplicateFrame } = props; - const { spaceInfo } = (0, import_react103.useContext)(SpaceContext); - const { addNode, ungroupNode, updateNode, saveNodes, frameProperties } = (0, import_react103.useContext)(FramesEditorRootContext); - const { selectionMode } = (0, import_react103.useContext)(FrameSelectionContext); - const { instance } = (0, import_react103.useContext)(FrameInstanceContext); - const saveNodeValue = (0, import_react103.useCallback)( + const { spaceInfo } = (0, import_react105.useContext)(SpaceContext); + const { addNode, ungroupNode, updateNode, saveNodes, frameProperties } = (0, import_react105.useContext)(FramesEditorRootContext); + const { selectionMode } = (0, import_react105.useContext)(FrameSelectionContext); + const { instance } = (0, import_react105.useContext)(FrameInstanceContext); + const saveNodeValue = (0, import_react105.useCallback)( (values2, node) => { updateNode(node, { props: { @@ -118187,9 +118540,9 @@ var FrameNodeEditor = (props) => { } }); }; - const [editMode, setEditMode] = (0, import_react103.useState)(0 /* EditModeNone */); - const [frameProps, setFrameProps] = (0, import_react103.useState)(props.node.props); - const fields = (0, import_react103.useMemo)(() => { + const [editMode, setEditMode] = (0, import_react105.useState)(0 /* EditModeNone */); + const [frameProps, setFrameProps] = (0, import_react105.useState)(props.node.props); + const fields = (0, import_react105.useMemo)(() => { return Object.keys(props.node.types).map((f2) => ({ type: props.node.types[f2], name: f2, @@ -118198,10 +118551,10 @@ var FrameNodeEditor = (props) => { value: props.node.propsValue?.[f2] })); }, [props.node]); - (0, import_react103.useEffect)(() => { + (0, import_react105.useEffect)(() => { setFrameProps(props.node.props); }, [props.node]); - const savePropValue = (0, import_react103.useCallback)( + const savePropValue = (0, import_react105.useCallback)( (prop2, value) => { setFrameProps((p) => ({ ...p, [prop2]: value })); saveNodeValue({ [prop2]: value }, props.node); @@ -118269,7 +118622,7 @@ var FrameNodeEditor = (props) => { defaultMenu(props.superstate.ui, menuOptions) ); }; - const propertiesRef = (0, import_react103.useRef)(null); + const propertiesRef = (0, import_react105.useRef)(null); const submenuProps = { superstate: props.superstate, exitMenu: () => setEditMode(0), @@ -118287,20 +118640,20 @@ var FrameNodeEditor = (props) => { frameProperties, instance }; - (0, import_react103.useEffect)(() => { + (0, import_react105.useEffect)(() => { if (propertiesRef.current) { propertiesRef.current.update(propertiesProps); } }, [instance, fields, props.state, props.node, frameProps]); - const ref2 = (0, import_react103.useRef)(null); - return /* @__PURE__ */ import_react103.default.createElement("div", { + const ref2 = (0, import_react105.useRef)(null); + return /* @__PURE__ */ import_react105.default.createElement("div", { className: "mk-editor-frame-node-selector", style: { pointerEvents: "auto" }, ref: ref2, onClick: (e5) => { e5.preventDefault(); } - }, props.node.type == "new" && /* @__PURE__ */ import_react103.default.createElement(import_react103.default.Fragment, null, /* @__PURE__ */ import_react103.default.createElement("div", { + }, props.node.type == "new" && /* @__PURE__ */ import_react105.default.createElement(import_react105.default.Fragment, null, /* @__PURE__ */ import_react105.default.createElement("div", { className: "mk-editor-frame-node-button-primary", dangerouslySetInnerHTML: { __html: props.superstate.ui.getSticker("ui//plus") @@ -118326,7 +118679,7 @@ var FrameNodeEditor = (props) => { ); e5.stopPropagation(); } - }), /* @__PURE__ */ import_react103.default.createElement("div", { + }), /* @__PURE__ */ import_react105.default.createElement("div", { className: "mk-editor-frame-node-button-primary", dangerouslySetInnerHTML: { __html: props.superstate.ui.getSticker("ui//plus") @@ -118355,9 +118708,9 @@ var FrameNodeEditor = (props) => { } e5.stopPropagation(); } - })), editMode == 0 /* EditModeNone */ ? /* @__PURE__ */ import_react103.default.createElement(import_react103.default.Fragment, null, props.node.type == "group" || props.node.type == "content" ? /* @__PURE__ */ import_react103.default.createElement(ContentSubmenu, { + })), editMode == 0 /* EditModeNone */ ? /* @__PURE__ */ import_react105.default.createElement(import_react105.default.Fragment, null, props.node.type == "group" || props.node.type == "content" ? /* @__PURE__ */ import_react105.default.createElement(ContentSubmenu, { ...submenuProps - }) : fields.length > 0 && /* @__PURE__ */ import_react103.default.createElement("div", { + }) : fields.length > 0 && /* @__PURE__ */ import_react105.default.createElement("div", { "aria-label": "Properties", className: "mk-editor-frame-node-button", onClick: (e5) => { @@ -118369,7 +118722,7 @@ var FrameNodeEditor = (props) => { e5.preventDefault(); propertiesRef.current = props.superstate.ui.openCustomMenu( ref2.current.getBoundingClientRect(), - /* @__PURE__ */ import_react103.default.createElement(PropertiesSubmenu, { + /* @__PURE__ */ import_react105.default.createElement(PropertiesSubmenu, { ...propertiesProps }), propertiesProps, @@ -118379,10 +118732,10 @@ var FrameNodeEditor = (props) => { dangerouslySetInnerHTML: { __html: props.superstate.ui.getSticker("ui//list") } - }), props.node.type == "text" && /* @__PURE__ */ import_react103.default.createElement(import_react103.default.Fragment, null, /* @__PURE__ */ import_react103.default.createElement("div", { + }), props.node.type == "text" && /* @__PURE__ */ import_react105.default.createElement(import_react105.default.Fragment, null, /* @__PURE__ */ import_react105.default.createElement("div", { className: "mk-editor-frame-node-button", onClick: (e5) => showTypographyMenu(e5) - }, /* @__PURE__ */ import_react103.default.createElement("div", { + }, /* @__PURE__ */ import_react105.default.createElement("div", { dangerouslySetInnerHTML: { __html: props.superstate.ui.getSticker( typographyOptions.find( @@ -118392,13 +118745,13 @@ var FrameNodeEditor = (props) => { } }), typographyOptions.find( (f2) => f2.class == removeQuotes(props.node.styles?.["class"]) - )?.name ?? "Paragraph"), /* @__PURE__ */ import_react103.default.createElement("div", { + )?.name ?? "Paragraph"), /* @__PURE__ */ import_react105.default.createElement("div", { className: "mk-divider" - })), props.node.type == "icon" && /* @__PURE__ */ import_react103.default.createElement(ColorSetter, { + })), props.node.type == "icon" && /* @__PURE__ */ import_react105.default.createElement(ColorSetter, { superstate: props.superstate, value: removeQuotes(props.node.styles?.["color"]), setValue: (value) => saveStyleValue("color", `'${value}'`) - }), /* @__PURE__ */ import_react103.default.createElement("div", { + }), /* @__PURE__ */ import_react105.default.createElement("div", { "aria-label": "Layout", className: "mk-editor-frame-node-button", onClick: (e5) => { @@ -118410,7 +118763,7 @@ var FrameNodeEditor = (props) => { dangerouslySetInnerHTML: { __html: props.superstate.ui.getSticker("ui//scaling") } - }), /* @__PURE__ */ import_react103.default.createElement("div", { + }), /* @__PURE__ */ import_react105.default.createElement("div", { "aria-label": "Style", className: `mk-editor-frame-node-button`, onClick: (e5) => { @@ -118421,9 +118774,9 @@ var FrameNodeEditor = (props) => { dangerouslySetInnerHTML: { __html: props.superstate.ui.getSticker("ui//paintbrush") } - }), (props.node.type == "flow" || props.node.type == "space") && /* @__PURE__ */ import_react103.default.createElement(ModeSubmenu, { + }), (props.node.type == "flow" || props.node.type == "space") && /* @__PURE__ */ import_react105.default.createElement(ModeSubmenu, { ...submenuProps - }), /* @__PURE__ */ import_react103.default.createElement("div", { + }), /* @__PURE__ */ import_react105.default.createElement("div", { "aria-label": "Text Style", className: `mk-editor-frame-node-button`, onClick: (e5) => { @@ -118434,9 +118787,9 @@ var FrameNodeEditor = (props) => { dangerouslySetInnerHTML: { __html: props.superstate.ui.getSticker("ui//type") } - }), selectionMode == 1 /* Page */ && /* @__PURE__ */ import_react103.default.createElement(import_react103.default.Fragment, null, /* @__PURE__ */ import_react103.default.createElement("div", { + }), selectionMode == 1 /* Page */ && /* @__PURE__ */ import_react105.default.createElement(import_react105.default.Fragment, null, /* @__PURE__ */ import_react105.default.createElement("div", { className: "mk-divider" - }), /* @__PURE__ */ import_react103.default.createElement(ToggleSetter, { + }), /* @__PURE__ */ import_react105.default.createElement(ToggleSetter, { superstate: props.superstate, name: "Page Width", setValue: (value) => { @@ -118446,23 +118799,23 @@ var FrameNodeEditor = (props) => { onValue: wrapQuotes("100%"), value: props.node.styles?.["--max-width"], icon: "ui//full-width" - })), /* @__PURE__ */ import_react103.default.createElement("div", { + })), /* @__PURE__ */ import_react105.default.createElement("div", { className: "mk-divider" - }), props.node.type == "group" || props.node.type == "container" ? /* @__PURE__ */ import_react103.default.createElement("div", { + }), props.node.type == "group" || props.node.type == "container" ? /* @__PURE__ */ import_react105.default.createElement("div", { "aria-label": "Ungroup", className: "mk-editor-frame-node-button", onClick: () => ungroupNode(props.node), dangerouslySetInnerHTML: { __html: props.superstate.ui.getSticker("ui//copy-x") } - }) : /* @__PURE__ */ import_react103.default.createElement(import_react103.default.Fragment, null), /* @__PURE__ */ import_react103.default.createElement("div", { + }) : /* @__PURE__ */ import_react105.default.createElement(import_react105.default.Fragment, null), /* @__PURE__ */ import_react105.default.createElement("div", { className: "mk-editor-frame-node-button", "aria-label": "Delete", onClick: () => deleteFrame(), dangerouslySetInnerHTML: { __html: props.superstate.ui.getSticker("ui//trash") } - })) : /* @__PURE__ */ import_react103.default.createElement(import_react103.default.Fragment, null, /* @__PURE__ */ import_react103.default.createElement("div", { + })) : /* @__PURE__ */ import_react105.default.createElement(import_react105.default.Fragment, null, /* @__PURE__ */ import_react105.default.createElement("div", { className: "mk-editor-frame-node-button", onMouseDown: (e5) => { e5.stopPropagation(); @@ -118472,28 +118825,28 @@ var FrameNodeEditor = (props) => { dangerouslySetInnerHTML: { __html: props.superstate.ui.getSticker("ui//close") } - }), /* @__PURE__ */ import_react103.default.createElement("div", { + }), /* @__PURE__ */ import_react105.default.createElement("div", { className: "mk-editor-frame-node-divider" - }), editMode == 3 /* EditModeText */ ? /* @__PURE__ */ import_react103.default.createElement(TextSubmenu, { + }), editMode == 3 /* EditModeText */ ? /* @__PURE__ */ import_react105.default.createElement(TextSubmenu, { ...submenuProps - }) : editMode == 4 /* EditModeLayout */ ? /* @__PURE__ */ import_react103.default.createElement(LayoutSubmenu, { + }) : editMode == 4 /* EditModeLayout */ ? /* @__PURE__ */ import_react105.default.createElement(LayoutSubmenu, { ...submenuProps - }) : editMode == 5 /* EditModeStyle */ ? /* @__PURE__ */ import_react103.default.createElement(StyleSubmenu, { + }) : editMode == 5 /* EditModeStyle */ ? /* @__PURE__ */ import_react105.default.createElement(StyleSubmenu, { ...submenuProps - }) : /* @__PURE__ */ import_react103.default.createElement(import_react103.default.Fragment, null))); + }) : /* @__PURE__ */ import_react105.default.createElement(import_react105.default.Fragment, null))); }; // src/core/react/components/SpaceView/Frames/EditorNodes/ContentNodeView.tsx -var import_react104 = __toESM(require_react()); +var import_react106 = __toESM(require_react()); var ContentNodeView = (props) => { - return /* @__PURE__ */ import_react104.default.createElement(import_react104.default.Fragment, null, props.children); + return /* @__PURE__ */ import_react106.default.createElement(import_react106.default.Fragment, null, props.children); }; // src/core/react/components/PathView/PathView.tsx -var import_react117 = __toESM(require_react()); +var import_react119 = __toESM(require_react()); // src/core/react/components/SpaceView/Contexts/SpaceView.tsx -var import_react114 = __toESM(require_react()); +var import_react116 = __toESM(require_react()); // node_modules/react-error-boundary/dist/react-error-boundary.cjs.mjs var import_react_error_boundary_cjs = __toESM(require_react_error_boundary_cjs(), 1); @@ -118503,8 +118856,8 @@ var import_lodash17 = __toESM(require_lodash()); // src/core/react/context/SidebarContext.tsx var import_lodash16 = __toESM(require_lodash()); -var import_react105 = __toESM(require_react()); -var NavigatorContext = (0, import_react105.createContext)({ +var import_react107 = __toESM(require_react()); +var NavigatorContext = (0, import_react107.createContext)({ dragPaths: [], setDragPaths: import_lodash16.default.noop, selectedPaths: [], @@ -118520,14 +118873,14 @@ var NavigatorContext = (0, import_react105.createContext)({ setModifier: import_lodash16.default.noop }); var SidebarProvider = (props) => { - const [modifier, setModifier] = (0, import_react105.useState)(null); - const [dragPaths, setDragPaths] = (0, import_react105.useState)([]); - const [selectedPaths, setSelectedPaths] = (0, import_react105.useState)([]); - const [activePath, setActivePath] = (0, import_react105.useState)(null); - const [waypoints, setWaypoints] = (0, import_react105.useState)( + const [modifier, setModifier] = (0, import_react107.useState)(null); + const [dragPaths, setDragPaths] = (0, import_react107.useState)([]); + const [selectedPaths, setSelectedPaths] = (0, import_react107.useState)([]); + const [activePath, setActivePath] = (0, import_react107.useState)(null); + const [waypoints, setWaypoints] = (0, import_react107.useState)( props.superstate.waypoints ); - const [activeViewSpaces, setActiveViewSpaces] = (0, import_react105.useState)( + const [activeViewSpaces, setActiveViewSpaces] = (0, import_react107.useState)( (props.superstate.waypoints[props.superstate.settings.currentWaypoint]?.paths ?? []).map((f2) => props.superstate.spacesIndex.get(f2)).filter((f2) => f2) ); const setActiveViewSpaceByPath = (path2) => { @@ -118574,7 +118927,7 @@ var SidebarProvider = (props) => { (props.superstate.waypoints[props.superstate.settings.currentWaypoint]?.paths ?? []).map((f2) => props.superstate.spacesIndex.get(f2)).filter((f2) => f2) ); }; - (0, import_react105.useEffect)(() => { + (0, import_react107.useEffect)(() => { props.superstate.eventsDispatcher.addListener( "spaceStateUpdated", refreshSpaces @@ -118602,7 +118955,7 @@ var SidebarProvider = (props) => { ); }; }, []); - return /* @__PURE__ */ import_react105.default.createElement(NavigatorContext.Provider, { + return /* @__PURE__ */ import_react107.default.createElement(NavigatorContext.Provider, { value: { dragPaths, setDragPaths, @@ -118735,14 +119088,14 @@ function getProjection(activeItem, items, paths, overItemIndex, dragDepth, yOffs var normalizedAltName = () => window.navigator.platform.startsWith("Mac") ? "\u2325" : "Alt"; // src/core/react/components/Navigator/SpaceTree/SpaceTreeView.tsx -var import_react109 = __toESM(require_react()); +var import_react111 = __toESM(require_react()); // src/core/react/components/Navigator/SpaceTree/SpaceTreeItem.tsx var import_classnames3 = __toESM(require_classnames()); -var import_react107 = __toESM(require_react()); +var import_react109 = __toESM(require_react()); // node_modules/react-dropzone/dist/es/index.js -var import_react106 = __toESM(require_react()); +var import_react108 = __toESM(require_react()); var import_prop_types = __toESM(require_prop_types()); // node_modules/tslib/tslib.es6.mjs @@ -119582,15 +119935,15 @@ function _objectWithoutPropertiesLoose2(source, excluded) { } return target; } -var Dropzone = /* @__PURE__ */ (0, import_react106.forwardRef)(function(_ref, ref2) { +var Dropzone = /* @__PURE__ */ (0, import_react108.forwardRef)(function(_ref, ref2) { var children = _ref.children, params = _objectWithoutProperties(_ref, _excluded2); var _useDropzone = useDropzone(params), open = _useDropzone.open, props = _objectWithoutProperties(_useDropzone, _excluded22); - (0, import_react106.useImperativeHandle)(ref2, function() { + (0, import_react108.useImperativeHandle)(ref2, function() { return { open }; }, [open]); - return /* @__PURE__ */ import_react106.default.createElement(import_react106.Fragment, null, children(_objectSpread5(_objectSpread5({}, props), {}, { + return /* @__PURE__ */ import_react108.default.createElement(import_react108.Fragment, null, children(_objectSpread5(_objectSpread5({}, props), {}, { open }))); }); @@ -119651,23 +120004,23 @@ var initialState = { function useDropzone() { var props = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : {}; var _defaultProps$props = _objectSpread5(_objectSpread5({}, defaultProps2), props), accept = _defaultProps$props.accept, disabled = _defaultProps$props.disabled, getFilesFromEvent = _defaultProps$props.getFilesFromEvent, maxSize = _defaultProps$props.maxSize, minSize = _defaultProps$props.minSize, multiple = _defaultProps$props.multiple, maxFiles = _defaultProps$props.maxFiles, onDragEnter = _defaultProps$props.onDragEnter, onDragLeave = _defaultProps$props.onDragLeave, onDragOver = _defaultProps$props.onDragOver, onDrop = _defaultProps$props.onDrop, onDropAccepted = _defaultProps$props.onDropAccepted, onDropRejected = _defaultProps$props.onDropRejected, onFileDialogCancel = _defaultProps$props.onFileDialogCancel, onFileDialogOpen = _defaultProps$props.onFileDialogOpen, useFsAccessApi = _defaultProps$props.useFsAccessApi, autoFocus = _defaultProps$props.autoFocus, preventDropOnDocument = _defaultProps$props.preventDropOnDocument, noClick = _defaultProps$props.noClick, noKeyboard = _defaultProps$props.noKeyboard, noDrag = _defaultProps$props.noDrag, noDragEventsBubbling = _defaultProps$props.noDragEventsBubbling, onError = _defaultProps$props.onError, validator = _defaultProps$props.validator; - var acceptAttr = (0, import_react106.useMemo)(function() { + var acceptAttr = (0, import_react108.useMemo)(function() { return acceptPropAsAcceptAttr(accept); }, [accept]); - var pickerTypes = (0, import_react106.useMemo)(function() { + var pickerTypes = (0, import_react108.useMemo)(function() { return pickerOptionsFromAccept(accept); }, [accept]); - var onFileDialogOpenCb = (0, import_react106.useMemo)(function() { + var onFileDialogOpenCb = (0, import_react108.useMemo)(function() { return typeof onFileDialogOpen === "function" ? onFileDialogOpen : noop2; }, [onFileDialogOpen]); - var onFileDialogCancelCb = (0, import_react106.useMemo)(function() { + var onFileDialogCancelCb = (0, import_react108.useMemo)(function() { return typeof onFileDialogCancel === "function" ? onFileDialogCancel : noop2; }, [onFileDialogCancel]); - var rootRef = (0, import_react106.useRef)(null); - var inputRef = (0, import_react106.useRef)(null); - var _useReducer = (0, import_react106.useReducer)(reducer2, initialState), _useReducer2 = _slicedToArray2(_useReducer, 2), state = _useReducer2[0], dispatch = _useReducer2[1]; + var rootRef = (0, import_react108.useRef)(null); + var inputRef = (0, import_react108.useRef)(null); + var _useReducer = (0, import_react108.useReducer)(reducer2, initialState), _useReducer2 = _slicedToArray2(_useReducer, 2), state = _useReducer2[0], dispatch = _useReducer2[1]; var isFocused = state.isFocused, isFileDialogActive = state.isFileDialogActive; - var fsAccessApiWorksRef = (0, import_react106.useRef)(typeof window !== "undefined" && window.isSecureContext && useFsAccessApi && canUseFileSystemAccessAPI()); + var fsAccessApiWorksRef = (0, import_react108.useRef)(typeof window !== "undefined" && window.isSecureContext && useFsAccessApi && canUseFileSystemAccessAPI()); var onWindowFocus = function onWindowFocus2() { if (!fsAccessApiWorksRef.current && isFileDialogActive) { setTimeout(function() { @@ -119683,13 +120036,13 @@ function useDropzone() { }, 300); } }; - (0, import_react106.useEffect)(function() { + (0, import_react108.useEffect)(function() { window.addEventListener("focus", onWindowFocus, false); return function() { window.removeEventListener("focus", onWindowFocus, false); }; }, [inputRef, isFileDialogActive, onFileDialogCancelCb, fsAccessApiWorksRef]); - var dragTargetsRef = (0, import_react106.useRef)([]); + var dragTargetsRef = (0, import_react108.useRef)([]); var onDocumentDrop = function onDocumentDrop2(event) { if (rootRef.current && rootRef.current.contains(event.target)) { return; @@ -119697,7 +120050,7 @@ function useDropzone() { event.preventDefault(); dragTargetsRef.current = []; }; - (0, import_react106.useEffect)(function() { + (0, import_react108.useEffect)(function() { if (preventDropOnDocument) { document.addEventListener("dragover", onDocumentDragOver, false); document.addEventListener("drop", onDocumentDrop, false); @@ -119709,21 +120062,21 @@ function useDropzone() { } }; }, [rootRef, preventDropOnDocument]); - (0, import_react106.useEffect)(function() { + (0, import_react108.useEffect)(function() { if (!disabled && autoFocus && rootRef.current) { rootRef.current.focus(); } return function() { }; }, [rootRef, autoFocus, disabled]); - var onErrCb = (0, import_react106.useCallback)(function(e5) { + var onErrCb = (0, import_react108.useCallback)(function(e5) { if (onError) { onError(e5); } else { console.error(e5); } }, [onError]); - var onDragEnterCb = (0, import_react106.useCallback)(function(event) { + var onDragEnterCb = (0, import_react108.useCallback)(function(event) { event.preventDefault(); event.persist(); stopPropagation2(event); @@ -119758,7 +120111,7 @@ function useDropzone() { }); } }, [getFilesFromEvent, onDragEnter, onErrCb, noDragEventsBubbling, acceptAttr, minSize, maxSize, multiple, maxFiles, validator]); - var onDragOverCb = (0, import_react106.useCallback)(function(event) { + var onDragOverCb = (0, import_react108.useCallback)(function(event) { event.preventDefault(); event.persist(); stopPropagation2(event); @@ -119774,7 +120127,7 @@ function useDropzone() { } return false; }, [onDragOver, noDragEventsBubbling]); - var onDragLeaveCb = (0, import_react106.useCallback)(function(event) { + var onDragLeaveCb = (0, import_react108.useCallback)(function(event) { event.preventDefault(); event.persist(); stopPropagation2(event); @@ -119799,7 +120152,7 @@ function useDropzone() { onDragLeave(event); } }, [rootRef, onDragLeave, noDragEventsBubbling]); - var setFiles = (0, import_react106.useCallback)(function(files, event) { + var setFiles = (0, import_react108.useCallback)(function(files, event) { var acceptedFiles = []; var fileRejections = []; files.forEach(function(file) { @@ -119845,7 +120198,7 @@ function useDropzone() { onDropAccepted(acceptedFiles, event); } }, [dispatch, multiple, acceptAttr, minSize, maxSize, maxFiles, onDrop, onDropAccepted, onDropRejected, validator]); - var onDropCb = (0, import_react106.useCallback)(function(event) { + var onDropCb = (0, import_react108.useCallback)(function(event) { event.preventDefault(); event.persist(); stopPropagation2(event); @@ -119864,7 +120217,7 @@ function useDropzone() { type: "reset" }); }, [getFilesFromEvent, setFiles, onErrCb, noDragEventsBubbling]); - var openFileDialog = (0, import_react106.useCallback)(function() { + var openFileDialog = (0, import_react108.useCallback)(function() { if (fsAccessApiWorksRef.current) { dispatch({ type: "openDialog" @@ -119910,7 +120263,7 @@ function useDropzone() { inputRef.current.click(); } }, [dispatch, onFileDialogOpenCb, onFileDialogCancelCb, useFsAccessApi, setFiles, onErrCb, pickerTypes, multiple]); - var onKeyDownCb = (0, import_react106.useCallback)(function(event) { + var onKeyDownCb = (0, import_react108.useCallback)(function(event) { if (!rootRef.current || !rootRef.current.isEqualNode(event.target)) { return; } @@ -119919,17 +120272,17 @@ function useDropzone() { openFileDialog(); } }, [rootRef, openFileDialog]); - var onFocusCb = (0, import_react106.useCallback)(function() { + var onFocusCb = (0, import_react108.useCallback)(function() { dispatch({ type: "focus" }); }, []); - var onBlurCb = (0, import_react106.useCallback)(function() { + var onBlurCb = (0, import_react108.useCallback)(function() { dispatch({ type: "blur" }); }, []); - var onClickCb = (0, import_react106.useCallback)(function() { + var onClickCb = (0, import_react108.useCallback)(function() { if (noClick) { return; } @@ -119953,7 +120306,7 @@ function useDropzone() { event.stopPropagation(); } }; - var getRootProps = (0, import_react106.useMemo)(function() { + var getRootProps = (0, import_react108.useMemo)(function() { return function() { var _ref2 = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : {}, _ref2$refKey = _ref2.refKey, refKey = _ref2$refKey === void 0 ? "ref" : _ref2$refKey, role = _ref2.role, onKeyDown = _ref2.onKeyDown, onFocus = _ref2.onFocus, onBlur = _ref2.onBlur, onClick = _ref2.onClick, onDragEnter2 = _ref2.onDragEnter, onDragOver2 = _ref2.onDragOver, onDragLeave2 = _ref2.onDragLeave, onDrop2 = _ref2.onDrop, rest = _objectWithoutProperties(_ref2, _excluded3); return _objectSpread5(_objectSpread5(_defineProperty3({ @@ -119971,10 +120324,10 @@ function useDropzone() { } : {}), rest); }; }, [rootRef, onKeyDownCb, onFocusCb, onBlurCb, onClickCb, onDragEnterCb, onDragOverCb, onDragLeaveCb, onDropCb, noKeyboard, noDrag, disabled]); - var onInputElementClick = (0, import_react106.useCallback)(function(event) { + var onInputElementClick = (0, import_react108.useCallback)(function(event) { event.stopPropagation(); }, []); - var getInputProps = (0, import_react106.useMemo)(function() { + var getInputProps = (0, import_react108.useMemo)(function() { return function() { var _ref3 = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : {}, _ref3$refKey = _ref3.refKey, refKey = _ref3$refKey === void 0 ? "ref" : _ref3$refKey, onChange = _ref3.onChange, onClick = _ref3.onClick, rest = _objectWithoutProperties(_ref3, _excluded4); var inputProps = _defineProperty3({ @@ -120071,14 +120424,14 @@ var TreeItem = (props) => { setSelectedPaths, setDragPaths, closeActiveSpace - } = (0, import_react107.useContext)(NavigatorContext); - const [hoverTarget, setHoverTarget] = (0, import_react107.useState)(null); - const innerRef = (0, import_react107.useRef)(null); - const [dropHighlighted, setDropHighlighted] = (0, import_react107.useState)(false); - const [pathState, setPathState] = (0, import_react107.useState)( + } = (0, import_react109.useContext)(NavigatorContext); + const [hoverTarget, setHoverTarget] = (0, import_react109.useState)(null); + const innerRef = (0, import_react109.useRef)(null); + const [dropHighlighted, setDropHighlighted] = (0, import_react109.useState)(false); + const [pathState, setPathState] = (0, import_react109.useState)( superstate.pathsIndex.get(data2.item.path) ); - (0, import_react107.useEffect)( + (0, import_react109.useEffect)( () => setPathState(superstate.pathsIndex.get(data2.item.path)), [data2.item.path] ); @@ -120137,7 +120490,7 @@ var TreeItem = (props) => { superstate.ui.openPath(pathState.path, "hover", el); } }; - const onDrop = (0, import_react107.useCallback)((files) => { + const onDrop = (0, import_react109.useCallback)((files) => { if (isFolder) { files.map(async (file) => { file.arrayBuffer().then((arrayBuffer) => { @@ -120150,7 +120503,7 @@ var TreeItem = (props) => { }); } }, []); - const onDragEnter = (0, import_react107.useCallback)(() => { + const onDragEnter = (0, import_react109.useCallback)(() => { if (isFolder) setDropHighlighted(true); }, []); @@ -120171,14 +120524,16 @@ var TreeItem = (props) => { const newAction = (e5) => { const space2 = superstate.spacesIndex.get(pathState.path); if (e5.shiftKey) { + const offset2 = e5.target.getBoundingClientRect(); showLinkMenu( - e5, + offset2, superstate, (link) => { pinPathToSpaceAtIndex(superstate, space2, link); }, { placeholder: i18n_default.labels.pinNotePlaceholder } ); + e5.stopPropagation(); return; } defaultAddAction(superstate, space2); @@ -120214,7 +120569,7 @@ var TreeItem = (props) => { setPathState(_pathState); } }; - (0, import_react107.useEffect)(() => { + (0, import_react109.useEffect)(() => { superstate.eventsDispatcher.addListener( "pathStateUpdated", pathStateUpdated @@ -120234,7 +120589,7 @@ var TreeItem = (props) => { } } }; - (0, import_react107.useEffect)(() => { + (0, import_react109.useEffect)(() => { if (hoverTarget && superstate.settings.filePreviewOnHover) { window.addEventListener("keydown", onKeyDown); return () => { @@ -120255,7 +120610,7 @@ var TreeItem = (props) => { const extension = pathState?.metadata?.file?.extension; const isLink = pathState?.parent != data2.space; const spacing = data2.type == "group" ? 0 : indentationWidth * (depth - 1) + (data2.type == "space" ? 0 : isTouchScreen(props.superstate.ui) ? 30 : 20); - return /* @__PURE__ */ import_react107.default.createElement(import_react107.default.Fragment, null, /* @__PURE__ */ import_react107.default.createElement("div", { + return /* @__PURE__ */ import_react109.default.createElement(import_react109.default.Fragment, null, /* @__PURE__ */ import_react109.default.createElement("div", { className: (0, import_classnames3.default)( "mk-tree-wrapper", data2.type == "group" ? "mk-tree-section" : "", @@ -120279,16 +120634,16 @@ var TreeItem = (props) => { onContextMenu: (e5) => handleRightClick(e5), ...dropProps, ...innerProps - }, /* @__PURE__ */ import_react107.default.createElement("div", { + }, /* @__PURE__ */ import_react109.default.createElement("div", { className: (0, import_classnames3.default)(isFolder ? "nav-folder" : "nav-file"), style: { ...style, ...dragActive ? { pointerEvents: "none" } : {} }, ...!isTouchScreen(props.superstate.ui) ? getRootProps({ className: "dropzone" }) : {} - }, /* @__PURE__ */ import_react107.default.createElement("input", { + }, /* @__PURE__ */ import_react109.default.createElement("input", { ...getInputProps() - }), /* @__PURE__ */ import_react107.default.createElement("div", { + }), /* @__PURE__ */ import_react109.default.createElement("div", { className: (0, import_classnames3.default)( "mk-tree-item", "tree-item-self", @@ -120302,33 +120657,33 @@ var TreeItem = (props) => { "--childrenCount": `${data2.type == "space" && !collapsed ? childCount * spaceRowHeight(superstate, false) - 13 : 0}px` }, "data-path": pathState?.path - }, data2.type == "space" && /* @__PURE__ */ import_react107.default.createElement(CollapseToggle, { + }, data2.type == "space" && /* @__PURE__ */ import_react109.default.createElement(CollapseToggle, { superstate: props.superstate, collapsed, onToggle: (c3, e5) => { onCollapse(data2, false); e5.stopPropagation(); } - }), superstate.settings.spacesStickers && pathState && /* @__PURE__ */ import_react107.default.createElement(PathStickerView, { + }), superstate.settings.spacesStickers && pathState && /* @__PURE__ */ import_react109.default.createElement(PathStickerView, { superstate, pathState, editable: true - }), /* @__PURE__ */ import_react107.default.createElement("div", { + }), /* @__PURE__ */ import_react109.default.createElement("div", { className: `mk-tree-text ${isFolder ? "nav-folder-title-content" : "nav-file-title-content"}` - }, pathState?.displayName ?? pathState?.name ?? data2.path), data2.type == "group" && data2.childrenCount > 0 && /* @__PURE__ */ import_react107.default.createElement(CollapseToggle, { + }, pathState?.displayName ?? pathState?.name ?? data2.path), data2.type == "group" && data2.childrenCount > 0 && /* @__PURE__ */ import_react109.default.createElement(CollapseToggle, { superstate: props.superstate, collapsed, onToggle: (c3, e5) => { onCollapse(data2, false); e5.stopPropagation(); } - }), /* @__PURE__ */ import_react107.default.createElement("div", { + }), /* @__PURE__ */ import_react109.default.createElement("div", { className: "mk-tree-span" - }), !isSpace && extension != "md" && /* @__PURE__ */ import_react107.default.createElement("span", { + }), !isSpace && extension != "md" && /* @__PURE__ */ import_react109.default.createElement("span", { className: "nav-file-tag" - }, extension), !clone5 ? /* @__PURE__ */ import_react107.default.createElement("div", { + }, extension), !clone5 ? /* @__PURE__ */ import_react109.default.createElement("div", { className: "mk-folder-buttons" - }, /* @__PURE__ */ import_react107.default.createElement("button", { + }, /* @__PURE__ */ import_react109.default.createElement("button", { "aria-label": i18n_default.buttons.moreOptions, onClick: (e5) => { contextMenu(e5); @@ -120337,7 +120692,7 @@ var TreeItem = (props) => { dangerouslySetInnerHTML: { __html: superstate.ui.getSticker("ui//options") } - }), isSpace && /* @__PURE__ */ import_react107.default.createElement("button", { + }), isSpace && /* @__PURE__ */ import_react109.default.createElement("button", { "aria-label": i18n_default.buttons.newNote, onClick: (e5) => { newAction(e5); @@ -120346,12 +120701,12 @@ var TreeItem = (props) => { dangerouslySetInnerHTML: { __html: superstate.ui.getSticker("ui//plus") } - })) : /* @__PURE__ */ import_react107.default.createElement(import_react107.default.Fragment, null))))); + })) : /* @__PURE__ */ import_react109.default.createElement(import_react109.default.Fragment, null))))); }; TreeItem.displayName = "TreeItem"; // node_modules/@tanstack/react-virtual/dist/esm/index.js -var React105 = __toESM(require_react(), 1); +var React107 = __toESM(require_react(), 1); var import_react_dom6 = __toESM(require_react_dom(), 1); // node_modules/@tanstack/virtual-core/dist/esm/utils.js @@ -121002,9 +121357,9 @@ function calculateRange({ } // node_modules/@tanstack/react-virtual/dist/esm/index.js -var useIsomorphicLayoutEffect3 = typeof document !== "undefined" ? React105.useLayoutEffect : React105.useEffect; +var useIsomorphicLayoutEffect3 = typeof document !== "undefined" ? React107.useLayoutEffect : React107.useEffect; function useVirtualizerBase(options) { - const rerender = React105.useReducer(() => ({}), {})[1]; + const rerender = React107.useReducer(() => ({}), {})[1]; const resolvedOptions = { ...options, onChange: (instance2, sync) => { @@ -121017,11 +121372,11 @@ function useVirtualizerBase(options) { (_a = options.onChange) == null ? void 0 : _a.call(options, instance2, sync); } }; - const [instance] = React105.useState( + const [instance] = React107.useState( () => new Virtualizer(resolvedOptions) ); instance.setOptions(resolvedOptions); - React105.useEffect(() => { + React107.useEffect(() => { return instance._didMount(); }, []); useIsomorphicLayoutEffect3(() => { @@ -121039,8 +121394,8 @@ function useVirtualizer(options) { } // src/core/react/components/Navigator/SpaceTree/SpaceTreeVirtualized.tsx -var import_react108 = __toESM(require_react()); -var VirtualizedList = import_react108.default.memo(function VirtualizedList2(props) { +var import_react110 = __toESM(require_react()); +var VirtualizedList = import_react110.default.memo(function VirtualizedList2(props) { const { flattenedTree, rowHeights, @@ -121055,16 +121410,16 @@ var VirtualizedList = import_react108.default.memo(function VirtualizedList2(pro activeIndex, indentationWidth } = props; - const parentRef = import_react108.default.useRef(null); + const parentRef = import_react110.default.useRef(null); const rowVirtualizer = useVirtualizer({ count: flattenedTree.length, paddingEnd: 24, getScrollElement: () => parentRef.current, - estimateSize: import_react108.default.useCallback((index2) => rowHeights[index2], [rowHeights]), + estimateSize: import_react110.default.useCallback((index2) => rowHeights[index2], [rowHeights]), overscan: 0 }); vRef.current = rowVirtualizer; - const { saveActiveSpace } = (0, import_react108.useContext)(NavigatorContext); + const { saveActiveSpace } = (0, import_react110.useContext)(NavigatorContext); const dropIndicator = (index2) => { return overIndex == index2 && projected && projected.insert; }; @@ -121113,7 +121468,7 @@ var VirtualizedList = import_react108.default.memo(function VirtualizedList2(pro } } }; - return /* @__PURE__ */ import_react108.default.createElement("div", { + return /* @__PURE__ */ import_react110.default.createElement("div", { ref: parentRef, style: { width: `100%`, @@ -121121,13 +121476,13 @@ var VirtualizedList = import_react108.default.memo(function VirtualizedList2(pro overflow: "auto", "--spaceRowHeight": spaceRowHeight(superstate, false) + "px" } - }, /* @__PURE__ */ import_react108.default.createElement("div", { + }, /* @__PURE__ */ import_react110.default.createElement("div", { style: { height: `${rowVirtualizer.getTotalSize()}px`, width: "100%", position: "relative" } - }, rowVirtualizer.getVirtualItems().map((virtualRow) => /* @__PURE__ */ import_react108.default.createElement("div", { + }, rowVirtualizer.getVirtualItems().map((virtualRow) => /* @__PURE__ */ import_react110.default.createElement("div", { key: virtualRow.index, style: { position: "absolute", @@ -121137,34 +121492,37 @@ var VirtualizedList = import_react108.default.memo(function VirtualizedList2(pro height: `${rowHeights[virtualRow.index]}px`, transform: `translateY(${virtualRow.start}px)` } - }, flattenedTree[virtualRow.index].type == "new" ? /* @__PURE__ */ import_react108.default.createElement("div", { + }, flattenedTree[virtualRow.index].type == "new" ? /* @__PURE__ */ import_react110.default.createElement("div", { className: "mk-tree-wrapper mk-tree-section", - onClick: (e5) => showSpacesMenu( - e5, - props.superstate, - (link, isNew) => { - if (isNew) { - createSpace(props.superstate, link, {}).then((f2) => { - saveActiveSpace(link); - props.superstate.ui.openPath(link, false); - }); - return; - } - saveActiveSpace(link); - }, - true, - true - ) - }, /* @__PURE__ */ import_react108.default.createElement("div", { + onClick: (e5) => { + const offset2 = e5.target.getBoundingClientRect(); + showSpacesMenu( + offset2, + props.superstate, + (link, isNew) => { + if (isNew) { + createSpace(props.superstate, link, {}).then((f2) => { + saveActiveSpace(link); + props.superstate.ui.openPath(link, false); + }); + return; + } + saveActiveSpace(link); + }, + true, + true + ); + } + }, /* @__PURE__ */ import_react110.default.createElement("div", { className: "mk-tree-item tree-item-self nav-folder-title mk-tree-new" - }, /* @__PURE__ */ import_react108.default.createElement("div", { + }, /* @__PURE__ */ import_react110.default.createElement("div", { className: `mk-path-icon mk-path-icon-placeholder`, dangerouslySetInnerHTML: { __html: props.superstate.ui.getSticker("ui//plus") } - }), /* @__PURE__ */ import_react108.default.createElement("div", { + }), /* @__PURE__ */ import_react110.default.createElement("div", { className: "mk-tree-text nav-folder-title-content" - }, i18n_default.menu.openSpace))) : /* @__PURE__ */ import_react108.default.createElement(TreeItem, { + }, i18n_default.menu.openSpace))) : /* @__PURE__ */ import_react110.default.createElement(TreeItem, { key: flattenedTree[virtualRow.index].id, id: flattenedTree[virtualRow.index].id, data: flattenedTree[virtualRow.index], @@ -121356,7 +121714,7 @@ var retrieveData = (superstate, activeViewSpaces, active, expandedSpaces) => { var SpaceTreeComponent = (props) => { const { superstate } = props; const indentationWidth = isTouchScreen(props.superstate.ui) ? 20 : 16; - const [expandedSpaces, setExpandedSpaces] = (0, import_react109.useState)( + const [expandedSpaces, setExpandedSpaces] = (0, import_react111.useState)( superstate.settings.expandedSpaces ); const { @@ -121369,21 +121727,21 @@ var SpaceTreeComponent = (props) => { setDragPaths, modifier, setModifier - } = (0, import_react109.useContext)(NavigatorContext); - const [active, setActive] = (0, import_react109.useState)(null); - const [overId, setOverId] = (0, import_react109.useState)(null); - const [flattenedTree, setFlattenedTree] = (0, import_react109.useState)([]); - const nextTreeScrollPath = (0, import_react109.useRef)(null); - const [offset2, setOffset] = (0, import_react109.useState)({ x: 0, y: 0 }); - const listRef = (0, import_react109.useRef)(null); - const refreshableSpaces = (0, import_react109.useMemo)( + } = (0, import_react111.useContext)(NavigatorContext); + const [active, setActive] = (0, import_react111.useState)(null); + const [overId, setOverId] = (0, import_react111.useState)(null); + const [flattenedTree, setFlattenedTree] = (0, import_react111.useState)([]); + const nextTreeScrollPath = (0, import_react111.useRef)(null); + const [offset2, setOffset] = (0, import_react111.useState)({ x: 0, y: 0 }); + const listRef = (0, import_react111.useRef)(null); + const refreshableSpaces = (0, import_react111.useMemo)( () => [ ...activeViewSpaces.filter((f2) => f2).map((f2) => f2.path), ...flattenedTree.filter((f2) => f2.type == "space").map((f2) => f2.path) ].filter((f2) => f2), [activeViewSpaces, flattenedTree] ); - (0, import_react109.useEffect)(() => { + (0, import_react111.useEffect)(() => { if (selectedPaths.length <= 1) { if (!selectedPaths[0] || selectedPaths[0].item.path != activePath) setSelectedPaths([]); @@ -121401,13 +121759,13 @@ var SpaceTreeComponent = (props) => { ); }; }, [activePath]); - (0, import_react109.useEffect)(() => { + (0, import_react111.useEffect)(() => { window.addEventListener("dragend", resetState); return () => { window.removeEventListener("dragend", resetState); }; }); - (0, import_react109.useEffect)(() => { + (0, import_react111.useEffect)(() => { const settingsChanged = () => { setExpandedSpaces(superstate.settings.expandedSpaces); }; @@ -121419,7 +121777,7 @@ var SpaceTreeComponent = (props) => { ); }; }, [activeViewSpaces, active, setExpandedSpaces, setFlattenedTree]); - const revealPath = (0, import_react109.useCallback)( + const revealPath = (0, import_react111.useCallback)( (path2) => { if (!path2 || !activeViewSpaces?.some((f2) => f2.path == "/")) return; @@ -121438,7 +121796,7 @@ var SpaceTreeComponent = (props) => { }, [expandedSpaces, activeViewSpaces] ); - (0, import_react109.useEffect)(() => { + (0, import_react111.useEffect)(() => { const handleRevealPathEvent = (evt) => { if (evt.detail) revealPath(evt.detail.path); @@ -121448,7 +121806,7 @@ var SpaceTreeComponent = (props) => { window.removeEventListener(eventTypes.revealPath, handleRevealPathEvent); }; }, [revealPath]); - (0, import_react109.useEffect)(() => { + (0, import_react111.useEffect)(() => { const reloadData = () => { setFlattenedTree( retrieveData(superstate, activeViewSpaces, active, expandedSpaces) @@ -121477,7 +121835,7 @@ var SpaceTreeComponent = (props) => { refreshableSpaces, setFlattenedTree ]); - (0, import_react109.useEffect)(() => { + (0, import_react111.useEffect)(() => { setFlattenedTree( retrieveData(superstate, activeViewSpaces, active, expandedSpaces) ); @@ -121485,19 +121843,19 @@ var SpaceTreeComponent = (props) => { const changeActivePath = (path2) => { setActivePath(path2); }; - const overIndex = (0, import_react109.useMemo)( + const overIndex = (0, import_react111.useMemo)( () => flattenedTree.findIndex((f2) => f2.id == overId), [overId, flattenedTree] ); - const activeIndex = (0, import_react109.useMemo)( + const activeIndex = (0, import_react111.useMemo)( () => active?.id ? flattenedTree.findIndex((f2) => f2.id == active.id) : -1, [active, flattenedTree] ); - const sortedIds = (0, import_react109.useMemo)( + const sortedIds = (0, import_react111.useMemo)( () => flattenedTree.map(({ id: id3 }) => id3), [flattenedTree] ); - const selectRange2 = (0, import_react109.useCallback)( + const selectRange2 = (0, import_react111.useCallback)( (fromId) => { const startIndex = sortedIds.findIndex((f2) => f2 == fromId); const selectedPathsStartIndex = sortedIds.findIndex( @@ -121518,8 +121876,8 @@ var SpaceTreeComponent = (props) => { }, [sortedIds, selectedPaths, setSelectedPaths, flattenedTree] ); - const [projected, setProjected] = (0, import_react109.useState)(null); - (0, import_react109.useEffect)(() => { + const [projected, setProjected] = (0, import_react111.useState)(null); + (0, import_react111.useEffect)(() => { const dragDepth = getDragDepth(offset2.x, indentationWidth); const _projected = overId ? getProjection( active, @@ -121558,11 +121916,11 @@ var SpaceTreeComponent = (props) => { } document.body.style.setProperty("cursor", "grabbing"); }; - const parentName = (0, import_react109.useMemo)( + const parentName = (0, import_react111.useMemo)( () => projected ? flattenedTree.find((f2) => f2.id == projected.parentId)?.item?.name : null, [flattenedTree, projected] ); - const overName = (0, import_react109.useMemo)( + const overName = (0, import_react111.useMemo)( () => projected && flattenedTree.find((f2) => f2.id == projected.overId)?.item?.name, [flattenedTree, projected] ); @@ -121593,7 +121951,7 @@ var SpaceTreeComponent = (props) => { }); } }; - (0, import_react109.useEffect)(() => { + (0, import_react111.useEffect)(() => { if (dragPaths.length == 0) { setOverId(null); setActive(null); @@ -121618,7 +121976,7 @@ var SpaceTreeComponent = (props) => { ); resetState(); }; - const handleCollapse = (0, import_react109.useCallback)( + const handleCollapse = (0, import_react111.useCallback)( (folder, open) => { const folderOpen = expandedSpaces?.includes(folder.id); const newOpenFolders = !folderOpen || open ? [...expandedSpaces, folder.id] : expandedSpaces.filter( @@ -121639,7 +121997,7 @@ var SpaceTreeComponent = (props) => { dragCounter.current = 0; document.body.style.setProperty("cursor", ""); } - const dragCounter = (0, import_react109.useRef)(0); + const dragCounter = (0, import_react111.useRef)(0); const dragEnter = () => { dragCounter.current++; }; @@ -121652,11 +122010,11 @@ var SpaceTreeComponent = (props) => { dragCounter.current = 0; } }; - const rowHeights = (0, import_react109.useMemo)( + const rowHeights = (0, import_react111.useMemo)( () => flattenedTree.map((f2) => spaceRowHeight(superstate, f2.type == "group")), [flattenedTree] ); - return /* @__PURE__ */ import_react109.default.createElement("div", { + return /* @__PURE__ */ import_react111.default.createElement("div", { className: `mk-path-tree`, onDragEnter: () => dragEnter(), onDragLeave: () => dragLeave(), @@ -121668,7 +122026,7 @@ var SpaceTreeComponent = (props) => { resetState(); } } - }, /* @__PURE__ */ import_react109.default.createElement(VirtualizedList, { + }, /* @__PURE__ */ import_react111.default.createElement(VirtualizedList, { vRef: listRef, rowHeights, flattenedTree, @@ -121684,7 +122042,7 @@ var SpaceTreeComponent = (props) => { dragEnded, overIndex, activeIndex - }), modifier && !isTouchScreen(props.superstate.ui) && /* @__PURE__ */ import_react109.default.createElement("div", { + }), modifier && !isTouchScreen(props.superstate.ui) && /* @__PURE__ */ import_react111.default.createElement("div", { className: "mk-hint-dnd", style: { position: "absolute", @@ -121697,49 +122055,49 @@ var SpaceTreeComponent = (props) => { color: "var(--text-on-accent)", fontSize: "12px" } - }, /* @__PURE__ */ import_react109.default.createElement("div", null, i18n_default.hintText.dragDropModifierKeys.replace("${1}", "shift").replace("${2}", normalizedAltName())))); + }, /* @__PURE__ */ import_react111.default.createElement("div", null, i18n_default.hintText.dragDropModifierKeys.replace("${1}", "shift").replace("${2}", normalizedAltName())))); }; // src/core/react/components/Navigator/MainList.tsx -var import_react113 = __toESM(require_react()); +var import_react115 = __toESM(require_react()); // src/core/react/components/Navigator/MainMenu.tsx var import_classnames4 = __toESM(require_classnames()); -var import_react110 = __toESM(require_react()); +var import_react112 = __toESM(require_react()); var MainMenu = (props) => { const { superstate } = props; - const { setActivePath, setDragPaths } = (0, import_react110.useContext)(NavigatorContext); - const ref2 = (0, import_react110.useRef)(); - return /* @__PURE__ */ import_react110.default.createElement("div", { + const { setActivePath, setDragPaths } = (0, import_react112.useContext)(NavigatorContext); + const ref2 = (0, import_react112.useRef)(); + return /* @__PURE__ */ import_react112.default.createElement("div", { className: "mk-main-menu-container" - }, /* @__PURE__ */ import_react110.default.createElement("div", { + }, /* @__PURE__ */ import_react112.default.createElement("div", { className: "mk-main-menu-inner" - }, /* @__PURE__ */ import_react110.default.createElement("div", { + }, /* @__PURE__ */ import_react112.default.createElement("div", { className: (0, import_classnames4.default)("mk-main-menu") - }, /* @__PURE__ */ import_react110.default.createElement("div", { + }, /* @__PURE__ */ import_react112.default.createElement("div", { className: `mk-main-menu-button mk-main-menu-button-primary`, ref: ref2, onClick: (e5) => { props.superstate.ui.mainMenu(ref2.current, superstate); } - }, props.superstate.settings.systemName, /* @__PURE__ */ import_react110.default.createElement("div", { + }, props.superstate.settings.systemName, /* @__PURE__ */ import_react112.default.createElement("div", { className: "mk-icon-xsmall", dangerouslySetInnerHTML: { __html: props.superstate.ui.getSticker("ui//chevrons-up-down") } - })), /* @__PURE__ */ import_react110.default.createElement("div", { + })), /* @__PURE__ */ import_react112.default.createElement("div", { className: "mk-main-menu-button", onClick: (e5) => props.superstate.ui.quickOpen(superstate) - }, /* @__PURE__ */ import_react110.default.createElement("div", { + }, /* @__PURE__ */ import_react112.default.createElement("div", { className: "mk-icon-small", dangerouslySetInnerHTML: { __html: props.superstate.ui.getSticker("ui//search") } - }))), /* @__PURE__ */ import_react110.default.createElement("button", { + }))), /* @__PURE__ */ import_react112.default.createElement("button", { "aria-label": i18n_default.buttons.newNote, className: "mk-main-menu-button", onClick: (e5) => defaultAddAction(superstate, null, e5.metaKey ? "tab" : false) - }, /* @__PURE__ */ import_react110.default.createElement("div", { + }, /* @__PURE__ */ import_react112.default.createElement("div", { className: "mk-icon-small", dangerouslySetInnerHTML: { __html: props.superstate.ui.getSticker("ui//new-note") @@ -121748,23 +122106,23 @@ var MainMenu = (props) => { }; // src/core/react/components/Navigator/Waypoints/Waypoints.tsx -var import_react112 = __toESM(require_react()); +var import_react114 = __toESM(require_react()); var import_react_dom7 = __toESM(require_react_dom()); // src/core/react/components/Navigator/Waypoints/Waypoint.tsx var import_classnames5 = __toESM(require_classnames()); -var import_react111 = __toESM(require_react()); +var import_react113 = __toESM(require_react()); var SortablePinnedSpaceItem = ({ id: id3, index: index2, ...props }) => { - return /* @__PURE__ */ import_react111.default.createElement(PinnedSpace, { + return /* @__PURE__ */ import_react113.default.createElement(PinnedSpace, { index: index2, ...props }); }; -var PinnedSpace = (0, import_react111.forwardRef)( +var PinnedSpace = (0, import_react113.forwardRef)( ({ pin, indicator, @@ -121778,13 +122136,13 @@ var PinnedSpace = (0, import_react111.forwardRef)( dragEnded, index: index2 }, ref2) => { - const innerRef = (0, import_react111.useRef)(null); + const innerRef = (0, import_react113.useRef)(null); const { activePath, waypoints, setWaypoints, setModifier - } = (0, import_react111.useContext)(NavigatorContext); + } = (0, import_react113.useContext)(NavigatorContext); const onDragStarted = (e5) => { if (dragStart && pin) { dragStart(index2); @@ -121801,7 +122159,7 @@ var PinnedSpace = (0, import_react111.forwardRef)( onDragEnd: onDragEnded, onDrop: onDragEnded }; - return pin ? /* @__PURE__ */ import_react111.default.createElement("div", { + return pin ? /* @__PURE__ */ import_react113.default.createElement("div", { onContextMenu: (e5) => { const menuOptions = [ { @@ -121809,7 +122167,7 @@ var PinnedSpace = (0, import_react111.forwardRef)( icon: "ui//edit", value: "change-sticker", onClick: () => { - superstate.ui.openPalette((_props) => /* @__PURE__ */ import_react111.default.createElement(StickerModal_default, { + superstate.ui.openPalette((_props) => /* @__PURE__ */ import_react113.default.createElement(StickerModal_default, { ui: superstate.ui, hide: _props.hide, selectedSticker: (emoji) => { @@ -121854,7 +122212,7 @@ var PinnedSpace = (0, import_react111.forwardRef)( dragOver(index2, x2); }, ...innerProps - }, /* @__PURE__ */ import_react111.default.createElement("div", { + }, /* @__PURE__ */ import_react113.default.createElement("div", { ref: ref2, className: (0, import_classnames5.default)( "mk-waypoints-item", @@ -121871,10 +122229,10 @@ var PinnedSpace = (0, import_react111.forwardRef)( dangerouslySetInnerHTML: { __html: superstate.ui.getSticker(pin.sticker) } - })) : /* @__PURE__ */ import_react111.default.createElement("div", { + })) : /* @__PURE__ */ import_react113.default.createElement("div", { ref: innerRef, className: "mk-waypoint" - }, /* @__PURE__ */ import_react111.default.createElement("div", { + }, /* @__PURE__ */ import_react113.default.createElement("div", { ref: ref2, onClick: (e5) => { setWaypoints([ @@ -121904,16 +122262,16 @@ var SpaceSwitcher = (props) => { modifier, setModifier, setWaypoints - } = (0, import_react112.useContext)(NavigatorContext); + } = (0, import_react114.useContext)(NavigatorContext); const { superstate } = props; - const { dragPaths, setDragPaths } = (0, import_react112.useContext)(NavigatorContext); - const [activeId, setActiveId] = (0, import_react112.useState)(null); - const [overId, setOverId] = (0, import_react112.useState)(null); - const dragCounter = (0, import_react112.useRef)(0); - const [offset2, setOffset] = (0, import_react112.useState)(0); - const [projected, setProjected] = (0, import_react112.useState)(null); - const [dropPlaceholder, setDragPlaceholder] = (0, import_react112.useState)(null); - (0, import_react112.useEffect)(() => { + const { dragPaths, setDragPaths } = (0, import_react114.useContext)(NavigatorContext); + const [activeId, setActiveId] = (0, import_react114.useState)(null); + const [overId, setOverId] = (0, import_react114.useState)(null); + const dragCounter = (0, import_react114.useRef)(0); + const [offset2, setOffset] = (0, import_react114.useState)(0); + const [projected, setProjected] = (0, import_react114.useState)(null); + const [dropPlaceholder, setDragPlaceholder] = (0, import_react114.useState)(null); + (0, import_react114.useEffect)(() => { if (overId === null || dragPaths.length == 0) { setProjected(null); return; @@ -122030,7 +122388,7 @@ var SpaceSwitcher = (props) => { function handleDragEnd({ active, over }) { dragEnded(); } - (0, import_react112.useEffect)(() => { + (0, import_react114.useEffect)(() => { window.addEventListener("dragend", resetState); return () => { window.removeEventListener("dragend", resetState); @@ -122057,14 +122415,14 @@ var SpaceSwitcher = (props) => { return 0; } }; - return /* @__PURE__ */ import_react112.default.createElement(import_react112.default.Fragment, null, /* @__PURE__ */ import_react112.default.createElement("div", { + return /* @__PURE__ */ import_react114.default.createElement(import_react114.default.Fragment, null, /* @__PURE__ */ import_react114.default.createElement("div", { className: "mk-waypoints nav-header", onDragEnter: () => dragEnter(), onDragLeave: () => dragLeave(), onDragOver: (e5) => e5.preventDefault() - }, /* @__PURE__ */ import_react112.default.createElement("div", { + }, /* @__PURE__ */ import_react114.default.createElement("div", { className: "mk-waypoints-inner nav-buttons-container" - }, waypoints.map((pin, i4) => /* @__PURE__ */ import_react112.default.createElement(SortablePinnedSpaceItem, { + }, waypoints.map((pin, i4) => /* @__PURE__ */ import_react114.default.createElement(SortablePinnedSpaceItem, { id: i4, superstate: props.superstate, highlighted: overId == i4 && projected && projected.insert && projected.droppable, @@ -122084,7 +122442,7 @@ var SpaceSwitcher = (props) => { dragEnded, dragActive: activeId !== null, ghost: activeId === i4 - })), /* @__PURE__ */ import_react112.default.createElement("div", { + })), /* @__PURE__ */ import_react114.default.createElement("div", { className: "mk-waypoint-new", onClick: (e5) => { const newWaypoints = [ @@ -122097,18 +122455,18 @@ var SpaceSwitcher = (props) => { dangerouslySetInnerHTML: { __html: props.superstate.ui.getSticker("ui//plus") } - }), overId != null && activeId === null && /* @__PURE__ */ import_react112.default.createElement(SortablePinnedSpaceItem, { + }), overId != null && activeId === null && /* @__PURE__ */ import_react114.default.createElement(SortablePinnedSpaceItem, { id: waypoints.length, superstate: props.superstate, highlighted: false, index: waypoints.length, pin: null })), (0, import_react_dom7.createPortal)( - /* @__PURE__ */ import_react112.default.createElement(DragOverlay, { + /* @__PURE__ */ import_react114.default.createElement(DragOverlay, { dropAnimation: null, modifiers: [adjustTranslate], zIndex: 1600 - }, activeId !== null ? /* @__PURE__ */ import_react112.default.createElement(SortablePinnedSpaceItem, { + }, activeId !== null ? /* @__PURE__ */ import_react114.default.createElement(SortablePinnedSpaceItem, { id: -1, superstate: props.superstate, highlighted: false, @@ -122123,8 +122481,8 @@ var SpaceSwitcher = (props) => { // src/core/react/components/Navigator/MainList.tsx var MainList = (props) => { - const [indexing, setIndexing] = import_react113.default.useState(false); - (0, import_react113.useEffect)(() => { + const [indexing, setIndexing] = import_react115.default.useState(false); + (0, import_react115.useEffect)(() => { const reindex = async () => { setIndexing(true); }; @@ -122147,17 +122505,17 @@ var MainList = (props) => { ); }; }, []); - return /* @__PURE__ */ import_react113.default.createElement(import_react113.default.Fragment, null, /* @__PURE__ */ import_react113.default.createElement(import_react_error_boundary_cjs.ErrorBoundary, { + return /* @__PURE__ */ import_react115.default.createElement(import_react115.default.Fragment, null, /* @__PURE__ */ import_react115.default.createElement(import_react_error_boundary_cjs.ErrorBoundary, { FallbackComponent: ErrorFallback - }, /* @__PURE__ */ import_react113.default.createElement("div", { + }, /* @__PURE__ */ import_react115.default.createElement("div", { className: "mk-progress-bar" - }, indexing && /* @__PURE__ */ import_react113.default.createElement("div", { + }, indexing && /* @__PURE__ */ import_react115.default.createElement("div", { className: "mk-progress-bar-value" - })), !isTouchScreen(props.superstate.ui) && /* @__PURE__ */ import_react113.default.createElement(MainMenu, { + })), !isTouchScreen(props.superstate.ui) && /* @__PURE__ */ import_react115.default.createElement(MainMenu, { superstate: props.superstate - }), /* @__PURE__ */ import_react113.default.createElement(SpaceSwitcher, { + }), /* @__PURE__ */ import_react115.default.createElement(SpaceSwitcher, { superstate: props.superstate - }), /* @__PURE__ */ import_react113.default.createElement(SpaceTreeComponent, { + }), /* @__PURE__ */ import_react115.default.createElement(SpaceTreeComponent, { superstate: props.superstate }))); }; @@ -122166,48 +122524,48 @@ function ErrorFallback({ error }) { const copyError = () => { navigator.clipboard.writeText(error.message); }; - return /* @__PURE__ */ import_react113.default.createElement("div", { + return /* @__PURE__ */ import_react115.default.createElement("div", { role: "alert" - }, /* @__PURE__ */ import_react113.default.createElement("p", null, "Something went wrong:"), /* @__PURE__ */ import_react113.default.createElement("p", { + }, /* @__PURE__ */ import_react115.default.createElement("p", null, "Something went wrong:"), /* @__PURE__ */ import_react115.default.createElement("p", { style: { color: "red" } - }, error.message), /* @__PURE__ */ import_react113.default.createElement("button", { + }, error.message), /* @__PURE__ */ import_react115.default.createElement("button", { onClick: copyError - }, "Copy Error"), /* @__PURE__ */ import_react113.default.createElement("button", { + }, "Copy Error"), /* @__PURE__ */ import_react115.default.createElement("button", { onClick: resetBoundary }, "Reload")); } // src/core/react/components/SpaceView/Contexts/SpaceView.tsx var SpaceView = (props) => { - return /* @__PURE__ */ import_react114.default.createElement(import_react_error_boundary_cjs.ErrorBoundary, { + return /* @__PURE__ */ import_react116.default.createElement(import_react_error_boundary_cjs.ErrorBoundary, { FallbackComponent: ErrorFallback - }, /* @__PURE__ */ import_react114.default.createElement(PathProvider, { + }, /* @__PURE__ */ import_react116.default.createElement(PathProvider, { superstate: props.superstate, path: props.path, readMode: false - }, /* @__PURE__ */ import_react114.default.createElement(SpaceProvider, { + }, /* @__PURE__ */ import_react116.default.createElement(SpaceProvider, { superstate: props.superstate - }, /* @__PURE__ */ import_react114.default.createElement(FramesMDBProvider, { + }, /* @__PURE__ */ import_react116.default.createElement(FramesMDBProvider, { superstate: props.superstate, schema: "main" - }, /* @__PURE__ */ import_react114.default.createElement(FrameSelectionProvider, { + }, /* @__PURE__ */ import_react116.default.createElement(FrameSelectionProvider, { id: "main", superstate: props.superstate, editMode: props.readOnly ? 0 /* Read */ : 1 /* Page */ - }, /* @__PURE__ */ import_react114.default.createElement(SpaceRoot, { + }, /* @__PURE__ */ import_react116.default.createElement(SpaceRoot, { superstate: props.superstate }, props.children)))))); }; var SpaceRoot = (props) => { - const { pathState } = (0, import_react114.useContext)(PathContext); - const { tableData } = (0, import_react114.useContext)(FramesMDBContext); + const { pathState } = (0, import_react116.useContext)(PathContext); + const { tableData } = (0, import_react116.useContext)(FramesMDBContext); const cols = [ ...[...props.superstate.spacesMap.get(pathState.path) ?? []].flatMap( (f2) => props.superstate.contextsIndex.get(f2)?.cols.map((g) => ({ ...g, table: f2 })) ), ...tableData?.cols.map((f2) => ({ ...f2, table: "" })) ?? [] ]; - return /* @__PURE__ */ import_react114.default.createElement(FrameEditorProvider, { + return /* @__PURE__ */ import_react116.default.createElement(FrameEditorProvider, { superstate: props.superstate, editMode: 1 /* Page */, cols @@ -122215,7 +122573,7 @@ var SpaceRoot = (props) => { }; // node_modules/@air/react-drag-to-select/dist/index.modern.js -var import_react115 = __toESM(require_react(), 1); +var import_react117 = __toESM(require_react(), 1); var import_react_dom8 = __toESM(require_react_dom(), 1); var import_react_style_object_to_css = __toESM(require_react_style_object_to_css(), 1); function a3() { @@ -122229,7 +122587,7 @@ function a3() { }, a3.apply(this, arguments); } var s3 = ["style"]; -var d3 = (0, import_react115.forwardRef)((t5, u3) => { +var d3 = (0, import_react117.forwardRef)((t5, u3) => { let { style: d4 = {} } = t5, m4 = function(e5, t6) { if (null == e5) return {}; @@ -122238,8 +122596,8 @@ var d3 = (0, import_react115.forwardRef)((t5, u3) => { t6.indexOf(n3 = l2[r2]) >= 0 || (o2[n3] = e5[n3]); return o2; }(t5, s3); - const v2 = (0, import_react115.useRef)(null), f2 = (0, import_react115.useRef)(null), [, p] = (0, import_react115.useState)(0); - return (0, import_react115.useImperativeHandle)(u3, () => ({ getBoundingClientRect: () => { + const v2 = (0, import_react117.useRef)(null), f2 = (0, import_react117.useRef)(null), [, p] = (0, import_react117.useState)(0); + return (0, import_react117.useImperativeHandle)(u3, () => ({ getBoundingClientRect: () => { var e5; return null == (e5 = v2.current) ? void 0 : e5.getBoundingClientRect(); }, getParentBoundingClientRect: () => { @@ -122256,26 +122614,26 @@ var d3 = (0, import_react115.forwardRef)((t5, u3) => { requestAnimationFrame(() => { f2.current && (f2.current.style.cssText = (0, import_react_style_object_to_css.default)({ top: 0, left: 0, width: 0, height: 0 })); }); - } })), (0, import_react115.useEffect)(() => { + } })), (0, import_react117.useEffect)(() => { p((e5) => e5 + 1); - }, []), import_react115.default.createElement("div", { ref: v2 }, v2.current ? import_react_dom8.default.createPortal(import_react115.default.createElement("div", a3({ ref: f2 }, m4)), v2.current) : null); + }, []), import_react117.default.createElement("div", { ref: v2 }, v2.current ? import_react_dom8.default.createPortal(import_react117.default.createElement("div", a3({ ref: f2 }, m4)), v2.current) : null); }); var m3 = (e5, t5) => e5.left <= t5.left + t5.width && e5.left + e5.width >= t5.left && e5.top <= t5.top + t5.height && e5.top + e5.height >= t5.top; function v(t5) { - const { onSelectionChange: r2, onSelectionEnd: o2, onSelectionStart: c3, isEnabled: i4 = true, selectionProps: s4 = {}, eventsElement: m4, shouldStartSelecting: v2 } = t5 || {}, f2 = (0, import_react115.useRef)(null), { cancelCurrentSelection: p } = function({ containerRef: e5, onSelectionChange: t6, onSelectionStart: r3, onSelectionEnd: o3, isEnabled: c4 = true, eventsElement: i5, shouldStartSelecting: s5 }) { - const d4 = (0, import_react115.useRef)(null), m5 = (0, import_react115.useRef)(null), v3 = (0, import_react115.useRef)(false), f3 = (0, import_react115.useRef)(t6), p2 = (0, import_react115.useRef)(r3), h3 = (0, import_react115.useRef)(o3), g = (0, import_react115.useRef)(), y3 = (0, import_react115.useRef)(c4); - f3.current = (0, import_react115.useCallback)((e6) => { + const { onSelectionChange: r2, onSelectionEnd: o2, onSelectionStart: c3, isEnabled: i4 = true, selectionProps: s4 = {}, eventsElement: m4, shouldStartSelecting: v2 } = t5 || {}, f2 = (0, import_react117.useRef)(null), { cancelCurrentSelection: p } = function({ containerRef: e5, onSelectionChange: t6, onSelectionStart: r3, onSelectionEnd: o3, isEnabled: c4 = true, eventsElement: i5, shouldStartSelecting: s5 }) { + const d4 = (0, import_react117.useRef)(null), m5 = (0, import_react117.useRef)(null), v3 = (0, import_react117.useRef)(false), f3 = (0, import_react117.useRef)(t6), p2 = (0, import_react117.useRef)(r3), h3 = (0, import_react117.useRef)(o3), g = (0, import_react117.useRef)(), y3 = (0, import_react117.useRef)(c4); + f3.current = (0, import_react117.useCallback)((e6) => { g.current = t6 ? requestAnimationFrame(() => { t6(e6); }) : void 0; }, [t6]), p2.current = r3, h3.current = o3, y3.current = c4; - const b2 = (0, import_react115.useCallback)(() => { + const b2 = (0, import_react117.useCallback)(() => { var t7; d4.current = null, m5.current = null, v3.current = false, null == (t7 = e5.current) || t7.clearSelectionBox(), "number" == typeof g.current && cancelAnimationFrame(g.current); - }, [e5]), S3 = (0, import_react115.useCallback)((t7, n3) => { + }, [e5]), S3 = (0, import_react117.useCallback)((t7, n3) => { var r4, o4, l2; return n3 || (n3 = null == (l2 = e5.current) ? void 0 : l2.getParentBoundingClientRect()), { x: t7.clientX - ("number" == typeof (null == (r4 = n3) ? void 0 : r4.left) ? n3.left : 0), y: t7.clientY - ("number" == typeof (null == (o4 = n3) ? void 0 : o4.top) ? n3.top : 0) }; - }, [e5]), E2 = (0, import_react115.useCallback)((t7, n3) => { + }, [e5]), E2 = (0, import_react117.useCallback)((t7, n3) => { if (d4.current && m5.current) { if (!n3) return; @@ -122285,16 +122643,16 @@ function v(t5) { } else b2(); var o4; - }, [b2, e5]), w2 = (0, import_react115.useCallback)((t7) => { + }, [b2, e5]), w2 = (0, import_react117.useCallback)((t7) => { var n3; if (!d4.current) return; const r4 = null == (n3 = e5.current) ? void 0 : n3.getParentBoundingClientRect(); m5.current = S3(t7, r4), E2(t7, r4); - }, [E2, S3, e5]), x2 = (0, import_react115.useCallback)((e6) => { + }, [E2, S3, e5]), x2 = (0, import_react117.useCallback)((e6) => { var t7; 0 === e6.button && (m5.current && (null == h3.current || h3.current(e6)), b2(), document.body.style.removeProperty("user-select"), document.body.style.removeProperty("-webkit-user-select"), (i5 || document.body).removeEventListener("mousemove", w2), null == (t7 = window) || t7.removeEventListener("mouseup", x2)); - }, [i5, b2, w2]), C = (0, import_react115.useCallback)((e6) => { + }, [i5, b2, w2]), C = (0, import_react117.useCallback)((e6) => { if (0 === e6.button && y3.current) { var t7; if ("function" == typeof s5 && !s5(e6.target)) @@ -122302,30 +122660,30 @@ function v(t5) { document.body.style.userSelect = "none", document.body.style.webkitUserSelect = "none", d4.current = S3(e6), (i5 || document.body).addEventListener("mousemove", w2), null == (t7 = window) || t7.addEventListener("mouseup", x2); } }, [i5, S3, w2, x2]); - return (0, import_react115.useEffect)(() => ((i5 || document.body).addEventListener("mousedown", C), () => { + return (0, import_react117.useEffect)(() => ((i5 || document.body).addEventListener("mousedown", C), () => { (i5 || document.body).removeEventListener("mousedown", C), (i5 || document.body).removeEventListener("mousemove", w2), window.removeEventListener("mouseup", x2); }), [i5, C, w2, x2]), { cancelCurrentSelection: b2 }; }({ containerRef: f2, onSelectionEnd: o2, onSelectionStart: c3, onSelectionChange: r2, isEnabled: i4, eventsElement: m4, shouldStartSelecting: v2 }); - return { cancelCurrentSelection: p, DragSelection: (0, import_react115.useCallback)(() => import_react115.default.createElement(d3, a3({ ref: f2 }, s4)), []) }; + return { cancelCurrentSelection: p, DragSelection: (0, import_react117.useCallback)(() => import_react117.default.createElement(d3, a3({ ref: f2 }, s4)), []) }; } // src/core/react/components/SpaceView/SpaceOuter.tsx -var import_react116 = __toESM(require_react()); -var SpaceOuter = (0, import_react116.forwardRef)( +var import_react118 = __toESM(require_react()); +var SpaceOuter = (0, import_react118.forwardRef)( (props, ref2) => { - const [selectionBox, setSelectionBox] = (0, import_react116.useState)(); - const selectableItems = (0, import_react116.useRef)([]); - const { frameProperties } = (0, import_react116.useContext)(FramesEditorRootContext); - const { selectableNodeBounds, id: id3 } = (0, import_react116.useContext)(FrameInstanceContext); - const { selectMulti } = (0, import_react116.useContext)(FrameSelectionContext); - const { tableData } = (0, import_react116.useContext)(FramesMDBContext); - const [dragging, setDragging] = (0, import_react116.useState)(false); - const localRef = (0, import_react116.useRef)(null); - const [contexts, setContexts] = (0, import_react116.useState)({}); - const [frameProps, setFrameProps] = (0, import_react116.useState)({}); - const { pathState } = (0, import_react116.useContext)(PathContext); - const { spaceInfo } = (0, import_react116.useContext)(SpaceContext); - (0, import_react116.useEffect)(() => { + const [selectionBox, setSelectionBox] = (0, import_react118.useState)(); + const selectableItems = (0, import_react118.useRef)([]); + const { frameProperties } = (0, import_react118.useContext)(FramesEditorRootContext); + const { selectableNodeBounds, id: id3 } = (0, import_react118.useContext)(FrameInstanceContext); + const { selectMulti } = (0, import_react118.useContext)(FrameSelectionContext); + const { tableData } = (0, import_react118.useContext)(FramesMDBContext); + const [dragging, setDragging] = (0, import_react118.useState)(false); + const localRef = (0, import_react118.useRef)(null); + const [contexts, setContexts] = (0, import_react118.useState)({}); + const [frameProps, setFrameProps] = (0, import_react118.useState)({}); + const { pathState } = (0, import_react118.useContext)(PathContext); + const { spaceInfo } = (0, import_react118.useContext)(SpaceContext); + (0, import_react118.useEffect)(() => { if (!spaceInfo) { return; } @@ -122402,7 +122760,7 @@ var SpaceOuter = (0, import_react116.forwardRef)( props.superstate.ui.resetSelection(null); } }; - (0, import_react116.useEffect)(() => { + (0, import_react118.useEffect)(() => { window.addEventListener("keydown", onKeyDown); return () => { window.removeEventListener("keydown", onKeyDown); @@ -122449,7 +122807,7 @@ var SpaceOuter = (0, import_react116.forwardRef)( return false; } }); - return /* @__PURE__ */ import_react116.default.createElement("div", { + return /* @__PURE__ */ import_react118.default.createElement("div", { className: "mk-space-body cm-line", ref: (el) => { localRef.current = el; @@ -122458,7 +122816,7 @@ var SpaceOuter = (0, import_react116.forwardRef)( else if (ref2 !== null) ref2.current = el; } - }, /* @__PURE__ */ import_react116.default.createElement(DragSelection, null), /* @__PURE__ */ import_react116.default.createElement(FrameInstanceProvider, { + }, /* @__PURE__ */ import_react118.default.createElement(DragSelection, null), /* @__PURE__ */ import_react118.default.createElement(FrameInstanceProvider, { id: id3 ?? "root", superstate: props.superstate, props: frameProps, @@ -122473,11 +122831,11 @@ var SpaceOuter_default = SpaceOuter; // src/core/react/components/PathView/PathView.tsx var PathView = (props) => { - const [pathState, setPathState] = (0, import_react117.useState)( + const [pathState, setPathState] = (0, import_react119.useState)( props.superstate.pathsIndex.get(props.path) ); - const ref2 = (0, import_react117.useRef)(null); - (0, import_react117.useEffect)(() => { + const ref2 = (0, import_react119.useRef)(null); + (0, import_react119.useEffect)(() => { const uri = props.superstate.spaceManager.uriByString(props.path); if (uri?.scheme == "https" || uri?.scheme == "http") { setPathState({ @@ -122497,45 +122855,45 @@ var PathView = (props) => { const pathState2 = props.superstate.pathsIndex.get(props.path); setPathState(pathState2); }, [props.path]); - return /* @__PURE__ */ import_react117.default.createElement("div", { + return /* @__PURE__ */ import_react119.default.createElement("div", { className: "mk-path-view", style: { ...props.styles ?? {} } - }, pathState?.type == "remote" ? /* @__PURE__ */ import_react117.default.createElement("iframe", { + }, pathState?.type == "remote" ? /* @__PURE__ */ import_react119.default.createElement("iframe", { src: props.path - }) : pathState?.type == "space" ? /* @__PURE__ */ import_react117.default.createElement(SpaceView, { + }) : pathState?.type == "space" ? /* @__PURE__ */ import_react119.default.createElement(SpaceView, { superstate: props.superstate, path: props.path, readOnly: props.readOnly - }, /* @__PURE__ */ import_react117.default.createElement(SpaceOuter_default, { + }, /* @__PURE__ */ import_react119.default.createElement(SpaceOuter_default, { superstate: props.superstate, ref: ref2 - }, /* @__PURE__ */ import_react117.default.createElement(FrameEditorInstance, { + }, /* @__PURE__ */ import_react119.default.createElement(FrameEditorInstance, { containerRef: props.containerRef, superstate: props.superstate - }))) : props.superstate.ui.availableViews().some((f2) => f2 == props.path?.split(".").pop()) ? /* @__PURE__ */ import_react117.default.createElement(NoteView, { + }))) : props.superstate.ui.availableViews().some((f2) => f2 == props.path?.split(".").pop()) ? /* @__PURE__ */ import_react119.default.createElement(NoteView, { superstate: props.superstate, path: props.path, load: true, classname: "mk-flow-node" - }) : /* @__PURE__ */ import_react117.default.createElement(import_react117.default.Fragment, null)); + }) : /* @__PURE__ */ import_react119.default.createElement(import_react119.default.Fragment, null)); }; // src/core/react/components/SpaceView/Frames/EditorNodes/FlowNodeView.tsx -var import_react119 = __toESM(require_react()); +var import_react121 = __toESM(require_react()); // src/core/react/components/SpaceView/Frames/SpaceCommand/Suggester.tsx -var import_react118 = __toESM(require_react()); +var import_react120 = __toESM(require_react()); var import_react_dom9 = __toESM(require_react_dom()); -var Suggester = (0, import_react118.forwardRef)( +var Suggester = (0, import_react120.forwardRef)( (props, outerRef) => { - const ref2 = (0, import_react118.useRef)(null); - const [index2, setIndex] = (0, import_react118.useState)(0); - const [isReady, setIsReady] = (0, import_react118.useState)(false); - const menuRef = (0, import_react118.useRef)(null); - const [pos, setPos] = (0, import_react118.useState)({ x: 0, y: 0 }); - const [active, setActive] = (0, import_react118.useState)(false); - const [section, setSection] = (0, import_react118.useState)(""); - (0, import_react118.useEffect)(() => { + const ref2 = (0, import_react120.useRef)(null); + const [index2, setIndex] = (0, import_react120.useState)(0); + const [isReady, setIsReady] = (0, import_react120.useState)(false); + const menuRef = (0, import_react120.useRef)(null); + const [pos, setPos] = (0, import_react120.useState)({ x: 0, y: 0 }); + const [active, setActive] = (0, import_react120.useState)(false); + const [section, setSection] = (0, import_react120.useState)(""); + (0, import_react120.useEffect)(() => { const resizeObserver = new ResizeObserver((entries) => { if (menuRef.current) { const rect = menuRef.current.getBoundingClientRect(); @@ -122624,7 +122982,7 @@ var Suggester = (0, import_react118.forwardRef)( suggestionActive: "mk-active", suggestionDisabled: "mk-disabled" }; - return /* @__PURE__ */ import_react118.default.createElement(import_react118.default.Fragment, null, /* @__PURE__ */ import_react118.default.createElement("div", { + return /* @__PURE__ */ import_react120.default.createElement(import_react120.default.Fragment, null, /* @__PURE__ */ import_react120.default.createElement("div", { ref: (node) => { ref2.current = node; if (outerRef) { @@ -122652,7 +123010,7 @@ var Suggester = (0, import_react118.forwardRef)( className: "mk-suggester", contentEditable: true }), active && (0, import_react_dom9.createPortal)( - /* @__PURE__ */ import_react118.default.createElement("div", { + /* @__PURE__ */ import_react120.default.createElement("div", { ref: menuRef, className: `mk-menu mk-menu-suggester ${isReady ? "mk-ready" : ""}`, style: { @@ -122664,13 +123022,13 @@ var Suggester = (0, import_react118.forwardRef)( "--mk-menu-max-height": "300px", visibility: active ? "visible" : "hidden" } - }, props.sections ? /* @__PURE__ */ import_react118.default.createElement("div", { + }, props.sections ? /* @__PURE__ */ import_react120.default.createElement("div", { className: "mk-menu-sections" - }, props.sections.map((f2, i4) => /* @__PURE__ */ import_react118.default.createElement("div", { + }, props.sections.map((f2, i4) => /* @__PURE__ */ import_react120.default.createElement("div", { key: i4, onClick: () => setSection(f2.value), className: `${section == f2.value ? "is-active" : ""} mk-menu-section` - }, f2.name == "" ? i18n_default.labels.all : f2.name))) : /* @__PURE__ */ import_react118.default.createElement(import_react118.default.Fragment, null), /* @__PURE__ */ import_react118.default.createElement(SelectMenuSuggestions_default, { + }, f2.name == "" ? i18n_default.labels.all : f2.name))) : /* @__PURE__ */ import_react120.default.createElement(import_react120.default.Fragment, null), /* @__PURE__ */ import_react120.default.createElement(SelectMenuSuggestions_default, { expanded: false, addKeyword: "Add", options: props.suggestions, @@ -122701,8 +123059,8 @@ function parseContent(input) { return match1 ? match1[1] : match2 ? match2[1] : input; } var FlowNodeView = (props) => { - const { spaceState } = (0, import_react119.useContext)(SpaceContext); - const pathState = (0, import_react119.useMemo)(() => { + const { spaceState } = (0, import_react121.useContext)(SpaceContext); + const pathState = (0, import_react121.useMemo)(() => { const fullPath = props.state?.props?.value; const path2 = fullPath ? props.superstate.spaceManager.resolvePath( parseContent(fullPath), @@ -122725,9 +123083,9 @@ var FlowNodeView = (props) => { } return props.superstate.pathsIndex.get(path2); }, [props.state, props.source]); - const { updateNode, nodes } = (0, import_react119.useContext)(FramesEditorRootContext); - const { selectionMode } = (0, import_react119.useContext)(FrameSelectionContext); - const [expanded, setExpanded] = (0, import_react119.useState)( + const { updateNode, nodes } = (0, import_react121.useContext)(FramesEditorRootContext); + const { selectionMode } = (0, import_react121.useContext)(FrameSelectionContext); + const [expanded, setExpanded] = (0, import_react121.useState)( props.state?.styles?.["--mk-expanded"] ); const updateValue2 = (newValue) => { @@ -122750,9 +123108,9 @@ var FlowNodeView = (props) => { } }; const hideToggle = props.state?.styles?.["--mk-link"]; - const { id: id3 } = (0, import_react119.useContext)(FrameInstanceContext); - const [pathString, setPathString] = (0, import_react119.useState)(""); - const options = (0, import_react119.useMemo)(() => { + const { id: id3 } = (0, import_react121.useContext)(FrameInstanceContext); + const [pathString, setPathString] = (0, import_react121.useState)(""); + const options = (0, import_react121.useMemo)(() => { const fuseOptions = { keys: ["name", "value"] }; @@ -122763,7 +123121,7 @@ var FlowNodeView = (props) => { icon: f2.label?.sticker })); const fuse = new Fuse(suggestions, fuseOptions); - return pathString.length == 0 ? suggestions : fuse.search(pathString).map((result) => result.item); + return pathString?.length == 0 ? suggestions : fuse.search(pathString).map((result) => result.item); }, [pathString]); const toggleCollapse = () => { setExpanded((p) => !p); @@ -122775,21 +123133,21 @@ var FlowNodeView = (props) => { } }); }; - const [isTransition, startTransition] = (0, import_react119.useTransition)(); - return /* @__PURE__ */ import_react119.default.createElement("div", { + const [isTransition, startTransition] = (0, import_react121.useTransition)(); + return /* @__PURE__ */ import_react121.default.createElement("div", { className: "mk-node-flow" - }, !props.state?.styles?.["--mk-min-mode"] && /* @__PURE__ */ import_react119.default.createElement(import_react119.default.Fragment, null, pathState ? /* @__PURE__ */ import_react119.default.createElement("div", { + }, !props.state?.styles?.["--mk-min-mode"] && /* @__PURE__ */ import_react121.default.createElement(import_react121.default.Fragment, null, pathState ? /* @__PURE__ */ import_react121.default.createElement("div", { className: "mk-node-link" - }, /* @__PURE__ */ import_react119.default.createElement(PathCrumb, { + }, /* @__PURE__ */ import_react121.default.createElement(PathCrumb, { superstate: props.superstate, path: pathState.path - }), !hideToggle && /* @__PURE__ */ import_react119.default.createElement(CollapseToggle, { + }), !hideToggle && /* @__PURE__ */ import_react121.default.createElement(CollapseToggle, { superstate: props.superstate, collapsed: !expanded, onToggle: toggleCollapse - })) : selectionMode > 0 /* Read */ && /* @__PURE__ */ import_react119.default.createElement("div", { + })) : selectionMode > 0 /* Read */ && /* @__PURE__ */ import_react121.default.createElement("div", { className: "mk-node-text-placeholder" - }, /* @__PURE__ */ import_react119.default.createElement(Suggester, { + }, /* @__PURE__ */ import_react121.default.createElement(Suggester, { placeholder: i18n_default.hintText.selectNote, onChange: (e5) => { setPathString(e5); @@ -122799,14 +123157,14 @@ var FlowNodeView = (props) => { onSelect: (option) => { updateValue2(option.value); } - }))), props.state && expanded && (props.state?.props?.value.length > 0 ? /* @__PURE__ */ import_react119.default.createElement(PathView, { + }))), props.state && expanded && (props.state?.props?.value?.length > 0 ? /* @__PURE__ */ import_react121.default.createElement(PathView, { id: id3, superstate: props.superstate, path: pathState?.path ?? props.state?.props?.value, containerRef: props.containerRef, styles: {}, readOnly: true - }) : /* @__PURE__ */ import_react119.default.createElement("div", { + }) : /* @__PURE__ */ import_react121.default.createElement("div", { onClick: () => newPathInSpace( props.superstate, spaceState, @@ -122818,21 +123176,21 @@ var FlowNodeView = (props) => { }; // src/core/react/components/SpaceView/Frames/FrameNodeEditor/FrameHoverMenu.tsx -var import_react120 = __toESM(require_react()); +var import_react122 = __toESM(require_react()); var FrameHoverMenu = (props) => { - const { spaceInfo } = (0, import_react120.useContext)(SpaceContext); - const { addNode, moveUp, moveDown, setLastCreatedId } = (0, import_react120.useContext)( + const { spaceInfo } = (0, import_react122.useContext)(SpaceContext); + const { addNode, moveUp, moveDown, setLastCreatedId } = (0, import_react122.useContext)( FramesEditorRootContext ); - const { select, selection: selection2 } = (0, import_react120.useContext)(FrameSelectionContext); + const { select, selection: selection2 } = (0, import_react122.useContext)(FrameSelectionContext); const selected = selection2.includes(props.node.id); - return /* @__PURE__ */ import_react120.default.createElement(import_react120.default.Fragment, null, /* @__PURE__ */ import_react120.default.createElement("div", { + return /* @__PURE__ */ import_react122.default.createElement(import_react122.default.Fragment, null, /* @__PURE__ */ import_react122.default.createElement("div", { className: `${"mk-editor-frame-hover-horizontal"}`, style: { pointerEvents: "auto", opacity: props.visible ? "1" : "0" } - }, props.dragRef && /* @__PURE__ */ import_react120.default.createElement("div", { + }, props.dragRef && /* @__PURE__ */ import_react122.default.createElement("div", { className: "mk-icon-small mk-editor-frame-hover-button", dangerouslySetInnerHTML: { __html: props.superstate.ui.getSticker("ui//handle") @@ -122853,7 +123211,7 @@ var FrameHoverMenu = (props) => { }, ...props.listeners ?? {}, ...props.attributes ?? {} - }), !isTouchScreen(props.superstate.ui) && /* @__PURE__ */ import_react120.default.createElement("div", { + }), !isTouchScreen(props.superstate.ui) && /* @__PURE__ */ import_react122.default.createElement("div", { onClick: (e5) => { addNode(newNode.node, props.node).then( (f2) => setLastCreatedId(f2.id) @@ -122868,10 +123226,10 @@ var FrameHoverMenu = (props) => { }; // src/core/react/components/SpaceView/Frames/FrameNodeEditor/FrameNodeEditorContainer.tsx -var import_react121 = __toESM(require_react()); +var import_react123 = __toESM(require_react()); var FrameNodeEditorContainer = (props) => { - const menuRef = (0, import_react121.useRef)(null); - const [pos, setPos] = (0, import_react121.useState)(0); + const menuRef = (0, import_react123.useRef)(null); + const [pos, setPos] = (0, import_react123.useState)(0); const calculateXBasedOnBounds = (targetRect, rect, containerRect) => { const x2 = targetRect.x - props.containerRect.x; const overflowX = x2 + rect.width - containerRect.width; @@ -122885,8 +123243,8 @@ var FrameNodeEditorContainer = (props) => { } return newX; }; - const [ready, setReady] = (0, import_react121.useState)(false); - (0, import_react121.useEffect)(() => { + const [ready, setReady] = (0, import_react123.useState)(false); + (0, import_react123.useEffect)(() => { const resizeObserver = new ResizeObserver((entries) => { const rect = entries[0].target.getBoundingClientRect(); setReady(true); @@ -122900,7 +123258,7 @@ var FrameNodeEditorContainer = (props) => { resizeObserver.disconnect(); }; }, [menuRef]); - return /* @__PURE__ */ import_react121.default.createElement("div", { + return /* @__PURE__ */ import_react123.default.createElement("div", { className: "mk-editor-frame-node-container", ref: menuRef, style: { @@ -122919,17 +123277,17 @@ var FrameNodeEditorContainer = (props) => { // src/core/react/components/SpaceView/Frames/FrameNodeEditor/Overlays/FrameCorners.tsx var import_classnames6 = __toESM(require_classnames()); -var import_react123 = __toESM(require_react()); +var import_react125 = __toESM(require_react()); // src/core/react/components/SpaceView/Frames/FrameNodeEditor/Overlays/FrameDraggableHandle.tsx -var import_react122 = __toESM(require_react()); +var import_react124 = __toESM(require_react()); var FrameDraggableHandle = (props) => { - const [modifier, setModifier] = (0, import_react122.useState)(null); - const startValue = (0, import_react122.useRef)(props.value); - const currentValue = (0, import_react122.useRef)(props.value); - const [, setStartPos] = (0, import_react122.useState)([0, 0]); + const [modifier, setModifier] = (0, import_react124.useState)(null); + const startValue = (0, import_react124.useRef)(props.value); + const currentValue = (0, import_react124.useRef)(props.value); + const [, setStartPos] = (0, import_react124.useState)([0, 0]); const step = props.step ?? 1; - const handleMove = (0, import_react122.useCallback)( + const handleMove = (0, import_react124.useCallback)( (e5) => { setStartPos((pos) => { const { clientX: x2, clientY: y22 } = e5; @@ -122961,7 +123319,7 @@ var FrameDraggableHandle = (props) => { }, [modifier, props.max, props.min, step, props.onDragMove, props.mod] ); - const handleMoveEnd = (0, import_react122.useCallback)( + const handleMoveEnd = (0, import_react124.useCallback)( (e5) => { const captureClick = (e6) => { e6.stopPropagation(); @@ -122985,7 +123343,7 @@ var FrameDraggableHandle = (props) => { }, [handleMove, props.onDragEnd] ); - const handleDown = (0, import_react122.useCallback)( + const handleDown = (0, import_react124.useCallback)( (e5) => { startValue.current = props.value; setStartPos([e5.clientX, e5.clientY]); @@ -123009,7 +123367,7 @@ var FrameDraggableHandle = (props) => { const handleKeyUp = () => { setModifier(null); }; - (0, import_react122.useEffect)(() => { + (0, import_react124.useEffect)(() => { document.addEventListener("keydown", handleKeyDown); document.addEventListener("keyup", handleKeyUp); return () => { @@ -123019,7 +123377,7 @@ var FrameDraggableHandle = (props) => { document.removeEventListener("keyup", handleKeyUp); }; }, []); - return /* @__PURE__ */ import_react122.default.createElement("div", { + return /* @__PURE__ */ import_react124.default.createElement("div", { className: "mk-frame-draggable-handle", onMouseDown: handleDown, "data-placeholder": currentValue.current.toString(), @@ -123029,7 +123387,7 @@ var FrameDraggableHandle = (props) => { height: "100%", pointerEvents: "auto" } - }, /* @__PURE__ */ import_react122.default.createElement("span", null)); + }, /* @__PURE__ */ import_react124.default.createElement("span", null)); }; // src/core/react/components/SpaceView/Frames/FrameNodeEditor/Overlays/FrameCorners.tsx @@ -123037,8 +123395,8 @@ var FrameCorners = (props) => { const match2 = props.styles.borderRadius ? props.styles.borderRadius.match(/^(\d+(?:\.\d+)?)\s?([a-zA-Z%]+)$/) : null; const numericValue = match2 ? parseInt(match2[1]) : 0; const unit2 = match2 && match2[2] ? match2[2] : "px"; - const [offset2, setOffset] = import_react123.default.useState(Math.max(8, numericValue)); - (0, import_react123.useEffect)(() => { + const [offset2, setOffset] = import_react125.default.useState(Math.max(8, numericValue)); + (0, import_react125.useEffect)(() => { setOffset(numericValue); }, [numericValue]); const handleProps = { @@ -123053,7 +123411,7 @@ var FrameCorners = (props) => { } }; const minOffset = Math.max(8, offset2); - return /* @__PURE__ */ import_react123.default.createElement("div", { + return /* @__PURE__ */ import_react125.default.createElement("div", { style: { position: "absolute", top: 0, @@ -123065,49 +123423,49 @@ var FrameCorners = (props) => { borderRadius: offset2, border: "1px solid var(--mk-ui-border-accent)" } - }, /* @__PURE__ */ import_react123.default.createElement("div", { + }, /* @__PURE__ */ import_react125.default.createElement("div", { className: (0, import_classnames6.default)("mk-frame-corners") - }, /* @__PURE__ */ import_react123.default.createElement("div", { + }, /* @__PURE__ */ import_react125.default.createElement("div", { className: "mk-frame-corner", style: { position: "absolute", transform: `translate(${minOffset}px, ${minOffset}px)`, zIndex: "var(--mk-layer-editor-overlay)" } - }, /* @__PURE__ */ import_react123.default.createElement(FrameDraggableHandle, { + }, /* @__PURE__ */ import_react125.default.createElement(FrameDraggableHandle, { ...handleProps, cursor: "nwse-resize", reverseY: true - })), /* @__PURE__ */ import_react123.default.createElement("div", { + })), /* @__PURE__ */ import_react125.default.createElement("div", { className: "mk-frame-corner", style: { position: "absolute", transform: `translate(${props.clientSize.width - minOffset}px, ${minOffset}px)`, zIndex: "var(--mk-layer-editor-overlay)" } - }, /* @__PURE__ */ import_react123.default.createElement(FrameDraggableHandle, { + }, /* @__PURE__ */ import_react125.default.createElement(FrameDraggableHandle, { ...handleProps, cursor: "nesw-resize", reverseX: true, reverseY: true - })), /* @__PURE__ */ import_react123.default.createElement("div", { + })), /* @__PURE__ */ import_react125.default.createElement("div", { className: "mk-frame-corner", style: { position: "absolute", transform: `translate(${minOffset}px, ${props.clientSize.height - minOffset}px)`, zIndex: "var(--mk-layer-editor-overlay)" } - }, /* @__PURE__ */ import_react123.default.createElement(FrameDraggableHandle, { + }, /* @__PURE__ */ import_react125.default.createElement(FrameDraggableHandle, { ...handleProps, cursor: "nesw-resize" - })), /* @__PURE__ */ import_react123.default.createElement("div", { + })), /* @__PURE__ */ import_react125.default.createElement("div", { className: "mk-frame-corner", style: { position: "absolute", transform: `translate(${props.clientSize.width - minOffset}px, ${props.clientSize.height - minOffset}px)`, zIndex: "var(--mk-layer-editor-overlay)" } - }, /* @__PURE__ */ import_react123.default.createElement(FrameDraggableHandle, { + }, /* @__PURE__ */ import_react125.default.createElement(FrameDraggableHandle, { ...handleProps, reverseX: true, cursor: "nwse-resize" @@ -123116,10 +123474,10 @@ var FrameCorners = (props) => { // src/core/react/components/SpaceView/Frames/FrameNodeEditor/Overlays/FrameDropZone.tsx var import_classnames7 = __toESM(require_classnames()); -var import_react124 = __toESM(require_react()); +var import_react126 = __toESM(require_react()); var FrameDropZone = (props) => { - const { instance, id: id3 } = (0, import_react124.useContext)(FrameInstanceContext); - const { spaceInfo } = (0, import_react124.useContext)(SpaceContext); + const { instance, id: id3 } = (0, import_react126.useContext)(FrameInstanceContext); + const { spaceInfo } = (0, import_react126.useContext)(SpaceContext); const { setNodeRef } = useDroppable({ id: props.id + props.direction, data: { @@ -123139,7 +123497,7 @@ var FrameDropZone = (props) => { const width = props.direction == "left" || props.direction == "right" ? offset2 : props.width; const height = props.direction == "top" || props.direction == "bottom" ? props.insertMode != 0 ? offset2 : props.height / 2 : props.height; const indicator = props.insertMode != 0 ? props.direction == "top" ? "bottom" : props.direction == "bottom" ? "top" : props.direction : props.direction; - return /* @__PURE__ */ import_react124.default.createElement("div", { + return /* @__PURE__ */ import_react126.default.createElement("div", { ref: setNodeRef, className: (0, import_classnames7.default)( props.active ? `mk-indicator-${indicator}` : "", @@ -123154,19 +123512,19 @@ var FrameDropZone = (props) => { }); }; var FrameEditorDropZone = (props) => { - const { frameSchema } = (0, import_react124.useContext)(FramesMDBContext); - const { hoverNode } = (0, import_react124.useContext)(FrameInstanceContext); + const { frameSchema } = (0, import_react126.useContext)(FramesMDBContext); + const { hoverNode } = (0, import_react126.useContext)(FrameInstanceContext); const directions2 = [ ...props.mode == 1 /* DropModeRowColumn */ ? ["top", "bottom", "left", "right"] : props.mode == 2 /* DropModeRowOnly */ ? ["top", "bottom"] : props.mode == 3 /* DropModeColumnOnly */ ? ["left", "right"] : [], ...props.insertMode == 1 ? ["inside"] : [] ]; - return /* @__PURE__ */ import_react124.default.createElement("div", { + return /* @__PURE__ */ import_react126.default.createElement("div", { className: `mk-frame-drop-zone-container`, style: { width: props.width, height: props.height } - }, directions2.map((d4) => /* @__PURE__ */ import_react124.default.createElement(FrameDropZone, { + }, directions2.map((d4) => /* @__PURE__ */ import_react126.default.createElement(FrameDropZone, { ...props, key: d4, active: hoverNode?.node == props.node && hoverNode?.direction == d4, @@ -123177,7 +123535,7 @@ var FrameEditorDropZone = (props) => { }; // src/core/react/components/SpaceView/Frames/FrameNodeEditor/Overlays/FrameGapHandle.tsx -var import_react125 = __toESM(require_react()); +var import_react127 = __toESM(require_react()); var reduceFlexItems = (items, container, xAxis, axisGap) => { const rows = {}; let row2 = 0; @@ -123232,11 +123590,11 @@ var FrameGapHandle = (props) => { const numericValue = match2 ? parseInt(match2[1]) : 0; return numericValue; }; - const [offset2, setOffset] = import_react125.default.useState({ + const [offset2, setOffset] = import_react127.default.useState({ row: calculateOffset(props.styles["rowGap"]), column: calculateOffset(props.styles["columnGap"]) }); - (0, import_react125.useEffect)(() => { + (0, import_react127.useEffect)(() => { setOffset({ row: calculateOffset(props.styles["rowGap"]), column: calculateOffset(props.styles["columnGap"]) @@ -123278,7 +123636,7 @@ var FrameGapHandle = (props) => { ); } }; - const rows = (0, import_react125.useMemo)( + const rows = (0, import_react127.useMemo)( () => reduceFlexItems( props.childSizes, { @@ -123290,14 +123648,14 @@ var FrameGapHandle = (props) => { ), [props.childSizes, props.clientSize, props.direction, offset2] ); - const items = (0, import_react125.useMemo)(() => { + const items = (0, import_react127.useMemo)(() => { const items2 = []; Object.keys(rows).forEach((f2) => { items2.push(...rows[f2].items); }); return items2; }, [rows]); - return /* @__PURE__ */ import_react125.default.createElement("div", { + return /* @__PURE__ */ import_react127.default.createElement("div", { className: `mk-frame-gaps ${parseStylesToClass(props.styles)}`, style: { position: "absolute", @@ -123311,9 +123669,9 @@ var FrameGapHandle = (props) => { paddingRight: props.clientSize.paddingRight, flexWrap: props.styles.flexWrap } - }, props.direction === "row" ? items.map((f2, i4, array) => /* @__PURE__ */ import_react125.default.createElement(import_react125.default.Fragment, null, /* @__PURE__ */ import_react125.default.createElement("div", { + }, props.direction === "row" ? items.map((f2, i4, array) => /* @__PURE__ */ import_react127.default.createElement(import_react127.default.Fragment, null, /* @__PURE__ */ import_react127.default.createElement("div", { style: { width: f2.width, height: f2.height } - }), i4 == array.length - 1 ? /* @__PURE__ */ import_react125.default.createElement(import_react125.default.Fragment, null) : rows[f2.row].end == i4 ? /* @__PURE__ */ import_react125.default.createElement("div", { + }), i4 == array.length - 1 ? /* @__PURE__ */ import_react127.default.createElement(import_react127.default.Fragment, null) : rows[f2.row].end == i4 ? /* @__PURE__ */ import_react127.default.createElement("div", { key: i4, className: "mk-frame-gap-handle-h", style: { @@ -123321,12 +123679,12 @@ var FrameGapHandle = (props) => { height: Math.max(8, Math.abs(offset2["row"])), zIndex: "var(--mk-layer-editor-overlay)" } - }, /* @__PURE__ */ import_react125.default.createElement(FrameDraggableHandle, { + }, /* @__PURE__ */ import_react127.default.createElement(FrameDraggableHandle, { ...offAxisHandleProps, cursor: "col-resize", disableX: true, reverseY: true - })) : /* @__PURE__ */ import_react125.default.createElement("div", { + })) : /* @__PURE__ */ import_react127.default.createElement("div", { key: i4, className: "mk-frame-gap-handle-v", style: { @@ -123334,13 +123692,13 @@ var FrameGapHandle = (props) => { height: rows[f2.row].maxValue, zIndex: "var(--mk-layer-editor-overlay)" } - }, /* @__PURE__ */ import_react125.default.createElement(FrameDraggableHandle, { + }, /* @__PURE__ */ import_react127.default.createElement(FrameDraggableHandle, { ...handleProps, cursor: "col-resize", disableY: true - })))) : items.map((f2, i4, array) => /* @__PURE__ */ import_react125.default.createElement(import_react125.default.Fragment, null, /* @__PURE__ */ import_react125.default.createElement("div", { + })))) : items.map((f2, i4, array) => /* @__PURE__ */ import_react127.default.createElement(import_react127.default.Fragment, null, /* @__PURE__ */ import_react127.default.createElement("div", { style: { width: f2.width, height: f2.height } - }), i4 == array.length - 1 ? /* @__PURE__ */ import_react125.default.createElement(import_react125.default.Fragment, null) : rows[f2.row].end == i4 ? /* @__PURE__ */ import_react125.default.createElement("div", { + }), i4 == array.length - 1 ? /* @__PURE__ */ import_react127.default.createElement(import_react127.default.Fragment, null) : rows[f2.row].end == i4 ? /* @__PURE__ */ import_react127.default.createElement("div", { key: i4, className: "mk-frame-gap-handle-v", style: { @@ -123348,12 +123706,12 @@ var FrameGapHandle = (props) => { width: Math.max(8, Math.abs(offset2["column"])), zIndex: "var(--mk-layer-editor-overlay)" } - }, /* @__PURE__ */ import_react125.default.createElement(FrameDraggableHandle, { + }, /* @__PURE__ */ import_react127.default.createElement(FrameDraggableHandle, { ...offAxisHandleProps, cursor: "col-resize", disableX: true, reverseY: true - })) : /* @__PURE__ */ import_react125.default.createElement("div", { + })) : /* @__PURE__ */ import_react127.default.createElement("div", { key: i4, className: "mk-frame-gap-handle-h", style: { @@ -123361,7 +123719,7 @@ var FrameGapHandle = (props) => { width: rows[f2.row].maxValue, zIndex: "var(--mk-layer-editor-overlay)" } - }, /* @__PURE__ */ import_react125.default.createElement(FrameDraggableHandle, { + }, /* @__PURE__ */ import_react127.default.createElement(FrameDraggableHandle, { ...handleProps, cursor: "row-resize", disableX: true, @@ -123371,7 +123729,7 @@ var FrameGapHandle = (props) => { // src/core/react/components/SpaceView/Frames/FrameNodeEditor/Overlays/FramePaddingHandle.tsx var import_classnames8 = __toESM(require_classnames()); -var import_react126 = __toESM(require_react()); +var import_react128 = __toESM(require_react()); var FramePadding = (props) => { const paddingTypes = [ "padding", @@ -123380,7 +123738,7 @@ var FramePadding = (props) => { "paddingLeft", "paddingRight" ]; - const [offset2, setOffset] = import_react126.default.useState({ + const [offset2, setOffset] = import_react128.default.useState({ padding: 0, paddingTop: null, paddingBottom: null, @@ -123388,7 +123746,7 @@ var FramePadding = (props) => { paddingRight: null }); const unit2 = "px"; - (0, import_react126.useEffect)(() => { + (0, import_react128.useEffect)(() => { const getNumericValue = (type) => { if (!props.styles[type]) return null; @@ -123405,7 +123763,7 @@ var FramePadding = (props) => { }, p); }); }, [props.styles]); - const [shiftModifier, setShiftModifier] = import_react126.default.useState(false); + const [shiftModifier, setShiftModifier] = import_react128.default.useState(false); const handleProps = { min: 0, mod: 2 @@ -123433,7 +123791,7 @@ var FramePadding = (props) => { } : { [type]: `'${value}${unit2}'` } ); }; - (0, import_react126.useEffect)(() => { + (0, import_react128.useEffect)(() => { const handleKeyDown = (e5) => { if (e5.key === "Shift") { setShiftModifier(true); @@ -123451,7 +123809,7 @@ var FramePadding = (props) => { window.removeEventListener("keyup", handleKeyUp); }; }, []); - return /* @__PURE__ */ import_react126.default.createElement("div", { + return /* @__PURE__ */ import_react128.default.createElement("div", { style: { position: "absolute", top: 0, @@ -123462,12 +123820,12 @@ var FramePadding = (props) => { zIndex: 200, border: "1px solid var(--mk-ui-color-border-accent)" } - }, /* @__PURE__ */ import_react126.default.createElement("div", { + }, /* @__PURE__ */ import_react128.default.createElement("div", { className: (0, import_classnames8.default)( "mk-frame-paddings", shiftModifier && "mk-modifier-shift" ) - }, /* @__PURE__ */ import_react126.default.createElement("div", { + }, /* @__PURE__ */ import_react128.default.createElement("div", { className: "mk-frame-padding-handle-h", style: { position: "absolute", @@ -123475,7 +123833,7 @@ var FramePadding = (props) => { height: inset("paddingTop"), zIndex: "var(--mk-layer-editor-overlay)" } - }, /* @__PURE__ */ import_react126.default.createElement(FrameDraggableHandle, { + }, /* @__PURE__ */ import_react128.default.createElement(FrameDraggableHandle, { ...handleProps, value: offset2["paddingTop"] ?? offset2.padding, cursor: "s-resize", @@ -123488,7 +123846,7 @@ var FramePadding = (props) => { }, reverseY: true, disableX: true - })), /* @__PURE__ */ import_react126.default.createElement("div", { + })), /* @__PURE__ */ import_react128.default.createElement("div", { className: "mk-frame-padding-handle-v", style: { position: "absolute", @@ -123496,7 +123854,7 @@ var FramePadding = (props) => { width: inset("paddingRight"), zIndex: "var(--mk-layer-editor-overlay)" } - }, /* @__PURE__ */ import_react126.default.createElement(FrameDraggableHandle, { + }, /* @__PURE__ */ import_react128.default.createElement(FrameDraggableHandle, { ...handleProps, value: offset2["paddingRight"] ?? offset2.padding, cursor: "w-resize", @@ -123510,7 +123868,7 @@ var FramePadding = (props) => { reverseX: true, reverseY: true, disableY: true - })), /* @__PURE__ */ import_react126.default.createElement("div", { + })), /* @__PURE__ */ import_react128.default.createElement("div", { className: "mk-frame-padding-handle-v", style: { position: "absolute", @@ -123518,7 +123876,7 @@ var FramePadding = (props) => { width: inset("paddingLeft"), zIndex: "var(--mk-layer-editor-overlay)" } - }, /* @__PURE__ */ import_react126.default.createElement(FrameDraggableHandle, { + }, /* @__PURE__ */ import_react128.default.createElement(FrameDraggableHandle, { ...handleProps, value: offset2["paddingLeft"] ?? offset2.padding, cursor: "e-resize", @@ -123530,7 +123888,7 @@ var FramePadding = (props) => { saveValue("paddingLeft", value, modifiers); }, disableY: true - })), /* @__PURE__ */ import_react126.default.createElement("div", { + })), /* @__PURE__ */ import_react128.default.createElement("div", { className: "mk-frame-padding-handle-h", style: { position: "absolute", @@ -123538,7 +123896,7 @@ var FramePadding = (props) => { height: inset("paddingBottom"), zIndex: "var(--mk-layer-editor-overlay)" } - }, /* @__PURE__ */ import_react126.default.createElement(FrameDraggableHandle, { + }, /* @__PURE__ */ import_react128.default.createElement(FrameDraggableHandle, { ...handleProps, value: offset2["paddingBottom"] ?? offset2.padding, cursor: "n-resize", @@ -123558,11 +123916,11 @@ var FramePadding = (props) => { var import_classnames9 = __toESM(require_classnames()); // node_modules/re-resizable/lib/index.js -var React125 = __toESM(require_react()); +var React127 = __toESM(require_react()); var import_react_dom10 = __toESM(require_react_dom()); // node_modules/re-resizable/lib/resizer.js -var React124 = __toESM(require_react()); +var React126 = __toESM(require_react()); var __extends = function() { var extendStatics = function(d4, b2) { extendStatics = Object.setPrototypeOf || { __proto__: [] } instanceof Array && function(d5, b3) { @@ -123636,10 +123994,10 @@ var Resizer = function(_super) { return _this; } Resizer2.prototype.render = function() { - return React124.createElement("div", { className: this.props.className || "", style: __assign2(__assign2({ position: "absolute", userSelect: "none" }, styles[this.props.direction]), this.props.replaceStyles || {}), onMouseDown: this.onMouseDown, onTouchStart: this.onTouchStart }, this.props.children); + return React126.createElement("div", { className: this.props.className || "", style: __assign2(__assign2({ position: "absolute", userSelect: "none" }, styles[this.props.direction]), this.props.replaceStyles || {}), onMouseDown: this.onMouseDown, onTouchStart: this.onTouchStart }, this.props.children); }; return Resizer2; -}(React124.PureComponent); +}(React126.PureComponent); // node_modules/re-resizable/lib/index.js var __extends2 = function() { @@ -124302,11 +124660,11 @@ var Resizable = function(_super) { } var resizers = Object.keys(enable).map(function(dir) { if (enable[dir] !== false) { - return React125.createElement(Resizer, { key: dir, direction: dir, onResizeStart: _this.onResizeStart, replaceStyles: handleStyles && handleStyles[dir], className: handleClasses && handleClasses[dir] }, handleComponent && handleComponent[dir] ? handleComponent[dir] : null); + return React127.createElement(Resizer, { key: dir, direction: dir, onResizeStart: _this.onResizeStart, replaceStyles: handleStyles && handleStyles[dir], className: handleClasses && handleClasses[dir] }, handleComponent && handleComponent[dir] ? handleComponent[dir] : null); } return null; }); - return React125.createElement("div", { className: handleWrapperClass, style: handleWrapperStyle }, resizers); + return React127.createElement("div", { className: handleWrapperClass, style: handleWrapperStyle }, resizers); }; Resizable2.prototype.render = function() { var _this = this; @@ -124322,10 +124680,10 @@ var Resizable = function(_super) { style.flexBasis = this.state.flexBasis; } var Wrapper = this.props.as || "div"; - return React125.createElement( + return React127.createElement( Wrapper, __assign3({ ref: this.ref, style, className: this.props.className }, extendsProps), - this.state.isResizing && React125.createElement("div", { style: this.state.backgroundStyle }), + this.state.isResizing && React127.createElement("div", { style: this.state.backgroundStyle }), this.props.children, this.renderResizer() ); @@ -124358,10 +124716,10 @@ var Resizable = function(_super) { snapGap: 0 }; return Resizable2; -}(React125.PureComponent); +}(React127.PureComponent); // src/core/react/components/SpaceView/Frames/FrameNodeEditor/Overlays/FrameResizer.tsx -var import_react127 = __toESM(require_react()); +var import_react129 = __toESM(require_react()); var FrameResizer = (props) => { const labelForValue = (value) => { if (!value) @@ -124372,18 +124730,18 @@ var FrameResizer = (props) => { return "Fill"; return value; }; - const [modifiers, setModifiers] = import_react127.default.useState(null); - const [size2, setSize2] = import_react127.default.useState({ + const [modifiers, setModifiers] = import_react129.default.useState(null); + const [size2, setSize2] = import_react129.default.useState({ width: props.resizeMode != 2 /* ResizeColumn */ ? props.size.width : props.size.minWidth, height: props.size.height }); - import_react127.default.useEffect(() => { + import_react129.default.useEffect(() => { setSize2({ width: props.resizeMode != 2 /* ResizeColumn */ ? props.size.width : props.size.minWidth, height: props.size.height }); }, [props.size, props.resizeMode]); - (0, import_react127.useEffect)(() => { + (0, import_react129.useEffect)(() => { const captureShift = (e5) => { setModifiers({ shiftKey: e5.shiftKey }); }; @@ -124394,7 +124752,7 @@ var FrameResizer = (props) => { props.superstate.ui.inputManager.off("keyup", captureShift); }; }, [setModifiers]); - return /* @__PURE__ */ import_react127.default.createElement("div", { + return /* @__PURE__ */ import_react129.default.createElement("div", { style: { position: "absolute", top: 0, @@ -124402,7 +124760,7 @@ var FrameResizer = (props) => { width: props.clientSize.width, height: props.clientSize.height } - }, /* @__PURE__ */ import_react127.default.createElement(Resizable, { + }, /* @__PURE__ */ import_react129.default.createElement(Resizable, { lockAspectRatio: modifiers?.shiftKey, className: (0, import_classnames9.default)( props.resizeMode == 2 /* ResizeColumn */ ? "mk-frame-column" : "mk-frame-bounds" @@ -124450,9 +124808,9 @@ var FrameResizer = (props) => { height: size2.height && size2.height != "auto" ? size2.height : "100%" }, ...props.listeners - }), props.clientSize?.width > 50 && props.resizeMode == 1 /* ResizeSelected */ && /* @__PURE__ */ import_react127.default.createElement("div", { + }), props.clientSize?.width > 50 && props.resizeMode == 1 /* ResizeSelected */ && /* @__PURE__ */ import_react129.default.createElement("div", { className: "mk-frame-resize-label-width" - }, /* @__PURE__ */ import_react127.default.createElement("div", null, /* @__PURE__ */ import_react127.default.createElement("span", null, labelForValue(size2.width) ?? i18n_default.editor.fit), size2.width && size2.width != "auto" ? /* @__PURE__ */ import_react127.default.createElement("div", { + }, /* @__PURE__ */ import_react129.default.createElement("div", null, /* @__PURE__ */ import_react129.default.createElement("span", null, labelForValue(size2.width) ?? i18n_default.editor.fit), size2.width && size2.width != "auto" ? /* @__PURE__ */ import_react129.default.createElement("div", { onClick: (e5) => { props.resize({ width: wrapQuotes("auto") @@ -124466,7 +124824,7 @@ var FrameResizer = (props) => { "ui//fold-horizontal" ) } - }) : /* @__PURE__ */ import_react127.default.createElement("div", { + }) : /* @__PURE__ */ import_react129.default.createElement("div", { onClick: (e5) => { props.resize({ width: wrapQuotes("100%") @@ -124480,9 +124838,9 @@ var FrameResizer = (props) => { "ui//unfold-horizontal" ) } - }))), props.clientSize?.height > 50 && props.resizeMode == 1 /* ResizeSelected */ && /* @__PURE__ */ import_react127.default.createElement("div", { + }))), props.clientSize?.height > 50 && props.resizeMode == 1 /* ResizeSelected */ && /* @__PURE__ */ import_react129.default.createElement("div", { className: "mk-frame-resize-label-height" - }, /* @__PURE__ */ import_react127.default.createElement("div", null, /* @__PURE__ */ import_react127.default.createElement("span", null, labelForValue(size2.height) ?? i18n_default.editor.fit), size2.height && size2.height != "auto" ? /* @__PURE__ */ import_react127.default.createElement("div", { + }, /* @__PURE__ */ import_react129.default.createElement("div", null, /* @__PURE__ */ import_react129.default.createElement("span", null, labelForValue(size2.height) ?? i18n_default.editor.fit), size2.height && size2.height != "auto" ? /* @__PURE__ */ import_react129.default.createElement("div", { onClick: (e5) => { props.resize({ height: wrapQuotes("auto") @@ -124494,7 +124852,7 @@ var FrameResizer = (props) => { dangerouslySetInnerHTML: { __html: props.superstate.ui.getSticker("ui//fold-vertical") } - }) : /* @__PURE__ */ import_react127.default.createElement("div", { + }) : /* @__PURE__ */ import_react129.default.createElement("div", { onClick: (e5) => { props.resize({ height: wrapQuotes("100%") @@ -124512,27 +124870,27 @@ var FrameResizer = (props) => { }; // src/core/react/components/SpaceView/Frames/ViewNodes/FrameView.tsx -var import_react145 = __toESM(require_react()); +var import_react147 = __toESM(require_react()); // src/core/react/components/SpaceView/Frames/EditorNodes/AudioNodeView.tsx -var import_react128 = __toESM(require_react()); +var import_react130 = __toESM(require_react()); var AudioNodeView = (props) => { const value = props.state.props.value; - const sourcePath = (0, import_react128.useMemo)(() => { + const sourcePath = (0, import_react130.useMemo)(() => { return props.superstate.ui.getUIPath(value); }, [value]); - return props.state?.props.value?.length > 0 ? /* @__PURE__ */ import_react128.default.createElement("audio", { + return props.state?.props.value?.length > 0 ? /* @__PURE__ */ import_react130.default.createElement("audio", { controls: true, preload: "none", src: sourcePath - }) : /* @__PURE__ */ import_react128.default.createElement(import_react128.default.Fragment, null); + }) : /* @__PURE__ */ import_react130.default.createElement(import_react130.default.Fragment, null); }; // src/core/react/components/SpaceEditor/Actions/SpaceActions.tsx -var import_react134 = __toESM(require_react()); +var import_react136 = __toESM(require_react()); // src/core/react/components/UI/Dropdown.tsx -var import_react129 = __toESM(require_react()); +var import_react131 = __toESM(require_react()); var Dropdown2 = (props) => { const openMenu = (e5) => { const offset2 = e5.target.getBoundingClientRect(); @@ -124546,10 +124904,10 @@ var Dropdown2 = (props) => { } }); }; - return /* @__PURE__ */ import_react129.default.createElement("div", { + return /* @__PURE__ */ import_react131.default.createElement("div", { className: "mk-cell-option-item", onClick: (e5) => props.triggerMenu ? props.triggerMenu(e5) : openMenu(e5) - }, /* @__PURE__ */ import_react129.default.createElement("div", null, props.options ? props.options.find((f2) => f2.value == props.value)?.name : props.value), /* @__PURE__ */ import_react129.default.createElement("div", { + }, /* @__PURE__ */ import_react131.default.createElement("div", null, props.options ? props.options.find((f2) => f2.value == props.value)?.name : props.value), /* @__PURE__ */ import_react131.default.createElement("div", { className: "mk-cell-option-select mk-icon-xxsmall mk-icon-rotated", dangerouslySetInnerHTML: { __html: props.superstate.ui.getSticker("ui//collapse-solid") @@ -124558,15 +124916,15 @@ var Dropdown2 = (props) => { }; // src/core/react/components/SpaceEditor/Actions/ActionEditor.tsx -var import_react132 = __toESM(require_react()); +var import_react134 = __toESM(require_react()); // src/core/react/components/SpaceEditor/Actions/ActionNode.tsx -var import_react131 = __toESM(require_react()); +var import_react133 = __toESM(require_react()); // src/core/react/components/SpaceEditor/Actions/BuiltinPropertyEditor.tsx -var import_react130 = __toESM(require_react()); +var import_react132 = __toESM(require_react()); var BuiltinPropertyEditor = (props) => { - const allOptions = (0, import_react130.useMemo)(() => { + const allOptions = (0, import_react132.useMemo)(() => { const options = props.fields.map((f2) => ({ id: f2.name, field: f2.name, @@ -124595,16 +124953,16 @@ var BuiltinPropertyEditor = (props) => { }; props.superstate.ui.openCustomMenu( e5.target.getBoundingClientRect(), - /* @__PURE__ */ import_react130.default.createElement(FormulaEditor, { + /* @__PURE__ */ import_react132.default.createElement(FormulaEditor, { ..._props }), { ..._props }, "bottom" ); }; - return props.command.schema.id == "formula" ? /* @__PURE__ */ import_react130.default.createElement("button", { + return props.command.schema.id == "formula" ? /* @__PURE__ */ import_react132.default.createElement("button", { onClick: (e5) => editFormula(e5) - }, "Edit Formula") : props.command.schema.id == "filter" ? /* @__PURE__ */ import_react130.default.createElement(SpaceQuery, { + }, "Edit Formula") : props.command.schema.id == "filter" ? /* @__PURE__ */ import_react132.default.createElement(SpaceQuery, { superstate: props.superstate, filters: props.actionTree.props["$function"] ?? [], setFilters: (filters) => { @@ -124619,17 +124977,17 @@ var BuiltinPropertyEditor = (props) => { fields: allOptions, sections: [], removeable: true - }) : /* @__PURE__ */ import_react130.default.createElement(import_react130.default.Fragment, null); + }) : /* @__PURE__ */ import_react132.default.createElement(import_react132.default.Fragment, null); }; // src/core/react/components/SpaceEditor/Actions/ActionNode.tsx var ActionNode = (props) => { - const [action, setAction] = import_react131.default.useState(props.actionTree?.action); - const command = (0, import_react131.useMemo)( + const [action, setAction] = import_react133.default.useState(props.actionTree?.action); + const command = (0, import_react133.useMemo)( () => props.superstate.cli.commandForAction(action), [action] ); - (0, import_react131.useEffect)(() => { + (0, import_react133.useEffect)(() => { setAction(props.actionTree?.action); }, [props.actionTree]); const selectAction = (e5, add4) => { @@ -124677,31 +125035,31 @@ var ActionNode = (props) => { } }); }; - return /* @__PURE__ */ import_react131.default.createElement("div", { + return /* @__PURE__ */ import_react133.default.createElement("div", { className: "mk-editor-actions-node" - }, /* @__PURE__ */ import_react131.default.createElement("div", { + }, /* @__PURE__ */ import_react133.default.createElement("div", { className: "mk-editor-actions-body" - }, /* @__PURE__ */ import_react131.default.createElement("div", { + }, /* @__PURE__ */ import_react133.default.createElement("div", { className: "mk-editor-actions-name" - }, /* @__PURE__ */ import_react131.default.createElement("div", { + }, /* @__PURE__ */ import_react133.default.createElement("div", { className: "mk-path-icon", dangerouslySetInnerHTML: { __html: props.superstate.ui.getSticker( command ? stickerForSchema(command.schema) : "ui//plus" ) } - }), /* @__PURE__ */ import_react131.default.createElement("div", { + }), /* @__PURE__ */ import_react133.default.createElement("div", { onClick: (e5) => !command && selectAction(e5), className: "mk-editor-actions-selector" - }, command?.schema.name ?? "Select"), /* @__PURE__ */ import_react131.default.createElement("span", null), props.deleteTree && /* @__PURE__ */ import_react131.default.createElement("div", { + }, command?.schema.name ?? "Select"), /* @__PURE__ */ import_react133.default.createElement("span", null), props.deleteTree && /* @__PURE__ */ import_react133.default.createElement("div", { className: "mk-icon-small", onClick: (e5) => props.deleteTree(), dangerouslySetInnerHTML: { __html: props.superstate.ui.getSticker("ui//close") } - })), command && /* @__PURE__ */ import_react131.default.createElement("div", { + })), command && /* @__PURE__ */ import_react133.default.createElement("div", { className: "mk-editor-actions-fields" - }, command.schema.type == "builtin" ? /* @__PURE__ */ import_react131.default.createElement(BuiltinPropertyEditor, { + }, command.schema.type == "builtin" ? /* @__PURE__ */ import_react133.default.createElement(BuiltinPropertyEditor, { superstate: props.superstate, command, actionTree: props.actionTree, @@ -124710,7 +125068,7 @@ var ActionNode = (props) => { values: props.values, path: props.path }) : command?.fields.map((f2, i4) => { - return /* @__PURE__ */ import_react131.default.createElement(DataPropertyView, { + return /* @__PURE__ */ import_react133.default.createElement(DataPropertyView, { key: i4, superstate: props.superstate, column: f2, @@ -124730,9 +125088,9 @@ var ActionNode = (props) => { editMode: 5 /* EditModeAlways */, linkProp: (e5) => selectLinkedProp(e5, f2.name) }); - }))), /* @__PURE__ */ import_react131.default.createElement("div", { + }))), /* @__PURE__ */ import_react133.default.createElement("div", { className: props.hasSiblings ? "mk-editor-actions-children" : "" - }, props.actionTree.children.map((child, i4) => /* @__PURE__ */ import_react131.default.createElement(ActionNode, { + }, props.actionTree.children.map((child, i4) => /* @__PURE__ */ import_react133.default.createElement(ActionNode, { key: i4, hasSiblings: props.actionTree.children.length > 1, prevField: command?.fields[i4], @@ -124751,10 +125109,10 @@ var ActionNode = (props) => { newTree.children.splice(i4, 1); props.saveTree(newTree); } - })), props.actionTree.children.length == 0 && /* @__PURE__ */ import_react131.default.createElement("button", { + })), props.actionTree.children.length == 0 && /* @__PURE__ */ import_react133.default.createElement("button", { onClick: (e5) => selectAction(e5, true), className: "mk-inline-button" - }, /* @__PURE__ */ import_react131.default.createElement("div", { + }, /* @__PURE__ */ import_react133.default.createElement("div", { className: "mk-icon-xsmall", dangerouslySetInnerHTML: { __html: props.superstate.ui.getSticker("ui//plus") @@ -124764,7 +125122,7 @@ var ActionNode = (props) => { // src/core/react/components/SpaceEditor/Actions/ActionEditor.tsx var ActionEditor = (props) => { - const [actionTree, setActionTree] = import_react132.default.useState( + const [actionTree, setActionTree] = import_react134.default.useState( parseActionString(props.formula) ?? { action: "", props: {}, @@ -124772,9 +125130,9 @@ var ActionEditor = (props) => { children: [] } ); - return /* @__PURE__ */ import_react132.default.createElement("div", { + return /* @__PURE__ */ import_react134.default.createElement("div", { className: "mk-editor-actions-nodes" - }, /* @__PURE__ */ import_react132.default.createElement(ActionNode, { + }, /* @__PURE__ */ import_react134.default.createElement(ActionNode, { hasSiblings: false, superstate: props.superstate, prevField: null, @@ -124790,7 +125148,7 @@ var ActionEditor = (props) => { }; // src/core/react/components/SpaceEditor/Actions/ScriptEditor.tsx -var import_react133 = __toESM(require_react()); +var import_react135 = __toESM(require_react()); // node_modules/@uiw/codemirror-theme-github/esm/index.js var defaultSettingsGithubLight = { @@ -124932,7 +125290,7 @@ var githubDark = githubDarkInit(); // src/core/react/components/SpaceEditor/Actions/ScriptEditor.tsx var ScriptEditor = (props) => { const { command } = props; - const value = (0, import_react133.useMemo)(() => { + const value = (0, import_react135.useMemo)(() => { if (!command) return ""; return `const ${command.schema.id} = (${command.fields.map((f2) => `${f2.name}: ${f2.type}`).join(", ")}, $api: API, $contexts) => { @@ -124946,14 +125304,14 @@ ${command.code} codeType: "script" }); }; - return /* @__PURE__ */ import_react133.default.createElement("div", null, /* @__PURE__ */ import_react133.default.createElement(esm_default, { + return /* @__PURE__ */ import_react135.default.createElement("div", null, /* @__PURE__ */ import_react135.default.createElement(esm_default, { className: "mk-editor-code", value, height: "100%", theme: githubDark, extensions: [javascript({ jsx: true })], onChange: saveCommand - }), /* @__PURE__ */ import_react133.default.createElement(ActionTester, { + }), /* @__PURE__ */ import_react135.default.createElement(ActionTester, { type: "script", code: command.code, fields: command.fields, @@ -124965,8 +125323,8 @@ ${command.code} // src/core/react/components/SpaceEditor/Actions/SpaceActions.tsx var SpaceCommand = (props) => { - const [command, setCommand] = (0, import_react134.useState)(null); - const uri = (0, import_react134.useMemo)(() => { + const [command, setCommand] = (0, import_react136.useState)(null); + const uri = (0, import_react136.useMemo)(() => { return props.superstate.spaceManager.uriByString(props.action); }, [props.action]); const saveCommand = (command2) => { @@ -124984,10 +125342,10 @@ var SpaceCommand = (props) => { () => command2 ); }; - (0, import_react134.useEffect)(() => { + (0, import_react136.useEffect)(() => { setCommand(props.superstate.cli.commandForAction(props.action)); }, [props.action]); - (0, import_react134.useEffect)(() => { + (0, import_react136.useEffect)(() => { const listener = (f2) => { if (f2.path == uri.basePath) setCommand(props.superstate.cli.commandForAction(props.action)); @@ -125062,22 +125420,22 @@ var SpaceCommand = (props) => { field ); }; - const defaultValues = (0, import_react134.useMemo)(() => { + const defaultValues = (0, import_react136.useMemo)(() => { return command?.fields.reduce((p, c3) => { return { ...p, [c3.name]: defaultValueForField(c3) }; }, {}) ?? {}; }, [command?.fields]); - return /* @__PURE__ */ import_react134.default.createElement("div", { + return /* @__PURE__ */ import_react136.default.createElement("div", { className: "mk-editor-actions" - }, command && /* @__PURE__ */ import_react134.default.createElement(import_react134.default.Fragment, null, /* @__PURE__ */ import_react134.default.createElement("div", { + }, command && /* @__PURE__ */ import_react136.default.createElement(import_react136.default.Fragment, null, /* @__PURE__ */ import_react136.default.createElement("div", { className: "mk-props-contexts" - }, /* @__PURE__ */ import_react134.default.createElement("div", { + }, /* @__PURE__ */ import_react136.default.createElement("div", { className: "mk-path-context-row" - }, /* @__PURE__ */ import_react134.default.createElement("div", { + }, /* @__PURE__ */ import_react136.default.createElement("div", { className: "mk-path-context-field" - }, "Type"), /* @__PURE__ */ import_react134.default.createElement("div", { + }, "Type"), /* @__PURE__ */ import_react136.default.createElement("div", { className: "mk-path-context-value" - }, /* @__PURE__ */ import_react134.default.createElement(Dropdown2, { + }, /* @__PURE__ */ import_react136.default.createElement(Dropdown2, { superstate: props.superstate, options: menuItems, value: command.schema.type, @@ -125088,14 +125446,14 @@ var SpaceCommand = (props) => { type: value } }) - }))), /* @__PURE__ */ import_react134.default.createElement("div", { + }))), /* @__PURE__ */ import_react136.default.createElement("div", { className: "mk-path-context-row" - }, /* @__PURE__ */ import_react134.default.createElement("div", { + }, /* @__PURE__ */ import_react136.default.createElement("div", { className: "mk-path-context-field" - }, "Properties")), /* @__PURE__ */ import_react134.default.createElement("div", { + }, "Properties")), /* @__PURE__ */ import_react136.default.createElement("div", { className: "mk-cell-object" }, command.fields.map((f2) => { - return /* @__PURE__ */ import_react134.default.createElement(DataPropertyView, { + return /* @__PURE__ */ import_react136.default.createElement(DataPropertyView, { key: f2.name, superstate: props.superstate, initialValue: defaultValueForField(f2), @@ -125133,21 +125491,21 @@ var SpaceCommand = (props) => { }); } }); - })), /* @__PURE__ */ import_react134.default.createElement("button", { + })), /* @__PURE__ */ import_react136.default.createElement("button", { className: "mk-inline-button", onClick: (e5) => newProperty(e5) - }, /* @__PURE__ */ import_react134.default.createElement("div", { + }, /* @__PURE__ */ import_react136.default.createElement("div", { className: "mk-icon-xsmall", dangerouslySetInnerHTML: { __html: props.superstate.ui.getSticker("ui//plus") } - }), i18n_default.labels.newProperty)), command.schema.type == "script" ? /* @__PURE__ */ import_react134.default.createElement(ScriptEditor, { + }), i18n_default.labels.newProperty)), command.schema.type == "script" ? /* @__PURE__ */ import_react136.default.createElement(ScriptEditor, { superstate: props.superstate, command, saveCommand, values: defaultValues, path: uri.path - }) : command.schema.type == "actions" ? /* @__PURE__ */ import_react134.default.createElement(ActionEditor, { + }) : command.schema.type == "actions" ? /* @__PURE__ */ import_react136.default.createElement(ActionEditor, { superstate: props.superstate, formula: command.code, path: uri.path, @@ -125165,7 +125523,7 @@ var SpaceCommand = (props) => { }, fields: command.fields, value: defaultValues - }) : command.schema.type == "formula" ? /* @__PURE__ */ import_react134.default.createElement(FormulaEditor, { + }) : command.schema.type == "formula" ? /* @__PURE__ */ import_react136.default.createElement(FormulaEditor, { superstate: props.superstate, formula: command.code, saveFormula: (formula) => { @@ -125177,17 +125535,17 @@ var SpaceCommand = (props) => { fields: command.fields, value: defaultValues, path: uri.path - }) : /* @__PURE__ */ import_react134.default.createElement("div", null))); + }) : /* @__PURE__ */ import_react136.default.createElement("div", null))); }; // src/core/react/components/SpaceView/Editor/EmbedView/SpaceFragmentView.tsx -var import_react136 = __toESM(require_react()); +var import_react138 = __toESM(require_react()); // src/core/react/components/SpaceView/Frames/ViewNodes/FrameInstance.tsx -var import_react135 = __toESM(require_react()); +var import_react137 = __toESM(require_react()); var FrameInstanceView = (props) => { - const { saveState, instance } = (0, import_react135.useContext)(FrameInstanceContext); - return instance.exec && /* @__PURE__ */ import_react135.default.createElement(FrameView, { + const { saveState, instance } = (0, import_react137.useContext)(FrameInstanceContext); + return instance.exec && /* @__PURE__ */ import_react137.default.createElement(FrameView, { superstate: props.superstate, treeNode: instance.exec, instance, @@ -125198,12 +125556,12 @@ var FrameInstanceView = (props) => { // src/core/react/components/SpaceView/Editor/EmbedView/SpaceFragmentView.tsx var SpaceFragmentViewComponent = (props) => { - const path2 = (0, import_react136.useMemo)( + const path2 = (0, import_react138.useMemo)( () => props.superstate.spaceManager.uriByString(props.path, props.source), [props.path, props.source] ); - const [spaceFragment, setSpaceFragment] = (0, import_react136.useState)(null); - (0, import_react136.useEffect)(() => { + const [spaceFragment, setSpaceFragment] = (0, import_react138.useState)(null); + (0, import_react138.useEffect)(() => { if (path2.refType == "context") { setSpaceFragment({ type: "context", @@ -125248,47 +125606,47 @@ var SpaceFragmentViewComponent = (props) => { }); } }, [path2]); - return /* @__PURE__ */ import_react136.default.createElement(import_react136.default.Fragment, null, spaceFragment?.path && (spaceFragment?.type == "context" ? /* @__PURE__ */ import_react136.default.createElement(PathProvider, { + return /* @__PURE__ */ import_react138.default.createElement(import_react138.default.Fragment, null, spaceFragment?.path && (spaceFragment?.type == "context" ? /* @__PURE__ */ import_react138.default.createElement(PathProvider, { superstate: props.superstate, path: spaceFragment.path, readMode: false - }, /* @__PURE__ */ import_react136.default.createElement(SpaceProvider, { + }, /* @__PURE__ */ import_react138.default.createElement(SpaceProvider, { superstate: props.superstate - }, /* @__PURE__ */ import_react136.default.createElement(FramesMDBProvider, { + }, /* @__PURE__ */ import_react138.default.createElement(FramesMDBProvider, { superstate: props.superstate, contextSchema: spaceFragment.contextSchema, schema: spaceFragment.frameSchema - }, /* @__PURE__ */ import_react136.default.createElement(ContextEditorProvider, { + }, /* @__PURE__ */ import_react138.default.createElement(ContextEditorProvider, { superstate: props.superstate - }, /* @__PURE__ */ import_react136.default.createElement(ContextListContainer, { + }, /* @__PURE__ */ import_react138.default.createElement(ContextListContainer, { superstate: props.superstate, minMode: props.minMode, containerRef: props.containerRef, setView: props.setFrameSchema - }))))) : spaceFragment?.type == "frame" ? /* @__PURE__ */ import_react136.default.createElement(FrameRootProvider, { + }))))) : spaceFragment?.type == "frame" ? /* @__PURE__ */ import_react138.default.createElement(FrameRootProvider, { superstate: props.superstate, path: path2, cols: [] - }, /* @__PURE__ */ import_react136.default.createElement(FrameInstanceProvider, { + }, /* @__PURE__ */ import_react138.default.createElement(FrameInstanceProvider, { id: props.id, superstate: props.superstate, props: {}, editable: false - }, /* @__PURE__ */ import_react136.default.createElement(FrameInstanceView, { + }, /* @__PURE__ */ import_react138.default.createElement(FrameInstanceView, { superstate: props.superstate, source: props.source - }))) : spaceFragment?.type == "action" ? /* @__PURE__ */ import_react136.default.createElement(SpaceCommand, { + }))) : spaceFragment?.type == "action" ? /* @__PURE__ */ import_react138.default.createElement(SpaceCommand, { superstate: props.superstate, action: props.path - }) : /* @__PURE__ */ import_react136.default.createElement(import_react136.default.Fragment, null))); + }) : /* @__PURE__ */ import_react138.default.createElement(import_react138.default.Fragment, null))); }; // src/core/react/components/SpaceView/Frames/EditorNodes/ContextNodeView.tsx -var import_react137 = __toESM(require_react()); +var import_react139 = __toESM(require_react()); var ContextNodeView = (props) => { const fullPath = props.state?.props?.value; - const { updateNode } = (0, import_react137.useContext)(FramesEditorRootContext); - const { id: id3 } = (0, import_react137.useContext)(FrameInstanceContext); + const { updateNode } = (0, import_react139.useContext)(FramesEditorRootContext); + const { id: id3 } = (0, import_react139.useContext)(FrameInstanceContext); const selectLink = (e5) => { showSpacesMenu( e5, @@ -125323,7 +125681,7 @@ var ContextNodeView = (props) => { } }); }; - return props.state && fullPath ? /* @__PURE__ */ import_react137.default.createElement(SpaceFragmentViewComponent, { + return props.state && fullPath ? /* @__PURE__ */ import_react139.default.createElement(SpaceFragmentViewComponent, { id: id3, source: props.source, superstate: props.superstate, @@ -125331,21 +125689,21 @@ var ContextNodeView = (props) => { minMode: props.state?.styles?.["--mk-min-mode"], containerRef: props.containerRef, setFrameSchema - }) : /* @__PURE__ */ import_react137.default.createElement("div", { + }) : /* @__PURE__ */ import_react139.default.createElement("div", { className: "mk-frame-placeholder", onClick: (e5) => selectLink(e5) }, i18n_default.labels.selectSpace); }; // src/core/react/components/SpaceView/Frames/EditorNodes/IconNodeView.tsx -var import_react138 = __toESM(require_react()); +var import_react140 = __toESM(require_react()); var IconNodeView = (props) => { const { selectionMode, selected: frameSelected, selection: selection2 - } = (0, import_react138.useContext)(FrameSelectionContext); - const { updateNode, nodes } = (0, import_react138.useContext)(FramesEditorRootContext); + } = (0, import_react140.useContext)(FrameSelectionContext); + const { updateNode, nodes } = (0, import_react140.useContext)(FramesEditorRootContext); const updateValue2 = (newValue) => { if (newValue != props.state.props?.value) { if (props.treeNode.editorProps?.linkedNode) { @@ -125366,7 +125724,7 @@ var IconNodeView = (props) => { } }; const selected = selection2?.includes(props.treeNode.node.id); - const editable = (0, import_react138.useMemo)(() => { + const editable = (0, import_react140.useMemo)(() => { if (selectionMode == 0 /* Read */) return false; if (selectionMode == 1 /* Page */) @@ -125381,55 +125739,55 @@ var IconNodeView = (props) => { return true; }, [props.treeNode, selectionMode, frameSelected, selected]); const selectIcon = () => { - props.superstate.ui.openPalette((_props) => /* @__PURE__ */ import_react138.default.createElement(StickerModal_default, { + props.superstate.ui.openPalette((_props) => /* @__PURE__ */ import_react140.default.createElement(StickerModal_default, { ui: props.superstate.ui, hide: _props.hide, selectedSticker: (emoji) => updateValue2(emoji) })); }; const [stickerType, stickerPath] = props.state.props?.value ? parseStickerString(props.state.props?.value) : [null, null]; - return props.state && (props.state.props?.value?.length > 0 ? stickerType == "image" ? /* @__PURE__ */ import_react138.default.createElement("img", { + return props.state && (props.state.props?.value?.length > 0 ? stickerType == "image" ? /* @__PURE__ */ import_react140.default.createElement("img", { className: "mk-frame-icon", src: props.superstate.ui.getUIPath( props.superstate.imagesCache.get(stickerPath) ) - }) : /* @__PURE__ */ import_react138.default.createElement("div", { + }) : /* @__PURE__ */ import_react140.default.createElement("div", { className: "mk-frame-icon", style: {}, dangerouslySetInnerHTML: { __html: props.superstate.ui.getSticker(props.state.props?.value) } - }) : editable ? /* @__PURE__ */ import_react138.default.createElement("div", { + }) : editable ? /* @__PURE__ */ import_react140.default.createElement("div", { onClick: () => selectIcon(), "aria-label": "Select Sticker", className: "mk-node-icon-placeholder", dangerouslySetInnerHTML: { __html: props.superstate.ui.getSticker("ui//smile") } - }) : /* @__PURE__ */ import_react138.default.createElement(import_react138.default.Fragment, null)); + }) : /* @__PURE__ */ import_react140.default.createElement(import_react140.default.Fragment, null)); }; // src/core/react/components/SpaceView/Frames/EditorNodes/ImageNodeView.tsx -var import_react139 = __toESM(require_react()); +var import_react141 = __toESM(require_react()); var ImageNodeView = (props) => { const value = props.state.props.value; - const sourcePath = (0, import_react139.useMemo)(() => { + const sourcePath = (0, import_react141.useMemo)(() => { return props.superstate.ui.getUIPath(value, true); }, [value]); - const { nodes, updateNode } = (0, import_react139.useContext)(FramesEditorRootContext); - const { linkedProps } = (0, import_react139.useContext)(FrameInstanceContext); + const { nodes, updateNode } = (0, import_react141.useContext)(FramesEditorRootContext); + const { linkedProps } = (0, import_react141.useContext)(FrameInstanceContext); const { selectionMode, selected: frameSelected, selection: selection2 - } = (0, import_react139.useContext)(FrameSelectionContext); + } = (0, import_react141.useContext)(FrameSelectionContext); const selected = selection2?.includes(props.treeNode.node.id); const showModal2 = () => { if (!stringIsConst(props.treeNode.node.props.value) && !linkedProps.some( (f2) => props.treeNode.editorProps.linkedNode?.node == props.treeNode.node.schemaId && props.treeNode.editorProps.linkedNode?.prop == f2 )) return; - props.superstate.ui.openPalette((_props) => /* @__PURE__ */ import_react139.default.createElement(ImageModal_default, { + props.superstate.ui.openPalette((_props) => /* @__PURE__ */ import_react141.default.createElement(ImageModal_default, { superstate: props.superstate, hide: _props.hide, selectedPath: (image) => saveValue(image) @@ -125454,7 +125812,7 @@ var ImageNodeView = (props) => { } } }; - const editable = (0, import_react139.useMemo)(() => { + const editable = (0, import_react141.useMemo)(() => { if (selectionMode == 0 /* Read */) return false; if (selectionMode == 1 /* Page */) @@ -125468,7 +125826,7 @@ var ImageNodeView = (props) => { } return true; }, [props.treeNode, selectionMode, frameSelected, selected]); - return props.state?.props.value?.length > 0 ? /* @__PURE__ */ import_react139.default.createElement("img", { + return props.state?.props.value?.length > 0 ? /* @__PURE__ */ import_react141.default.createElement("img", { className: "mk-node-image", width: props.state?.styles.width, height: props.state?.styles.height, @@ -125477,7 +125835,7 @@ var ImageNodeView = (props) => { maxHeight: props.state?.styles.maxHeight }, src: sourcePath - }) : editable ? /* @__PURE__ */ import_react139.default.createElement("div", { + }) : editable ? /* @__PURE__ */ import_react141.default.createElement("div", { className: "mk-node-image-placeholder", dangerouslySetInnerHTML: { __html: props.superstate.ui.getPlaceholderImage("image-select") @@ -125487,25 +125845,25 @@ var ImageNodeView = (props) => { maxHeight: props.state?.styles.maxHeight }, onClick: (e5) => showModal2() - }) : /* @__PURE__ */ import_react139.default.createElement(import_react139.default.Fragment, null); + }) : /* @__PURE__ */ import_react141.default.createElement(import_react141.default.Fragment, null); }; // src/core/react/components/SpaceView/Frames/EditorNodes/InputNodeView.tsx -var import_react140 = __toESM(require_react()); +var import_react142 = __toESM(require_react()); var InputNodeView = (props) => { - const { selectionMode } = (0, import_react140.useContext)(FrameSelectionContext); - const { saveState, instance } = (0, import_react140.useContext)(FrameInstanceContext); - const [value, setValue] = (0, import_react140.useState)(""); + const { selectionMode } = (0, import_react142.useContext)(FrameSelectionContext); + const { saveState, instance } = (0, import_react142.useContext)(FrameInstanceContext); + const [value, setValue] = (0, import_react142.useState)(""); const state = props.state; const type = props.state.styles?.as; - (0, import_react140.useEffect)(() => { + (0, import_react142.useEffect)(() => { const linkedNode = parseLinkedNode(props.state?.props?.value); if (linkedNode) { const node = linkedNode.node == "$root" ? instance.exec.id : linkedNode.node; setValue(instance.state?.[node]?.props?.[linkedNode.prop]); } }, [props.state.props]); - return /* @__PURE__ */ import_react140.default.createElement("input", { + return /* @__PURE__ */ import_react142.default.createElement("input", { className: "mk-node-input", type, value: type == "checkbox" ? null : value, @@ -125547,22 +125905,22 @@ var InputNodeView = (props) => { }; // src/core/react/components/SpaceView/Frames/EditorNodes/TextNodeView.tsx -var import_react144 = __toESM(require_react()); +var import_react146 = __toESM(require_react()); // src/core/react/hooks/useEffectOnce.ts -var import_react141 = __toESM(require_react()); +var import_react143 = __toESM(require_react()); function useEffectOnce(cb) { - (0, import_react141.useEffect)(cb, []); + (0, import_react143.useEffect)(cb, []); } // src/core/react/hooks/useEventListener.ts -var import_react142 = __toESM(require_react()); +var import_react144 = __toESM(require_react()); function useEventListener(eventType, callback, element = window) { - const callbackRef = (0, import_react142.useRef)(callback); - (0, import_react142.useEffect)(() => { + const callbackRef = (0, import_react144.useRef)(callback); + (0, import_react144.useEffect)(() => { callbackRef.current = callback; }, [callback]); - (0, import_react142.useEffect)(() => { + (0, import_react144.useEffect)(() => { if (element == null) return; const handler = (e5) => callbackRef.current(e5); @@ -125572,24 +125930,24 @@ function useEventListener(eventType, callback, element = window) { } // src/core/react/hooks/useTimeout.tsx -var import_react143 = __toESM(require_react()); +var import_react145 = __toESM(require_react()); function useTimeout(callback, delay) { - const callbackRef = (0, import_react143.useRef)(callback); - const timeoutRef = (0, import_react143.useRef)(null); - (0, import_react143.useEffect)(() => { + const callbackRef = (0, import_react145.useRef)(callback); + const timeoutRef = (0, import_react145.useRef)(null); + (0, import_react145.useEffect)(() => { callbackRef.current = callback; }, [callback]); - const set = (0, import_react143.useCallback)(() => { + const set = (0, import_react145.useCallback)(() => { timeoutRef.current = setTimeout(() => callbackRef.current(), delay); }, [delay]); - const clear = (0, import_react143.useCallback)(() => { + const clear = (0, import_react145.useCallback)(() => { timeoutRef.current && clearTimeout(timeoutRef.current); }, []); - (0, import_react143.useEffect)(() => { + (0, import_react145.useEffect)(() => { set(); return clear; }, [delay, set, clear]); - const reset2 = (0, import_react143.useCallback)(() => { + const reset2 = (0, import_react145.useCallback)(() => { clear(); set(); }, [clear, set]); @@ -125615,9 +125973,9 @@ var TextNodeView = (props) => { selectable, selected: frameSelected, select - } = (0, import_react144.useContext)(FrameSelectionContext); - const fileNameRef = (0, import_react144.useRef)(null); - const { updateNode, nodes, deleteNode } = (0, import_react144.useContext)(FramesEditorRootContext); + } = (0, import_react146.useContext)(FrameSelectionContext); + const fileNameRef = (0, import_react146.useRef)(null); + const { updateNode, nodes, deleteNode } = (0, import_react146.useContext)(FramesEditorRootContext); const updateValue2 = (newValue) => { if (newValue != props.state.props?.value) { if (props.treeNode.editorProps?.linkedNode) { @@ -125690,8 +126048,8 @@ var TextNodeView = (props) => { }; useLongPress(fileNameRef, onLongPress); const selected = selection2.includes(props.treeNode.id); - const { linkedProps } = (0, import_react144.useContext)(FrameInstanceContext); - const editable = (0, import_react144.useMemo)(() => { + const { linkedProps } = (0, import_react146.useContext)(FrameInstanceContext); + const editable = (0, import_react146.useMemo)(() => { if (selectionMode == 0 /* Read */) return false; if (props.treeNode.isRef) { @@ -125711,7 +126069,7 @@ var TextNodeView = (props) => { return true; return false; }, [props.treeNode, selectionMode, frameSelected, selected, linkedProps]); - return props.state && /* @__PURE__ */ import_react144.default.createElement("div", { + return props.state && /* @__PURE__ */ import_react146.default.createElement("div", { className: `mk-frame-text`, "data-placeholder": editable || selectable ? i18n_default.labels.textPlaceholder : "", dangerouslySetInnerHTML: { @@ -125736,30 +126094,30 @@ var FrameView = (props) => { treeNode: props.treeNode, state: props.instance.state[props.treeNode.id] }; - const innerComponents = props.treeNode.node.type == "input" ? /* @__PURE__ */ import_react145.default.createElement(InputNodeView, { + const innerComponents = props.treeNode.node.type == "input" ? /* @__PURE__ */ import_react147.default.createElement(InputNodeView, { ...nodeProps - }) : props.treeNode.node.type == "text" ? /* @__PURE__ */ import_react145.default.createElement(TextNodeView, { + }) : props.treeNode.node.type == "text" ? /* @__PURE__ */ import_react147.default.createElement(TextNodeView, { ...nodeProps - }) : props.treeNode.node.type == "icon" ? /* @__PURE__ */ import_react145.default.createElement(IconNodeView, { + }) : props.treeNode.node.type == "icon" ? /* @__PURE__ */ import_react147.default.createElement(IconNodeView, { ...nodeProps - }) : props.treeNode.node.type == "audio" ? /* @__PURE__ */ import_react145.default.createElement(AudioNodeView, { + }) : props.treeNode.node.type == "audio" ? /* @__PURE__ */ import_react147.default.createElement(AudioNodeView, { ...nodeProps - }) : props.treeNode.node.type == "image" ? /* @__PURE__ */ import_react145.default.createElement(ImageNodeView, { + }) : props.treeNode.node.type == "image" ? /* @__PURE__ */ import_react147.default.createElement(ImageNodeView, { ...nodeProps - }) : props.treeNode.node.type == "space" ? /* @__PURE__ */ import_react145.default.createElement(ContextNodeView, { + }) : props.treeNode.node.type == "space" ? /* @__PURE__ */ import_react147.default.createElement(ContextNodeView, { ...nodeProps, source: props.source - }) : props.treeNode.node.type == "content" ? /* @__PURE__ */ import_react145.default.createElement(ContentNodeView, null, props.treeNode.children.filter((f2) => f2.node.type != "slides").map((c3, i4) => /* @__PURE__ */ import_react145.default.createElement(FrameView, { + }) : props.treeNode.node.type == "content" ? /* @__PURE__ */ import_react147.default.createElement(ContentNodeView, null, props.treeNode.children.filter((f2) => f2.node.type != "slides").map((c3, i4) => /* @__PURE__ */ import_react147.default.createElement(FrameView, { superstate: props.superstate, key: i4, treeNode: c3, instance: props.instance, saveState: props.saveState, source: props.source - }, props.children)), props.children) : props.treeNode.node.type == "flow" ? /* @__PURE__ */ import_react145.default.createElement(FlowNodeView, { + }, props.children)), props.children) : props.treeNode.node.type == "flow" ? /* @__PURE__ */ import_react147.default.createElement(FlowNodeView, { ...nodeProps, source: props.source - }) : props.treeNode.children.filter((f2) => f2.node.type != "slides").map((c3, i4) => /* @__PURE__ */ import_react145.default.createElement(FrameView, { + }) : props.treeNode.children.filter((f2) => f2.node.type != "slides").map((c3, i4) => /* @__PURE__ */ import_react147.default.createElement(FrameView, { superstate: props.superstate, key: i4, treeNode: c3, @@ -125768,7 +126126,7 @@ var FrameView = (props) => { source: props.source }, props.children)); const hidden = props.instance.state[props.treeNode.id]?.styles ? props.instance.state[props.treeNode.id]?.styles?.hidden ? true : false : false; - return props.instance.state[props.treeNode.id] && !hidden && /* @__PURE__ */ import_react145.default.createElement("div", { + return props.instance.state[props.treeNode.id] && !hidden && /* @__PURE__ */ import_react147.default.createElement("div", { className: `mk-frame ${parseStylesToClass( props.instance.state[props.treeNode.id]?.styles )}`, @@ -125819,10 +126177,10 @@ var FrameView = (props) => { }; // src/core/react/components/SpaceView/Frames/EditorNodes/NewNodeView.tsx -var import_react146 = __toESM(require_react()); +var import_react148 = __toESM(require_react()); var NewNodeView = (props) => { - const ref2 = import_react146.default.createRef(); - const { spaceState } = (0, import_react146.useContext)(SpaceContext); + const ref2 = import_react148.default.createRef(); + const { spaceState } = (0, import_react148.useContext)(SpaceContext); const { updateNode, nodes, @@ -125831,10 +126189,10 @@ var NewNodeView = (props) => { saveNodes, lastCreatedId, setLastCreatedId - } = (0, import_react146.useContext)(FramesEditorRootContext); - const { selection: selection2, select } = (0, import_react146.useContext)(FrameSelectionContext); - const [type, setType] = (0, import_react146.useState)("label"); - const { instance } = (0, import_react146.useContext)(FrameInstanceContext); + } = (0, import_react148.useContext)(FramesEditorRootContext); + const { selection: selection2, select } = (0, import_react148.useContext)(FrameSelectionContext); + const [type, setType] = (0, import_react148.useState)("label"); + const { instance } = (0, import_react148.useContext)(FrameInstanceContext); const spaces2 = [...props.superstate.allSpaces(true)].filter((f2) => f2.type != "default").map((f2) => ({ name: f2.name, value: f2.path, @@ -125853,8 +126211,8 @@ var NewNodeView = (props) => { threshold: 0, keys: ["name", "value"] }; - const [query, setQuery] = (0, import_react146.useState)(""); - const suggestions = (0, import_react146.useMemo)(() => { + const [query, setQuery] = (0, import_react148.useState)(""); + const suggestions = (0, import_react148.useMemo)(() => { const menuOptions = []; const label = { name: i18n_default.frames.label.label, @@ -126055,7 +126413,7 @@ var NewNodeView = (props) => { ...props.treeNode.node, name: contextNode.node.name, type: "space", - props: { value: wrapQuotes(`${spaceState.path}/#^${f2}`) }, + props: { value: wrapQuotes(`${spaceState.path}/#*${f2}`) }, styles: { ...contextNode.node.styles } @@ -126081,15 +126439,15 @@ var NewNodeView = (props) => { ref2.current.blur(); ref2.current.innerHTML = ""; }; - (0, import_react146.useEffect)(() => { + (0, import_react148.useEffect)(() => { if (ref2.current && lastCreatedId && lastCreatedId == props.treeNode?.node.id) { ref2.current.focus(); setLastCreatedId(null); } }, [ref2, selection2, props.treeNode]); - return /* @__PURE__ */ import_react146.default.createElement("div", { + return /* @__PURE__ */ import_react148.default.createElement("div", { className: "mk-node-new" - }, /* @__PURE__ */ import_react146.default.createElement(Suggester, { + }, /* @__PURE__ */ import_react148.default.createElement(Suggester, { superstate: props.superstate, placeholder: i18n_default.hintText.newFrame, suggestions, @@ -126110,39 +126468,39 @@ var NewNodeView = (props) => { var defaultFrameStyles = { position: "relative" }; -var FrameEditorInner = (0, import_react147.memo)(function FrameEditorInner2(props) { +var FrameEditorInner = (0, import_react149.memo)(function FrameEditorInner2(props) { const nodeProps = { superstate: props.superstate, treeNode: props.treeNode, state: props.state }; const { treeNode } = props; - const { pathState } = (0, import_react147.useContext)(PathContext); - const { instance } = (0, import_react147.useContext)(FrameInstanceContext); - return /* @__PURE__ */ import_react147.default.createElement(import_react147.default.Fragment, null, treeNode.node.type == "new" ? /* @__PURE__ */ import_react147.default.createElement(NewNodeView, { + const { pathState } = (0, import_react149.useContext)(PathContext); + const { instance } = (0, import_react149.useContext)(FrameInstanceContext); + return /* @__PURE__ */ import_react149.default.createElement(import_react149.default.Fragment, null, treeNode.node.type == "new" ? /* @__PURE__ */ import_react149.default.createElement(NewNodeView, { ...nodeProps - }) : treeNode.node.type == "input" ? /* @__PURE__ */ import_react147.default.createElement(InputNodeView, { + }) : treeNode.node.type == "input" ? /* @__PURE__ */ import_react149.default.createElement(InputNodeView, { ...nodeProps - }) : treeNode.node.type == "text" ? /* @__PURE__ */ import_react147.default.createElement(TextNodeView, { + }) : treeNode.node.type == "text" ? /* @__PURE__ */ import_react149.default.createElement(TextNodeView, { ...nodeProps - }) : treeNode.node.type == "icon" ? /* @__PURE__ */ import_react147.default.createElement(IconNodeView, { + }) : treeNode.node.type == "icon" ? /* @__PURE__ */ import_react149.default.createElement(IconNodeView, { ...nodeProps - }) : treeNode.node.type == "audio" ? /* @__PURE__ */ import_react147.default.createElement(AudioNodeView, { + }) : treeNode.node.type == "audio" ? /* @__PURE__ */ import_react149.default.createElement(AudioNodeView, { ...nodeProps - }) : treeNode.node.type == "image" ? /* @__PURE__ */ import_react147.default.createElement(ImageNodeView, { + }) : treeNode.node.type == "image" ? /* @__PURE__ */ import_react149.default.createElement(ImageNodeView, { ...nodeProps - }) : treeNode.node.type == "space" ? /* @__PURE__ */ import_react147.default.createElement(ContextNodeView, { + }) : treeNode.node.type == "space" ? /* @__PURE__ */ import_react149.default.createElement(ContextNodeView, { ...nodeProps, containerRef: props.containerRef, source: pathState.path - }) : treeNode.node.type == "flow" ? /* @__PURE__ */ import_react147.default.createElement(FlowNodeView, { + }) : treeNode.node.type == "flow" ? /* @__PURE__ */ import_react149.default.createElement(FlowNodeView, { ...nodeProps, source: pathState.path, containerRef: props.containerRef - }) : treeNode.node.type == "content" ? /* @__PURE__ */ import_react147.default.createElement(ContentNodeView, { + }) : treeNode.node.type == "content" ? /* @__PURE__ */ import_react149.default.createElement(ContentNodeView, { editable: !props.treeNode.isRef }, props.treeNode.children.map( - (c3, i4) => c3.node.type == "slides" ? null : /* @__PURE__ */ import_react147.default.createElement(FrameEditorNodeView, { + (c3, i4) => c3.node.type == "slides" ? null : /* @__PURE__ */ import_react149.default.createElement(FrameEditorNodeView, { superstate: props.superstate, key: c3.id, treeNode: c3, @@ -126150,19 +126508,19 @@ var FrameEditorInner = (0, import_react147.memo)(function FrameEditorInner2(prop containerRef: props.containerRef }, props.children) ), props.children) : (treeNode.node.type == "column" || treeNode.node.type == "container") && treeNode.children.length == 0 ? null : props.treeNode.id == props.instance.exec.id || treeNode.node.type == "column" || treeNode.node.type == "container" ? props.treeNode.children.map( - (c3, i4) => c3.node.type == "slides" ? null : /* @__PURE__ */ import_react147.default.createElement(FrameEditorNodeView, { + (c3, i4) => c3.node.type == "slides" ? null : /* @__PURE__ */ import_react149.default.createElement(FrameEditorNodeView, { superstate: props.superstate, key: c3.id, treeNode: c3, instance: props.instance, containerRef: props.containerRef }, props.children) - ) : /* @__PURE__ */ import_react147.default.createElement(import_react147.default.Fragment, null, /* @__PURE__ */ import_react147.default.createElement(FrameSelectionProvider, { + ) : /* @__PURE__ */ import_react149.default.createElement(import_react149.default.Fragment, null, /* @__PURE__ */ import_react149.default.createElement(FrameSelectionProvider, { superstate: props.superstate, id: treeNode.id, editMode: props.editMode }, treeNode.children.map( - (c3, i4) => c3.node.type == "slides" ? null : /* @__PURE__ */ import_react147.default.createElement(FrameEditorNodeView, { + (c3, i4) => c3.node.type == "slides" ? null : /* @__PURE__ */ import_react149.default.createElement(FrameEditorNodeView, { superstate: props.superstate, key: c3.id, treeNode: c3, @@ -126179,28 +126537,28 @@ var FrameEditorNodeView = (props) => { isParentToSelection, select, selection: selection2 - } = (0, import_react147.useContext)(FrameSelectionContext); + } = (0, import_react149.useContext)(FrameSelectionContext); const { updateNode, addNode, deleteNode, nodes, selectedSlide - } = (0, import_react147.useContext)(FramesEditorRootContext); - const { setDragNode } = (0, import_react147.useContext)(WindowContext); - const { saveState, selectableNodeBounds, id: id3 } = (0, import_react147.useContext)(FrameInstanceContext); - const { dragActive } = (0, import_react147.useContext)(WindowContext); + } = (0, import_react149.useContext)(FramesEditorRootContext); + const { setDragNode } = (0, import_react149.useContext)(WindowContext); + const { saveState, selectableNodeBounds, id: id3 } = (0, import_react149.useContext)(FrameInstanceContext); + const { dragActive } = (0, import_react149.useContext)(WindowContext); const editMode = props.treeNode.isRef ? 0 /* Read */ : props.treeNode.id == props.instance.exec.id ? selectionMode : 3 /* Group */; const selected = selection2.some((f2) => f2 == props.treeNode.id); const isSelectable = selectable && !props.treeNode.isRef && !selected; const state = props.instance.state[props.treeNode.id]; - const deltas = (0, import_react147.useMemo)( + const deltas = (0, import_react149.useMemo)( () => selectedSlide ? nodes.find( (f2) => f2.ref == props.treeNode.id && selectedSlide == f2.parentId ) ?? null : null, [nodes, props.treeNode, selectedSlide] ); - const treeNode = (0, import_react147.useMemo)( + const treeNode = (0, import_react149.useMemo)( () => deltas ? { ...props.treeNode, node: { @@ -126221,11 +126579,11 @@ var FrameEditorNodeView = (props) => { } : props.treeNode, [deltas, props.treeNode] ); - const { frameSchema } = (0, import_react147.useContext)(FramesMDBContext); + const { frameSchema } = (0, import_react149.useContext)(FramesMDBContext); const dragId = id3 + frameSchema.id + props.treeNode.id; - const [hover, setHover] = (0, import_react147.useState)(false); - const [isMouseOverElement, setIsMouseOverElement] = import_react147.default.useState(false); - const [isMouseOverPortal, setIsMouseOverPortal] = import_react147.default.useState(false); + const [hover, setHover] = (0, import_react149.useState)(false); + const [isMouseOverElement, setIsMouseOverElement] = import_react149.default.useState(false); + const [isMouseOverPortal, setIsMouseOverPortal] = import_react149.default.useState(false); const draggable = props.treeNode.editorProps.dragMode == 1 /* DragHandle */ || (isSelectable && !isParentToSelection || selected) && props.treeNode.editorProps.dragMode != 0; const { attributes, @@ -126244,7 +126602,7 @@ var FrameEditorNodeView = (props) => { }, disabled: !draggable }); - const ref2 = (0, import_react147.useRef)(null); + const ref2 = (0, import_react149.useRef)(null); const onLongPress = () => { if (isSelectable && props.treeNode.id != props.instance.exec.id) { select(treeNode.node.id); @@ -126302,11 +126660,11 @@ var FrameEditorNodeView = (props) => { e5.stopPropagation(); } }; - (0, import_react147.useEffect)(() => { + (0, import_react149.useEffect)(() => { selection2.some((f2) => f2 != props.treeNode.id) && setHover(false); }, [selection2, props.treeNode]); - const [canEditLayout, setCanEditLayout] = (0, import_react147.useState)(false); - (0, import_react147.useEffect)(() => { + const [canEditLayout, setCanEditLayout] = (0, import_react149.useState)(false); + (0, import_react149.useEffect)(() => { if (selected && isTouchScreen(props.superstate.ui) && (props.treeNode.node.type == "group" || props.treeNode.node.type == "image" || selectionMode >= 3 /* Group */)) { setCanEditLayout(true); } else { @@ -126320,7 +126678,7 @@ var FrameEditorNodeView = (props) => { const computedStyle = ref2.current && getComputedStyle(ref2.current); const clientWidth = ref2.current && ref2.current.clientWidth; const clientHeight = ref2.current && ref2.current.clientHeight; - const [childNodeSizes, setChildNodeSizes] = (0, import_react147.useState)([]); + const [childNodeSizes, setChildNodeSizes] = (0, import_react149.useState)([]); const calculateRectInContainer = (rect, containerRect2) => { return { left: rect.x - containerRect2.x, @@ -126329,7 +126687,7 @@ var FrameEditorNodeView = (props) => { height: rect.height }; }; - (0, import_react147.useEffect)(() => { + (0, import_react149.useEffect)(() => { if (!ref2.current || !props.containerRef?.current) { return () => null; } @@ -126390,11 +126748,11 @@ var FrameEditorNodeView = (props) => { onDragStart: (e5) => { if (e5.active?.id == dragId) { setDragNode( - /* @__PURE__ */ import_react147.default.createElement("div", { + /* @__PURE__ */ import_react149.default.createElement("div", { style: { width: ref2.current.clientWidth } - }, /* @__PURE__ */ import_react147.default.createElement(FrameView, { + }, /* @__PURE__ */ import_react149.default.createElement(FrameView, { superstate: props.superstate, treeNode: props.treeNode, instance: props.instance, @@ -126404,7 +126762,7 @@ var FrameEditorNodeView = (props) => { } } }); - return /* @__PURE__ */ import_react147.default.createElement(import_react147.default.Fragment, null, (!hidden || !props.treeNode.isRef) && /* @__PURE__ */ import_react147.default.createElement("div", { + return /* @__PURE__ */ import_react149.default.createElement(import_react149.default.Fragment, null, (!hidden || !props.treeNode.isRef) && /* @__PURE__ */ import_react149.default.createElement("div", { ref: (el) => { ref2.current = el; selectionMode > 1 /* Page */ && draggable && setDraggableNodeRef(el); @@ -126430,13 +126788,13 @@ var FrameEditorNodeView = (props) => { ...{ onClick }, ...selectionMode > 1 /* Page */ ? { ...listeners, ...attributes } : {}, style: styles2 - }, /* @__PURE__ */ import_react147.default.createElement(FrameEditorInner, { + }, /* @__PURE__ */ import_react149.default.createElement(FrameEditorInner, { ...nodeProps, containerRef: props.containerRef, editMode, instance: props.instance }, props.children)), state && props.treeNode.node.type != "new" && props.containerRef?.current && selectionMode > 0 /* Read */ && ref2.current && (0, import_react_dom11.createPortal)( - /* @__PURE__ */ import_react147.default.createElement(import_react147.default.Fragment, null, /* @__PURE__ */ import_react147.default.createElement("div", { + /* @__PURE__ */ import_react149.default.createElement(import_react149.default.Fragment, null, /* @__PURE__ */ import_react149.default.createElement("div", { style: { position: "absolute", top: nodeRect.top - containerRect.top, @@ -126461,7 +126819,7 @@ var FrameEditorNodeView = (props) => { return; } } - }, props.treeNode.editorProps.resizeMode == 2 /* ResizeColumn */ && /* @__PURE__ */ import_react147.default.createElement(FrameResizer, { + }, props.treeNode.editorProps.resizeMode == 2 /* ResizeColumn */ && /* @__PURE__ */ import_react149.default.createElement(FrameResizer, { size: state?.styles, superstate: props.superstate, resizeMode: props.treeNode.editorProps.resizeMode, @@ -126470,7 +126828,7 @@ var FrameEditorNodeView = (props) => { width: clientWidth, height: clientHeight } - }), dragActive && (selectionMode == 1 /* Page */ || selectionMode == 3 /* Group */) && dropMode > 0 /* DropModeNone */ && /* @__PURE__ */ import_react147.default.createElement(FrameEditorDropZone, { + }), dragActive && (selectionMode == 1 /* Page */ || selectionMode == 3 /* Group */) && dropMode > 0 /* DropModeNone */ && /* @__PURE__ */ import_react149.default.createElement(FrameEditorDropZone, { parentId: treeNode.node.parentId, superstate: props.superstate, height: clientHeight, @@ -126479,7 +126837,7 @@ var FrameEditorNodeView = (props) => { id: dragId, mode: dropMode, insertMode: treeNode.node.type == "group" ? 1 : treeNode.node.type == "space" ? -1 : 0 - }), canEditLayout && /* @__PURE__ */ import_react147.default.createElement(import_react147.default.Fragment, null, /* @__PURE__ */ import_react147.default.createElement(FrameResizer, { + }), canEditLayout && /* @__PURE__ */ import_react149.default.createElement(import_react149.default.Fragment, null, /* @__PURE__ */ import_react149.default.createElement(FrameResizer, { superstate: props.superstate, resizeMode: 1 /* ResizeSelected */, size: state?.styles, @@ -126488,14 +126846,14 @@ var FrameEditorNodeView = (props) => { width: clientWidth, height: clientHeight } - }), /* @__PURE__ */ import_react147.default.createElement(FrameCorners, { + }), /* @__PURE__ */ import_react149.default.createElement(FrameCorners, { styles: state?.styles, saveStyles, clientSize: { width: clientWidth, height: clientHeight } - }), (treeNode.node.type == "group" || treeNode.node.type == "content") && (state.styles?.layout == "row" || state.styles?.layout == "column") && /* @__PURE__ */ import_react147.default.createElement(import_react147.default.Fragment, null, /* @__PURE__ */ import_react147.default.createElement(FrameGapHandle, { + }), (treeNode.node.type == "group" || treeNode.node.type == "content") && (state.styles?.layout == "row" || state.styles?.layout == "column") && /* @__PURE__ */ import_react149.default.createElement(import_react149.default.Fragment, null, /* @__PURE__ */ import_react149.default.createElement(FrameGapHandle, { childSizes: childNodeSizes, clientSize: { width: clientWidth, @@ -126516,14 +126874,14 @@ var FrameEditorNodeView = (props) => { styles: state?.styles, saveStyles, direction: state?.styles.layout == "column" ? "column" : "row" - }), /* @__PURE__ */ import_react147.default.createElement(FramePadding, { + }), /* @__PURE__ */ import_react149.default.createElement(FramePadding, { clientSize: { width: clientWidth, height: clientHeight }, styles: state?.styles, saveStyles - }))), treeNode.editorProps.dragMode == 1 /* DragHandle */ && (!isTouchScreen(props.superstate.ui) || selected) ? /* @__PURE__ */ import_react147.default.createElement("div", { + }))), treeNode.editorProps.dragMode == 1 /* DragHandle */ && (!isTouchScreen(props.superstate.ui) || selected) ? /* @__PURE__ */ import_react149.default.createElement("div", { onMouseEnter: () => { setIsMouseOverPortal(true); setHover(true); @@ -126538,7 +126896,7 @@ var FrameEditorNodeView = (props) => { style: { zIndex: hover ? "calc(var(--layer-popover) + 1)" : "var(--layer-popover)" } - }, /* @__PURE__ */ import_react147.default.createElement(FrameHoverMenu, { + }, /* @__PURE__ */ import_react149.default.createElement(FrameHoverMenu, { superstate: props.superstate, node: treeNode.node, mode: selectionMode == 1 /* Page */ ? 0 : 1, @@ -126547,10 +126905,10 @@ var FrameEditorNodeView = (props) => { dragRef: setDraggableNodeRef, attributes, listeners - })) : /* @__PURE__ */ import_react147.default.createElement(import_react147.default.Fragment, null)), selection2 && !dragActive && selected && selection2.length == 1 ? /* @__PURE__ */ import_react147.default.createElement(FrameNodeEditorContainer, { + })) : /* @__PURE__ */ import_react149.default.createElement(import_react149.default.Fragment, null)), selection2 && !dragActive && selected && selection2.length == 1 ? /* @__PURE__ */ import_react149.default.createElement(FrameNodeEditorContainer, { nodeRect, containerRect - }, /* @__PURE__ */ import_react147.default.createElement(FrameNodeEditor, { + }, /* @__PURE__ */ import_react149.default.createElement(FrameNodeEditor, { editLayout: (state2) => setCanEditLayout(state2), superstate: props.superstate, node: treeNode.node, @@ -126560,10 +126918,10 @@ var FrameEditorNodeView = (props) => { state, deleteFrame: () => deleteNode(treeNode.node), fields: propertiesForNode(treeNode.node) - })) : selection2.length > 1 && selection2[0] == treeNode.id ? /* @__PURE__ */ import_react147.default.createElement(FrameNodeEditorContainer, { + })) : selection2.length > 1 && selection2[0] == treeNode.id ? /* @__PURE__ */ import_react149.default.createElement(FrameNodeEditorContainer, { nodeRect, containerRect - }, /* @__PURE__ */ import_react147.default.createElement(FrameMultiNodeEditor, { + }, /* @__PURE__ */ import_react149.default.createElement(FrameMultiNodeEditor, { superstate: props.superstate })) : null), props.containerRef.current @@ -126572,13 +126930,13 @@ var FrameEditorNodeView = (props) => { // src/core/react/components/SpaceView/Frames/ViewNodes/FrameEditorInstance.tsx var FrameEditorInstance = (props) => { - const { spaceInfo } = (0, import_react148.useContext)(SpaceContext); - const { undoLastAction, redoAction, frameSchema } = (0, import_react148.useContext)(FramesMDBContext); - const { nodes, addNode, saveNodes, setLastCreatedId } = (0, import_react148.useContext)( + const { spaceInfo } = (0, import_react150.useContext)(SpaceContext); + const { undoLastAction, redoAction, frameSchema } = (0, import_react150.useContext)(FramesMDBContext); + const { nodes, addNode, saveNodes, setLastCreatedId } = (0, import_react150.useContext)( FramesEditorRootContext ); - const { hoverNode, setHoverNode, instance, id: id3 } = (0, import_react148.useContext)(FrameInstanceContext); - const { selectionMode, selection: selection2, select } = (0, import_react148.useContext)( + const { hoverNode, setHoverNode, instance, id: id3 } = (0, import_react150.useContext)(FrameInstanceContext); + const { selectionMode, selection: selection2, select } = (0, import_react150.useContext)( FrameSelectionContext ); const resetState = () => { @@ -126728,7 +127086,7 @@ var FrameEditorInstance = (props) => { } return node; }; - const handleKeyDown = (0, import_react148.useCallback)( + const handleKeyDown = (0, import_react150.useCallback)( (e5) => { if (e5.key == "ArrowUp") { if (selection2.length > 0) { @@ -126779,28 +127137,28 @@ var FrameEditorInstance = (props) => { }, [selection2, nodes, undoLastAction, redoAction, saveNodes] ); - (0, import_react148.useEffect)(() => { + (0, import_react150.useEffect)(() => { props.superstate.ui.inputManager.on("keydown", handleKeyDown); return () => { props.superstate.ui.inputManager.off("keydown", handleKeyDown); }; }, [handleKeyDown]); - return /* @__PURE__ */ import_react148.default.createElement(import_react148.default.Fragment, null, instance.exec && /* @__PURE__ */ import_react148.default.createElement("div", { + return /* @__PURE__ */ import_react150.default.createElement(import_react150.default.Fragment, null, instance.exec && /* @__PURE__ */ import_react150.default.createElement("div", { className: "mk-f-root", style: { position: "relative" } - }, selectionMode >= 3 /* Group */ && /* @__PURE__ */ import_react148.default.createElement("div", { + }, selectionMode >= 3 /* Group */ && /* @__PURE__ */ import_react150.default.createElement("div", { className: "mk-f-root-label", onClick: (e5) => { select(instance.exec.id); e5.stopPropagation(); } - }, instance.exec.node.name), /* @__PURE__ */ import_react148.default.createElement(FrameEditorNodeView, { + }, instance.exec.node.name), /* @__PURE__ */ import_react150.default.createElement(FrameEditorNodeView, { key: spaceInfo.path, superstate: props.superstate, treeNode: instance.exec, instance, containerRef: props.containerRef - }, props.children), instance.exec.children.length == 0 && /* @__PURE__ */ import_react148.default.createElement(NewNodeView, { + }, props.children), instance.exec.children.length == 0 && /* @__PURE__ */ import_react150.default.createElement(NewNodeView, { superstate: props.superstate, treeNode: null, state: null @@ -126809,15 +127167,15 @@ var FrameEditorInstance = (props) => { // src/core/react/components/SpaceView/Contexts/ContextBuilder/ContextListInstance.tsx var ContextListInstance = (props) => { - const [contexts, setContexts] = (0, import_react149.useState)(props.contexts); - (0, import_react149.useEffect)( + const [contexts, setContexts] = (0, import_react151.useState)(props.contexts); + (0, import_react151.useEffect)( () => setContexts((p) => import_lodash18.default.isEqual(props.contexts, p) ? p : props.contexts), [props.contexts] ); - const { spaceInfo } = (0, import_react149.useContext)(SpaceContext); - const { dbSchema } = (0, import_react149.useContext)(ContextEditorContext); - const { setDragNode } = (0, import_react149.useContext)(WindowContext); - const ref2 = import_react149.default.useRef(null); + const { spaceInfo } = (0, import_react151.useContext)(SpaceContext); + const { dbSchema } = (0, import_react151.useContext)(ContextEditorContext); + const { setDragNode } = (0, import_react151.useContext)(WindowContext); + const ref2 = import_react151.default.useRef(null); const { attributes, listeners, @@ -126845,7 +127203,7 @@ var ContextListInstance = (props) => { onDragStart: (e5) => { if (e5.active.data.current.id == props.id) { setDragNode( - /* @__PURE__ */ import_react149.default.createElement("div", { + /* @__PURE__ */ import_react151.default.createElement("div", { dangerouslySetInnerHTML: { __html: ref2.current.innerHTML } }) ); @@ -126858,31 +127216,31 @@ var ContextListInstance = (props) => { dropListItem(dragReorder, over2, props, active2, spaceInfo); } }); - return props.editMode >= 1 /* Page */ && props.uri.authority != "$kit" ? /* @__PURE__ */ import_react149.default.createElement(FrameSelectionProvider, { + return props.editMode >= 1 /* Page */ && props.uri.authority != "$kit" ? /* @__PURE__ */ import_react151.default.createElement(FrameSelectionProvider, { superstate: props.superstate, id: props.id, editMode: props.editMode, selected: props.editMode == 3 /* Group */ - }, /* @__PURE__ */ import_react149.default.createElement(FrameInstanceProvider, { + }, /* @__PURE__ */ import_react151.default.createElement(FrameInstanceProvider, { id: props.id, superstate: props.superstate, props: props.props, propSetters: props.propSetters, contexts, editable: true - }, /* @__PURE__ */ import_react149.default.createElement(FrameEditorInstance, { + }, /* @__PURE__ */ import_react151.default.createElement(FrameEditorInstance, { superstate: props.superstate, containerRef: props.containerRef - }, props.children))) : /* @__PURE__ */ import_react149.default.createElement(import_react149.default.Fragment, null, over?.id == props.id && active.data.current.type == props.type && !(active.data.current.space == spaceInfo?.path && active.data.current.schema == dbSchema?.id && active.data.current.props?._groupValue == props.props?._groupValue) && /* @__PURE__ */ import_react149.default.createElement(FrameInstanceProvider, { + }, props.children))) : /* @__PURE__ */ import_react151.default.createElement(import_react151.default.Fragment, null, over?.id == props.id && active.data.current.type == props.type && !(active.data.current.space == spaceInfo?.path && active.data.current.schema == dbSchema?.id && active.data.current.props?._groupValue == props.props?._groupValue) && /* @__PURE__ */ import_react151.default.createElement(FrameInstanceProvider, { id: props.id, superstate: props.superstate, props: props.props, propSetters: props.propSetters, contexts, editable: false - }, /* @__PURE__ */ import_react149.default.createElement(FrameInstanceView, { + }, /* @__PURE__ */ import_react151.default.createElement(FrameInstanceView, { superstate: props.superstate - })), /* @__PURE__ */ import_react149.default.createElement("div", { + })), /* @__PURE__ */ import_react151.default.createElement("div", { ref: (el) => { setDraggableNodeRef(el); ref2.current = el; @@ -126893,60 +127251,69 @@ var ContextListInstance = (props) => { transform: CSS.Transform.toString(transform), transition } - }, /* @__PURE__ */ import_react149.default.createElement(FrameInstanceProvider, { + }, /* @__PURE__ */ import_react151.default.createElement(FrameInstanceProvider, { id: props.id, superstate: props.superstate, props: props.props, propSetters: props.propSetters, contexts, editable: false - }, /* @__PURE__ */ import_react149.default.createElement(FrameInstanceView, { + }, /* @__PURE__ */ import_react151.default.createElement(FrameInstanceView, { superstate: props.superstate }, props.children)))); }; var dropListItem = async (dragReorder, over, props, active, spaceInfo) => { if (dragReorder && over.id == props.id) { - const activePath = active.data.current.contexts?.$context?.["_keyValue"]; - const context = over.data.current.contexts?.$context; - const groupValueMismatch = props.props?._groupValue != active.data.current.props?._groupValue; - if (activePath && context) { - if (groupValueMismatch) { - updateContextValue( - props.superstate.spaceManager, - spaceInfo, - activePath, - props.props?._groupField, - props.props?._groupValue, - null, - context._index - ); - } else { - updatePathRankInSpace( - props.superstate, - activePath, - context._index, - spaceInfo.path - ); + if (active.data.current.schema == defaultContextSchemaID) { + const activePath = active.data.current.contexts?.$context?.["_keyValue"]; + const context = over.data.current.contexts?.$context; + const groupValueMismatch = props.props?._groupValue != active.data.current.props?._groupValue; + if (activePath && context) { + if (groupValueMismatch) { + { + saveProperties(props.superstate, activePath, { + [props.props?._groupField]: props.props?._groupValue + }); + } + } else { + updatePathRankInSpace( + props.superstate, + activePath, + context._index, + spaceInfo.path + ); + } } + } else { + const context = over.data.current.contexts?.$context; + updateTableValue( + props.superstate.spaceManager, + spaceInfo, + active.data.current.schema, + active.data.current.contexts?.$context?.["_index"], + props.props?._groupField, + props.props?._groupValue, + context?._index + ); } } }; // src/core/react/components/SpaceView/Contexts/ContextBuilder/ContextListView.tsx -var import_react151 = __toESM(require_react()); +var import_react153 = __toESM(require_react()); // src/core/react/components/SpaceView/Contexts/ContextBuilder/FrameContainerView.tsx -var import_react150 = __toESM(require_react()); +var import_react152 = __toESM(require_react()); var FrameContainerView = (props) => { - const { selected: _selected } = (0, import_react150.useContext)(FrameSelectionContext); - return props.editMode >= 1 /* Page */ && props.uri.authority != "$kit" ? /* @__PURE__ */ import_react150.default.createElement(FramesMDBProvider, { + const { selected: _selected } = (0, import_react152.useContext)(FrameSelectionContext); + return props.editMode >= 1 /* Page */ && props.uri.authority != "$kit" ? /* @__PURE__ */ import_react152.default.createElement(FramesMDBProvider, { superstate: props.superstate, schema: props.uri.ref - }, /* @__PURE__ */ import_react150.default.createElement(FrameEditorProvider, { + }, /* @__PURE__ */ import_react152.default.createElement(FrameEditorProvider, { superstate: props.superstate, cols: props.cols, editMode: props.editMode - }, props.children)) : /* @__PURE__ */ import_react150.default.createElement(FrameRootProvider, { + }, props.children)) : /* @__PURE__ */ import_react152.default.createElement(FrameRootProvider, { superstate: props.superstate, path: props.uri, cols: props.cols @@ -126956,7 +127323,7 @@ var FrameContainerView = (props) => { // src/core/react/components/SpaceView/Contexts/ContextBuilder/ContextListView.tsx var ContextListView = (props) => { const { editSection, selectedIndex, setSelectedIndex, groupURI, itemURI } = props; - const { spaceInfo } = (0, import_react151.useContext)(SpaceContext); + const { spaceInfo } = (0, import_react153.useContext)(SpaceContext); const { predicate, filteredData: data2, @@ -126965,10 +127332,10 @@ var ContextListView = (props) => { contextTable, cols, dbSchema - } = (0, import_react151.useContext)(ContextEditorContext); - const { instance } = (0, import_react151.useContext)(FrameInstanceContext); + } = (0, import_react153.useContext)(ContextEditorContext); + const { instance } = (0, import_react153.useContext)(FrameInstanceContext); const groupBy2 = predicate?.groupBy?.length > 0 ? cols.find((f2) => f2.name + f2.table == predicate.groupBy[0]) : null; - const groupByOptions = (0, import_react151.useMemo)(() => { + const groupByOptions = (0, import_react153.useMemo)(() => { const groupByOptions2 = instance?.state[instance?.root?.id].props?.groupOptions; if (groupByOptions2) return ensureArray(groupByOptions2); @@ -126984,11 +127351,11 @@ var ContextListView = (props) => { ]); return options; }, [groupBy2, data2, instance]); - const groupByFilter = (0, import_react151.useMemo)(() => { + const groupByFilter = (0, import_react153.useMemo)(() => { const filter4 = instance?.state[instance?.root?.id].props?.groupFilter; return filterFnTypes[filter4] ?? filterFnTypes.is; }, [instance]); - const items = (0, import_react151.useMemo)(() => { + const items = (0, import_react153.useMemo)(() => { return groupByOptions.reduce((p, c3) => { if (!groupBy2) { return c3 == "" ? { @@ -127011,10 +127378,10 @@ var ContextListView = (props) => { }; }, {}); }, [data2, groupByOptions, groupByFilter, groupBy2]); - const primaryKey = (0, import_react151.useMemo)(() => { + const primaryKey = (0, import_react153.useMemo)(() => { return cols.find((f2) => f2.primary == "true")?.name; }, [cols]); - const visibleCols = (0, import_react151.useMemo)(() => { + const visibleCols = (0, import_react153.useMemo)(() => { return sortedColumns.filter((f2) => !predicate?.colsHidden.includes(f2.name)); }, [predicate, sortedColumns]); const context = { @@ -127023,7 +127390,7 @@ var ContextListView = (props) => { _key: primaryKey, _properties: visibleCols }; - const contextMap = (0, import_react151.useMemo)(() => { + const contextMap = (0, import_react153.useMemo)(() => { return dbSchema?.primary == "true" ? data2.reduce((p, c3) => { return { ...p, @@ -127032,6 +127399,7 @@ var ContextListView = (props) => { _index: c3["_index"], _keyValue: c3[primaryKey], _schema: dbSchema.id, + _name: props.superstate.pathsIndex.get(c3[primaryKey])?.name, ...context }, $properties: cols, @@ -127058,9 +127426,12 @@ var ContextListView = (props) => { return { ...p, [c3["_index"]]: { - $context: {}, - $listItem: { - _index: c3["_index"] + $context: { + _index: c3["_index"], + _keyValue: c3[primaryKey], + _schema: dbSchema.id, + _name: c3[primaryKey], + ...context }, $properties: cols, [spaceInfo.path]: cols.reduce((a4, b2) => { @@ -127073,17 +127444,17 @@ var ContextListView = (props) => { }; }, {}); }, [data2, cols, contextTable]); - return /* @__PURE__ */ import_react151.default.createElement(FrameContainerView, { + return /* @__PURE__ */ import_react153.default.createElement(FrameContainerView, { superstate: props.superstate, uri: groupURI, editMode: editSection == "listGroup" ? editMode : 0 /* Read */, cols: [] - }, /* @__PURE__ */ import_react151.default.createElement(SortableContext, { + }, /* @__PURE__ */ import_react153.default.createElement(SortableContext, { items: Object.keys(items).map( (f2, i4) => spaceInfo.path + "listGroup" + i4 ), strategy: rectSortingStrategy - }, Object.keys(items).map((c3, i4) => /* @__PURE__ */ import_react151.default.createElement(ContextListInstance, { + }, Object.keys(items).map((c3, i4) => /* @__PURE__ */ import_react153.default.createElement(ContextListInstance, { key: "listGroup" + i4, id: spaceInfo.path + "listGroup" + i4, type: "listGroup", @@ -127101,18 +127472,18 @@ var ContextListView = (props) => { cols: [], containerRef: props.containerRef, contexts: { $context: context } - }, /* @__PURE__ */ import_react151.default.createElement(FrameContainerView, { + }, /* @__PURE__ */ import_react153.default.createElement(FrameContainerView, { uri: itemURI, superstate: props.superstate, cols: [], editMode: editSection == "listItem" ? editMode : 0 /* Read */ - }, /* @__PURE__ */ import_react151.default.createElement(SortableContext, { + }, /* @__PURE__ */ import_react153.default.createElement(SortableContext, { items: items[c3].flatMap( (f2, k2) => spaceInfo.path + "listGroup" + i4 + "_listItem" + k2 ), strategy: rectSortingStrategy }, items[c3].map((f2, j) => { - return /* @__PURE__ */ import_react151.default.createElement(ContextListInstance, { + return /* @__PURE__ */ import_react153.default.createElement(ContextListInstance, { key: "listGroup" + i4 + "_listItem" + j, id: spaceInfo.path + "listGroup" + i4 + "_listItem" + j, type: "listItem", @@ -127137,11 +127508,11 @@ var ContextListView = (props) => { // src/core/react/components/SpaceView/Contexts/ContextListContainer.tsx var ContextListContainer = (props) => { - const { predicate, editMode, setEditMode, dbSchema } = (0, import_react152.useContext)(ContextEditorContext); - const { frameSchema } = (0, import_react152.useContext)(FramesMDBContext); - const [editSection, setEditSection] = (0, import_react152.useState)(null); - const [selectedIndex, setSelectedIndex] = (0, import_react152.useState)(null); - const [uris, setURIs] = (0, import_react152.useState)( + const { predicate, editMode, setEditMode, dbSchema } = (0, import_react154.useContext)(ContextEditorContext); + const { frameSchema } = (0, import_react154.useContext)(FramesMDBContext); + const [editSection, setEditSection] = (0, import_react154.useState)(null); + const [selectedIndex, setSelectedIndex] = (0, import_react154.useState)(null); + const [uris, setURIs] = (0, import_react154.useState)( predicate ? { listView: props.superstate.spaceManager.uriByString( initiateString(predicate.listView, "spaces://$kit/#*listView") @@ -127154,7 +127525,7 @@ var ContextListContainer = (props) => { ) } : null ); - (0, import_react152.useEffect)(() => { + (0, import_react154.useEffect)(() => { if (!predicate) return; const newURIs = { @@ -127170,30 +127541,30 @@ var ContextListContainer = (props) => { }; setURIs((p) => !import_lodash19.default.isEqual(newURIs, p) ? newURIs : p); }, [predicate]); - return /* @__PURE__ */ import_react152.default.createElement("div", { + return /* @__PURE__ */ import_react154.default.createElement("div", { className: "mk-context-container" - }, !props.minMode && /* @__PURE__ */ import_react152.default.createElement(FilterBar, { + }, !props.minMode && /* @__PURE__ */ import_react154.default.createElement(FilterBar, { superstate: props.superstate, setView: props.setView - }), uris ? predicate.view == "table" || predicate.view == "db" || dbSchema?.primary != "true" && !frameSchema ? /* @__PURE__ */ import_react152.default.createElement(TableView, { + }), uris ? predicate.view == "table" || predicate.view == "db" || dbSchema?.primary != "true" && !frameSchema ? /* @__PURE__ */ import_react154.default.createElement(TableView, { superstate: props.superstate - }) : /* @__PURE__ */ import_react152.default.createElement("div", { + }) : /* @__PURE__ */ import_react154.default.createElement("div", { className: "mk-editor-context" - }, /* @__PURE__ */ import_react152.default.createElement(FrameSelectionProvider, { + }, /* @__PURE__ */ import_react154.default.createElement(FrameSelectionProvider, { superstate: props.superstate, id: "list", editMode: editSection == "listView" ? editMode : 0 /* Read */ - }, editMode > 0 && /* @__PURE__ */ import_react152.default.createElement(ContextListEditSelector, { + }, editMode > 0 && /* @__PURE__ */ import_react154.default.createElement(ContextListEditSelector, { editSection, superstate: props.superstate, setEditSection, setEditMode - }), /* @__PURE__ */ import_react152.default.createElement(FrameContainerView, { + }), /* @__PURE__ */ import_react154.default.createElement(FrameContainerView, { superstate: props.superstate, uri: uris.listView, cols: [], editMode: editSection == "listView" ? editMode : 0 /* Read */ - }, /* @__PURE__ */ import_react152.default.createElement(ContextListInstance, { + }, /* @__PURE__ */ import_react154.default.createElement(ContextListInstance, { superstate: props.superstate, id: "listView", type: "listView", @@ -127207,7 +127578,7 @@ var ContextListContainer = (props) => { editMode: editSection == "listView" ? editMode : 0 /* Read */, cols: [], contexts: null - }, /* @__PURE__ */ import_react152.default.createElement(ContextListView, { + }, /* @__PURE__ */ import_react154.default.createElement(ContextListView, { superstate: props.superstate, containerRef: props.containerRef, editSection, @@ -127215,31 +127586,31 @@ var ContextListContainer = (props) => { setSelectedIndex, groupURI: uris.listGroup, itemURI: uris.listItem - }))))) : /* @__PURE__ */ import_react152.default.createElement(import_react152.default.Fragment, null)); + }))))) : /* @__PURE__ */ import_react154.default.createElement(import_react154.default.Fragment, null)); }; // src/core/react/components/MDBView/MDBViewer.tsx var MDBViewer = (props) => { - return /* @__PURE__ */ import_react153.default.createElement(PathProvider, { + return /* @__PURE__ */ import_react155.default.createElement(PathProvider, { superstate: props.superstate, path: props.space.path, readMode: false - }, /* @__PURE__ */ import_react153.default.createElement(SpaceProvider, { + }, /* @__PURE__ */ import_react155.default.createElement(SpaceProvider, { superstate: props.superstate - }, /* @__PURE__ */ import_react153.default.createElement(FramesMDBProvider, { + }, /* @__PURE__ */ import_react155.default.createElement(FramesMDBProvider, { superstate: props.superstate, schema: props.schema - }, /* @__PURE__ */ import_react153.default.createElement(ContextEditorProvider, { + }, /* @__PURE__ */ import_react155.default.createElement(ContextEditorProvider, { superstate: props.superstate - }, /* @__PURE__ */ import_react153.default.createElement(ContextListContainer, { + }, /* @__PURE__ */ import_react155.default.createElement(ContextListContainer, { superstate: props.superstate }))))); }; // src/core/react/components/MarkdownEditor/Backlinks.tsx -var import_react154 = __toESM(require_react()); +var import_react156 = __toESM(require_react()); var BacklinkItem = (props) => { - const [block, setBlock] = (0, import_react154.useState)([null, null]); + const [block, setBlock] = (0, import_react156.useState)([null, null]); const refreshBlock = (path2) => { const fCache = props.superstate.pathsIndex.get(path2); const link = [ @@ -127258,40 +127629,40 @@ var BacklinkItem = (props) => { setBlock([null, null]); } }; - (0, import_react154.useEffect)(() => { + (0, import_react156.useEffect)(() => { refreshBlock(props.path); }, []); - (0, import_react154.useEffect)(() => { + (0, import_react156.useEffect)(() => { refreshBlock(props.path); }, [props.path]); - const [collapsed, setCollapsed] = (0, import_react154.useState)(false); - return /* @__PURE__ */ import_react154.default.createElement(import_react154.default.Fragment, null, /* @__PURE__ */ import_react154.default.createElement("div", { + const [collapsed, setCollapsed] = (0, import_react156.useState)(false); + return /* @__PURE__ */ import_react156.default.createElement(import_react156.default.Fragment, null, /* @__PURE__ */ import_react156.default.createElement("div", { className: "mk-path-context-title" - }, /* @__PURE__ */ import_react154.default.createElement(CollapseToggle, { + }, /* @__PURE__ */ import_react156.default.createElement(CollapseToggle, { superstate: props.superstate, collapsed, onToggle: (c3) => setCollapsed(c3) - }), /* @__PURE__ */ import_react154.default.createElement("div", { + }), /* @__PURE__ */ import_react156.default.createElement("div", { onClick: (e5) => { props.superstate.ui.openPath(props.path, false); e5.stopPropagation(); } - }, pathNameToString(props.path))), !collapsed ? /* @__PURE__ */ import_react154.default.createElement("div", { + }, pathNameToString(props.path))), !collapsed ? /* @__PURE__ */ import_react156.default.createElement("div", { className: "mk-path-context-backlink" - }, /* @__PURE__ */ import_react154.default.createElement(NoteView, { + }, /* @__PURE__ */ import_react156.default.createElement(NoteView, { load: true, superstate: props.superstate, path: props.path, properties: { from: block[0], to: block[1] }, classname: "mk-path-context-flow" - })) : /* @__PURE__ */ import_react154.default.createElement(import_react154.default.Fragment, null)); + })) : /* @__PURE__ */ import_react156.default.createElement(import_react156.default.Fragment, null)); }; var Backlinks = (props) => { - const [collapsed, setCollapsed] = (0, import_react154.useState)( + const [collapsed, setCollapsed] = (0, import_react156.useState)( !props.superstate.settings.inlineBacklinksExpanded ); - const [backlinks, setBacklinks] = (0, import_react154.useState)([]); - (0, import_react154.useEffect)(() => { + const [backlinks, setBacklinks] = (0, import_react156.useState)([]); + (0, import_react156.useEffect)(() => { if (!props.path) return; Promise.all( @@ -127300,83 +127671,83 @@ var Backlinks = (props) => { ) ).then((bls) => setBacklinks(bls.filter((f2) => f2))); }, [props.path]); - (0, import_react154.useEffect)(() => { + (0, import_react156.useEffect)(() => { props.superstate.settings.inlineBacklinksExpanded = !collapsed; props.superstate.saveSettings(); }, [collapsed]); const toggleBacklinks = () => { setCollapsed(!collapsed); }; - (0, import_react154.useEffect)(() => { + (0, import_react156.useEffect)(() => { window.addEventListener(eventTypes.toggleBacklinks, toggleBacklinks); return () => { window.removeEventListener(eventTypes.toggleBacklinks, toggleBacklinks); }; }, [collapsed]); - return backlinks.length > 0 && props.path ? /* @__PURE__ */ import_react154.default.createElement("div", { + return backlinks.length > 0 && props.path ? /* @__PURE__ */ import_react156.default.createElement("div", { className: "mk-path-context-component mk-note-footer" - }, /* @__PURE__ */ import_react154.default.createElement("div", { + }, /* @__PURE__ */ import_react156.default.createElement("div", { className: "mk-path-context-section" - }, /* @__PURE__ */ import_react154.default.createElement("div", { + }, /* @__PURE__ */ import_react156.default.createElement("div", { onClick: (e5) => { setCollapsed(!collapsed); e5.stopPropagation(); }, className: "mk-path-context-title" - }, /* @__PURE__ */ import_react154.default.createElement("div", { + }, /* @__PURE__ */ import_react156.default.createElement("div", { className: `mk-icon-xsmall`, dangerouslySetInnerHTML: { __html: props.superstate.ui.getSticker("ui//backlink") } - }), i18n_default.labels.backlinks, /* @__PURE__ */ import_react154.default.createElement(CollapseToggleSmall, { + }), i18n_default.labels.backlinks, /* @__PURE__ */ import_react156.default.createElement(CollapseToggleSmall, { superstate: props.superstate, collapsed, onToggle: () => null - })), /* @__PURE__ */ import_react154.default.createElement("div", null, !collapsed && backlinks.map((f2, i4) => /* @__PURE__ */ import_react154.default.createElement(BacklinkItem, { + })), /* @__PURE__ */ import_react156.default.createElement("div", null, !collapsed && backlinks.map((f2, i4) => /* @__PURE__ */ import_react156.default.createElement(BacklinkItem, { path: f2, key: i4, superstate: props.superstate, source: props.path - }))))) : /* @__PURE__ */ import_react154.default.createElement(import_react154.default.Fragment, null); + }))))) : /* @__PURE__ */ import_react156.default.createElement(import_react156.default.Fragment, null); }; // src/core/react/components/SpaceView/Contexts/SpaceEditor/NoteSpacesBar.tsx -var import_react156 = __toESM(require_react()); +var import_react158 = __toESM(require_react()); // src/core/react/components/SpaceView/Contexts/SpaceEditor/SpaceProperties.tsx -var import_react155 = __toESM(require_react()); +var import_react157 = __toESM(require_react()); var SpaceHeaderView = (props) => { - const { pathState } = (0, import_react155.useContext)(PathContext); - const { spaceState } = (0, import_react155.useContext)(SpaceContext); - const [tab, setTab] = (0, import_react155.useState)(0); + const { pathState } = (0, import_react157.useContext)(PathContext); + const { spaceState } = (0, import_react157.useContext)(SpaceContext); + const [tab, setTab] = (0, import_react157.useState)(0); const tabs = [ { label: "Items", icon: "ui//file-stack", tab: 0 }, { label: "Lists", icon: "ui//layout-list", tab: 2 }, { label: "Actions", icon: "ui//mouse-pointer-click", tab: 3 } ]; - return /* @__PURE__ */ import_react155.default.createElement(import_react155.default.Fragment, null, /* @__PURE__ */ import_react155.default.createElement("div", { + return /* @__PURE__ */ import_react157.default.createElement(import_react157.default.Fragment, null, /* @__PURE__ */ import_react157.default.createElement("div", { className: "mk-header-space" - }, /* @__PURE__ */ import_react155.default.createElement("div", { + }, /* @__PURE__ */ import_react157.default.createElement("div", { className: "mk-tabs-space" - }, tabs.map((f2, i4) => /* @__PURE__ */ import_react155.default.createElement("div", { + }, tabs.map((f2, i4) => /* @__PURE__ */ import_react157.default.createElement("div", { key: i4, onClick: () => { openSpaceEditorModal(props.superstate, spaceState, f2.tab); }, className: `mk-path-info` - }, /* @__PURE__ */ import_react155.default.createElement("div", { + }, /* @__PURE__ */ import_react157.default.createElement("div", { "aria-label": f2.label, className: "mk-icon-small", dangerouslySetInnerHTML: { __html: props.superstate.ui.getSticker(f2.icon) } - }), f2.label))), /* @__PURE__ */ import_react155.default.createElement("div", { + }), f2.label))), /* @__PURE__ */ import_react157.default.createElement("div", { className: "mk-props-contexts" - }, /* @__PURE__ */ import_react155.default.createElement(PathContextList, { + }, /* @__PURE__ */ import_react157.default.createElement(PathContextList, { superstate: props.superstate, color: "var(--tag-background)", path: pathState.path - }), /* @__PURE__ */ import_react155.default.createElement(PropertiesView, { + }), /* @__PURE__ */ import_react157.default.createElement(PropertiesView, { superstate: props.superstate, spaces: props.spaces.map((f2) => f2.path), force: true, @@ -127390,7 +127761,7 @@ var SpaceHeaderView = (props) => { // src/core/react/components/SpaceView/Contexts/SpaceEditor/NoteSpacesBar.tsx var NoteSpacesBar = (props) => { - const { addToSpace, removeFromSpace, pathState } = (0, import_react156.useContext)(PathContext); + const { addToSpace, removeFromSpace, pathState } = (0, import_react158.useContext)(PathContext); const showContextMenu = (e5, path2) => { const space2 = props.superstate.spacesIndex.get(path2); if (!space2) @@ -127430,11 +127801,11 @@ var NoteSpacesBar = (props) => { (f2, k2) => path2.startsWith(f2.path) ? -1 : path2.startsWith(k2.path) ? 1 : 0 ).filter((f2) => f2); }; - const spacePathStates = (0, import_react156.useMemo)( + const spacePathStates = (0, import_react158.useMemo)( () => spacesFromPath(pathState.path), [pathState] ); - const spaces2 = (0, import_react156.useMemo)( + const spaces2 = (0, import_react158.useMemo)( () => [...props.superstate.spacesMap.get(pathState?.path) ?? []].map((f2) => props.superstate.spacesIndex.get(f2)?.space).filter((f2) => f2), [pathState] ); @@ -127458,8 +127829,9 @@ var NoteSpacesBar = (props) => { ); }; const showAddMenu = (e5) => { + const offset2 = e5.target.getBoundingClientRect(); showSpacesMenu( - e5, + offset2, props.superstate, (link, isNew) => { if (isNew) { @@ -127476,13 +127848,13 @@ var NoteSpacesBar = (props) => { true ); }; - return /* @__PURE__ */ import_react156.default.createElement(import_react156.default.Fragment, null, /* @__PURE__ */ import_react156.default.createElement("div", { + return /* @__PURE__ */ import_react158.default.createElement(import_react158.default.Fragment, null, /* @__PURE__ */ import_react158.default.createElement("div", { className: "mk-props-contexts" - }, /* @__PURE__ */ import_react156.default.createElement("div", { + }, /* @__PURE__ */ import_react158.default.createElement("div", { className: "mk-path-context-row" - }, /* @__PURE__ */ import_react156.default.createElement("div", { + }, /* @__PURE__ */ import_react158.default.createElement("div", { className: "mk-props-contexts-space-list" - }, spacePathStates.map((f2, i4) => /* @__PURE__ */ import_react156.default.createElement("div", { + }, spacePathStates.map((f2, i4) => /* @__PURE__ */ import_react158.default.createElement("div", { key: i4, className: "mk-props-contexts-space-name", onContextMenu: (e5) => showContextMenu(e5, f2.path), @@ -127491,31 +127863,31 @@ var NoteSpacesBar = (props) => { "--tag-background": f2.label?.color, "--tag-color": "var(--color-white)" } : {} - }, /* @__PURE__ */ import_react156.default.createElement("div", { + }, /* @__PURE__ */ import_react158.default.createElement("div", { className: `mk-icon-xsmall`, dangerouslySetInnerHTML: { __html: props.superstate.ui.getSticker(f2.label?.sticker) } - }), f2.name)), /* @__PURE__ */ import_react156.default.createElement("div", { + }), f2.name)), /* @__PURE__ */ import_react158.default.createElement("div", { className: "mk-props-contexts-space-name", onClick: (e5) => showAddMenu(e5), style: { opacity: 0.5 } - }, /* @__PURE__ */ import_react156.default.createElement("span", { + }, /* @__PURE__ */ import_react158.default.createElement("span", { className: "mk-icon-xsmall", dangerouslySetInnerHTML: { __html: props.superstate.ui.getSticker("ui//plus") } - }), i18n_default.buttons.addToSpace))), pathState.type == "space" ? /* @__PURE__ */ import_react156.default.createElement(SpaceHeaderView, { + }), i18n_default.buttons.addToSpace))), pathState.type == "space" ? /* @__PURE__ */ import_react158.default.createElement(SpaceHeaderView, { superstate: props.superstate, spacePathStates, spaces: spaces2 - }) : /* @__PURE__ */ import_react156.default.createElement(import_react156.default.Fragment, null, /* @__PURE__ */ import_react156.default.createElement(PathContextList, { + }) : /* @__PURE__ */ import_react158.default.createElement(import_react158.default.Fragment, null, /* @__PURE__ */ import_react158.default.createElement(PathContextList, { superstate: props.superstate, color: "var(--tag-background)", path: pathState.path - }), /* @__PURE__ */ import_react156.default.createElement(PropertiesView, { + }), /* @__PURE__ */ import_react158.default.createElement(PropertiesView, { superstate: props.superstate, spaces: spaces2.map((f2) => f2.path), force: true, @@ -127528,15 +127900,15 @@ var NoteSpacesBar = (props) => { }; // src/core/react/components/MarkdownEditor/MarkdownHeaderView.tsx -var import_react159 = __toESM(require_react()); +var import_react161 = __toESM(require_react()); // src/core/react/components/SpaceView/TitleComponent.tsx -var import_react157 = __toESM(require_react()); +var import_react159 = __toESM(require_react()); var TitleComponent = (props) => { - const { pathState } = (0, import_react157.useContext)(PathContext); - const { spaceState } = (0, import_react157.useContext)(SpaceContext); - const fileNameRef = (0, import_react157.useRef)(null); - const name317 = (0, import_react157.useMemo)( + const { pathState } = (0, import_react159.useContext)(PathContext); + const { spaceState } = (0, import_react159.useContext)(SpaceContext); + const fileNameRef = (0, import_react159.useRef)(null); + const name317 = (0, import_react159.useMemo)( () => pathState ? props.superstate.settings.spacesUseAlias ? pathState?.displayName : pathState.subtype == "tag" ? stringFromTag(pathState?.name) : pathState?.name : null, [pathState] ); @@ -127589,32 +127961,32 @@ var TitleComponent = (props) => { }; const hasSticker = pathState?.metadata.property?.[props.superstate.settings.fmKeySticker]?.length > 0; const hasBanner = pathState?.metadata.property?.[props.superstate.settings.fmKeyBanner]; - return pathState && /* @__PURE__ */ import_react157.default.createElement(import_react157.default.Fragment, null, props.superstate.settings.spacesStickers && /* @__PURE__ */ import_react157.default.createElement("div", { + return pathState && /* @__PURE__ */ import_react159.default.createElement(import_react159.default.Fragment, null, props.superstate.settings.spacesStickers && /* @__PURE__ */ import_react159.default.createElement("div", { className: "mk-header-icon", style: hasBanner ? { "--label-color": "var(--mk-ui-background)" } : {} - }, hasSticker ? /* @__PURE__ */ import_react157.default.createElement(PathStickerContainer, { + }, hasSticker ? /* @__PURE__ */ import_react159.default.createElement(PathStickerContainer, { superstate: props.superstate, path: pathState.path - }) : /* @__PURE__ */ import_react157.default.createElement("button", { + }) : /* @__PURE__ */ import_react159.default.createElement("button", { className: "mk-inline-button", onClick: (e5) => props.superstate.ui.openPalette( - (_props) => /* @__PURE__ */ import_react157.default.createElement(StickerModal_default, { + (_props) => /* @__PURE__ */ import_react159.default.createElement(StickerModal_default, { ui: props.superstate.ui, hide: _props.hide, selectedSticker: (emoji) => savePathIcon(props.superstate, pathState.path, emoji) }) ) - }, /* @__PURE__ */ import_react157.default.createElement("div", { + }, /* @__PURE__ */ import_react159.default.createElement("div", { className: "mk-icon-xsmall", dangerouslySetInnerHTML: { __html: props.superstate.ui.getSticker("ui//smile") } - }), i18n_default.buttons.addIcon), /* @__PURE__ */ import_react157.default.createElement("span", null), !hasBanner && /* @__PURE__ */ import_react157.default.createElement("button", { + }), i18n_default.buttons.addIcon), /* @__PURE__ */ import_react159.default.createElement("span", null), !hasBanner && /* @__PURE__ */ import_react159.default.createElement("button", { className: "mk-inline-button", onClick: (e5) => props.superstate.ui.openPalette( - (_props) => /* @__PURE__ */ import_react157.default.createElement(ImageModal_default, { + (_props) => /* @__PURE__ */ import_react159.default.createElement(ImageModal_default, { superstate: props.superstate, hide: _props.hide, selectedPath: (image) => savePathBanner( @@ -127624,16 +127996,16 @@ var TitleComponent = (props) => { ) }) ) - }, /* @__PURE__ */ import_react157.default.createElement("div", { + }, /* @__PURE__ */ import_react159.default.createElement("div", { className: "mk-icon-xsmall", dangerouslySetInnerHTML: { __html: props.superstate.ui.getSticker("ui//mk-make-image") } - }), i18n_default.buttons.addCover)), /* @__PURE__ */ import_react157.default.createElement("div", { + }), i18n_default.buttons.addCover)), /* @__PURE__ */ import_react159.default.createElement("div", { className: "mk-title-container" - }, pathState?.subtype == "tag" ? /* @__PURE__ */ import_react157.default.createElement("div", { + }, pathState?.subtype == "tag" ? /* @__PURE__ */ import_react159.default.createElement("div", { className: "mk-title-prefix" - }, "#") : "", /* @__PURE__ */ import_react157.default.createElement("div", { + }, "#") : "", /* @__PURE__ */ import_react159.default.createElement("div", { className: "mk-inline-title inline-title", ref: fileNameRef, contentEditable, @@ -127649,16 +128021,16 @@ var TitleComponent = (props) => { }; // src/core/react/components/MarkdownEditor/BannerView.tsx -var import_react158 = __toESM(require_react()); +var import_react160 = __toESM(require_react()); var BannerView = (props) => { - const [hasSticker, setHasSticker] = (0, import_react158.useState)(false); - const { pathState } = (0, import_react158.useContext)(PathContext); - const [banner, setBanner] = (0, import_react158.useState)( + const [hasSticker, setHasSticker] = (0, import_react160.useState)(false); + const { pathState } = (0, import_react160.useContext)(PathContext); + const [banner, setBanner] = (0, import_react160.useState)( props.superstate.spaceManager.uriByString( pathState?.metadata.property?.[props.superstate.settings.fmKeyBanner] ) ); - (0, import_react158.useEffect)(() => { + (0, import_react160.useEffect)(() => { const banner2 = props.superstate.spaceManager.uriByString( pathState?.metadata.property?.[props.superstate.settings.fmKeyBanner] ); @@ -127679,7 +128051,7 @@ var BannerView = (props) => { value: "change", icon: "ui//image", onClick: (ev) => { - props.superstate.ui.openPalette((_props) => /* @__PURE__ */ import_react158.default.createElement(ImageModal_default, { + props.superstate.ui.openPalette((_props) => /* @__PURE__ */ import_react160.default.createElement(ImageModal_default, { superstate: props.superstate, hide: _props.hide, selectedPath: (image) => savePathBanner(props.superstate, pathState.path, image) @@ -127715,7 +128087,7 @@ var BannerView = (props) => { ); return false; }; - return banner ? /* @__PURE__ */ import_react158.default.createElement(import_react158.default.Fragment, null, /* @__PURE__ */ import_react158.default.createElement("div", { + return banner ? /* @__PURE__ */ import_react160.default.createElement(import_react160.default.Fragment, null, /* @__PURE__ */ import_react160.default.createElement("div", { className: `mk-space-banner`, onContextMenu: triggerBannerContextMenu, style: { @@ -127723,68 +128095,68 @@ var BannerView = (props) => { backgroundImage: `url("${banner.scheme == "vault" ? props.superstate.ui.getUIPath(banner.basePath) : banner.fullPath}")`, backgroundPositionY: offset2 } - }), /* @__PURE__ */ import_react158.default.createElement("div", { + }), /* @__PURE__ */ import_react160.default.createElement("div", { className: `mk-spacer`, style: { "--mk-header-height": ((isTouchScreen(props.superstate.ui) ? 1 : 0) * 26 + (props.superstate.settings.bannerHeight - 62) + (!props.superstate.settings.spacesStickers || props.superstate.settings.inlineContextNameLayout == "horizontal" ? 50 : hasSticker ? 0 : 30)).toString() + "px" }, onContextMenu: (e5) => e5.preventDefault() - })) : /* @__PURE__ */ import_react158.default.createElement(import_react158.default.Fragment, null); + })) : /* @__PURE__ */ import_react160.default.createElement(import_react160.default.Fragment, null); }; // src/core/react/components/MarkdownEditor/MarkdownHeaderView.tsx var MarkdownHeaderView = (props) => { - const { pathState } = (0, import_react159.useContext)(PathContext); - const [collapsed, setCollapsed] = (0, import_react159.useState)( + const { pathState } = (0, import_react161.useContext)(PathContext); + const [collapsed, setCollapsed] = (0, import_react161.useState)( !props.superstate.settings.inlineContextExpanded ); - (0, import_react159.useEffect)(() => { + (0, import_react161.useEffect)(() => { props.superstate.settings.inlineContextExpanded = !collapsed; props.superstate.saveSettings(); }, [collapsed]); - (0, import_react159.useLayoutEffect)(() => { + (0, import_react161.useLayoutEffect)(() => { props.editorView?.requestMeasure(); }, []); - return pathState && /* @__PURE__ */ import_react159.default.createElement(import_react159.default.Fragment, null, /* @__PURE__ */ import_react159.default.createElement("div", { + return pathState && /* @__PURE__ */ import_react161.default.createElement(import_react161.default.Fragment, null, /* @__PURE__ */ import_react161.default.createElement("div", { className: "mk-path-context-component" - }, /* @__PURE__ */ import_react159.default.createElement("div", { + }, /* @__PURE__ */ import_react161.default.createElement("div", { className: `mk-path-context-label ${props.superstate.settings.inlineContextNameLayout == "horizontal" ? "mk-path-context-file-horizontal" : ""}` - }, /* @__PURE__ */ import_react159.default.createElement(BannerView, { + }, /* @__PURE__ */ import_react161.default.createElement(BannerView, { superstate: props.superstate - }), /* @__PURE__ */ import_react159.default.createElement(TitleComponent, { + }), /* @__PURE__ */ import_react161.default.createElement(TitleComponent, { superstate: props.superstate, readOnly: !props.editable - }), /* @__PURE__ */ import_react159.default.createElement("div", { + }), /* @__PURE__ */ import_react161.default.createElement("div", { style: { position: "relative" } - }, /* @__PURE__ */ import_react159.default.createElement("div", { + }, /* @__PURE__ */ import_react161.default.createElement("div", { className: "mk-fold" - }, /* @__PURE__ */ import_react159.default.createElement(CollapseToggle, { + }, /* @__PURE__ */ import_react161.default.createElement(CollapseToggle, { superstate: props.superstate, collapsed, onToggle: (c3) => setCollapsed(c3) - })))), props.editable && !collapsed && /* @__PURE__ */ import_react159.default.createElement(NoteSpacesBar, { + })))), props.editable && !collapsed && /* @__PURE__ */ import_react161.default.createElement(NoteSpacesBar, { superstate: props.superstate }))); }; // src/core/react/components/Navigator/Navigator.tsx -var import_react160 = __toESM(require_react()); +var import_react162 = __toESM(require_react()); var Navigator = (props) => { - return /* @__PURE__ */ import_react160.default.createElement("div", { + return /* @__PURE__ */ import_react162.default.createElement("div", { className: "mk-sidebar" - }, /* @__PURE__ */ import_react160.default.createElement(SidebarProvider, { + }, /* @__PURE__ */ import_react162.default.createElement(SidebarProvider, { superstate: props.superstate - }, /* @__PURE__ */ import_react160.default.createElement(MainList, { + }, /* @__PURE__ */ import_react162.default.createElement(MainList, { superstate: props.superstate }))); }; // src/core/react/components/SpaceView/Editor/EmbedView/SpaceFragmentWrapper.tsx -var import_react161 = __toESM(require_react()); -var import_react162 = __toESM(require_react()); +var import_react163 = __toESM(require_react()); +var import_react164 = __toESM(require_react()); var SpaceFragmentTitleComponent = (props) => { - const { pathState } = (0, import_react162.useContext)(PathContext); - const fileNameRef = (0, import_react162.useRef)(null); + const { pathState } = (0, import_react164.useContext)(PathContext); + const fileNameRef = (0, import_react164.useRef)(null); const contentEditable = true; const onBlur = (e5) => { const newValue = e5.target.innerHTML; @@ -127818,19 +128190,19 @@ var SpaceFragmentTitleComponent = (props) => { } }; const triggerStickerMenu = (e5) => { - props.superstate.ui.openPalette((_props) => /* @__PURE__ */ import_react161.default.createElement(StickerModal_default, { + props.superstate.ui.openPalette((_props) => /* @__PURE__ */ import_react163.default.createElement(StickerModal_default, { ui: props.superstate.ui, hide: _props.hide, selectedSticker: (emoji) => props.saveSticker(emoji) })); }; - return /* @__PURE__ */ import_react161.default.createElement("div", null, /* @__PURE__ */ import_react161.default.createElement("div", { + return /* @__PURE__ */ import_react163.default.createElement("div", null, /* @__PURE__ */ import_react163.default.createElement("div", { className: "mk-header-icon" - }), /* @__PURE__ */ import_react161.default.createElement("div", { + }), /* @__PURE__ */ import_react163.default.createElement("div", { className: "mk-title-container" - }, pathState?.subtype == "tag" ? /* @__PURE__ */ import_react161.default.createElement("div", { + }, pathState?.subtype == "tag" ? /* @__PURE__ */ import_react163.default.createElement("div", { className: "mk-title-prefix" - }, "#") : "", /* @__PURE__ */ import_react161.default.createElement("div", { + }, "#") : "", /* @__PURE__ */ import_react163.default.createElement("div", { className: "mk-inline-title inline-title", ref: fileNameRef, contentEditable, @@ -127845,8 +128217,8 @@ var SpaceFragmentTitleComponent = (props) => { }))); }; var SpaceFragmentWrapper = (props) => { - const [schema, setSchema] = import_react161.default.useState(null); - (0, import_react161.useEffect)(() => { + const [schema, setSchema] = import_react163.default.useState(null); + (0, import_react163.useEffect)(() => { const uri = props.superstate.spaceManager.uriByString(props.path); if (uri.refType == "context") { const schema2 = props.superstate.contextsIndex.get(uri.path)?.schemas.find((s4) => s4.id == uri.ref); @@ -127939,11 +128311,11 @@ var SpaceFragmentWrapper = (props) => { ); } }; - return /* @__PURE__ */ import_react161.default.createElement("div", { + return /* @__PURE__ */ import_react163.default.createElement("div", { className: "mk-editor-space-fragment markdown-source-view mod-cm6 is-readable-line-width" - }, /* @__PURE__ */ import_react161.default.createElement("div", { + }, /* @__PURE__ */ import_react163.default.createElement("div", { className: "mk-editor-header" - }, schema && /* @__PURE__ */ import_react161.default.createElement(SpaceFragmentTitleComponent, { + }, schema && /* @__PURE__ */ import_react163.default.createElement(SpaceFragmentTitleComponent, { superstate: props.superstate, readOnly: true, name: schema.name, @@ -127970,7 +128342,7 @@ var createTable2 = (object, columns) => { // src/adapters/obsidian/ui/editors/EmbedContextView.tsx var import_obsidian = require("obsidian"); -var import_react163 = __toESM(require_react()); +var import_react165 = __toESM(require_react()); var EMBED_CONTEXT_VIEW_TYPE = "mk-space-embed"; var EmbedContextView = class extends import_obsidian.ItemView { constructor(leaf, plugin) { @@ -128022,7 +128394,7 @@ var EmbedContextView = class extends import_obsidian.ItemView { this.root = this.plugin.ui.createRoot(this.contentEl); if (this.root) { this.root.render( - /* @__PURE__ */ import_react163.default.createElement(SpaceFragmentViewComponent, { + /* @__PURE__ */ import_react165.default.createElement(SpaceFragmentViewComponent, { id: this.path, superstate: this.plugin.superstate, path: this.path, @@ -128042,7 +128414,7 @@ var EmbedContextView = class extends import_obsidian.ItemView { // src/adapters/obsidian/ui/editors/markdownView/FileView.tsx var import_obsidian3 = require("obsidian"); -var import_react166 = __toESM(require_react()); +var import_react168 = __toESM(require_react()); // src/adapters/text/removemd.js function removemd(md, options) { @@ -128140,7 +128512,7 @@ var TextCacher = class { // src/adapters/obsidian/ui/editors/markdownView/FileLinkViewComponent.tsx var import_obsidian2 = require("obsidian"); var import_classnames11 = __toESM(require_classnames()); -var import_react165 = __toESM(require_react()); +var import_react167 = __toESM(require_react()); // src/adapters/obsidian/filetypes/frontmatter/frontMatterKeys.ts var frontMatterKeys = (fm) => { @@ -128148,14 +128520,14 @@ var frontMatterKeys = (fm) => { }; // src/adapters/obsidian/ui/editors/markdownView/RemoteMarkdownHeaderView.tsx -var import_react164 = __toESM(require_react()); +var import_react166 = __toESM(require_react()); var RemoteMarkdownHeaderView = (props) => { const { name: name317, fm } = props; - const [collapsed, setCollapsed] = (0, import_react164.useState)(false); + const [collapsed, setCollapsed] = (0, import_react166.useState)(false); const tags3 = fm.tags ?? []; - const [values2, setValues] = (0, import_react164.useState)({}); - const [columns, setColumns] = (0, import_react164.useState)([]); - (0, import_react164.useEffect)(() => { + const [values2, setValues] = (0, import_react166.useState)({}); + const [columns, setColumns] = (0, import_react166.useState)([]); + (0, import_react166.useEffect)(() => { const newCols = []; const newValues = {}; const fmKeys = uniqCaseInsensitive(frontMatterKeys(fm)); @@ -128174,7 +128546,7 @@ var RemoteMarkdownHeaderView = (props) => { setValues(newValues); setColumns(newCols); }, []); - const pathState = (0, import_react164.useMemo)( + const pathState = (0, import_react166.useMemo)( () => ({ name: name317, path: name317, @@ -128193,32 +128565,32 @@ var RemoteMarkdownHeaderView = (props) => { }), [fm, name317] ); - return /* @__PURE__ */ import_react164.default.createElement(PathProvider, { + return /* @__PURE__ */ import_react166.default.createElement(PathProvider, { superstate: props.superstate, path: props.name, pathState, readMode: true - }, pathState.metadata.property.banner && /* @__PURE__ */ import_react164.default.createElement(BannerView, { + }, pathState.metadata.property.banner && /* @__PURE__ */ import_react166.default.createElement(BannerView, { superstate: props.superstate - }), /* @__PURE__ */ import_react164.default.createElement("div", { + }), /* @__PURE__ */ import_react166.default.createElement("div", { className: "mk-path-context-component" - }, /* @__PURE__ */ import_react164.default.createElement("div", { + }, /* @__PURE__ */ import_react166.default.createElement("div", { className: `mk-path-context-label ${props.superstate.settings.inlineContextNameLayout == "horizontal" ? "mk-path-context-file-horizontal" : ""}` - }, /* @__PURE__ */ import_react164.default.createElement(import_react164.default.Fragment, null, fm.sticker ? /* @__PURE__ */ import_react164.default.createElement("div", { + }, /* @__PURE__ */ import_react166.default.createElement(import_react166.default.Fragment, null, fm.sticker ? /* @__PURE__ */ import_react166.default.createElement("div", { className: "mk-header-icon" - }, /* @__PURE__ */ import_react164.default.createElement("div", { + }, /* @__PURE__ */ import_react166.default.createElement("div", { className: `mk-path-icon` - }, /* @__PURE__ */ import_react164.default.createElement("div", { + }, /* @__PURE__ */ import_react166.default.createElement("div", { dangerouslySetInnerHTML: { __html: props.superstate.ui.getSticker(fm.sticker) } - }))) : /* @__PURE__ */ import_react164.default.createElement(import_react164.default.Fragment, null), /* @__PURE__ */ import_react164.default.createElement("div", { + }))) : /* @__PURE__ */ import_react166.default.createElement(import_react166.default.Fragment, null), /* @__PURE__ */ import_react166.default.createElement("div", { className: "mk-inline-title inline-title" - }, pathNameToString(name317))))), !collapsed ? /* @__PURE__ */ import_react164.default.createElement("div", { + }, pathNameToString(name317))))), !collapsed ? /* @__PURE__ */ import_react166.default.createElement("div", { className: "mk-path-context-component" - }, /* @__PURE__ */ import_react164.default.createElement(import_react164.default.Fragment, null, /* @__PURE__ */ import_react164.default.createElement("div", { + }, /* @__PURE__ */ import_react166.default.createElement(import_react166.default.Fragment, null, /* @__PURE__ */ import_react166.default.createElement("div", { className: "mk-path-context-section" - }, columns.map((f2, i4) => /* @__PURE__ */ import_react164.default.createElement(DataPropertyView, { + }, columns.map((f2, i4) => /* @__PURE__ */ import_react166.default.createElement(DataPropertyView, { key: i4, superstate: props.superstate, initialValue: values2[f2.name], @@ -128230,15 +128602,15 @@ var RemoteMarkdownHeaderView = (props) => { updateFieldValue: (fieldValue, value) => { }, contextTable: {} - }))))) : /* @__PURE__ */ import_react164.default.createElement(import_react164.default.Fragment, null)); + }))))) : /* @__PURE__ */ import_react166.default.createElement(import_react166.default.Fragment, null)); }; // src/adapters/obsidian/ui/editors/markdownView/FileLinkViewComponent.tsx var FileLinkViewComponent = (props) => { - const ref2 = (0, import_react165.useRef)(null); - const [markdown, setMarkdown] = (0, import_react165.useState)(""); - const [fm, setFM] = (0, import_react165.useState)({}); - (0, import_react165.useEffect)(() => { + const ref2 = (0, import_react167.useRef)(null); + const [markdown, setMarkdown] = (0, import_react167.useState)(""); + const [fm, setFM] = (0, import_react167.useState)({}); + (0, import_react167.useEffect)(() => { if (ref2.current) { import_obsidian2.MarkdownRenderer.render( props.app, @@ -128261,7 +128633,7 @@ var FileLinkViewComponent = (props) => { return () => observer.disconnect(); } }, [markdown]); - (0, import_react165.useEffect)(() => { + (0, import_react167.useEffect)(() => { fetch(props.path).then((res) => res.text()).then((f2) => { setMarkdown(f2); const match2 = f2.match(regexYaml); @@ -128271,18 +128643,18 @@ var FileLinkViewComponent = (props) => { } }); }, [props.path]); - return /* @__PURE__ */ import_react165.default.createElement("div", { + return /* @__PURE__ */ import_react167.default.createElement("div", { className: (0, import_classnames11.default)( "markdown-preview-view markdown-rendered node-insert-event allow-fold-headings show-indentation-guide allow-fold-lists show-frontmatter", props.superstate.settings.readableLineWidth ? "is-readable-line-width" : "" ) - }, /* @__PURE__ */ import_react165.default.createElement("div", { + }, /* @__PURE__ */ import_react167.default.createElement("div", { className: "mk-remote-header" - }, /* @__PURE__ */ import_react165.default.createElement(RemoteMarkdownHeaderView, { + }, /* @__PURE__ */ import_react167.default.createElement(RemoteMarkdownHeaderView, { superstate: props.superstate, name: "Release Notes", fm - })), /* @__PURE__ */ import_react165.default.createElement("div", { + })), /* @__PURE__ */ import_react167.default.createElement("div", { className: "markdown-preview-sizer markdown-preview-section", ref: ref2 })); @@ -128337,9 +128709,9 @@ var FileLinkView = class extends import_obsidian3.ItemView { this.destroy(); this.root = this.superstate.ui.createRoot(this.contentEl); this.root.render( - /* @__PURE__ */ import_react166.default.createElement("div", { + /* @__PURE__ */ import_react168.default.createElement("div", { className: "markdown-reading-view" - }, /* @__PURE__ */ import_react166.default.createElement(FileLinkViewComponent, { + }, /* @__PURE__ */ import_react168.default.createElement(FileLinkViewComponent, { superstate: this.superstate, path: path2, app: this.app, @@ -128353,7 +128725,7 @@ var FileLinkView = class extends import_obsidian3.ItemView { var import_obsidian6 = require("obsidian"); // src/core/react/components/System/SystemSettings.tsx -var import_react172 = __toESM(require_react()); +var import_react174 = __toESM(require_react()); // src/core/assets/icons.ts var uiIconSet = { @@ -129106,16 +129478,16 @@ var uiIconSet = { }; // src/core/react/components/System/IconsSet.tsx -var import_react167 = __toESM(require_react()); +var import_react169 = __toESM(require_react()); var IconSet = (props) => { - const [iconSets, setIconSets] = import_react167.default.useState([]); - const [icons, setIcons] = import_react167.default.useState([]); - (0, import_react167.useEffect)(() => { + const [iconSets, setIconSets] = import_react169.default.useState([]); + const [icons, setIcons] = import_react169.default.useState([]); + (0, import_react169.useEffect)(() => { Object.keys(uiIconSet).filter((f2, i4) => i4 < 10).forEach((icon) => { setIcons((f2) => [...f2, "ui//" + icon]); }); }, []); - return /* @__PURE__ */ import_react167.default.createElement("div", null, /* @__PURE__ */ import_react167.default.createElement("div", null, icons.map((c3, i4) => /* @__PURE__ */ import_react167.default.createElement("div", { + return /* @__PURE__ */ import_react169.default.createElement("div", null, /* @__PURE__ */ import_react169.default.createElement("div", null, icons.map((c3, i4) => /* @__PURE__ */ import_react169.default.createElement("div", { key: i4, className: "mk-icon-small", dangerouslySetInnerHTML: { @@ -129125,28 +129497,28 @@ var IconSet = (props) => { }; // src/core/react/components/System/ImageSet.tsx -var import_react168 = __toESM(require_react()); +var import_react170 = __toESM(require_react()); var ImageSet = (props) => { - const [images, setImages] = import_react168.default.useState([]); - const [currentSet, setCurrentSet] = import_react168.default.useState(null); + const [images, setImages] = import_react170.default.useState([]); + const [currentSet, setCurrentSet] = import_react170.default.useState(null); const addImage = (image) => { setImages([...images, image]); }; - return /* @__PURE__ */ import_react168.default.createElement("div", null); + return /* @__PURE__ */ import_react170.default.createElement("div", null); }; // src/core/react/components/System/MaterialsSet.tsx -var import_react169 = __toESM(require_react()); +var import_react171 = __toESM(require_react()); var MaterialsSet = (props) => { - const [materials, setMaterials] = import_react169.default.useState([]); - return /* @__PURE__ */ import_react169.default.createElement("div", null, /* @__PURE__ */ import_react169.default.createElement("div", null, colors.map((c3, i4) => /* @__PURE__ */ import_react169.default.createElement("div", { + const [materials, setMaterials] = import_react171.default.useState([]); + return /* @__PURE__ */ import_react171.default.createElement("div", null, /* @__PURE__ */ import_react171.default.createElement("div", null, colors.map((c3, i4) => /* @__PURE__ */ import_react171.default.createElement("div", { key: i4, "aria-label": c3[0], onMouseDown: () => { }, className: "mk-color", style: { background: c3[1] } - })), /* @__PURE__ */ import_react169.default.createElement("div", null, "Add")), /* @__PURE__ */ import_react169.default.createElement("div", null, colorsBase.map((c3, i4) => /* @__PURE__ */ import_react169.default.createElement("div", { + })), /* @__PURE__ */ import_react171.default.createElement("div", null, "Add")), /* @__PURE__ */ import_react171.default.createElement("div", null, colorsBase.map((c3, i4) => /* @__PURE__ */ import_react171.default.createElement("div", { key: i4, "aria-label": c3[0], onMouseDown: () => { @@ -129157,9 +129529,9 @@ var MaterialsSet = (props) => { }; // src/core/react/components/System/SystemActions.tsx -var import_react170 = __toESM(require_react()); +var import_react172 = __toESM(require_react()); var SystemActionsEditor = (props) => { - const [selectedCommand, setSelectedCommand] = (0, import_react170.useState)(); + const [selectedCommand, setSelectedCommand] = (0, import_react172.useState)(); const saveCommand = (command) => { props.superstate.spaceManager.saveSystemCommand( selectedCommand.library, @@ -129172,44 +129544,44 @@ var SystemActionsEditor = (props) => { null ); }; - return /* @__PURE__ */ import_react170.default.createElement("div", { + return /* @__PURE__ */ import_react172.default.createElement("div", { style: { display: "flex" } - }, selectedCommand && /* @__PURE__ */ import_react170.default.createElement("div", null, /* @__PURE__ */ import_react170.default.createElement(SpaceCommand, { + }, selectedCommand && /* @__PURE__ */ import_react172.default.createElement("div", null, /* @__PURE__ */ import_react172.default.createElement(SpaceCommand, { superstate: props.superstate, action: "spaces://$actions/" + selectedCommand.library + "/#;" + selectedCommand.command.schema.id }))); }; // src/core/react/components/System/Templates.tsx -var import_react171 = __toESM(require_react()); +var import_react173 = __toESM(require_react()); var Templates = (props) => { - return /* @__PURE__ */ import_react171.default.createElement("div", null, /* @__PURE__ */ import_react171.default.createElement("h1", null, "Templates")); + return /* @__PURE__ */ import_react173.default.createElement("div", null, /* @__PURE__ */ import_react173.default.createElement("h1", null, "Templates")); }; // src/core/react/components/System/SystemSettings.tsx var SystemSettings = (props) => { - const [tab, setTab] = (0, import_react172.useState)(0); - const [loadout, setLoadOut] = (0, import_react172.useState)(); + const [tab, setTab] = (0, import_react174.useState)(0); + const [loadout, setLoadOut] = (0, import_react174.useState)(); const loadouts = props.superstate.loadouts; - return /* @__PURE__ */ import_react172.default.createElement("div", null, /* @__PURE__ */ import_react172.default.createElement("div", { + return /* @__PURE__ */ import_react174.default.createElement("div", null, /* @__PURE__ */ import_react174.default.createElement("div", { style: { display: "flex", flexDirection: "column" } - }, "System Name", /* @__PURE__ */ import_react172.default.createElement("input", { + }, "System Name", /* @__PURE__ */ import_react174.default.createElement("input", { value: props.superstate.settings.systemName, onChange: (e5) => { props.superstate.settings.systemName = e5.target.value; } - }), /* @__PURE__ */ import_react172.default.createElement("div", null, /* @__PURE__ */ import_react172.default.createElement("h2", null, "Loadouts"), loadouts.map((l2, i4) => /* @__PURE__ */ import_react172.default.createElement("div", { + }), /* @__PURE__ */ import_react174.default.createElement("div", null, /* @__PURE__ */ import_react174.default.createElement("h2", null, "Loadouts"), loadouts.map((l2, i4) => /* @__PURE__ */ import_react174.default.createElement("div", { key: i4, onClick: () => { setLoadOut(l2); } - }, l2.name)), /* @__PURE__ */ import_react172.default.createElement("button", { + }, l2.name)), /* @__PURE__ */ import_react174.default.createElement("button", { dangerouslySetInnerHTML: { __html: props.superstate.ui.getSticker("ui//plus") }, onClick: () => props.superstate.ui.openModal( "New Loadout", - (_props) => /* @__PURE__ */ import_react172.default.createElement(InputModal, { + (_props) => /* @__PURE__ */ import_react174.default.createElement(InputModal, { value: "", saveLabel: "Save", hide: _props.hide, @@ -129220,68 +129592,68 @@ var SystemSettings = (props) => { } }) ) - })), /* @__PURE__ */ import_react172.default.createElement("div", null, "Appearance", /* @__PURE__ */ import_react172.default.createElement("h2", null, "Typography")), "Space View", /* @__PURE__ */ import_react172.default.createElement("p", null, "Font"), "Palette Default New Template", /* @__PURE__ */ import_react172.default.createElement(MaterialsSet, { + })), /* @__PURE__ */ import_react174.default.createElement("div", null, "Appearance", /* @__PURE__ */ import_react174.default.createElement("h2", null, "Typography")), "Space View", /* @__PURE__ */ import_react174.default.createElement("p", null, "Font"), "Palette Default New Template", /* @__PURE__ */ import_react174.default.createElement(MaterialsSet, { superstate: props.superstate - }), "Icons", /* @__PURE__ */ import_react172.default.createElement(IconSet, { + }), "Icons", /* @__PURE__ */ import_react174.default.createElement(IconSet, { superstate: props.superstate - }), "Images", /* @__PURE__ */ import_react172.default.createElement(ImageSet, { + }), "Images", /* @__PURE__ */ import_react174.default.createElement(ImageSet, { superstate: props.superstate - }), /* @__PURE__ */ import_react172.default.createElement(Templates, { + }), /* @__PURE__ */ import_react174.default.createElement(Templates, { superstate: props.superstate - }), /* @__PURE__ */ import_react172.default.createElement(SystemActionsEditor, { + }), /* @__PURE__ */ import_react174.default.createElement(SystemActionsEditor, { superstate: props.superstate }))); }; // src/adapters/obsidian/SpaceViewContainer.tsx var import_obsidian4 = require("obsidian"); -var import_react175 = __toESM(require_react()); +var import_react177 = __toESM(require_react()); // src/core/react/components/SpaceView/SpaceHeader.tsx -var import_react173 = __toESM(require_react()); +var import_react175 = __toESM(require_react()); var SpaceHeader = (props) => { - const { readMode } = (0, import_react173.useContext)(PathContext); - const { spaceState } = (0, import_react173.useContext)(SpaceContext); - const [collapsed, setCollapsed] = (0, import_react173.useState)( + const { readMode } = (0, import_react175.useContext)(PathContext); + const { spaceState } = (0, import_react175.useContext)(SpaceContext); + const [collapsed, setCollapsed] = (0, import_react175.useState)( !props.superstate.settings.inlineContextExpanded ); - (0, import_react173.useEffect)(() => { + (0, import_react175.useEffect)(() => { props.superstate.settings.inlineContextExpanded = !collapsed; props.superstate.saveSettings(); }, [collapsed]); - return /* @__PURE__ */ import_react173.default.createElement(import_react173.default.Fragment, null, /* @__PURE__ */ import_react173.default.createElement(BannerView, { + return /* @__PURE__ */ import_react175.default.createElement(import_react175.default.Fragment, null, /* @__PURE__ */ import_react175.default.createElement(BannerView, { superstate: props.superstate - }), /* @__PURE__ */ import_react173.default.createElement("div", { + }), /* @__PURE__ */ import_react175.default.createElement("div", { className: "mk-space-header" - }, /* @__PURE__ */ import_react173.default.createElement("div", { + }, /* @__PURE__ */ import_react175.default.createElement("div", { className: "mk-path-context-label" - }, /* @__PURE__ */ import_react173.default.createElement(TitleComponent, { + }, /* @__PURE__ */ import_react175.default.createElement(TitleComponent, { superstate: props.superstate, readOnly: readMode - }), /* @__PURE__ */ import_react173.default.createElement("div", { + }), /* @__PURE__ */ import_react175.default.createElement("div", { style: { position: "relative" } - }, /* @__PURE__ */ import_react173.default.createElement("div", { + }, /* @__PURE__ */ import_react175.default.createElement("div", { className: "mk-fold" - }, /* @__PURE__ */ import_react173.default.createElement(CollapseToggle, { + }, /* @__PURE__ */ import_react175.default.createElement(CollapseToggle, { superstate: props.superstate, collapsed, onToggle: (c3) => setCollapsed(c3) - })))), !collapsed && spaceState?.type == "folder" && /* @__PURE__ */ import_react173.default.createElement(NoteSpacesBar, { + })))), !collapsed && spaceState?.type == "folder" && /* @__PURE__ */ import_react175.default.createElement(NoteSpacesBar, { superstate: props.superstate }))); }; // src/core/react/components/SpaceView/SpaceInner.tsx -var import_react174 = __toESM(require_react()); +var import_react176 = __toESM(require_react()); var SpaceInner = (props) => { - const ref2 = (0, import_react174.useRef)(null); - const { spaceState } = (0, import_react174.useContext)(SpaceContext); - return /* @__PURE__ */ import_react174.default.createElement(import_react174.default.Fragment, null, /* @__PURE__ */ import_react174.default.createElement(SpaceHeader, { + const ref2 = (0, import_react176.useRef)(null); + const { spaceState } = (0, import_react176.useContext)(SpaceContext); + return /* @__PURE__ */ import_react176.default.createElement(import_react176.default.Fragment, null, /* @__PURE__ */ import_react176.default.createElement(SpaceHeader, { superstate: props.superstate - }), spaceState && /* @__PURE__ */ import_react174.default.createElement(SpaceOuter_default, { + }), spaceState && /* @__PURE__ */ import_react176.default.createElement(SpaceOuter_default, { superstate: props.superstate, ref: ref2 - }, /* @__PURE__ */ import_react174.default.createElement(FrameEditorInstance, { + }, /* @__PURE__ */ import_react176.default.createElement(FrameEditorInstance, { containerRef: ref2, superstate: props.superstate }))); @@ -129393,18 +129765,18 @@ var SpaceViewContainer = class extends import_obsidian4.ItemView { this.root = this.ui.createRoot(this.contentEl); if (this.root) { this.root.render( - /* @__PURE__ */ import_react175.default.createElement("div", { + /* @__PURE__ */ import_react177.default.createElement("div", { className: "mk-space-view" - }, path2 == "spaces://$settings" ? /* @__PURE__ */ import_react175.default.createElement(SystemSettings, { + }, path2 == "spaces://$settings" ? /* @__PURE__ */ import_react177.default.createElement(SystemSettings, { superstate: this.superstate - }) : /* @__PURE__ */ import_react175.default.createElement(SpaceView, { + }) : /* @__PURE__ */ import_react177.default.createElement(SpaceView, { path: path2, superstate: this.superstate, key: path2, readOnly: false - }, /* @__PURE__ */ import_react175.default.createElement("div", { + }, /* @__PURE__ */ import_react177.default.createElement("div", { className: "mk-space-scroller markdown-source-view mod-cm6 is-readable-line-width" - }, /* @__PURE__ */ import_react175.default.createElement(SpaceInner, { + }, /* @__PURE__ */ import_react177.default.createElement(SpaceInner, { superstate: this.superstate })))) ); @@ -129418,7 +129790,7 @@ var SpaceViewContainer = class extends import_obsidian4.ItemView { // src/adapters/obsidian/ui/editors/SpaceFragmentViewComponent.tsx var import_obsidian5 = require("obsidian"); -var import_react176 = __toESM(require_react()); +var import_react178 = __toESM(require_react()); var SPACE_FRAGMENT_VIEW_TYPE = "mk-space-fragment"; var SpaceFragmentView = class extends import_obsidian5.ItemView { constructor(leaf, plugin) { @@ -129470,10 +129842,10 @@ var SpaceFragmentView = class extends import_obsidian5.ItemView { this.root = this.plugin.ui.createRoot(this.contentEl); if (this.root) { this.root.render( - /* @__PURE__ */ import_react176.default.createElement(SpaceFragmentWrapper, { + /* @__PURE__ */ import_react178.default.createElement(SpaceFragmentWrapper, { superstate: this.plugin.superstate, path: this.path - }, /* @__PURE__ */ import_react176.default.createElement(SpaceFragmentViewComponent, { + }, /* @__PURE__ */ import_react178.default.createElement(SpaceFragmentViewComponent, { id: this.path, superstate: this.plugin.superstate, path: this.path, @@ -129715,7 +130087,7 @@ var getAbstractFileAtPath = (app2, path2) => { // src/adapters/obsidian/ui/editors/markdownView/FlowEditorHover.tsx var import_obsidian7 = require("obsidian"); -var import_react177 = __toESM(require_react()); +var import_react179 = __toESM(require_react()); var FlowEditorHover = (props) => { const uri = props.superstate.spaceManager.uriByString(props.path); const file = getAbstractFileAtPath(props.app, uri.basePath) ?? props.app.metadataCache.getFirstLinkpathDest(uri.path, props.source ?? "/"); @@ -129816,23 +130188,23 @@ var FlowEditorHover = (props) => { defaultMenu(props.superstate.ui, menuOptions) ); }; - return /* @__PURE__ */ import_react177.default.createElement(import_react177.default.Fragment, null, file ? /* @__PURE__ */ import_react177.default.createElement("div", { + return /* @__PURE__ */ import_react179.default.createElement(import_react179.default.Fragment, null, file ? /* @__PURE__ */ import_react179.default.createElement("div", { className: "mk-flowblock-menu" - }, file instanceof import_obsidian7.TFile ? /* @__PURE__ */ import_react177.default.createElement(import_react177.default.Fragment, null, props.toggle && /* @__PURE__ */ import_react177.default.createElement("div", { + }, file instanceof import_obsidian7.TFile ? /* @__PURE__ */ import_react179.default.createElement(import_react179.default.Fragment, null, props.toggle && /* @__PURE__ */ import_react179.default.createElement("div", { "aria-label": i18n_default.buttons.toggleFlow, onClick: toggleFlow, className: `mk-hover-button ${props.toggleState ? "mk-toggle-on" : ""}`, dangerouslySetInnerHTML: { __html: !props.toggleState ? props.superstate.ui.getSticker("ui//edit-3") : props.superstate.ui.getSticker("ui//book-open") } - }), /* @__PURE__ */ import_react177.default.createElement("div", { + }), /* @__PURE__ */ import_react179.default.createElement("div", { "aria-label": i18n_default.buttons.openLink, onClick: openLink, className: "mk-hover-button", dangerouslySetInnerHTML: { __html: props.superstate.ui.getSticker("ui//open-link") } - })) : /* @__PURE__ */ import_react177.default.createElement(import_react177.default.Fragment, null, /* @__PURE__ */ import_react177.default.createElement("div", { + })) : /* @__PURE__ */ import_react179.default.createElement(import_react179.default.Fragment, null, /* @__PURE__ */ import_react179.default.createElement("div", { className: "mk-icon-small mk-hover-button", dangerouslySetInnerHTML: { __html: props.superstate.ui.getSticker("ui//handle") @@ -129840,7 +130212,7 @@ var FlowEditorHover = (props) => { onClick: (e5) => { showTableMenu(e5); } - }))) : /* @__PURE__ */ import_react177.default.createElement(import_react177.default.Fragment, null)); + }))) : /* @__PURE__ */ import_react179.default.createElement(import_react179.default.Fragment, null)); }; // src/adapters/obsidian/utils/flow/flowEditor.ts @@ -130760,7 +131132,7 @@ var FlowEditorSelector = class extends import_view10.WidgetType { const infoField = view.state.field(import_obsidian9.editorInfoField, false); const file = infoField.file; reactEl.render( - /* @__PURE__ */ import_react178.default.createElement(FlowEditorHover, { + /* @__PURE__ */ import_react180.default.createElement(FlowEditorHover, { app: this.plugin.app, superstate: this.plugin.superstate, toggle: true, @@ -131022,13 +131394,13 @@ var toggleMarkExtension = import_state11.EditorState.transactionFilter.of( // src/adapters/obsidian/ui/editors/markdownView/menus/inlineStylerView/InlineMenu.tsx var import_classnames12 = __toESM(require_classnames()); -var import_react180 = __toESM(require_react()); +var import_react182 = __toESM(require_react()); // src/adapters/obsidian/ui/editors/markdownView/menus/inlineStylerView/Mark.tsx -var import_react179 = __toESM(require_react()); +var import_react181 = __toESM(require_react()); var Mark = (props) => { const { i: i4, style, active, toggleMarkAction } = props; - return /* @__PURE__ */ import_react179.default.createElement("div", { + return /* @__PURE__ */ import_react181.default.createElement("div", { key: i4, "aria-label": !isTouchScreen(props.plugin.superstate.ui) ? i18n_default.styles[style.label] : void 0, className: `mk-mark ${style.mark && active ? "mk-mark-active" : ""}`, @@ -131093,7 +131465,7 @@ function resolveStyles() { var loadStylerIntoContainer = (el, plugin) => { const root = plugin.ui.createRoot(el); root.render( - /* @__PURE__ */ import_react180.default.createElement(InlineMenuComponent, { + /* @__PURE__ */ import_react182.default.createElement(InlineMenuComponent, { mobile: true, activeMarks: [], plugin @@ -131101,8 +131473,8 @@ var loadStylerIntoContainer = (el, plugin) => { ); }; var InlineMenuComponent = (props) => { - const [mode2, setMode] = (0, import_react180.useState)(props.mobile ? 0 : 1); - const [colorMode, setColorMode] = (0, import_react180.useState)(null); + const [mode2, setMode] = (0, import_react182.useState)(props.mobile ? 0 : 1); + const [colorMode, setColorMode] = (0, import_react182.useState)(null); const makeMenu = (e5) => { e5.preventDefault(); const cm = props.cm ?? getActiveCM(props.plugin); @@ -131150,7 +131522,7 @@ var InlineMenuComponent = (props) => { } }); }; - const makeMode = () => /* @__PURE__ */ import_react180.default.createElement(import_react180.default.Fragment, null, /* @__PURE__ */ import_react180.default.createElement("div", { + const makeMode = () => /* @__PURE__ */ import_react182.default.createElement(import_react182.default.Fragment, null, /* @__PURE__ */ import_react182.default.createElement("div", { "aria-label": !isTouchScreen(props.plugin.superstate.ui) ? i18n_default.commands.makeMenu : void 0, onMouseDown: (e5) => { makeMenu(e5); @@ -131159,7 +131531,7 @@ var InlineMenuComponent = (props) => { dangerouslySetInnerHTML: { __html: props.plugin.superstate.ui.getSticker("ui//mk-make-slash") } - }), /* @__PURE__ */ import_react180.default.createElement("div", { + }), /* @__PURE__ */ import_react182.default.createElement("div", { "aria-label": !isTouchScreen(props.plugin.superstate.ui) ? i18n_default.commands.selectStyle : void 0, onMouseDown: () => { setMode(1); @@ -131168,7 +131540,7 @@ var InlineMenuComponent = (props) => { dangerouslySetInnerHTML: { __html: props.plugin.superstate.ui.getSticker("ui//mk-make-style") } - }), /* @__PURE__ */ import_react180.default.createElement("div", { + }), /* @__PURE__ */ import_react182.default.createElement("div", { "aria-label": !isTouchScreen(props.plugin.superstate.ui) ? i18n_default.commands.image : void 0, onMouseDown: () => { const view = getActiveMarkdownView(props.plugin); @@ -131178,7 +131550,7 @@ var InlineMenuComponent = (props) => { dangerouslySetInnerHTML: { __html: props.plugin.superstate.ui.getSticker("ui//mk-make-attach") } - }), /* @__PURE__ */ import_react180.default.createElement("div", { + }), /* @__PURE__ */ import_react182.default.createElement("div", { "aria-label": !isTouchScreen(props.plugin.superstate.ui) ? i18n_default.commands.toggleKeyboard : void 0, onMouseDown: () => { const view = getActiveMarkdownView(props.plugin); @@ -131188,7 +131560,7 @@ var InlineMenuComponent = (props) => { dangerouslySetInnerHTML: { __html: props.plugin.superstate.ui.getSticker("ui//mk-make-indent") } - }), /* @__PURE__ */ import_react180.default.createElement("div", { + }), /* @__PURE__ */ import_react182.default.createElement("div", { "aria-label": !isTouchScreen(props.plugin.superstate.ui) ? i18n_default.commands.toggleKeyboard : void 0, onMouseDown: () => { const view = getActiveMarkdownView(props.plugin); @@ -131198,7 +131570,7 @@ var InlineMenuComponent = (props) => { dangerouslySetInnerHTML: { __html: props.plugin.superstate.ui.getSticker("ui//mk-make-unindent") } - }), /* @__PURE__ */ import_react180.default.createElement("div", { + }), /* @__PURE__ */ import_react182.default.createElement("div", { "aria-label": !isTouchScreen(props.plugin.superstate.ui) ? i18n_default.commands.toggleKeyboard : void 0, onMouseDown: () => { const view = getActiveMarkdownView(props.plugin); @@ -131209,7 +131581,7 @@ var InlineMenuComponent = (props) => { __html: props.plugin.superstate.ui.getSticker("ui//mk-make-keyboard") } })); - const colorsMode = () => /* @__PURE__ */ import_react180.default.createElement(import_react180.default.Fragment, null, /* @__PURE__ */ import_react180.default.createElement("div", { + const colorsMode = () => /* @__PURE__ */ import_react182.default.createElement(import_react182.default.Fragment, null, /* @__PURE__ */ import_react182.default.createElement("div", { className: "mk-mark", onMouseDown: () => { setColorMode(null); @@ -131218,7 +131590,7 @@ var InlineMenuComponent = (props) => { dangerouslySetInnerHTML: { __html: props.plugin.superstate.ui.getSticker("ui//mk-ui-close") } - }), colors.map((c3, i4) => /* @__PURE__ */ import_react180.default.createElement("div", { + }), colors.map((c3, i4) => /* @__PURE__ */ import_react182.default.createElement("div", { key: i4, onMouseDown: () => { setMode(1); @@ -131242,7 +131614,7 @@ var InlineMenuComponent = (props) => { className: "mk-color", style: { background: c3[1] } }))); - const marksMode = () => /* @__PURE__ */ import_react180.default.createElement(import_react180.default.Fragment, null, props.mobile ? /* @__PURE__ */ import_react180.default.createElement("div", { + const marksMode = () => /* @__PURE__ */ import_react182.default.createElement(import_react182.default.Fragment, null, props.mobile ? /* @__PURE__ */ import_react182.default.createElement("div", { className: "mk-mark", onMouseDown: () => { setMode(0); @@ -131250,8 +131622,8 @@ var InlineMenuComponent = (props) => { dangerouslySetInnerHTML: { __html: props.plugin.superstate.ui.getSticker("ui//mk-ui-close") } - }) : /* @__PURE__ */ import_react180.default.createElement(import_react180.default.Fragment, null), resolveStyles().map((s4, i4) => { - return /* @__PURE__ */ import_react180.default.createElement(Mark, { + }) : /* @__PURE__ */ import_react182.default.createElement(import_react182.default.Fragment, null), resolveStyles().map((s4, i4) => { + return /* @__PURE__ */ import_react182.default.createElement(Mark, { plugin: props.plugin, key: i4, i: i4, @@ -131259,9 +131631,9 @@ var InlineMenuComponent = (props) => { active: props.activeMarks.find((f2) => f2 == s4.mark) ? true : false, toggleMarkAction }); - }), props.plugin.superstate.settings.inlineStylerColors ? /* @__PURE__ */ import_react180.default.createElement(import_react180.default.Fragment, null, /* @__PURE__ */ import_react180.default.createElement("div", { + }), props.plugin.superstate.settings.inlineStylerColors ? /* @__PURE__ */ import_react182.default.createElement(import_react182.default.Fragment, null, /* @__PURE__ */ import_react182.default.createElement("div", { className: "mk-divider" - }), /* @__PURE__ */ import_react180.default.createElement("div", { + }), /* @__PURE__ */ import_react182.default.createElement("div", { "aria-label": !isTouchScreen(props.plugin.superstate.ui) ? i18n_default.styles.textColor : void 0, onMouseDown: () => { setMode(2); @@ -131275,7 +131647,7 @@ var InlineMenuComponent = (props) => { dangerouslySetInnerHTML: { __html: props.plugin.superstate.ui.getSticker("ui//mk-mark-color") } - }), /* @__PURE__ */ import_react180.default.createElement("div", { + }), /* @__PURE__ */ import_react182.default.createElement("div", { "aria-label": !isTouchScreen(props.plugin.superstate.ui) ? i18n_default.styles.highlight : void 0, onMouseDown: () => { setMode(2); @@ -131291,15 +131663,15 @@ var InlineMenuComponent = (props) => { "ui//mk-mark-highlight" ) } - })) : /* @__PURE__ */ import_react180.default.createElement(import_react180.default.Fragment, null)); - return /* @__PURE__ */ import_react180.default.createElement("div", { + })) : /* @__PURE__ */ import_react182.default.createElement(import_react182.default.Fragment, null)); + return /* @__PURE__ */ import_react182.default.createElement("div", { className: (0, import_classnames12.default)("mk-style-menu", props.mobile ? "" : "menu"), onMouseDown: (e5) => e5.preventDefault() }, mode2 == 0 && props.mobile ? makeMode() : mode2 == 2 ? colorsMode() : marksMode()); }; // src/adapters/obsidian/ui/editors/markdownView/menus/inlineStylerView/inlineStyler.tsx -var import_react181 = __toESM(require_react()); +var import_react183 = __toESM(require_react()); var cursorTooltipField = (plugin) => import_state12.StateField.define({ create: getCursorTooltips(plugin), update(tooltips2, tr) { @@ -131324,7 +131696,7 @@ var getCursorTooltips = (plugin) => (state) => { dom.className = "cm-tooltip-cursor"; const reactElement = plugin.ui.createRoot(dom); reactElement.render( - /* @__PURE__ */ import_react181.default.createElement(import_react181.default.Fragment, null, /* @__PURE__ */ import_react181.default.createElement(InlineMenuComponent, { + /* @__PURE__ */ import_react183.default.createElement(import_react183.default.Fragment, null, /* @__PURE__ */ import_react183.default.createElement(InlineMenuComponent, { plugin, cm: view, activeMarks, @@ -131394,7 +131766,7 @@ var cmExtensions = (plugin, mobile) => { }; // src/adapters/obsidian/utils/flow/markdownPost.tsx -var import_react182 = __toESM(require_react()); +var import_react184 = __toESM(require_react()); var getCMFromElement = (el, app2) => { let dom = el; while (!dom.hasClass("cm-editor") && dom.parentElement) { @@ -131421,7 +131793,7 @@ var replaceAllTables = (plugin, el, ctx) => { const link = match2[1]; const reactEl = plugin.ui.createRoot(element.parentElement); reactEl.render( - /* @__PURE__ */ import_react182.default.createElement(NoteView, { + /* @__PURE__ */ import_react184.default.createElement(NoteView, { load: true, superstate: plugin.superstate, path: link @@ -131479,7 +131851,7 @@ var replaceAllEmbed = (el, ctx, superstate, app2) => { const endPos = cm?.posAtDOM(nextDom); if (ctx.sourcePath) reactEl.render( - /* @__PURE__ */ import_react182.default.createElement(FlowEditorHover, { + /* @__PURE__ */ import_react184.default.createElement(FlowEditorHover, { app: app2, toggle: true, path: ctx.sourcePath, @@ -131975,7 +132347,7 @@ var MakeMDPluginSettingsTab = class extends import_obsidian10.PluginSettingTab { // src/adapters/obsidian/ui/navigator/NavigatorView.tsx var import_obsidian11 = require("obsidian"); -var import_react183 = __toESM(require_react()); +var import_react185 = __toESM(require_react()); var FILE_TREE_VIEW_TYPE = "mk-path-view"; var VIEW_DISPLAY_TEXT = "Spaces"; var ICON = "layout-grid"; @@ -132028,7 +132400,7 @@ var FileTreeView = class extends import_obsidian11.ItemView { this.destroy(); this.root = this.ui.createRoot(this.contentEl); if (this.root) { - this.root.render(/* @__PURE__ */ import_react183.default.createElement(Navigator, { + this.root.render(/* @__PURE__ */ import_react185.default.createElement(Navigator, { superstate: this.superstate })); } else { @@ -132040,7 +132412,7 @@ var FileTreeView = class extends import_obsidian11.ItemView { }; // src/adapters/obsidian/replaceMobileMainMenu.tsx -var import_react184 = __toESM(require_react()); +var import_react186 = __toESM(require_react()); var replaceMobileMainMenu = (superstate) => { if (isTouchScreen(superstate.ui)) { const header = app.workspace.containerEl.querySelector( @@ -132049,9 +132421,9 @@ var replaceMobileMainMenu = (superstate) => { header.innerHTML = ""; const reactEl = superstate.ui.createRoot(header); reactEl.render( - /* @__PURE__ */ import_react184.default.createElement(SidebarProvider, { + /* @__PURE__ */ import_react186.default.createElement(SidebarProvider, { superstate - }, /* @__PURE__ */ import_react184.default.createElement(MainMenu, { + }, /* @__PURE__ */ import_react186.default.createElement(MainMenu, { superstate })) ); @@ -132060,7 +132432,7 @@ var replaceMobileMainMenu = (superstate) => { // src/adapters/obsidian/ui/editors/MDBFileViewer.tsx var import_obsidian12 = require("obsidian"); -var import_react185 = __toESM(require_react()); +var import_react187 = __toESM(require_react()); var MDB_FILE_VIEWER_TYPE = "make-mdb-viewer"; var MDBFileViewer = class extends import_obsidian12.FileView { constructor(leaf, plugin) { @@ -132112,7 +132484,7 @@ var MDBFileViewer = class extends import_obsidian12.FileView { this.root = this.plugin.ui.createRoot(this.contentEl); if (this.root) { this.root.render( - /* @__PURE__ */ import_react185.default.createElement(MDBViewer, { + /* @__PURE__ */ import_react187.default.createElement(MDBViewer, { superstate: this.plugin.superstate, space: space2, schema @@ -132132,7 +132504,7 @@ var MDBFileViewer = class extends import_obsidian12.FileView { // src/adapters/obsidian/ui/explorer/ContextExplorerLeafView.tsx var import_obsidian13 = require("obsidian"); -var import_react186 = __toESM(require_react()); +var import_react188 = __toESM(require_react()); var ContextExplorerLeafView = class extends import_obsidian13.ItemView { constructor(leaf, superstate, ui) { super(leaf); @@ -132173,7 +132545,7 @@ var ContextExplorerLeafView = class extends import_obsidian13.ItemView { this.root = this.ui.createRoot(this.contentEl); if (this.root) this.root.render( - /* @__PURE__ */ import_react186.default.createElement(Explorer, { + /* @__PURE__ */ import_react188.default.createElement(Explorer, { superstate: this.superstate }) ); @@ -132184,18 +132556,18 @@ var ICON2 = "component"; var VIEW_DISPLAY_TEXT2 = i18n_default.views.explorer; // src/adapters/obsidian/ui/editors/ReadingModeHeader.tsx -var import_react187 = __toESM(require_react()); +var import_react189 = __toESM(require_react()); var ReadingModeHeader = (props) => { - const [path2, setPath] = (0, import_react187.useState)(props.filePath); - const ref2 = (0, import_react187.useRef)(null); - (0, import_react187.useEffect)(() => { + const [path2, setPath] = (0, import_react189.useState)(props.filePath); + const ref2 = (0, import_react189.useRef)(null); + (0, import_react189.useEffect)(() => { setPath(props.filePath); }, [props.filePath]); const changeActiveFile = (path3) => { if (ref2.current.closest(".mod-active")) setPath(path3); }; - (0, import_react187.useEffect)(() => { + (0, import_react189.useEffect)(() => { props.superstate.ui.eventsDispatch.addListener( "activePathChanged", changeActiveFile @@ -132207,13 +132579,13 @@ var ReadingModeHeader = (props) => { ); }; }, []); - return /* @__PURE__ */ import_react187.default.createElement("div", { + return /* @__PURE__ */ import_react189.default.createElement("div", { ref: ref2 - }, /* @__PURE__ */ import_react187.default.createElement(PathProvider, { + }, /* @__PURE__ */ import_react189.default.createElement(PathProvider, { superstate: props.superstate, path: path2, readMode: true - }, /* @__PURE__ */ import_react187.default.createElement(MarkdownHeaderView, { + }, /* @__PURE__ */ import_react189.default.createElement(MarkdownHeaderView, { superstate: props.superstate, editable: false }))); @@ -132221,7 +132593,7 @@ var ReadingModeHeader = (props) => { // src/adapters/obsidian/utils/markdownPost.tsx var import_obsidian14 = require("obsidian"); -var import_react188 = __toESM(require_react()); +var import_react190 = __toESM(require_react()); var replaceInlineContext = (plugin, el, ctx) => { replaceMarkdownForReadingMode(el, async (dom) => { const element = dom.querySelector(".mod-header"); @@ -132247,7 +132619,7 @@ var replaceInlineContext = (plugin, el, ctx) => { const construct = (root2) => { if (ctx.sourcePath.match(urlRegex)) { root2.render( - /* @__PURE__ */ import_react188.default.createElement(RemoteMarkdownHeaderView, { + /* @__PURE__ */ import_react190.default.createElement(RemoteMarkdownHeaderView, { superstate: plugin.superstate, fm: ctx.frontmatter, name: pathToString(ctx.sourcePath) @@ -132255,7 +132627,7 @@ var replaceInlineContext = (plugin, el, ctx) => { ); } else { root2.render( - /* @__PURE__ */ import_react188.default.createElement(ReadingModeHeader, { + /* @__PURE__ */ import_react190.default.createElement(ReadingModeHeader, { superstate: plugin.superstate, filePath: ctx.sourcePath }) @@ -133390,7 +133762,7 @@ var patchWorkspace = (plugin) => { }; // src/adapters/obsidian/utils/flow/flow.tsx -var import_react189 = __toESM(require_react()); +var import_react191 = __toESM(require_react()); var modifyFlowDom = (plugin) => { if (!plugin.superstate.settings.makerMode || !plugin.superstate.settings.inlineContext || !plugin.app.workspace.activeEditor) return; @@ -133412,11 +133784,11 @@ var modifyFlowDom = (plugin) => { } const construct = (root2) => { root2.render( - /* @__PURE__ */ import_react189.default.createElement(PathProvider, { + /* @__PURE__ */ import_react191.default.createElement(PathProvider, { superstate: plugin.superstate, path: file.path, readMode: false - }, /* @__PURE__ */ import_react189.default.createElement(MarkdownHeaderView, { + }, /* @__PURE__ */ import_react191.default.createElement(MarkdownHeaderView, { superstate: plugin.superstate, editorView: editorView.cm, editable: true, @@ -133448,7 +133820,7 @@ var modifyFlowDom = (plugin) => { } const backlinksReactEl = plugin.ui.createRoot(backlinksEl); backlinksReactEl.render( - /* @__PURE__ */ import_react189.default.createElement(Backlinks, { + /* @__PURE__ */ import_react191.default.createElement(Backlinks, { superstate: plugin.superstate, path: file.path }) @@ -133662,7 +134034,9 @@ var replaceDB = (db, tables) => { } } catch (e5) { console.log(e5); + return false; } + return true; }; var saveZippedDBToPath = async (plugin, path2, tables) => { const sqlJS = await plugin.sqlJS(); @@ -133683,10 +134057,12 @@ var saveDBToPath = async (plugin, path2, tables) => { db.close(); return false; } - replaceDB(db, tables); - await saveDBFile(plugin, path2, db.export().buffer); + const result = replaceDB(db, tables); + if (result) { + await saveDBFile(plugin, path2, db.export().buffer); + } db.close(); - return true; + return result; }; // src/adapters/obsidian/filesystem/schemas/vaultSchema.ts @@ -135187,7 +135563,7 @@ var ObsidianMarkdownFiletypeAdapter = class { } } } - return; + return true; } async deleteContent(file, fragmentType, fragmentId) { if (fragmentType == "frontmatter" || fragmentType == "property") { @@ -135233,6 +135609,7 @@ var stickerFromString = (sticker, plugin) => { // src/adapters/obsidian/ui/editors/markdownView/menus/MakeMenu/MakeMenu.tsx var import_obsidian22 = require("obsidian"); +var import_react192 = __toESM(require_react()); // src/adapters/obsidian/ui/editors/markdownView/menus/MakeMenu/commands/default.ts var default_default2 = [ @@ -135276,19 +135653,8 @@ var default_default2 = [ value: ` --- `, - icon: "ui//mk-make-hr" - }, - { - label: "link", - value: "", - offset: [-1, 1], - icon: "ui//mk-make-link" - }, - { - label: "image", - value: "![](Paste Link)", - offset: [-1, 4], - icon: "ui//mk-make-image" + icon: "ui//mk-make-hr", + section: "Basic" }, { label: "codeblock", @@ -135307,22 +135673,42 @@ Type/Paste Your Code icon: "ui//mk-make-callout" }, { - label: "note", - value: "[[Note Name]]", - offset: [-2, 2], + label: "internal", + value: "link", icon: "ui//mk-make-note" }, { - label: "table", - value: "table", - icon: "ui//mk-make-table" + label: "link", + value: "", + offset: [-1, 1], + icon: "ui//mk-make-link" + }, + { + label: "image", + value: "image", + icon: "ui//mk-make-image" }, { label: "flow", - value: `!![[Note Name]]`, + value: `note`, offset: [-2, 4], icon: "ui//mk-make-flow" }, + { + label: "context", + value: "context", + icon: "ui//layout-list" + }, + { + label: "table", + value: "table", + icon: "ui//mk-make-table" + }, + { + label: "board", + value: "board", + icon: "ui//square-kanban" + }, { label: "tag", value: "#tag", @@ -135338,7 +135724,7 @@ function resolveCommands(plugin) { value: `![![${f2.path}#*${f2.id}]]`, icon: safelyParseJSON(f2.def)?.icon })); - return [...default_default2]; + return [...default_default2].map((f2) => ({ ...f2, type: 1 /* Command */ })); } // src/adapters/obsidian/ui/editors/markdownView/menus/MakeMenu/MakeMenu.tsx @@ -135380,7 +135766,14 @@ var MakeMenu = class extends import_obsidian22.EditorSuggest { const suggestions = resolveCommands(this.plugin).filter( ({ label }) => label.toLowerCase().includes(context.query.toLowerCase()) || i18n_default.commands[label] && i18n_default.commands[label].toLowerCase().includes(context.query.toLowerCase()) ); - return suggestions.length > 0 ? suggestions : [{ label: i18n_default.commandsSuggest.noResult, value: "", icon: "" }]; + return suggestions.length > 0 ? suggestions : [ + { + label: i18n_default.commandsSuggest.noResult, + value: "", + icon: "", + type: 0 /* None */ + } + ]; } renderSuggestion(value, el) { if (value.value == "") { @@ -135394,27 +135787,77 @@ var MakeMenu = class extends import_obsidian22.EditorSuggest { title.setText(i18n_default.commands[value.label] ?? value.label); } selectSuggestion(cmd, _evt) { + const start = this.context.start; + const end = this.context.end; + const startCh = this.cmdStartCh; + const editor = this.context.editor; if (cmd.label === i18n_default.commandsSuggest.noResult) return; - if (cmd.value == "table") { - createInlineTable(this.plugin.superstate, this.file.parent.path).then( - (f2) => { - this.context.editor.replaceRange( - contextEmbedStringFromContext( - this.plugin.superstate.spacesIndex.get(this.file.parent.path), - f2 - ), - { ...this.context.start, ch: this.cmdStartCh }, - this.context.end + if (cmd.value == "note") { + const offset2 = _evt.target.getBoundingClientRect(); + showLinkMenu(offset2, this.plugin.superstate, (link) => { + editor.replaceRange(`![![${link}]]`, { ...start, ch: startCh }, end); + this.resetInfos(); + this.close(); + }); + } else if (cmd.value == "context") { + const offset2 = _evt.target.getBoundingClientRect(); + showSpacesMenu(offset2, this.plugin.superstate, (link) => { + editor.replaceRange( + contextEmbedStringFromContext( + this.plugin.superstate.spacesIndex.get(link), + "files" + ), + { ...start, ch: startCh }, + end + ); + editor.setSelection({ + line: start.line, + ch: 0 + }); + this.resetInfos(); + this.close(); + }); + } else if (cmd.value == "link") { + const offset2 = _evt.target.getBoundingClientRect(); + showLinkMenu(offset2, this.plugin.superstate, (link) => { + editor.replaceRange(`[[${link}]]`, { ...start, ch: startCh }, end); + this.resetInfos(); + this.close(); + }); + } else if (cmd.value == "image") { + this.plugin.superstate.ui.openPalette((_props) => /* @__PURE__ */ import_react192.default.createElement(ImageModal_default, { + superstate: this.plugin.superstate, + hide: _props.hide, + selectedPath: (image) => { + editor.replaceRange( + `![[${image}]]`, + { ...start, ch: startCh }, + end ); - this.context.editor.setSelection({ - line: this.context.start.line, - ch: 0 - }); this.resetInfos(); this.close(); } - ); + })); + } else if (cmd.value == "table" || cmd.value == "board" || cmd.value == "calendar") { + createInlineTable( + this.plugin.superstate, + this.file.parent.path, + cmd.value + ).then((f2) => { + editor.replaceRange( + contextViewEmbedStringFromContext( + this.plugin.superstate.spacesIndex.get(this.file.parent.path), + f2 + ), + { ...start, ch: startCh }, + end + ); + editor.setSelection({ + line: start.line, + ch: 0 + }); + }); } else { this.context.editor.replaceRange( cmd.value, @@ -135438,7 +135881,7 @@ var MakeMenu = class extends import_obsidian22.EditorSuggest { // src/adapters/obsidian/ui/editors/markdownView/menus/StickerMenu.tsx var import_obsidian23 = require("obsidian"); -var import_react190 = __toESM(require_react()); +var import_react193 = __toESM(require_react()); // src/schemas/emoji.ts var emojis = { @@ -140885,7 +141328,7 @@ var StickerMenu = class extends import_obsidian23.EditorSuggest { div2.setAttribute("aria-label", value.label); const reactElement = this.plugin.ui.createRoot(div2); reactElement.render( - /* @__PURE__ */ import_react190.default.createElement(import_react190.default.Fragment, null, value.unicode.length > 0 ? emojiFromString(value.unicode) : i18n_default.commandsSuggest.noResult) + /* @__PURE__ */ import_react193.default.createElement(import_react193.default.Fragment, null, value.unicode.length > 0 ? emojiFromString(value.unicode) : i18n_default.commandsSuggest.noResult) ); el.appendChild(div2); } @@ -140916,7 +141359,7 @@ var registerEditorMenus = (plugin) => { // src/adapters/obsidian/ui/ui.tsx var import_obsidian25 = require("obsidian"); -var import_react197 = __toESM(require_react()); +var import_react200 = __toESM(require_react()); var import_client = __toESM(require_client()); // src/adapters/obsidian/utils/leaf.ts @@ -140978,17 +141421,17 @@ var modifyTabSticker = (plugin) => { }; // src/core/react/hooks/useInTreeCreateRoot.tsx -var import_react191 = __toESM(require_react()); +var import_react194 = __toESM(require_react()); var import_react_dom12 = __toESM(require_react_dom()); function useInTreeCreateRoot() { - const [roots, setRoots] = (0, import_react191.useState)(/* @__PURE__ */ new Map()); - const [rootMap, setRootMap] = (0, import_react191.useState)( + const [roots, setRoots] = (0, import_react194.useState)(/* @__PURE__ */ new Map()); + const [rootMap, setRootMap] = (0, import_react194.useState)( /* @__PURE__ */ new Map() ); const getRoot = (container) => { return rootMap.get(container); }; - const createRoot2 = (0, import_react191.useCallback)( + const createRoot2 = (0, import_react194.useCallback)( (container, options) => { const root = { render: (children) => { @@ -141021,7 +141464,7 @@ function useInTreeCreateRoot() { }, [] ); - const portals = (0, import_react191.useMemo)(() => { + const portals = (0, import_react194.useMemo)(() => { return [...roots.entries()].map(([container, root]) => { return (0, import_react_dom12.createPortal)(root, container); }); @@ -141030,7 +141473,7 @@ function useInTreeCreateRoot() { } // src/adapters/obsidian/ui/WindowManager.tsx -var import_react192 = __toESM(require_react()); +var import_react195 = __toESM(require_react()); var WindowManager = (props) => { const sensors = useSensors( useSensor(MouseSensor, { @@ -141049,13 +141492,13 @@ var WindowManager = (props) => { }) ); const { createRoot: createRoot2, portals, getRoot } = useInTreeCreateRoot(); - (0, import_react192.useEffect)(() => { + (0, import_react195.useEffect)(() => { props.ui.createRoot = createRoot2; props.ui.getRoot = getRoot; props.ui.manager.eventsDispatch.dispatchEvent("windowReady", null); }, [createRoot2]); - const [dragActive, setDragActive] = import_react192.default.useState(false); - return /* @__PURE__ */ import_react192.default.createElement(DndContext, { + const [dragActive, setDragActive] = import_react195.default.useState(false); + return /* @__PURE__ */ import_react195.default.createElement(DndContext, { sensors, onDragStart: () => { setDragActive(true); @@ -141073,13 +141516,13 @@ var WindowManager = (props) => { strategy: MeasuringStrategy.Always } } - }, /* @__PURE__ */ import_react192.default.createElement(WindowProvider, { + }, /* @__PURE__ */ import_react195.default.createElement(WindowProvider, { dragActive }, portals)); }; // src/core/react/components/UI/Modals/modalWrapper.tsx -var import_react193 = __toESM(require_react()); +var import_react196 = __toESM(require_react()); var ModalWrapper = (props) => { const { setNodeRef, isOver } = useDroppable({ id: "_modal", @@ -141092,26 +141535,26 @@ var ModalWrapper = (props) => { } } }); - return /* @__PURE__ */ import_react193.default.createElement("div", { + return /* @__PURE__ */ import_react196.default.createElement("div", { className: `mk-modal-container`, ref: setNodeRef - }, /* @__PURE__ */ import_react193.default.createElement(ModalInner, { + }, /* @__PURE__ */ import_react196.default.createElement(ModalInner, { ui: props.ui, hide: props.hide, className: props.className }, props.children)); }; var ModalInner = (props) => { - const ref2 = import_react193.default.useRef(null); + const ref2 = import_react196.default.useRef(null); const { setNodeRef, isOver } = useDroppable({ id: "_modalInner", data: { id: "_modalInner" } }); - const [isPending, startTransition] = (0, import_react193.useTransition)(); - (0, import_react193.useEffect)(() => { + const [isPending, startTransition] = (0, import_react196.useTransition)(); + (0, import_react196.useEffect)(() => { startTransition(() => null); }, []); - (0, import_react193.useEffect)(() => { + (0, import_react196.useEffect)(() => { const onKeyDown = (e5) => { if (e5.key == "Escape") { props.hide(); @@ -141146,7 +141589,7 @@ var ModalInner = (props) => { props.ui.inputManager.off("keydown", onKeyDown); }; }, [props.hide]); - return /* @__PURE__ */ import_react193.default.createElement("div", { + return /* @__PURE__ */ import_react196.default.createElement("div", { className: `${props.className}`, style: !isPending ? {} : {}, ref: (el) => { @@ -141157,7 +141600,7 @@ var ModalInner = (props) => { }; // src/adapters/obsidian/ui/modal.tsx -var import_react194 = __toESM(require_react()); +var import_react197 = __toESM(require_react()); var showModal = (props) => { const portalElement = document.createElement("div"); if (isTouchScreen(props.ui.manager)) { @@ -141180,21 +141623,21 @@ var showModal = (props) => { const hide = hideFunction(root); const updateRoot = (newProps) => { root.render( - /* @__PURE__ */ import_react194.default.createElement(ModalWrapper, { + /* @__PURE__ */ import_react197.default.createElement(ModalWrapper, { ui: props.ui.manager, hide: () => hide(), className: `${props.isPalette ? "mk-palette" : "mk-modal"} ${props.className ? props.className : ""}` - }, !props.isPalette && /* @__PURE__ */ import_react194.default.createElement("div", { + }, !props.isPalette && /* @__PURE__ */ import_react197.default.createElement("div", { className: "mk-modal-header" - }, props.title && /* @__PURE__ */ import_react194.default.createElement("div", { + }, props.title && /* @__PURE__ */ import_react197.default.createElement("div", { className: "mk-modal-title" - }, props.title), /* @__PURE__ */ import_react194.default.createElement("div", { + }, props.title), /* @__PURE__ */ import_react197.default.createElement("div", { className: "mk-x-small", dangerouslySetInnerHTML: { __html: props.ui.getSticker("ui//close") }, onClick: () => hide() - })), /* @__PURE__ */ import_react194.default.createElement(props.fc, { + })), /* @__PURE__ */ import_react197.default.createElement(props.fc, { hide: () => hide(), ...newProps })) @@ -141208,14 +141651,14 @@ var showModal = (props) => { }; // src/core/react/components/UI/Modals/HiddenFiles.tsx -var import_react195 = __toESM(require_react()); +var import_react198 = __toESM(require_react()); var HiddenPaths = (props) => { const { superstate } = props; - const ref2 = (0, import_react195.useRef)(null); - const [hiddenPaths, setHiddenPaths] = (0, import_react195.useState)( + const ref2 = (0, import_react198.useRef)(null); + const [hiddenPaths, setHiddenPaths] = (0, import_react198.useState)( superstate.settings.hiddenFiles ); - const [hiddenExtensions, setHiddenExtensions] = (0, import_react195.useState)( + const [hiddenExtensions, setHiddenExtensions] = (0, import_react198.useState)( superstate.settings.hiddenExtensions ); const saveExtension = (value) => { @@ -141256,7 +141699,7 @@ var HiddenPaths = (props) => { setHiddenPaths(superstate.settings.hiddenFiles); setHiddenExtensions(superstate.settings.hiddenExtensions); }; - (0, import_react195.useEffect)(() => { + (0, import_react198.useEffect)(() => { props.superstate.eventsDispatcher.addListener( "settingsChanged", settingsChanged @@ -141287,57 +141730,57 @@ var HiddenPaths = (props) => { searchable: true }); }; - return /* @__PURE__ */ import_react195.default.createElement("div", { + return /* @__PURE__ */ import_react198.default.createElement("div", { className: "modal-content" - }, /* @__PURE__ */ import_react195.default.createElement("div", { + }, /* @__PURE__ */ import_react198.default.createElement("div", { className: "setting-item setting-item-heading" - }, i18n_default.labels.hiddenFilePattern), /* @__PURE__ */ import_react195.default.createElement("div", { + }, i18n_default.labels.hiddenFilePattern), /* @__PURE__ */ import_react198.default.createElement("div", { className: "setting-item-description" - }, i18n_default.descriptions.hiddenFileOptions), /* @__PURE__ */ import_react195.default.createElement("div", null, hiddenExtensions.map((f2, index2) => /* @__PURE__ */ import_react195.default.createElement("div", { + }, i18n_default.descriptions.hiddenFileOptions), /* @__PURE__ */ import_react198.default.createElement("div", null, hiddenExtensions.map((f2, index2) => /* @__PURE__ */ import_react198.default.createElement("div", { key: index2, className: "mobile-option-setting-item" - }, /* @__PURE__ */ import_react195.default.createElement("span", { + }, /* @__PURE__ */ import_react198.default.createElement("span", { className: "mobile-option-setting-item-name" - }, f2), /* @__PURE__ */ import_react195.default.createElement("div", { + }, f2), /* @__PURE__ */ import_react198.default.createElement("div", { className: "clickable-icon mobile-option-setting-item-option-icon", "aria-label": i18n_default.buttons.delete, dangerouslySetInnerHTML: { __html: props.superstate.ui.getSticker("ui//close") }, onClick: () => removeExtension(index2) - })))), /* @__PURE__ */ import_react195.default.createElement("div", { + })))), /* @__PURE__ */ import_react198.default.createElement("div", { className: "setting-item" - }, /* @__PURE__ */ import_react195.default.createElement("input", { + }, /* @__PURE__ */ import_react198.default.createElement("input", { placeholder: i18n_default.labels.addExtension, type: "text", ref: ref2 - }), /* @__PURE__ */ import_react195.default.createElement("button", { + }), /* @__PURE__ */ import_react198.default.createElement("button", { onClick: (e5) => addExtension() - }, i18n_default.buttons.add)), /* @__PURE__ */ import_react195.default.createElement("div", { + }, i18n_default.buttons.add)), /* @__PURE__ */ import_react198.default.createElement("div", { className: "setting-item setting-item-heading" - }, i18n_default.subViews.filesAndFolders), /* @__PURE__ */ import_react195.default.createElement("div", { + }, i18n_default.subViews.filesAndFolders), /* @__PURE__ */ import_react198.default.createElement("div", { className: "setting-item-description" - }, i18n_default.labels.hiddenFileSpecific), /* @__PURE__ */ import_react195.default.createElement("div", null, hiddenPaths.map((f2, index2) => /* @__PURE__ */ import_react195.default.createElement("div", { + }, i18n_default.labels.hiddenFileSpecific), /* @__PURE__ */ import_react198.default.createElement("div", null, hiddenPaths.map((f2, index2) => /* @__PURE__ */ import_react198.default.createElement("div", { key: index2, className: "mobile-option-setting-item" - }, /* @__PURE__ */ import_react195.default.createElement("span", { + }, /* @__PURE__ */ import_react198.default.createElement("span", { className: "mobile-option-setting-item-name" - }, f2), /* @__PURE__ */ import_react195.default.createElement("div", { + }, f2), /* @__PURE__ */ import_react198.default.createElement("div", { className: "clickable-icon mobile-option-setting-item-option-icon", "aria-label": i18n_default.buttons.delete, dangerouslySetInnerHTML: { __html: props.superstate.ui.getSticker("ui//close") }, onClick: () => removeItem(index2) - })))), /* @__PURE__ */ import_react195.default.createElement("div", { + })))), /* @__PURE__ */ import_react198.default.createElement("div", { className: "setting-item" - }, /* @__PURE__ */ import_react195.default.createElement("button", { + }, /* @__PURE__ */ import_react198.default.createElement("button", { onClick: (e5) => addMenu(e5) }, "+ ", i18n_default.buttons.addFile))); }; // src/adapters/obsidian/ui/showMainMenu.tsx -var import_react196 = __toESM(require_react()); +var import_react199 = __toESM(require_react()); var showMainMenu = (el, superstate, app2) => { const toggleSections = (collapse) => { const spaces2 = superstate.waypoints[superstate.settings.currentWaypoint].paths; @@ -141383,7 +141826,7 @@ var showMainMenu = (el, superstate, app2) => { onClick: () => { superstate.ui.openModal( "Rename System", - (props) => /* @__PURE__ */ import_react196.default.createElement(InputModal, { + (props) => /* @__PURE__ */ import_react199.default.createElement(InputModal, { value: "", saveLabel: "Rename System", hide: props.hide, @@ -141401,7 +141844,7 @@ var showMainMenu = (el, superstate, app2) => { onClick: () => { superstate.ui.openModal( i18n_default.labels.hiddenFiles, - (props) => /* @__PURE__ */ import_react196.default.createElement(HiddenPaths, { + (props) => /* @__PURE__ */ import_react199.default.createElement(HiddenPaths, { superstate, close: props.hide }) @@ -141707,7 +142150,7 @@ var ObsidianUI = class { this.createRoot = () => null; this.getRoot = () => null; this.root = (0, import_client.createRoot)(newDiv); - this.root.render(/* @__PURE__ */ import_react197.default.createElement(WindowManager, { + this.root.render(/* @__PURE__ */ import_react200.default.createElement(WindowManager, { ui: this })); } @@ -141891,20 +142334,20 @@ var CLIManager = class { }; // src/core/react/components/Blink/Blink.tsx -var import_react199 = __toESM(require_react()); +var import_react202 = __toESM(require_react()); // src/core/react/components/Blink/BlinkComponent.tsx var import_lodash25 = __toESM(require_lodash()); -var import_react198 = __toESM(require_react()); +var import_react201 = __toESM(require_react()); var BlinkComponent = (props) => { - const [previewPath, setPreviewPath] = (0, import_react198.useState)(null); - const [query, setQuery] = (0, import_react198.useState)(""); - const [index2, setIndex] = (0, import_react198.useState)(0); + const [previewPath, setPreviewPath] = (0, import_react201.useState)(null); + const [query, setQuery] = (0, import_react201.useState)(""); + const [index2, setIndex] = (0, import_react201.useState)(0); const onChange = (query2) => { setQuery(query2); }; - const [filters, setFilters] = (0, import_react198.useState)([]); - const queries = (0, import_react198.useMemo)(() => { + const [filters, setFilters] = (0, import_react201.useState)([]); + const queries = (0, import_react201.useMemo)(() => { return query.length > 0 ? [ { type: "any", @@ -141922,25 +142365,8 @@ var BlinkComponent = (props) => { ...filters ] : filters; }, [query, filters]); - const [suggestions, setFilteredPaths] = (0, import_react198.useState)([]); - const saveQuerySpace = (e5) => { - showSpacesMenu( - e5, - props.superstate, - (link, isNew) => { - if (!isNew) { - saveSpaceMetadataValue(props.superstate, link, "filters", queries); - } else { - createSpace(props.superstate, link, { - filters: queries - }).then((f2) => props.superstate.ui.openPath(link, false)); - } - }, - false, - true - ); - }; - (0, import_react198.useEffect)(() => { + const [suggestions, setFilteredPaths] = (0, import_react201.useState)([]); + (0, import_react201.useEffect)(() => { const runQuery = (path2, _queries) => { props.superstate.searcher.run({ type: "search", @@ -141959,7 +142385,7 @@ var BlinkComponent = (props) => { }; (0, import_lodash25.debounce)(() => runQuery(query, queries), 300)(); }, [query, queries]); - (0, import_react198.useEffect)(() => { + (0, import_react201.useEffect)(() => { const path2 = suggestions[index2]?.value; if (!path2 || path2 == previewPath) return; @@ -142029,8 +142455,8 @@ var BlinkComponent = (props) => { suggestionActive: "mk-active", suggestionDisabled: "mk-disabled" }; - const ref2 = import_react198.default.useRef(null); - (0, import_react198.useEffect)(() => { + const ref2 = import_react201.default.useRef(null); + (0, import_react201.useEffect)(() => { ref2.current?.focus(); }, [ref2.current]); const metadataProperties = allMetadata(props.superstate); @@ -142046,36 +142472,36 @@ var BlinkComponent = (props) => { value: f2 }; }); - return /* @__PURE__ */ import_react198.default.createElement(import_react198.default.Fragment, null, /* @__PURE__ */ import_react198.default.createElement("div", { + return /* @__PURE__ */ import_react201.default.createElement(import_react201.default.Fragment, null, /* @__PURE__ */ import_react201.default.createElement("div", { className: "mk-blink-input" - }, /* @__PURE__ */ import_react198.default.createElement("div", { + }, /* @__PURE__ */ import_react201.default.createElement("div", { className: "mk-icon-small", dangerouslySetInnerHTML: { __html: props.superstate.ui.getSticker("ui//search") } - }), /* @__PURE__ */ import_react198.default.createElement("div", { + }), /* @__PURE__ */ import_react201.default.createElement("div", { "data-placeholder": i18n_default.labels.blinkPlaceholder, onInput: (e5) => onChange(e5.currentTarget.innerText), onKeyDown: (e5) => keyDown(e5), ref: ref2, contentEditable: true - })), /* @__PURE__ */ import_react198.default.createElement("div", { + })), /* @__PURE__ */ import_react201.default.createElement("div", { className: "mk-blink-filters" - }, /* @__PURE__ */ import_react198.default.createElement("div", { + }, /* @__PURE__ */ import_react201.default.createElement("div", { className: "mk-icon-xsmall", dangerouslySetInnerHTML: { __html: props.superstate.ui.getSticker("ui//filter") } - }), /* @__PURE__ */ import_react198.default.createElement(SpaceQuery, { + }), /* @__PURE__ */ import_react201.default.createElement(SpaceQuery, { superstate: props.superstate, filters, setFilters, fields: allOptions, sections: allSections - })), /* @__PURE__ */ import_react198.default.createElement("div", { + })), /* @__PURE__ */ import_react201.default.createElement("div", { className: `mk-blink-suggester`, style: {} - }, /* @__PURE__ */ import_react198.default.createElement(SelectMenuSuggestions_default, { + }, /* @__PURE__ */ import_react201.default.createElement(SelectMenuSuggestions_default, { expanded: false, addKeyword: "Create", options: suggestions, @@ -142090,44 +142516,44 @@ var BlinkComponent = (props) => { allowNew: false, ui: props.superstate.ui, isDisclosureMenu: false - }), /* @__PURE__ */ import_react198.default.createElement(BlinkPathWrapper, { + }), /* @__PURE__ */ import_react201.default.createElement(BlinkPathWrapper, { superstate: props.superstate, path: previewPath }))); }; var BlinkPathWrapper = (props) => { - const ref2 = import_react198.default.useRef(null); - const [showProperties, setShowProperties] = (0, import_react198.useState)(false); - return /* @__PURE__ */ import_react198.default.createElement("div", { + const ref2 = import_react201.default.useRef(null); + const [showProperties, setShowProperties] = (0, import_react201.useState)(false); + return /* @__PURE__ */ import_react201.default.createElement("div", { className: "mk-blink-preview", ref: ref2 - }, /* @__PURE__ */ import_react198.default.createElement("div", { + }, /* @__PURE__ */ import_react201.default.createElement("div", { className: "mk-blink-preview-title" - }, /* @__PURE__ */ import_react198.default.createElement(PathCrumb, { + }, /* @__PURE__ */ import_react201.default.createElement(PathCrumb, { superstate: props.superstate, path: props.path - }), /* @__PURE__ */ import_react198.default.createElement("span", null), /* @__PURE__ */ import_react198.default.createElement("button", { + }), /* @__PURE__ */ import_react201.default.createElement("span", null), /* @__PURE__ */ import_react201.default.createElement("button", { className: showProperties ? "is-active mk-icon-small" : "mk-icon-small", dangerouslySetInnerHTML: { __html: props.superstate.ui.getSticker("ui//list") }, onClick: () => setShowProperties(!showProperties) - })), /* @__PURE__ */ import_react198.default.createElement(PathView, { + })), /* @__PURE__ */ import_react201.default.createElement(PathView, { id: "blink", superstate: props.superstate, path: props.path, containerRef: ref2, styles: {}, readOnly: true - }), showProperties && /* @__PURE__ */ import_react198.default.createElement("div", { + }), showProperties && /* @__PURE__ */ import_react201.default.createElement("div", { className: "mk-blink-properties" - }, /* @__PURE__ */ import_react198.default.createElement("div", { + }, /* @__PURE__ */ import_react201.default.createElement("div", { className: "mk-blink-properties-header" - }, "Properties"), /* @__PURE__ */ import_react198.default.createElement(PathProvider, { + }, "Properties"), /* @__PURE__ */ import_react201.default.createElement(PathProvider, { path: props.path, superstate: props.superstate, readMode: false - }, /* @__PURE__ */ import_react198.default.createElement(ContextPropertiesView, { + }, /* @__PURE__ */ import_react201.default.createElement(ContextPropertiesView, { superstate: props.superstate, editable: false })))); @@ -142136,7 +142562,7 @@ var BlinkPathWrapper = (props) => { // src/core/react/components/Blink/Blink.tsx var openBlinkModal = (superstate) => { superstate.ui.openPalette( - (props) => /* @__PURE__ */ import_react199.default.createElement(BlinkComponent, { + (props) => /* @__PURE__ */ import_react202.default.createElement(BlinkComponent, { superstate, hide: props.hide }), @@ -142145,39 +142571,39 @@ var openBlinkModal = (superstate) => { }; // src/core/test/TestComponent.tsx -var import_react200 = __toESM(require_react()); +var import_react203 = __toESM(require_react()); var openTestModal = (superstate) => { - superstate.ui.openModal("Tests", (props) => /* @__PURE__ */ import_react200.default.createElement(TestComponent, { + superstate.ui.openModal("Tests", (props) => /* @__PURE__ */ import_react203.default.createElement(TestComponent, { superstate })); }; var TestInputComponent = (props) => { - const [value, setValue] = (0, import_react200.useState)(""); - return /* @__PURE__ */ import_react200.default.createElement("div", null, /* @__PURE__ */ import_react200.default.createElement("input", { + const [value, setValue] = (0, import_react203.useState)(""); + return /* @__PURE__ */ import_react203.default.createElement("div", null, /* @__PURE__ */ import_react203.default.createElement("input", { onChange: (e5) => setValue(e5.target.value) - }), /* @__PURE__ */ import_react200.default.createElement("button", { + }), /* @__PURE__ */ import_react203.default.createElement("button", { onClick: () => props.action(value) }, props.children)); }; var TestActionComponent = (props) => { - return /* @__PURE__ */ import_react200.default.createElement("div", null, /* @__PURE__ */ import_react200.default.createElement("button", { + return /* @__PURE__ */ import_react203.default.createElement("div", null, /* @__PURE__ */ import_react203.default.createElement("button", { onClick: () => props.action() }, props.children)); }; var TestToggleSection = (props) => { - const [expanded, setExpanded] = (0, import_react200.useState)(false); - return /* @__PURE__ */ import_react200.default.createElement("div", null, /* @__PURE__ */ import_react200.default.createElement("h2", { + const [expanded, setExpanded] = (0, import_react203.useState)(false); + return /* @__PURE__ */ import_react203.default.createElement("div", null, /* @__PURE__ */ import_react203.default.createElement("h2", { onClick: () => setExpanded((f2) => !f2) - }, props.section), expanded && /* @__PURE__ */ import_react200.default.createElement("div", null, props.children)); + }, props.section), expanded && /* @__PURE__ */ import_react203.default.createElement("div", null, props.children)); }; var TestComponent = (props) => { const { superstate } = props; - const [space2, setSpace] = (0, import_react200.useState)(null); - const [path2, setPath] = (0, import_react200.useState)(null); - const [sticker, setSticker] = (0, import_react200.useState)(null); - const [image, setImage] = (0, import_react200.useState)(null); - const [output, setOutput] = (0, import_react200.useState)(""); - (0, import_react200.useEffect)(() => { + const [space2, setSpace] = (0, import_react203.useState)(null); + const [path2, setPath] = (0, import_react203.useState)(null); + const [sticker, setSticker] = (0, import_react203.useState)(null); + const [image, setImage] = (0, import_react203.useState)(null); + const [output, setOutput] = (0, import_react203.useState)(""); + (0, import_react203.useEffect)(() => { superstate.eventsDispatcher.addListener( "spaceStateUpdated", (payload) => { @@ -142195,50 +142621,50 @@ var TestComponent = (props) => { } ); }, []); - return /* @__PURE__ */ import_react200.default.createElement("div", { + return /* @__PURE__ */ import_react203.default.createElement("div", { className: "mk-layout-row", style: { fontSize: "10px" } - }, /* @__PURE__ */ import_react200.default.createElement("div", null, /* @__PURE__ */ import_react200.default.createElement(TestInputComponent, { + }, /* @__PURE__ */ import_react203.default.createElement("div", null, /* @__PURE__ */ import_react203.default.createElement(TestInputComponent, { action: (value) => setOutput( JSON.stringify(superstate.spaceManager.uriByString(value)) ) - }, "URI"), /* @__PURE__ */ import_react200.default.createElement(TestToggleSection, { + }, "URI"), /* @__PURE__ */ import_react203.default.createElement(TestToggleSection, { section: "Space" - }, /* @__PURE__ */ import_react200.default.createElement(TestInputComponent, { + }, /* @__PURE__ */ import_react203.default.createElement(TestInputComponent, { action: (value) => setSpace(superstate.spacesIndex.get(value)) - }, "Select Space"), /* @__PURE__ */ import_react200.default.createElement("p", null, space2?.path ?? "No Selected Space", /* @__PURE__ */ import_react200.default.createElement("button", { + }, "Select Space"), /* @__PURE__ */ import_react203.default.createElement("p", null, space2?.path ?? "No Selected Space", /* @__PURE__ */ import_react203.default.createElement("button", { onClick: () => setSpace(superstate.spacesIndex.get(space2.path)) - }, "Refresh"), /* @__PURE__ */ import_react200.default.createElement("button", { + }, "Refresh"), /* @__PURE__ */ import_react203.default.createElement("button", { onClick: () => setPath(superstate.pathsIndex.get(space2.path)) - }, "Set Path")), space2 && /* @__PURE__ */ import_react200.default.createElement("div", null, "Contexts ", space2.contexts?.map((f2) => f2), superstate.getSpaceItems(space2.path).map((f2, i4) => /* @__PURE__ */ import_react200.default.createElement("div", { + }, "Set Path")), space2 && /* @__PURE__ */ import_react203.default.createElement("div", null, "Contexts ", space2.contexts?.map((f2) => f2), superstate.getSpaceItems(space2.path).map((f2, i4) => /* @__PURE__ */ import_react203.default.createElement("div", { key: i4 - }, f2.path, " ", /* @__PURE__ */ import_react200.default.createElement("button", { + }, f2.path, " ", /* @__PURE__ */ import_react203.default.createElement("button", { onClick: () => setSpace(superstate.spacesIndex.get(f2.path)) - }, "Set Space"), /* @__PURE__ */ import_react200.default.createElement("button", { + }, "Set Space"), /* @__PURE__ */ import_react203.default.createElement("button", { onClick: () => setPath(superstate.pathsIndex.get(f2.path)) - }, "Set Path"), /* @__PURE__ */ import_react200.default.createElement("button", { + }, "Set Path"), /* @__PURE__ */ import_react203.default.createElement("button", { onClick: () => navigator.clipboard.writeText(f2.path) - }, "Copy"))))), /* @__PURE__ */ import_react200.default.createElement(TestToggleSection, { + }, "Copy"))))), /* @__PURE__ */ import_react203.default.createElement(TestToggleSection, { section: "Path" - }, /* @__PURE__ */ import_react200.default.createElement(TestInputComponent, { + }, /* @__PURE__ */ import_react203.default.createElement(TestInputComponent, { action: (value) => setPath(superstate.pathsIndex.get(value)) - }, "Select Path"), /* @__PURE__ */ import_react200.default.createElement("p", null, path2?.path ?? "No Selected Path"), path2 && /* @__PURE__ */ import_react200.default.createElement("div", null, "Sticker", /* @__PURE__ */ import_react200.default.createElement("div", { + }, "Select Path"), /* @__PURE__ */ import_react203.default.createElement("p", null, path2?.path ?? "No Selected Path"), path2 && /* @__PURE__ */ import_react203.default.createElement("div", null, "Sticker", /* @__PURE__ */ import_react203.default.createElement("div", { dangerouslySetInnerHTML: { __html: superstate.ui.getSticker(path2?.label.sticker) }, style: { height: "50px", width: "50px" } - }), "Banner", /* @__PURE__ */ import_react200.default.createElement("img", { + }), "Banner", /* @__PURE__ */ import_react203.default.createElement("img", { src: superstate.ui.getUIPath(path2?.metadata.banner), style: { height: "50px", width: "50px" } - }))), /* @__PURE__ */ import_react200.default.createElement("h2", null, "Sticker"), /* @__PURE__ */ import_react200.default.createElement("div", { + }))), /* @__PURE__ */ import_react203.default.createElement("h2", null, "Sticker"), /* @__PURE__ */ import_react203.default.createElement("div", { dangerouslySetInnerHTML: { __html: superstate.ui.getSticker(sticker) }, style: { height: "50px", width: "50px" } - }), /* @__PURE__ */ import_react200.default.createElement("h2", null, "Image"), /* @__PURE__ */ import_react200.default.createElement("img", { + }), /* @__PURE__ */ import_react203.default.createElement("h2", null, "Image"), /* @__PURE__ */ import_react203.default.createElement("img", { src: superstate.ui.getUIPath(image), style: { height: "50px", width: "50px" } - }), /* @__PURE__ */ import_react200.default.createElement("h2", null, "Output"), /* @__PURE__ */ import_react200.default.createElement("div", null, output)), /* @__PURE__ */ import_react200.default.createElement("div", null, /* @__PURE__ */ import_react200.default.createElement(TestInputComponent, { + }), /* @__PURE__ */ import_react203.default.createElement("h2", null, "Output"), /* @__PURE__ */ import_react203.default.createElement("div", null, output)), /* @__PURE__ */ import_react203.default.createElement("div", null, /* @__PURE__ */ import_react203.default.createElement(TestInputComponent, { action: (value) => { try { parse3(value, { @@ -142249,56 +142675,56 @@ var TestComponent = (props) => { setOutput(e5); } } - }, "Acorn"), /* @__PURE__ */ import_react200.default.createElement(TestToggleSection, { + }, "Acorn"), /* @__PURE__ */ import_react203.default.createElement(TestToggleSection, { section: "Space" - }, /* @__PURE__ */ import_react200.default.createElement(TestInputComponent, { + }, /* @__PURE__ */ import_react203.default.createElement(TestInputComponent, { action: (value) => superstate.spaceManager.createSpace(value, space2.path, {}) - }, "Create Space"), /* @__PURE__ */ import_react200.default.createElement(TestInputComponent, { + }, "Create Space"), /* @__PURE__ */ import_react203.default.createElement(TestInputComponent, { action: (value) => superstate.spaceManager.renameSpace(space2.path, value) - }, "Rename Space"), /* @__PURE__ */ import_react200.default.createElement(TestInputComponent, { + }, "Rename Space"), /* @__PURE__ */ import_react203.default.createElement(TestInputComponent, { action: (value) => removeSpace(superstate, value) - }, "Delete Space"), /* @__PURE__ */ import_react200.default.createElement(TestInputComponent, { + }, "Delete Space"), /* @__PURE__ */ import_react203.default.createElement(TestInputComponent, { action: (value) => saveSpaceMetadataValue(props.superstate, space2.path, "contexts", [ value ]) - }, "Set Space Context"), /* @__PURE__ */ import_react200.default.createElement(TestInputComponent, { + }, "Set Space Context"), /* @__PURE__ */ import_react203.default.createElement(TestInputComponent, { action: (value) => removeSpace(superstate, value) - }, "Remove Space Context"), /* @__PURE__ */ import_react200.default.createElement(TestActionComponent, { + }, "Remove Space Context"), /* @__PURE__ */ import_react203.default.createElement(TestActionComponent, { action: () => savePathBanner(superstate, space2.path, image) - }, "Set Space Banner"), /* @__PURE__ */ import_react200.default.createElement(TestInputComponent, { + }, "Set Space Banner"), /* @__PURE__ */ import_react203.default.createElement(TestInputComponent, { action: (value) => updatePrimaryAlias(superstate, space2.path, [], value) - }, "Set Space Alias"), /* @__PURE__ */ import_react200.default.createElement(TestActionComponent, { + }, "Set Space Alias"), /* @__PURE__ */ import_react203.default.createElement(TestActionComponent, { action: () => savePathSticker(superstate, space2.path, sticker) - }, "Set Space Sticker")), /* @__PURE__ */ import_react200.default.createElement(TestToggleSection, { + }, "Set Space Sticker")), /* @__PURE__ */ import_react203.default.createElement(TestToggleSection, { section: "Path" - }, /* @__PURE__ */ import_react200.default.createElement(TestInputComponent, { + }, /* @__PURE__ */ import_react203.default.createElement(TestInputComponent, { action: (value) => newPathInSpace(superstate, space2, "md", value) - }, "Create Path"), /* @__PURE__ */ import_react200.default.createElement(TestInputComponent, { + }, "Create Path"), /* @__PURE__ */ import_react203.default.createElement(TestInputComponent, { action: (value) => superstate.spaceManager.copyPath(path2.path, value) - }, "Copy Path"), /* @__PURE__ */ import_react200.default.createElement(TestInputComponent, { + }, "Copy Path"), /* @__PURE__ */ import_react203.default.createElement(TestInputComponent, { action: (value) => superstate.spaceManager.renamePath( path2.path, movePath(path2.path, value) ) - }, "Move Path"), /* @__PURE__ */ import_react200.default.createElement(TestInputComponent, { + }, "Move Path"), /* @__PURE__ */ import_react203.default.createElement(TestInputComponent, { action: (value) => deletePath(superstate, value) - }, "Delete Path"), /* @__PURE__ */ import_react200.default.createElement(TestInputComponent, { + }, "Delete Path"), /* @__PURE__ */ import_react203.default.createElement(TestInputComponent, { action: (value) => pinPathToSpaceAtIndex(superstate, space2, value) - }, "Pin Path")), /* @__PURE__ */ import_react200.default.createElement(TestToggleSection, { + }, "Pin Path")), /* @__PURE__ */ import_react203.default.createElement(TestToggleSection, { section: "Modals" - }, /* @__PURE__ */ import_react200.default.createElement("button", { - onClick: () => superstate.ui.openPalette((props2) => /* @__PURE__ */ import_react200.default.createElement(ImageModal_default, { + }, /* @__PURE__ */ import_react203.default.createElement("button", { + onClick: () => superstate.ui.openPalette((props2) => /* @__PURE__ */ import_react203.default.createElement(ImageModal_default, { hide: props2.hide, superstate, selectedPath: (value) => setImage(value) })) - }, "Set Image"), /* @__PURE__ */ import_react200.default.createElement("button", { - onClick: () => superstate.ui.openPalette((props2) => /* @__PURE__ */ import_react200.default.createElement(StickerModal_default, { + }, "Set Image"), /* @__PURE__ */ import_react203.default.createElement("button", { + onClick: () => superstate.ui.openPalette((props2) => /* @__PURE__ */ import_react203.default.createElement(StickerModal_default, { hide: props2.hide, ui: superstate.ui, selectedSticker: (value) => setSticker(value) })) - }, "Set Sticker")), /* @__PURE__ */ import_react200.default.createElement("div", null, /* @__PURE__ */ import_react200.default.createElement("h2", null, "Menus")), /* @__PURE__ */ import_react200.default.createElement("div", null, /* @__PURE__ */ import_react200.default.createElement("h2", null, "Modals")))); + }, "Set Sticker")), /* @__PURE__ */ import_react203.default.createElement("div", null, /* @__PURE__ */ import_react203.default.createElement("h2", null, "Menus")), /* @__PURE__ */ import_react203.default.createElement("div", null, /* @__PURE__ */ import_react203.default.createElement("h2", null, "Modals")))); }; // src/adapters/image/imageAdapter.ts @@ -142564,9 +142990,9 @@ var installSpaceKit = async (plugin, superstate, kit, space2, isTemplate) => { }; // src/adapters/obsidian/ui/kit/InstallKitModal.tsx -var import_react201 = __toESM(require_react()); +var import_react204 = __toESM(require_react()); var installKitModal = (plugin, superstate, kit) => { - superstate.ui.openModal("Add Kit", (props) => /* @__PURE__ */ import_react201.default.createElement(InstallKit, { + superstate.ui.openModal("Add Kit", (props) => /* @__PURE__ */ import_react204.default.createElement(InstallKit, { plugin, superstate, hide: props.hide, @@ -142574,8 +143000,8 @@ var installKitModal = (plugin, superstate, kit) => { })); }; var InstallKit = (props) => { - const [kit, setKit] = (0, import_react201.useState)(props.kit); - const [space2, setSpace] = (0, import_react201.useState)("/"); + const [kit, setKit] = (0, import_react204.useState)(props.kit); + const [space2, setSpace] = (0, import_react204.useState)("/"); const installKit = () => { if (!kit.startsWith("https://www.make.md/static/kits/")) { props.superstate.ui.notify("Invalid Kit URL"); @@ -142598,258 +143024,37 @@ var InstallKit = (props) => { props.hide(); }); }; - return /* @__PURE__ */ import_react201.default.createElement("div", null, /* @__PURE__ */ import_react201.default.createElement("div", { + return /* @__PURE__ */ import_react204.default.createElement("div", null, /* @__PURE__ */ import_react204.default.createElement("div", { className: "setting-item" - }, /* @__PURE__ */ import_react201.default.createElement("div", { + }, /* @__PURE__ */ import_react204.default.createElement("div", { className: "setting-item-heading" - }, "Kit Location"), /* @__PURE__ */ import_react201.default.createElement("span", null), /* @__PURE__ */ import_react201.default.createElement("input", { + }, "Kit Location"), /* @__PURE__ */ import_react204.default.createElement("span", null), /* @__PURE__ */ import_react204.default.createElement("input", { type: "text", value: props.kit, onChange: (e5) => setKit(e5.target.value) - })), /* @__PURE__ */ import_react201.default.createElement("div", { + })), /* @__PURE__ */ import_react204.default.createElement("div", { className: "setting-item" - }, /* @__PURE__ */ import_react201.default.createElement("div", { + }, /* @__PURE__ */ import_react204.default.createElement("div", { className: "setting-item-heading" - }, "Add Kit to Space"), /* @__PURE__ */ import_react201.default.createElement("span", null), /* @__PURE__ */ import_react201.default.createElement(Dropdown2, { + }, "Add Kit to Space"), /* @__PURE__ */ import_react204.default.createElement("span", null), /* @__PURE__ */ import_react204.default.createElement(Dropdown2, { superstate: props.superstate, - triggerMenu: (e5) => showSpacesMenu(e5, props.superstate, (link) => setSpace(link)), + triggerMenu: (e5) => { + const offset2 = e5.target.getBoundingClientRect(); + showSpacesMenu(offset2, props.superstate, (link) => setSpace(link)); + }, value: props.superstate.spacesIndex.get(space2)?.name, selectValue: (value) => { setSpace(value); } - })), /* @__PURE__ */ import_react201.default.createElement("div", { + })), /* @__PURE__ */ import_react204.default.createElement("div", { className: "setting-item" - }, /* @__PURE__ */ import_react201.default.createElement("button", { + }, /* @__PURE__ */ import_react204.default.createElement("button", { onClick: () => installKit() - }, "Add"), /* @__PURE__ */ import_react201.default.createElement("button", { + }, "Add"), /* @__PURE__ */ import_react204.default.createElement("button", { onClick: props.hide }, "Cancel"))); }; -// src/core/spaceManager/webAdapter/webAdapter.ts -var WebSpaceAdapter = class { - constructor() { - this.schemes = ["http", "https"]; - } - initiateAdapter(manager) { - this.spaceManager = manager; - } - async readTemplates(path2) { - return []; - } - async saveTemplate(path2, space2) { - return null; - } - deleteTemplate(path2, space2) { - return; - } - async readWaypoints() { - return []; - } - async saveWaypoints(waypoints) { - return; - } - async readTemplate(name317) { - return; - } - async readAllKits() { - return []; - } - async readAllTemplates() { - return {}; - } - async readKitFrames(name317) { - return {}; - } - async saveFrameKit(frames, name317) { - return; - } - async saveSpaceTemplate(frames, name317) { - return; - } - async onMetadataChange(payload) { - return; - } - allPaths(type) { - return []; - } - async pathExists(path2) { - return true; - } - async createItemAtPath(parent, type, name317, content3) { - return null; - } - async renamePath(oldPath, path2) { - return; - } - async deletePath(path2) { - return; - } - async getPathInfo(path2) { - return {}; - } - keysForCacheType(path2) { - return null; - } - readPathCache(path2) { - return null; - } - async readPath(path2) { - return ""; - } - async copyPath(path2, newPath, newName) { - return; - } - async writeToPath(path2, content3, binary) { - return; - } - async childrenForPath(path2, type) { - return []; - } - parentPathForPath(path2) { - return null; - } - async readFrame(path2, schema) { - return null; - } - async readAllFrames(path2) { - return {}; - } - async readTable(path2, schema) { - return null; - } - async spaceInitiated(path2) { - return false; - } - async tablesForSpace(path2) { - return []; - } - async createTable(path2, schema) { - return; - } - async saveTableSchema(path2, schemaId, saveSchema) { - return; - } - async saveTable(path2, table, force) { - return; - } - async deleteTable(path2, name317) { - return; - } - async readAllTables(path2) { - return {}; - } - async framesForSpace(path2) { - return []; - } - async createFrame(path2, schema) { - return; - } - async deleteFrame(path2, name317) { - return; - } - async saveFrameSchema(path2, schemaId, saveSchema) { - return; - } - async saveFrame(path2, frame) { - return; - } - async commandsForSpace(path2) { - return []; - } - async runCommand(path2, name317, args) { - return null; - } - async createCommand(path2, schema) { - return; - } - async readSystemCommands() { - return []; - } - async readLibraryCommands(name317) { - return []; - } - async saveSystemCommand(lib, command) { - return; - } - async deleteCommand(path2, name317) { - return; - } - async saveCommand(path2, schemaId, saveCommand) { - return; - } - async contextForSpace(path2) { - return null; - } - async addSpaceProperty(path2, property) { - return; - } - async deleteSpaceProperty(path2, property) { - return; - } - async saveSpaceProperty(path2, property, oldProperty) { - return; - } - async addProperty(path2, property) { - return; - } - async readLabel(path2) { - return null; - } - async saveLabel(path2, label, value) { - } - async renameProperty(path2, property, newProperty) { - } - async readProperties(path2) { - return null; - } - async deleteProperty(path2, property) { - } - async saveProperties(path2, properties3) { - return; - } - allSpaces() { - return []; - } - readTags() { - return []; - } - spaceInfoForPath(path2) { - return fileSystemSpaceInfoByPath(this.spaceManager, path2); - } - allCaches() { - return /* @__PURE__ */ new Map(); - } - async spaceDefForSpace(path2) { - return {}; - } - async createSpace(name317, parentPath, definition) { - return; - } - async saveSpace(path2, definitionFn, properties3) { - return; - } - renameSpace(oldPath, newPath) { - } - deleteSpace(path2) { - } - childrenForSpace(path2) { - return []; - } - addTag(path2, tag2) { - } - renameTag(path2, tag2, newTag) { - } - deleteTag(path2, tag2) { - } - pathsForTag(tag2) { - return []; - } - resolvePath(path2, source) { - return path2; - } -}; - // src/main.ts var makeMDVersion = 0.9; var MakeMDPlugin = class extends import_obsidian29.Plugin { @@ -143302,11 +143507,10 @@ var MakeMDPlugin = class extends import_obsidian29.Plugin { this.files.initiateFiletypeAdapter(new ImageFileTypeAdapter(this)); this.files.initiateFiletypeAdapter(new IconFileTypeAdapter(this)); const filesystemCosmoform = new FilesystemSpaceAdapter(this.files); - const webSpaceAdapter = new WebSpaceAdapter(); this.ui = new ObsidianUI(this); const uiManager = UIManager2.create(this.ui); const commandsManager = CLIManager.create(new ObsidianCommands(this)); - this.superstate = Superstate2.create( + this.superstate = Superstate10.create( "0.9", () => { this.debouncedRefresh(); diff --git a/manifest.json b/manifest.json index 0ab8d3e..e3b506b 100755 --- a/manifest.json +++ b/manifest.json @@ -1,7 +1,7 @@ { "id": "make-md", "name": "MAKE.md", - "version": "0.9.28", + "version": "0.9.29", "minAppVersion": "0.16.0", "description": "Make.md brings powerful and modern note-taking features to Obsidian. Capture, organize and connect information with more flexibility without any code.", "author": "MAKE.md",