function _array_like_to_array(arr, len) {
    if (len == null || len > arr.length) len = arr.length;
    for(var i = 0, arr2 = new Array(len); i < len; i++)arr2[i] = arr[i];
    return arr2;
}
function _array_with_holes(arr) {
    if (Array.isArray(arr)) return arr;
}
function _define_property(obj, key, value) {
    if (key in obj) {
        Object.defineProperty(obj, key, {
            value: value,
            enumerable: true,
            configurable: true,
            writable: true
        });
    } else {
        obj[key] = value;
    }
    return obj;
}
function _iterable_to_array_limit(arr, i) {
    var _i = arr == null ? null : typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"];
    if (_i == null) return;
    var _arr = [];
    var _n = true;
    var _d = false;
    var _s, _e;
    try {
        for(_i = _i.call(arr); !(_n = (_s = _i.next()).done); _n = true){
            _arr.push(_s.value);
            if (i && _arr.length === i) break;
        }
    } catch (err) {
        _d = true;
        _e = err;
    } finally{
        try {
            if (!_n && _i["return"] != null) _i["return"]();
        } finally{
            if (_d) throw _e;
        }
    }
    return _arr;
}
function _non_iterable_rest() {
    throw new TypeError("Invalid attempt to destructure non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
}
function _object_spread(target) {
    for(var i = 1; i < arguments.length; i++){
        var source = arguments[i] != null ? arguments[i] : {};
        var ownKeys = Object.keys(source);
        if (typeof Object.getOwnPropertySymbols === "function") {
            ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function(sym) {
                return Object.getOwnPropertyDescriptor(source, sym).enumerable;
            }));
        }
        ownKeys.forEach(function(key) {
            _define_property(target, key, source[key]);
        });
    }
    return target;
}
function ownKeys(object, enumerableOnly) {
    var keys = Object.keys(object);
    if (Object.getOwnPropertySymbols) {
        var symbols = Object.getOwnPropertySymbols(object);
        if (enumerableOnly) {
            symbols = symbols.filter(function(sym) {
                return Object.getOwnPropertyDescriptor(object, sym).enumerable;
            });
        }
        keys.push.apply(keys, symbols);
    }
    return keys;
}
function _object_spread_props(target, source) {
    source = source != null ? source : {};
    if (Object.getOwnPropertyDescriptors) {
        Object.defineProperties(target, Object.getOwnPropertyDescriptors(source));
    } else {
        ownKeys(Object(source)).forEach(function(key) {
            Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key));
        });
    }
    return target;
}
function _object_without_properties(source, excluded) {
    if (source == null) return {};
    var target = {}, sourceKeys, key, i;
    if (typeof Reflect !== "undefined" && Reflect.ownKeys) {
        sourceKeys = Reflect.ownKeys(source);
        for(i = 0; i < sourceKeys.length; i++){
            key = sourceKeys[i];
            if (excluded.indexOf(key) >= 0) continue;
            if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue;
            target[key] = source[key];
        }
        return target;
    }
    target = _object_without_properties_loose(source, excluded);
    if (Object.getOwnPropertySymbols) {
        sourceKeys = Object.getOwnPropertySymbols(source);
        for(i = 0; i < sourceKeys.length; i++){
            key = sourceKeys[i];
            if (excluded.indexOf(key) >= 0) continue;
            if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue;
            target[key] = source[key];
        }
    }
    return target;
}
function _object_without_properties_loose(source, excluded) {
    if (source == null) return {};
    var target = {}, sourceKeys = Object.getOwnPropertyNames(source), key, i;
    for(i = 0; i < sourceKeys.length; i++){
        key = sourceKeys[i];
        if (excluded.indexOf(key) >= 0) continue;
        if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue;
        target[key] = source[key];
    }
    return target;
}
function _sliced_to_array(arr, i) {
    return _array_with_holes(arr) || _iterable_to_array_limit(arr, i) || _unsupported_iterable_to_array(arr, i) || _non_iterable_rest();
}
function _type_of(obj) {
    "@swc/helpers - typeof";
    return obj && typeof Symbol !== "undefined" && obj.constructor === Symbol ? "symbol" : typeof obj;
}
function _unsupported_iterable_to_array(o, minLen) {
    if (!o) return;
    if (typeof o === "string") return _array_like_to_array(o, minLen);
    var n = Object.prototype.toString.call(o).slice(8, -1);
    if (n === "Object" && o.constructor) n = o.constructor.name;
    if (n === "Map" || n === "Set") return Array.from(n);
    if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _array_like_to_array(o, minLen);
}
import { Editor, Element, Node, Text, Transforms } from "slate";
import { HistoryEditor } from "slate-history";
import { EditorUtils } from "../utils/editorUtils";
var isValidChild = function isValidChild(child) {
    return child !== undefined && child !== null && Node.isNode(child);
};
/**
 * `Array.prototype.some` skips sparse holes; Slate still sees missing indices and
 * can pass `undefined` as `leaf` into `renderLeaf`, which then throws in `Text.isText`.
 */ var childArrayHasInvalidEntries = function childArrayHasInvalidEntries(rawChildren) {
    for(var i = 0; i < rawChildren.length; i += 1){
        if (!(i in rawChildren) || !isValidChild(rawChildren[i])) {
            return true;
        }
    }
    return false;
};
var getChildList = function getChildList(node) {
    if (!('children' in node)) {
        return [];
    }
    var children = node.children;
    return Array.isArray(children) ? children : [];
};
var createDefaultBlock = function createDefaultBlock() {
    return {
        type: 'paragraph',
        children: [
            {
                text: ''
            }
        ]
    };
};
var rebuildElement = function rebuildElement(node) {
    var children = getChildList(node).filter(isValidChild);
    if (children.length === 0 && 'type' in node && node.type) {
        children = [
            {
                text: ''
            }
        ];
    }
    var _drop = node.children, rest = _object_without_properties(node, [
        "children"
    ]);
    return _object_spread_props(_object_spread({}, rest), {
        children: children
    });
};
var runWithoutHistory = function runWithoutHistory(editor, fn) {
    if (HistoryEditor.isHistoryEditor(editor)) {
        HistoryEditor.withoutSaving(editor, fn);
    } else {
        fn();
    }
};
/**
 * Slate 的 `Node.nodes` / `Editor.normalize` 在遍历时假定非文本节点必有数组型 `children`。
 * 若仅有 `type` 而缺少 `children`，会在进入自定义 `normalizeNode` 之前就抛错，必须先修树。
 */ var rebuildOrDefaultBlock = function rebuildOrDefaultBlock(raw) {
    if (raw && (typeof raw === "undefined" ? "undefined" : _type_of(raw)) === 'object' && !Text.isText(raw) && typeof raw.type === 'string') {
        return rebuildElement(raw);
    }
    return createDefaultBlock();
};
/** 压缩根级子节点：去掉空洞与 null/undefined；残缺元素对象则 rebuild，不凭空多插空段落。 */ var compactEditorRootChildren = function compactEditorRootChildren(raw) {
    var out = [];
    for(var i = 0; i < raw.length; i += 1){
        if (!(i in raw)) {
            continue;
        }
        var c = raw[i];
        if (isValidChild(c)) {
            out.push(c);
            continue;
        }
        if (c === undefined || c === null) {
            continue;
        }
        out.push(rebuildOrDefaultBlock(c));
    }
    return out;
};
var repairBrokenChildArrays = function repairBrokenChildArrays(editor) {
    if (!Array.isArray(editor.children)) {
        /* eslint-disable no-param-reassign */ editor.children = [
            createDefaultBlock()
        ];
        /* eslint-enable no-param-reassign */ return true;
    }
    if (editor.children.length === 0) {
        EditorUtils.replaceEditorContent(editor, [
            createDefaultBlock()
        ]);
        return true;
    }
    if (childArrayHasInvalidEntries(editor.children)) {
        var fixedRoot = compactEditorRootChildren(editor.children);
        if (fixedRoot.length === 0) {
            EditorUtils.replaceEditorContent(editor, [
                createDefaultBlock()
            ]);
        } else {
            /* eslint-disable no-param-reassign */ editor.children = fixedRoot;
        /* eslint-enable no-param-reassign */ }
        return true;
    }
    var fixBranch = function fixBranch1(node) {
        if (!node || (typeof node === "undefined" ? "undefined" : _type_of(node)) !== 'object') {
            return false;
        }
        if (Text.isText(node)) {
            if ('children' in node) {
                delete node.children;
                return true;
            }
            return false;
        }
        var rawChildren = node.children;
        if (!Array.isArray(rawChildren)) {
            Object.assign(node, rebuildElement(node));
            return true;
        }
        if (childArrayHasInvalidEntries(rawChildren)) {
            var fixedChildren = rawChildren.filter(isValidChild);
            node.children = fixedChildren.length === 0 ? [
                {
                    text: ''
                }
            ] : fixedChildren;
            return true;
        }
        for(var i = 0; i < rawChildren.length; i++){
            if (fixBranch(rawChildren[i])) {
                return true;
            }
        }
        return false;
    };
    for(var i = 0; i < editor.children.length; i++){
        if (fixBranch(editor.children[i])) {
            return true;
        }
    }
    return false;
};
/**
 * 外部或合并后的 value 可能在 `children` 中混入 `undefined` / `null`；
 * Slate 的 `Node.string` 会对每个子节点调用 `Text.isText`，遇 `undefined` 即抛错。
 * 在 normalize 最外层剔除非法子节点，避免编辑器与 toMarkdown 崩溃。
 */ export var withSanitizeInvalidChildren = function withSanitizeInvalidChildren(editor) {
    var normalizeNode = editor.normalizeNode, normalize = editor.normalize;
    editor.normalize = function(options) {
        // 与 Slate 默认 `normalize` 一致：在 `withoutNormalizing` 嵌套批次末尾仍会调用
        // `Editor.normalize`，此时 `isNormalizing` 为 false，文档可能短暂为空（合法中间态）。
        // 若在此处 `repairBrokenChildArrays` 强行插入默认块，会与后续 `insertNodes` 叠成双段落。
        if (Editor.isNormalizing(editor)) {
            var guard = 0;
            while(guard < 100 && repairBrokenChildArrays(editor)){
                guard += 1;
            }
        }
        return normalize.call(editor, options);
    };
    editor.normalizeNode = function(entry) {
        var _entry = _sliced_to_array(entry, 2), node = _entry[0], path = _entry[1];
        // Text leaves have no `children`; also strip invalid `children` on text (Slate may treat as element).
        if (Text.isText(node)) {
            if ('children' in node) {
                delete node.children;
            }
            normalizeNode(entry);
            return;
        }
        if (Editor.isEditor(node) && path.length === 0) {
            var childList = getChildList(node);
            var hasInvalid = childArrayHasInvalidEntries(childList);
            if (hasInvalid || childList.length === 0) {
                var fixedTop = compactEditorRootChildren(childList);
                var nextNodes = fixedTop.length === 0 ? [
                    createDefaultBlock()
                ] : fixedTop;
                EditorUtils.replaceEditorContent(editor, nextNodes);
                normalizeNode(entry);
                return;
            }
            // 清空后 Slate 规范化可能再插一个空段，根上出现多个仅空文本的 paragraph；
            // 与 replaceEditorContent 已插入的一块叠成双 DOM（见 debug H6）。
            var validTop = childList.filter(isValidChild);
            if (validTop.length > 1) {
                var collapsed = EditorUtils.coalesceRootAllEmptyParagraphs(validTop);
                if (collapsed.length < validTop.length) {
                    EditorUtils.replaceEditorContent(editor, collapsed);
                    normalizeNode(entry);
                    return;
                }
            }
            normalizeNode(entry);
            return;
        }
        if (!Editor.isEditor(node) && !Text.isText(node)) {
            var rawChildren = node.children;
            if (!Array.isArray(rawChildren)) {
                Object.assign(node, rebuildElement(node));
                normalizeNode(entry);
                return;
            }
        }
        if (Element.isElement(node)) {
            var childList1 = getChildList(node);
            var hasInvalid1 = childArrayHasInvalidEntries(childList1);
            if (hasInvalid1) {
                var applyRebuild = function applyRebuild() {
                    Editor.withoutNormalizing(editor, function() {
                        var rebuilt = rebuildElement(node);
                        Transforms.removeNodes(editor, {
                            at: path,
                            voids: true
                        });
                        Transforms.insertNodes(editor, rebuilt, {
                            at: path,
                            voids: true
                        });
                    });
                };
                runWithoutHistory(editor, applyRebuild);
                return;
            }
        }
        normalizeNode(entry);
    };
    return editor;
};
