{
  "version": 3,
  "sources": ["../../apps/still-editor/node_modules/@tiptap/core/dist/rolldown-runtime-D7D4PA-g.js", "../../apps/still-editor/node_modules/orderedmap/dist/index.js", "../../apps/still-editor/node_modules/prosemirror-model/dist/index.js", "../../apps/still-editor/node_modules/prosemirror-transform/dist/index.js", "../../apps/still-editor/node_modules/prosemirror-state/dist/index.js", "../../apps/still-editor/node_modules/prosemirror-commands/dist/index.js", "../../apps/still-editor/node_modules/prosemirror-schema-list/dist/index.js", "../../apps/still-editor/node_modules/prosemirror-view/dist/index.js", "../../apps/still-editor/node_modules/w3c-keyname/index.js", "../../apps/still-editor/node_modules/prosemirror-keymap/dist/index.js", "../../apps/still-editor/node_modules/rope-sequence/dist/index.js", "../../apps/still-editor/node_modules/prosemirror-history/dist/index.js", "../../apps/still-editor/node_modules/@tiptap/core/src/helpers/createChainableState.ts", "../../apps/still-editor/node_modules/@tiptap/core/src/CommandManager.ts", "../../apps/still-editor/node_modules/@tiptap/core/src/commands/blur.ts", "../../apps/still-editor/node_modules/@tiptap/core/src/commands/clearContent.ts", "../../apps/still-editor/node_modules/@tiptap/core/src/commands/clearNodes.ts", "../../apps/still-editor/node_modules/@tiptap/core/src/commands/command.ts", "../../apps/still-editor/node_modules/@tiptap/core/src/commands/createParagraphNear.ts", "../../apps/still-editor/node_modules/@tiptap/core/src/commands/cut.ts", "../../apps/still-editor/node_modules/@tiptap/core/src/commands/deleteCurrentNode.ts", "../../apps/still-editor/node_modules/@tiptap/core/src/helpers/getNodeType.ts", "../../apps/still-editor/node_modules/@tiptap/core/src/commands/deleteNode.ts", "../../apps/still-editor/node_modules/@tiptap/core/src/commands/deleteRange.ts", "../../apps/still-editor/node_modules/@tiptap/core/src/commands/deleteSelection.ts", "../../apps/still-editor/node_modules/@tiptap/core/src/commands/enter.ts", "../../apps/still-editor/node_modules/@tiptap/core/src/commands/exitCode.ts", "../../apps/still-editor/node_modules/@tiptap/core/src/utilities/isRegExp.ts", "../../apps/still-editor/node_modules/@tiptap/core/src/utilities/objectIncludes.ts", "../../apps/still-editor/node_modules/@tiptap/core/src/helpers/getMarkRange.ts", "../../apps/still-editor/node_modules/@tiptap/core/src/helpers/getMarkType.ts", "../../apps/still-editor/node_modules/@tiptap/core/src/commands/extendMarkRange.ts", "../../apps/still-editor/node_modules/@tiptap/core/src/commands/first.ts", "../../apps/still-editor/node_modules/@tiptap/core/src/helpers/isTextSelection.ts", "../../apps/still-editor/node_modules/@tiptap/core/src/utilities/minMax.ts", "../../apps/still-editor/node_modules/@tiptap/core/src/helpers/resolveFocusPosition.ts", "../../apps/still-editor/node_modules/@tiptap/core/src/utilities/isAndroid.ts", "../../apps/still-editor/node_modules/@tiptap/core/src/utilities/isiOS.ts", "../../apps/still-editor/node_modules/@tiptap/core/src/utilities/isSafari.ts", "../../apps/still-editor/node_modules/@tiptap/core/src/commands/focus.ts", "../../apps/still-editor/node_modules/@tiptap/core/src/commands/forEach.ts", "../../apps/still-editor/node_modules/@tiptap/core/src/commands/insertContent.ts", "../../apps/still-editor/node_modules/@tiptap/core/src/utilities/elementFromString.ts", "../../apps/still-editor/node_modules/@tiptap/core/src/helpers/isProseMirrorContent.ts", "../../apps/still-editor/node_modules/@tiptap/core/src/helpers/createNodeFromContent.ts", "../../apps/still-editor/node_modules/@tiptap/core/src/helpers/isFragment.ts", "../../apps/still-editor/node_modules/@tiptap/core/src/helpers/selectionToInsertionEnd.ts", "../../apps/still-editor/node_modules/@tiptap/core/src/commands/insertContentAt.ts", "../../apps/still-editor/node_modules/@tiptap/core/src/helpers/defaultBlockAt.ts", "../../apps/still-editor/node_modules/@tiptap/core/src/commands/insertDefaultBlock.ts", "../../apps/still-editor/node_modules/@tiptap/core/src/commands/join.ts", "../../apps/still-editor/node_modules/@tiptap/core/src/commands/canJoinItemsAt.ts", "../../apps/still-editor/node_modules/@tiptap/core/src/commands/joinItemBackward.ts", "../../apps/still-editor/node_modules/@tiptap/core/src/commands/joinItemForward.ts", "../../apps/still-editor/node_modules/@tiptap/core/src/commands/joinTextblockBackward.ts", "../../apps/still-editor/node_modules/@tiptap/core/src/commands/joinTextblockForward.ts", "../../apps/still-editor/node_modules/@tiptap/core/src/utilities/isMacOS.ts", "../../apps/still-editor/node_modules/@tiptap/core/src/commands/keyboardShortcut.ts", "../../apps/still-editor/node_modules/@tiptap/core/src/helpers/isNodeActive.ts", "../../apps/still-editor/node_modules/@tiptap/core/src/commands/lift.ts", "../../apps/still-editor/node_modules/@tiptap/core/src/commands/liftEmptyBlock.ts", "../../apps/still-editor/node_modules/@tiptap/core/src/commands/liftListItem.ts", "../../apps/still-editor/node_modules/@tiptap/core/src/commands/newlineInCode.ts", "../../apps/still-editor/node_modules/@tiptap/core/src/helpers/getSchemaTypeNameByName.ts", "../../apps/still-editor/node_modules/@tiptap/core/src/utilities/deleteProps.ts", "../../apps/still-editor/node_modules/@tiptap/core/src/commands/resetAttributes.ts", "../../apps/still-editor/node_modules/@tiptap/core/src/commands/scrollIntoView.ts", "../../apps/still-editor/node_modules/@tiptap/core/src/commands/selectAll.ts", "../../apps/still-editor/node_modules/@tiptap/core/src/commands/selectNodeBackward.ts", "../../apps/still-editor/node_modules/@tiptap/core/src/commands/selectNodeForward.ts", "../../apps/still-editor/node_modules/@tiptap/core/src/commands/selectParentNode.ts", "../../apps/still-editor/node_modules/@tiptap/core/src/commands/selectTextblockEnd.ts", "../../apps/still-editor/node_modules/@tiptap/core/src/commands/selectTextblockStart.ts", "../../apps/still-editor/node_modules/@tiptap/core/src/helpers/createDocument.ts", "../../apps/still-editor/node_modules/@tiptap/core/src/commands/setContent.ts", "../../apps/still-editor/node_modules/@tiptap/core/src/helpers/getMarkAttributes.ts", "../../apps/still-editor/node_modules/@tiptap/core/src/helpers/combineTransactionSteps.ts", "../../apps/still-editor/node_modules/@tiptap/core/src/helpers/findChildren.ts", "../../apps/still-editor/node_modules/@tiptap/core/src/helpers/findChildrenInRange.ts", "../../apps/still-editor/node_modules/@tiptap/core/src/helpers/findParentNodeClosestToPos.ts", "../../apps/still-editor/node_modules/@tiptap/core/src/helpers/findParentNode.ts", "../../apps/still-editor/node_modules/@tiptap/core/src/helpers/getExtensionField.ts", "../../apps/still-editor/node_modules/@tiptap/core/src/helpers/flattenExtensions.ts", "../../apps/still-editor/node_modules/@tiptap/core/src/helpers/getHTMLFromFragment.ts", "../../apps/still-editor/node_modules/@tiptap/core/src/schema/getSchemaAttributes.ts", "../../apps/still-editor/node_modules/@tiptap/core/src/schema/schemaSpecFields.ts", "../../apps/still-editor/node_modules/@tiptap/core/src/schema/mergeSchemaSpec.ts", "../../apps/still-editor/node_modules/@tiptap/core/src/utilities/findDuplicates.ts", "../../apps/still-editor/node_modules/@tiptap/core/src/helpers/splitExtensions.ts", "../../apps/still-editor/node_modules/@tiptap/core/src/helpers/getAttributesFromExtensions.ts", "../../apps/still-editor/node_modules/@tiptap/core/src/utilities/isFunction.ts", "../../apps/still-editor/node_modules/@tiptap/core/src/utilities/callOrReturn.ts", "../../apps/still-editor/node_modules/@tiptap/core/src/utilities/isEmptyObject.ts", "../../apps/still-editor/node_modules/@tiptap/core/src/utilities/mergeAttributes.ts", "../../apps/still-editor/node_modules/@tiptap/core/src/helpers/getRenderedAttributes.ts", "../../apps/still-editor/node_modules/@tiptap/core/src/utilities/fromString.ts", "../../apps/still-editor/node_modules/@tiptap/core/src/helpers/injectExtensionAttributesToParseRule.ts", "../../apps/still-editor/node_modules/@tiptap/core/src/helpers/getSchemaSpecByResolvedExtensions.ts", "../../apps/still-editor/node_modules/@tiptap/core/src/helpers/getSchemaByResolvedExtensions.ts", "../../apps/still-editor/node_modules/@tiptap/core/src/helpers/sortExtensions.ts", "../../apps/still-editor/node_modules/@tiptap/core/src/helpers/resolveExtensions.ts", "../../apps/still-editor/node_modules/@tiptap/core/src/helpers/getSchema.ts", "../../apps/still-editor/node_modules/@tiptap/core/src/helpers/generateHTML.ts", "../../apps/still-editor/node_modules/@tiptap/core/src/helpers/generateJSON.ts", "../../apps/still-editor/node_modules/@tiptap/core/src/helpers/getTextBetween.ts", "../../apps/still-editor/node_modules/@tiptap/core/src/helpers/getText.ts", "../../apps/still-editor/node_modules/@tiptap/core/src/helpers/getTextSerializersFromSchema.ts", "../../apps/still-editor/node_modules/@tiptap/core/src/helpers/generateText.ts", "../../apps/still-editor/node_modules/@tiptap/core/src/helpers/getNodeAttributes.ts", "../../apps/still-editor/node_modules/@tiptap/core/src/helpers/getAttributes.ts", "../../apps/still-editor/node_modules/@tiptap/core/src/utilities/removeDuplicates.ts", "../../apps/still-editor/node_modules/@tiptap/core/src/helpers/getChangedRanges.ts", "../../apps/still-editor/node_modules/@tiptap/core/src/helpers/getDebugJSON.ts", "../../apps/still-editor/node_modules/@tiptap/core/src/helpers/getMarksBetween.ts", "../../apps/still-editor/node_modules/@tiptap/core/src/helpers/getNodeAtPosition.ts", "../../apps/still-editor/node_modules/@tiptap/core/src/helpers/getPreviousBlockSibling.ts", "../../apps/still-editor/node_modules/@tiptap/core/src/helpers/getSchemaTypeByName.ts", "../../apps/still-editor/node_modules/@tiptap/core/src/helpers/getSplittedAttributes.ts", "../../apps/still-editor/node_modules/@tiptap/core/src/helpers/getTextContentFromNodes.ts", "../../apps/still-editor/node_modules/@tiptap/core/src/helpers/isMarkActive.ts", "../../apps/still-editor/node_modules/@tiptap/core/src/helpers/isActive.ts", "../../apps/still-editor/node_modules/@tiptap/core/src/helpers/isAtEndOfNode.ts", "../../apps/still-editor/node_modules/@tiptap/core/src/helpers/isAtStartOfNode.ts", "../../apps/still-editor/node_modules/@tiptap/core/src/helpers/isExtensionRulesEnabled.ts", "../../apps/still-editor/node_modules/@tiptap/core/src/helpers/isList.ts", "../../apps/still-editor/node_modules/@tiptap/core/src/helpers/isNodeEmpty.ts", "../../apps/still-editor/node_modules/@tiptap/core/src/helpers/isNodeSelection.ts", "../../apps/still-editor/node_modules/@tiptap/core/src/helpers/isNodeViewSelected.ts", "../../apps/still-editor/node_modules/@tiptap/core/src/helpers/isProseMirrorStep.ts", "../../apps/still-editor/node_modules/@tiptap/core/src/helpers/isProseMirrorAddMarkStep.ts", "../../apps/still-editor/node_modules/@tiptap/core/src/helpers/isProseMirrorAddNodeMarkStep.ts", "../../apps/still-editor/node_modules/@tiptap/core/src/helpers/isProseMirrorAttrStep.ts", "../../apps/still-editor/node_modules/@tiptap/core/src/helpers/isProseMirrorCellSelection.ts", "../../apps/still-editor/node_modules/@tiptap/core/src/helpers/isProseMirrorDocAttrStep.ts", "../../apps/still-editor/node_modules/@tiptap/core/src/helpers/isProseMirrorFragment.ts", "../../apps/still-editor/node_modules/@tiptap/core/src/helpers/isProseMirrorNodeSelection.ts", "../../apps/still-editor/node_modules/@tiptap/core/src/helpers/isProseMirrorRemoveMarkStep.ts", "../../apps/still-editor/node_modules/@tiptap/core/src/helpers/isProseMirrorRemoveNodeMarkStep.ts", "../../apps/still-editor/node_modules/@tiptap/core/src/helpers/isProseMirrorReplaceAroundStep.ts", "../../apps/still-editor/node_modules/@tiptap/core/src/helpers/isProseMirrorReplaceStep.ts", "../../apps/still-editor/node_modules/@tiptap/core/src/helpers/isProseMirrorSlice.ts", "../../apps/still-editor/node_modules/@tiptap/core/src/helpers/isProseMirrorStepResult.ts", "../../apps/still-editor/node_modules/@tiptap/core/src/helpers/MappablePosition.ts", "../../apps/still-editor/node_modules/@tiptap/core/src/helpers/posToDOMRect.ts", "../../apps/still-editor/node_modules/@tiptap/core/src/helpers/rewriteUnknownContent.ts", "../../apps/still-editor/node_modules/@tiptap/core/src/commands/setMark.ts", "../../apps/still-editor/node_modules/@tiptap/core/src/commands/setMeta.ts", "../../apps/still-editor/node_modules/@tiptap/core/src/commands/setNode.ts", "../../apps/still-editor/node_modules/@tiptap/core/src/commands/setNodeSelection.ts", "../../apps/still-editor/node_modules/@tiptap/core/src/commands/setTextDirection.ts", "../../apps/still-editor/node_modules/@tiptap/core/src/commands/setTextSelection.ts", "../../apps/still-editor/node_modules/@tiptap/core/src/commands/sinkListItem.ts", "../../apps/still-editor/node_modules/@tiptap/core/src/commands/splitBlock.ts", "../../apps/still-editor/node_modules/@tiptap/core/src/commands/splitListItem.ts", "../../apps/still-editor/node_modules/@tiptap/core/src/commands/utils/createNode.ts", "../../apps/still-editor/node_modules/@tiptap/core/src/commands/utils/flushPendingContent.ts", "../../apps/still-editor/node_modules/@tiptap/core/src/commands/utils/appendContentNode.ts", "../../apps/still-editor/node_modules/@tiptap/core/src/commands/utils/appendNestedList.ts", "../../apps/still-editor/node_modules/@tiptap/core/src/commands/utils/convertListItem.ts", "../../apps/still-editor/node_modules/@tiptap/core/src/commands/utils/convertListItems.ts", "../../apps/still-editor/node_modules/@tiptap/core/src/commands/utils/findNodePosition.ts", "../../apps/still-editor/node_modules/@tiptap/core/src/commands/toggleList.ts", "../../apps/still-editor/node_modules/@tiptap/core/src/commands/toggleMark.ts", "../../apps/still-editor/node_modules/@tiptap/core/src/commands/toggleNode.ts", "../../apps/still-editor/node_modules/@tiptap/core/src/commands/toggleWrap.ts", "../../apps/still-editor/node_modules/@tiptap/core/src/commands/undoInputRule.ts", "../../apps/still-editor/node_modules/@tiptap/core/src/commands/unsetAllMarks.ts", "../../apps/still-editor/node_modules/@tiptap/core/src/commands/unsetMark.ts", "../../apps/still-editor/node_modules/@tiptap/core/src/commands/unsetTextDirection.ts", "../../apps/still-editor/node_modules/@tiptap/core/src/commands/updateAttributes.ts", "../../apps/still-editor/node_modules/@tiptap/core/src/decorations/constants.ts", "../../apps/still-editor/node_modules/@tiptap/core/src/commands/updateDecorations.ts", "../../apps/still-editor/node_modules/@tiptap/core/src/commands/wrapIn.ts", "../../apps/still-editor/node_modules/@tiptap/core/src/commands/wrapInList.ts", "../../apps/still-editor/node_modules/@tiptap/core/src/commands/index.ts", "../../apps/still-editor/node_modules/@tiptap/core/src/decorations/decorationApplyScope.ts", "../../apps/still-editor/node_modules/@tiptap/core/src/EventEmitter.ts", "../../apps/still-editor/node_modules/@tiptap/core/src/utilities/isDev.ts", "../../apps/still-editor/node_modules/@tiptap/core/src/decorations/helpers/decorationsToPMDecorations.ts", "../../apps/still-editor/node_modules/@tiptap/core/src/decorations/helpers/buildDecorationSet.ts", "../../apps/still-editor/node_modules/@tiptap/core/src/decorations/helpers/rangeOwnsPosition.ts", "../../apps/still-editor/node_modules/@tiptap/core/src/decorations/helpers/filterOutOfRangeDecorations.ts", "../../apps/still-editor/node_modules/@tiptap/core/src/decorations/helpers/widgetKeyOf.ts", "../../apps/still-editor/node_modules/@tiptap/core/src/decorations/helpers/findDuplicateWidgetKeys.ts", "../../apps/still-editor/node_modules/@tiptap/core/src/decorations/helpers/isAttrStep.ts", "../../apps/still-editor/node_modules/@tiptap/core/src/decorations/helpers/hasResolvableChangedRange.ts", "../../apps/still-editor/node_modules/@tiptap/core/src/decorations/helpers/getRebuildRanges.ts", "../../apps/still-editor/node_modules/@tiptap/core/src/decorations/helpers/mapDecorationSet.ts", "../../apps/still-editor/node_modules/@tiptap/core/src/decorations/helpers/mapDecorations.ts", "../../apps/still-editor/node_modules/@tiptap/core/src/decorations/helpers/mergeDecorationSets.ts", "../../apps/still-editor/node_modules/@tiptap/core/src/decorations/helpers/unionWidgetKeys.ts", "../../apps/still-editor/node_modules/@tiptap/core/src/decorations/helpers/validateDecorationSpec.ts", "../../apps/still-editor/node_modules/@tiptap/core/src/decorations/helpers/shouldRecomputeDecoration.ts", "../../apps/still-editor/node_modules/@tiptap/core/src/decorations/DecorationManager.ts", "../../apps/still-editor/node_modules/@tiptap/core/src/utilities/attrsEqual.ts", "../../apps/still-editor/node_modules/@tiptap/core/src/utilities/canInsertNode.ts", "../../apps/still-editor/node_modules/@tiptap/core/src/utilities/createStyleTag.ts", "../../apps/still-editor/node_modules/@tiptap/core/src/utilities/escapeForRegEx.ts", "../../apps/still-editor/node_modules/@tiptap/core/src/utilities/getStyleProperty.ts", "../../apps/still-editor/node_modules/@tiptap/core/src/utilities/htmlEntities.ts", "../../apps/still-editor/node_modules/@tiptap/core/src/utilities/isFirefox.ts", "../../apps/still-editor/node_modules/@tiptap/core/src/utilities/isNumber.ts", "../../apps/still-editor/node_modules/@tiptap/core/src/utilities/isPlainObject.ts", "../../apps/still-editor/node_modules/@tiptap/core/src/utilities/isString.ts", "../../apps/still-editor/node_modules/@tiptap/core/src/utilities/isValidCSSStyleValue.ts", "../../apps/still-editor/node_modules/@tiptap/core/src/utilities/markdown/tokenizeAttributes.ts", "../../apps/still-editor/node_modules/@tiptap/core/src/utilities/markdown/parseAttributes.ts", "../../apps/still-editor/node_modules/@tiptap/core/src/utilities/markdown/serializeAttributes.ts", "../../apps/still-editor/node_modules/@tiptap/core/src/utilities/markdown/createAtomBlockMarkdownSpec.ts", "../../apps/still-editor/node_modules/@tiptap/core/src/utilities/markdown/createBlockMarkdownSpec.ts", "../../apps/still-editor/node_modules/@tiptap/core/src/utilities/markdown/parseShortcodeAttributes.ts", "../../apps/still-editor/node_modules/@tiptap/core/src/utilities/markdown/createInlineMarkdownSpec.ts", "../../apps/still-editor/node_modules/@tiptap/core/src/utilities/markdown/parseIndentedBlocks.ts", "../../apps/still-editor/node_modules/@tiptap/core/src/utilities/markdown/renderNestedMarkdownContent.ts", "../../apps/still-editor/node_modules/@tiptap/core/src/utilities/markdown/index.ts", "../../apps/still-editor/node_modules/@tiptap/core/src/utilities/marksEqual.ts", "../../apps/still-editor/node_modules/@tiptap/core/src/utilities/mergeDeep.ts", "../../apps/still-editor/node_modules/@tiptap/core/src/MarkView.ts", "../../apps/still-editor/node_modules/@tiptap/core/src/InputRule.ts", "../../apps/still-editor/node_modules/@tiptap/core/src/Extendable.ts", "../../apps/still-editor/node_modules/@tiptap/core/src/Mark.ts", "../../apps/still-editor/node_modules/@tiptap/core/src/PasteRule.ts", "../../apps/still-editor/node_modules/@tiptap/core/src/ExtensionManager.ts", "../../apps/still-editor/node_modules/@tiptap/core/src/Extension.ts", "../../apps/still-editor/node_modules/@tiptap/core/src/extensions/clipboardTextSerializer.ts", "../../apps/still-editor/node_modules/@tiptap/core/src/extensions/commands.ts", "../../apps/still-editor/node_modules/@tiptap/core/src/extensions/delete.ts", "../../apps/still-editor/node_modules/@tiptap/core/src/extensions/drop.ts", "../../apps/still-editor/node_modules/@tiptap/core/src/extensions/editable.ts", "../../apps/still-editor/node_modules/@tiptap/core/src/extensions/focusEvents.ts", "../../apps/still-editor/node_modules/@tiptap/core/src/extensions/createAndroidDeletePlugin.ts", "../../apps/still-editor/node_modules/@tiptap/core/src/extensions/keymap.ts", "../../apps/still-editor/node_modules/@tiptap/core/src/extensions/paste.ts", "../../apps/still-editor/node_modules/@tiptap/core/src/extensions/tabindex.ts", "../../apps/still-editor/node_modules/@tiptap/core/src/extensions/textDirection.ts", "../../apps/still-editor/node_modules/@tiptap/core/src/extensions/index.ts", "../../apps/still-editor/node_modules/@tiptap/core/src/helpers/warnOnDuplicatedProseMirrorModel.ts", "../../apps/still-editor/node_modules/@tiptap/core/src/NodePos.ts", "../../apps/still-editor/node_modules/@tiptap/core/src/style.ts", "../../apps/still-editor/node_modules/@tiptap/core/src/Editor.ts", "../../apps/still-editor/node_modules/@tiptap/core/src/decorations/Decoration.ts", "../../apps/still-editor/node_modules/@tiptap/core/src/decorations/createWidgetDecoration.ts", "../../apps/still-editor/node_modules/@tiptap/core/src/inputRules/markInputRule.ts", "../../apps/still-editor/node_modules/@tiptap/core/src/inputRules/nodeInputRule.ts", "../../apps/still-editor/node_modules/@tiptap/core/src/inputRules/textblockTypeInputRule.ts", "../../apps/still-editor/node_modules/@tiptap/core/src/inputRules/textInputRule.ts", "../../apps/still-editor/node_modules/@tiptap/core/src/inputRules/wrappingInputRule.ts", "../../apps/still-editor/node_modules/@tiptap/core/src/jsx-runtime.ts", "../../apps/still-editor/node_modules/@tiptap/core/src/lib/ResizableNodeView.ts", "../../apps/still-editor/node_modules/@tiptap/core/src/Node.ts", "../../apps/still-editor/node_modules/@tiptap/core/src/NodeView.ts", "../../apps/still-editor/node_modules/@tiptap/core/src/pasteRules/markPasteRule.ts", "../../apps/still-editor/node_modules/@tiptap/core/src/pasteRules/nodePasteRule.ts", "../../apps/still-editor/node_modules/@tiptap/core/src/pasteRules/textPasteRule.ts", "../../apps/still-editor/node_modules/@tiptap/core/src/Tracker.ts", "../../apps/still-editor/node_modules/@tiptap/core/src/jsx-runtime.ts", "../../apps/still-editor/node_modules/@tiptap/extension-blockquote/src/handleBackspace.ts", "../../apps/still-editor/node_modules/@tiptap/extension-blockquote/src/blockquote.tsx", "../../apps/still-editor/node_modules/@tiptap/extension-blockquote/src/index.ts", "../../apps/still-editor/node_modules/@tiptap/extension-bold/src/bold.tsx", "../../apps/still-editor/node_modules/@tiptap/extension-bold/src/index.ts", "../../apps/still-editor/node_modules/@tiptap/extension-code/src/code.ts", "../../apps/still-editor/node_modules/@tiptap/extension-code/src/index.ts", "../../apps/still-editor/node_modules/@tiptap/extension-code-block/src/code-block.ts", "../../apps/still-editor/node_modules/@tiptap/extension-code-block/src/index.ts", "../../apps/still-editor/node_modules/@tiptap/extension-document/src/document.ts", "../../apps/still-editor/node_modules/@tiptap/extension-document/src/index.ts", "../../apps/still-editor/node_modules/@tiptap/extension-hard-break/src/hard-break.ts", "../../apps/still-editor/node_modules/@tiptap/extension-hard-break/src/index.ts", "../../apps/still-editor/node_modules/@tiptap/extension-heading/src/heading.ts", "../../apps/still-editor/node_modules/@tiptap/extension-heading/src/index.ts", "../../apps/still-editor/node_modules/@tiptap/extension-horizontal-rule/src/horizontal-rule.ts", "../../apps/still-editor/node_modules/@tiptap/extension-horizontal-rule/src/index.ts", "../../apps/still-editor/node_modules/@tiptap/extension-italic/src/italic.ts", "../../apps/still-editor/node_modules/@tiptap/extension-italic/src/index.ts", "../../apps/still-editor/node_modules/linkifyjs/dist/linkify.mjs", "../../apps/still-editor/node_modules/@tiptap/extension-link/src/helpers/whitespace.ts", "../../apps/still-editor/node_modules/@tiptap/extension-link/src/helpers/unlinkTrailingWhitespace.ts", "../../apps/still-editor/node_modules/@tiptap/extension-link/src/helpers/autolink.ts", "../../apps/still-editor/node_modules/@tiptap/extension-link/src/helpers/clickHandler.ts", "../../apps/still-editor/node_modules/@tiptap/extension-link/src/helpers/markdownLink.ts", "../../apps/still-editor/node_modules/@tiptap/extension-link/src/helpers/pasteHandler.ts", "../../apps/still-editor/node_modules/@tiptap/extension-link/src/link.ts", "../../apps/still-editor/node_modules/@tiptap/extension-link/src/index.ts", "../../apps/still-editor/node_modules/@tiptap/extension-list/src/bullet-list/bullet-list.ts", "../../apps/still-editor/node_modules/@tiptap/extension-list/src/helpers/getBranchingNestedListAtCursor.ts", "../../apps/still-editor/node_modules/@tiptap/extension-list/src/helpers/hoistBranchingNestedList.ts", "../../apps/still-editor/node_modules/@tiptap/extension-list/src/helpers/handleDeleteBranchingNestedList.ts", "../../apps/still-editor/node_modules/@tiptap/extension-list/src/helpers/createBranchingListDeleteKeymap.ts", "../../apps/still-editor/node_modules/@tiptap/extension-list/src/ordered-list/roman.ts", "../../apps/still-editor/node_modules/@tiptap/extension-list/src/item/ensureLeadingParagraph.ts", "../../apps/still-editor/node_modules/@tiptap/extension-list/src/item/hasEmptyLeadingParagraph.ts", "../../apps/still-editor/node_modules/@tiptap/extension-list/src/item/list-item.ts", "../../apps/still-editor/node_modules/@tiptap/extension-list/src/keymap/listHelpers/findListItemPos.ts", "../../apps/still-editor/node_modules/@tiptap/extension-list/src/keymap/listHelpers/getNextListDepth.ts", "../../apps/still-editor/node_modules/@tiptap/extension-list/src/keymap/listHelpers/hasListBefore.ts", "../../apps/still-editor/node_modules/@tiptap/extension-list/src/keymap/listHelpers/handleBackspace.ts", "../../apps/still-editor/node_modules/@tiptap/extension-list/src/keymap/listHelpers/nextListIsDeeper.ts", "../../apps/still-editor/node_modules/@tiptap/extension-list/src/keymap/listHelpers/nextListIsHigher.ts", "../../apps/still-editor/node_modules/@tiptap/extension-list/src/keymap/listHelpers/handleDelete.ts", "../../apps/still-editor/node_modules/@tiptap/extension-list/src/keymap/listHelpers/handleTab.ts", "../../apps/still-editor/node_modules/@tiptap/extension-list/src/keymap/listHelpers/hasListItemAfter.ts", "../../apps/still-editor/node_modules/@tiptap/extension-list/src/keymap/listHelpers/hasListItemBefore.ts", "../../apps/still-editor/node_modules/@tiptap/extension-list/src/keymap/listHelpers/listItemHasSubList.ts", "../../apps/still-editor/node_modules/@tiptap/extension-list/src/keymap/listHelpers/index.ts", "../../apps/still-editor/node_modules/@tiptap/extension-list/src/keymap/list-keymap.ts", "../../apps/still-editor/node_modules/@tiptap/extension-list/src/ordered-list/utils.ts", "../../apps/still-editor/node_modules/@tiptap/extension-list/src/ordered-list/collectOrderedListItemsFromSource.ts", "../../apps/still-editor/node_modules/@tiptap/extension-list/src/ordered-list/ordered-list.ts", "../../apps/still-editor/node_modules/@tiptap/extension-list/src/task-item/task-item.ts", "../../apps/still-editor/node_modules/@tiptap/extension-list/src/task-list/task-list.ts", "../../apps/still-editor/node_modules/@tiptap/extension-list/src/kit/index.ts", "../../apps/still-editor/node_modules/@tiptap/extension-paragraph/src/paragraph.ts", "../../apps/still-editor/node_modules/@tiptap/extension-paragraph/src/index.ts", "../../apps/still-editor/node_modules/@tiptap/extension-strike/src/strike.ts", "../../apps/still-editor/node_modules/@tiptap/extension-strike/src/index.ts", "../../apps/still-editor/node_modules/@tiptap/extension-text/src/text.ts", "../../apps/still-editor/node_modules/@tiptap/extension-text/src/index.ts", "../../apps/still-editor/node_modules/@tiptap/extension-underline/src/underline.ts", "../../apps/still-editor/node_modules/@tiptap/extension-underline/src/index.ts", "../../apps/still-editor/node_modules/prosemirror-dropcursor/dist/index.js", "../../apps/still-editor/node_modules/prosemirror-gapcursor/dist/index.js", "../../apps/still-editor/node_modules/@tiptap/extensions/src/character-count/character-count.ts", "../../apps/still-editor/node_modules/@tiptap/extensions/src/drop-cursor/drop-cursor.ts", "../../apps/still-editor/node_modules/@tiptap/extensions/src/focus/focus.ts", "../../apps/still-editor/node_modules/@tiptap/extensions/src/gap-cursor/gap-cursor.ts", "../../apps/still-editor/node_modules/@tiptap/extensions/src/placeholder/constants.ts", "../../apps/still-editor/node_modules/@tiptap/extensions/src/placeholder/utils/createPlaceholderDecoration.ts", "../../apps/still-editor/node_modules/@tiptap/extensions/src/placeholder/utils/buildPlaceholderDecorations.ts", "../../apps/still-editor/node_modules/@tiptap/extensions/src/placeholder/utils/resolveTopLevelRange.ts", "../../apps/still-editor/node_modules/@tiptap/extensions/src/placeholder/utils/placeholderStateField.ts", "../../apps/still-editor/node_modules/@tiptap/extensions/src/placeholder/utils/preparePlaceholderAttribute.ts", "../../apps/still-editor/node_modules/@tiptap/extensions/src/placeholder/plugins/PlaceholderPlugin.ts", "../../apps/still-editor/node_modules/@tiptap/extensions/src/placeholder/placeholder.ts", "../../apps/still-editor/node_modules/@tiptap/extensions/src/selection/selection.ts", "../../apps/still-editor/node_modules/@tiptap/extensions/src/trailing-node/trailing-node.ts", "../../apps/still-editor/node_modules/@tiptap/extensions/src/undo-redo/undo-redo.ts", "../../apps/still-editor/node_modules/@tiptap/starter-kit/src/starter-kit.ts", "../../apps/still-editor/node_modules/@tiptap/starter-kit/src/index.ts", "../../apps/still-editor/node_modules/@tiptap/extension-image/src/image.ts", "../../apps/still-editor/node_modules/@tiptap/extension-image/src/index.ts", "../../apps/still-editor/node_modules/prosemirror-tables/src/tablemap.ts", "../../apps/still-editor/node_modules/prosemirror-tables/src/schema.ts", "../../apps/still-editor/node_modules/prosemirror-tables/src/util.ts", "../../apps/still-editor/node_modules/prosemirror-tables/src/cellselection.ts", "../../apps/still-editor/node_modules/prosemirror-tables/src/fixtables.ts", "../../apps/still-editor/node_modules/prosemirror-tables/src/utils/convert.ts", "../../apps/still-editor/node_modules/prosemirror-tables/src/utils/move-row-in-array-of-rows.ts", "../../apps/still-editor/node_modules/prosemirror-tables/src/utils/query.ts", "../../apps/still-editor/node_modules/prosemirror-tables/src/utils/get-cells.ts", "../../apps/still-editor/node_modules/prosemirror-tables/src/utils/selection-range.ts", "../../apps/still-editor/node_modules/prosemirror-tables/src/utils/transpose.ts", "../../apps/still-editor/node_modules/prosemirror-tables/src/utils/move-column.ts", "../../apps/still-editor/node_modules/prosemirror-tables/src/utils/move-row.ts", "../../apps/still-editor/node_modules/prosemirror-tables/src/commands.ts", "../../apps/still-editor/node_modules/prosemirror-tables/src/copypaste.ts", "../../apps/still-editor/node_modules/prosemirror-tables/src/input.ts", "../../apps/still-editor/node_modules/prosemirror-tables/src/tableview.ts", "../../apps/still-editor/node_modules/prosemirror-tables/src/columnresizing.ts", "../../apps/still-editor/node_modules/prosemirror-tables/src/index.ts", "../../apps/still-editor/node_modules/@tiptap/extension-table/src/utils/parseAlign.ts", "../../apps/still-editor/node_modules/@tiptap/extension-table/src/utils/parseColwidth.ts", "../../apps/still-editor/node_modules/@tiptap/extension-table/src/utils/fillEmptyCellContent.ts", "../../apps/still-editor/node_modules/@tiptap/extension-table/src/utils/omitDefaultSpanAttribute.ts", "../../apps/still-editor/node_modules/@tiptap/extension-table/src/cell/table-cell.ts", "../../apps/still-editor/node_modules/@tiptap/extension-table/src/header/table-header.ts", "../../apps/still-editor/node_modules/@tiptap/extension-table/src/row/table-row.ts", "../../apps/still-editor/node_modules/@tiptap/extension-table/src/table/utilities/colStyle.ts", "../../apps/still-editor/node_modules/@tiptap/extension-table/src/table/TableView.ts", "../../apps/still-editor/node_modules/@tiptap/extension-table/src/table/utilities/createColGroup.ts", "../../apps/still-editor/node_modules/@tiptap/extension-table/src/table/utilities/createCell.ts", "../../apps/still-editor/node_modules/@tiptap/extension-table/src/table/utilities/getTableNodeTypes.ts", "../../apps/still-editor/node_modules/@tiptap/extension-table/src/table/utilities/createTable.ts", "../../apps/still-editor/node_modules/@tiptap/extension-table/src/table/utilities/isCellSelection.ts", "../../apps/still-editor/node_modules/@tiptap/extension-table/src/table/utilities/deleteTableWhenAllCellsSelected.ts", "../../apps/still-editor/node_modules/@tiptap/extension-table/src/table/utilities/keepCursorInTable.ts", "../../apps/still-editor/node_modules/@tiptap/extension-table/src/table/utilities/markdown.ts", "../../apps/still-editor/node_modules/@tiptap/extension-table/src/table/utilities/preserveCellSelectionOnContextMenu.ts", "../../apps/still-editor/node_modules/@tiptap/extension-table/src/table/table.ts", "../../apps/still-editor/node_modules/@tiptap/extension-table/src/kit/index.ts", "../../apps/still-editor/node_modules/@tiptap/extension-task-list/src/index.ts", "../../apps/still-editor/node_modules/@tiptap/extension-task-item/src/index.ts", "../../apps/still-editor/node_modules/@tiptap/extension-text-align/src/text-align.ts", "../../apps/still-editor/node_modules/@tiptap/extension-text-align/src/index.ts", "../../apps/still-editor/node_modules/turndown/lib/turndown.browser.es.js", "../../apps/still-editor/node_modules/turndown-plugin-gfm/lib/turndown-plugin-gfm.es.js", "../../apps/still-editor/entry.mjs"],
  "sourcesContent": ["//#region \\0rolldown/runtime.js\nvar __defProp = Object.defineProperty;\nvar __exportAll = (all, no_symbols) => {\n\tlet target = {};\n\tfor (var name in all) __defProp(target, name, {\n\t\tget: all[name],\n\t\tenumerable: true\n\t});\n\tif (!no_symbols) __defProp(target, Symbol.toStringTag, { value: \"Module\" });\n\treturn target;\n};\n//#endregion\nexport { __exportAll as t };\n", "// ::- Persistent data structure representing an ordered mapping from\n// strings to values, with some convenient update methods.\nfunction OrderedMap(content) {\n  this.content = content;\n}\n\nOrderedMap.prototype = {\n  constructor: OrderedMap,\n\n  find: function(key) {\n    for (var i = 0; i < this.content.length; i += 2)\n      if (this.content[i] === key) return i\n    return -1\n  },\n\n  // :: (string) \u2192 ?any\n  // Retrieve the value stored under `key`, or return undefined when\n  // no such key exists.\n  get: function(key) {\n    var found = this.find(key);\n    return found == -1 ? undefined : this.content[found + 1]\n  },\n\n  // :: (string, any, ?string) \u2192 OrderedMap\n  // Create a new map by replacing the value of `key` with a new\n  // value, or adding a binding to the end of the map. If `newKey` is\n  // given, the key of the binding will be replaced with that key.\n  update: function(key, value, newKey) {\n    var self = newKey && newKey != key ? this.remove(newKey) : this;\n    var found = self.find(key), content = self.content.slice();\n    if (found == -1) {\n      content.push(newKey || key, value);\n    } else {\n      content[found + 1] = value;\n      if (newKey) content[found] = newKey;\n    }\n    return new OrderedMap(content)\n  },\n\n  // :: (string) \u2192 OrderedMap\n  // Return a map with the given key removed, if it existed.\n  remove: function(key) {\n    var found = this.find(key);\n    if (found == -1) return this\n    var content = this.content.slice();\n    content.splice(found, 2);\n    return new OrderedMap(content)\n  },\n\n  // :: (string, any) \u2192 OrderedMap\n  // Add a new key to the start of the map.\n  addToStart: function(key, value) {\n    return new OrderedMap([key, value].concat(this.remove(key).content))\n  },\n\n  // :: (string, any) \u2192 OrderedMap\n  // Add a new key to the end of the map.\n  addToEnd: function(key, value) {\n    var content = this.remove(key).content.slice();\n    content.push(key, value);\n    return new OrderedMap(content)\n  },\n\n  // :: (string, string, any) \u2192 OrderedMap\n  // Add a key after the given key. If `place` is not found, the new\n  // key is added to the end.\n  addBefore: function(place, key, value) {\n    var without = this.remove(key), content = without.content.slice();\n    var found = without.find(place);\n    content.splice(found == -1 ? content.length : found, 0, key, value);\n    return new OrderedMap(content)\n  },\n\n  // :: ((key: string, value: any))\n  // Call the given function for each key/value pair in the map, in\n  // order.\n  forEach: function(f) {\n    for (var i = 0; i < this.content.length; i += 2)\n      f(this.content[i], this.content[i + 1]);\n  },\n\n  // :: (union<Object, OrderedMap>) \u2192 OrderedMap\n  // Create a new map by prepending the keys in this map that don't\n  // appear in `map` before the keys in `map`.\n  prepend: function(map) {\n    map = OrderedMap.from(map);\n    if (!map.size) return this\n    return new OrderedMap(map.content.concat(this.subtract(map).content))\n  },\n\n  // :: (union<Object, OrderedMap>) \u2192 OrderedMap\n  // Create a new map by appending the keys in this map that don't\n  // appear in `map` after the keys in `map`.\n  append: function(map) {\n    map = OrderedMap.from(map);\n    if (!map.size) return this\n    return new OrderedMap(this.subtract(map).content.concat(map.content))\n  },\n\n  // :: (union<Object, OrderedMap>) \u2192 OrderedMap\n  // Create a map containing all the keys in this map that don't\n  // appear in `map`.\n  subtract: function(map) {\n    var result = this;\n    map = OrderedMap.from(map);\n    for (var i = 0; i < map.content.length; i += 2)\n      result = result.remove(map.content[i]);\n    return result\n  },\n\n  // :: () \u2192 Object\n  // Turn ordered map into a plain object.\n  toObject: function() {\n    var result = {};\n    this.forEach(function(key, value) { result[key] = value; });\n    return result\n  },\n\n  // :: number\n  // The amount of keys in this map.\n  get size() {\n    return this.content.length >> 1\n  }\n};\n\n// :: (?union<Object, OrderedMap>) \u2192 OrderedMap\n// Return a map with the given content. If null, create an empty\n// map. If given an ordered map, return that map itself. If given an\n// object, create a map from the object's properties.\nOrderedMap.from = function(value) {\n  if (value instanceof OrderedMap) return value\n  var content = [];\n  if (value) for (var prop in value) content.push(prop, value[prop]);\n  return new OrderedMap(content)\n};\n\nexport default OrderedMap;\n", "import OrderedMap from 'orderedmap';\n\nfunction findDiffStart(a, b, pos) {\n    for (let i = 0;; i++) {\n        if (i == a.childCount || i == b.childCount)\n            return a.childCount == b.childCount ? null : pos;\n        let childA = a.child(i), childB = b.child(i);\n        if (childA == childB) {\n            pos += childA.nodeSize;\n            continue;\n        }\n        if (!childA.sameMarkup(childB))\n            return pos;\n        if (childA.isText && childA.text != childB.text) {\n            let tA = childA.text, tB = childB.text, j = 0;\n            for (; tA[j] == tB[j]; j++)\n                pos++;\n            if (j && j < tA.length && j < tB.length && surrogateHigh(tA.charCodeAt(j - 1)) && surrogateLow(tA.charCodeAt(j)))\n                pos--;\n            return pos;\n        }\n        if (childA.content.size || childB.content.size) {\n            let inner = findDiffStart(childA.content, childB.content, pos + 1);\n            if (inner != null)\n                return inner;\n        }\n        pos += childA.nodeSize;\n    }\n}\nfunction findDiffEnd(a, b, posA, posB) {\n    for (let iA = a.childCount, iB = b.childCount;;) {\n        if (iA == 0 || iB == 0)\n            return iA == iB ? null : { a: posA, b: posB };\n        let childA = a.child(--iA), childB = b.child(--iB), size = childA.nodeSize;\n        if (childA == childB) {\n            posA -= size;\n            posB -= size;\n            continue;\n        }\n        if (!childA.sameMarkup(childB))\n            return { a: posA, b: posB };\n        if (childA.isText && childA.text != childB.text) {\n            let tA = childA.text, tB = childB.text, iA = tA.length, iB = tB.length;\n            while (iA > 0 && iB > 0 && tA[iA - 1] == tB[iB - 1]) {\n                iA--;\n                iB--;\n                posA--;\n                posB--;\n            }\n            if (iA && iB && iA < tA.length && surrogateHigh(tA.charCodeAt(iA - 1)) && surrogateLow(tA.charCodeAt(iA))) {\n                posA++;\n                posB++;\n            }\n            return { a: posA, b: posB };\n        }\n        if (childA.content.size || childB.content.size) {\n            let inner = findDiffEnd(childA.content, childB.content, posA - 1, posB - 1);\n            if (inner)\n                return inner;\n        }\n        posA -= size;\n        posB -= size;\n    }\n}\nfunction surrogateLow(ch) { return ch >= 0xDC00 && ch < 0xE000; }\nfunction surrogateHigh(ch) { return ch >= 0xD800 && ch < 0xDC00; }\n\n/**\nA fragment represents a node's collection of child nodes.\n\nLike nodes, fragments are persistent data structures, and you\nshould not mutate them or their content. Rather, you create new\ninstances whenever needed. The API tries to make this easy.\n*/\nclass Fragment {\n    /**\n    @internal\n    */\n    constructor(\n    /**\n    The child nodes in this fragment.\n    */\n    content, size) {\n        this.content = content;\n        this.size = size || 0;\n        if (size == null)\n            for (let i = 0; i < content.length; i++)\n                this.size += content[i].nodeSize;\n    }\n    /**\n    Invoke a callback for all descendant nodes between the given two\n    positions (relative to start of this fragment). Doesn't descend\n    into a node when the callback returns `false`.\n    */\n    nodesBetween(from, to, f, nodeStart = 0, parent) {\n        for (let i = 0, pos = 0; pos < to; i++) {\n            let child = this.content[i], end = pos + child.nodeSize;\n            if (end > from && f(child, nodeStart + pos, parent || null, i) !== false && child.content.size) {\n                let start = pos + 1;\n                child.nodesBetween(Math.max(0, from - start), Math.min(child.content.size, to - start), f, nodeStart + start);\n            }\n            pos = end;\n        }\n    }\n    /**\n    Call the given callback for every descendant node. `pos` will be\n    relative to the start of the fragment. The callback may return\n    `false` to prevent traversal of a given node's children.\n    */\n    descendants(f) {\n        this.nodesBetween(0, this.size, f);\n    }\n    /**\n    Extract the text between `from` and `to`. See the same method on\n    [`Node`](https://prosemirror.net/docs/ref/#model.Node.textBetween).\n    */\n    textBetween(from, to, blockSeparator, leafText) {\n        let text = \"\", first = true;\n        this.nodesBetween(from, to, (node, pos) => {\n            let nodeText = node.isText ? node.text.slice(Math.max(from, pos) - pos, to - pos)\n                : !node.isLeaf ? \"\"\n                    : leafText ? (typeof leafText === \"function\" ? leafText(node) : leafText)\n                        : node.type.spec.leafText ? node.type.spec.leafText(node)\n                            : \"\";\n            if (node.isBlock && (node.isLeaf && nodeText || node.isTextblock) && blockSeparator) {\n                if (first)\n                    first = false;\n                else\n                    text += blockSeparator;\n            }\n            text += nodeText;\n        }, 0);\n        return text;\n    }\n    /**\n    Create a new fragment containing the combined content of this\n    fragment and the other.\n    */\n    append(other) {\n        if (!other.size)\n            return this;\n        if (!this.size)\n            return other;\n        let last = this.lastChild, first = other.firstChild, content = this.content.slice(), i = 0;\n        if (last.isText && last.sameMarkup(first)) {\n            content[content.length - 1] = last.withText(last.text + first.text);\n            i = 1;\n        }\n        for (; i < other.content.length; i++)\n            content.push(other.content[i]);\n        return new Fragment(content, this.size + other.size);\n    }\n    /**\n    Cut out the sub-fragment between the two given positions.\n    */\n    cut(from, to = this.size) {\n        if (from == 0 && to == this.size)\n            return this;\n        let result = [], size = 0;\n        if (to > from)\n            for (let i = 0, pos = 0; pos < to; i++) {\n                let child = this.content[i], end = pos + child.nodeSize;\n                if (end > from) {\n                    if (pos < from || end > to) {\n                        if (child.isText)\n                            child = child.cut(Math.max(0, from - pos), Math.min(child.text.length, to - pos));\n                        else\n                            child = child.cut(Math.max(0, from - pos - 1), Math.min(child.content.size, to - pos - 1));\n                    }\n                    result.push(child);\n                    size += child.nodeSize;\n                }\n                pos = end;\n            }\n        return new Fragment(result, size);\n    }\n    /**\n    @internal\n    */\n    cutByIndex(from, to) {\n        if (from == to)\n            return Fragment.empty;\n        if (from == 0 && to == this.content.length)\n            return this;\n        return new Fragment(this.content.slice(from, to));\n    }\n    /**\n    Create a new fragment in which the node at the given index is\n    replaced by the given node.\n    */\n    replaceChild(index, node) {\n        let current = this.content[index];\n        if (current == node)\n            return this;\n        let copy = this.content.slice();\n        let size = this.size + node.nodeSize - current.nodeSize;\n        copy[index] = node;\n        return new Fragment(copy, size);\n    }\n    /**\n    Create a new fragment by prepending the given node to this\n    fragment.\n    */\n    addToStart(node) {\n        return new Fragment([node].concat(this.content), this.size + node.nodeSize);\n    }\n    /**\n    Create a new fragment by appending the given node to this\n    fragment.\n    */\n    addToEnd(node) {\n        return new Fragment(this.content.concat(node), this.size + node.nodeSize);\n    }\n    /**\n    Compare this fragment to another one.\n    */\n    eq(other) {\n        if (this.content.length != other.content.length)\n            return false;\n        for (let i = 0; i < this.content.length; i++)\n            if (!this.content[i].eq(other.content[i]))\n                return false;\n        return true;\n    }\n    /**\n    The first child of the fragment, or `null` if it is empty.\n    */\n    get firstChild() { return this.content.length ? this.content[0] : null; }\n    /**\n    The last child of the fragment, or `null` if it is empty.\n    */\n    get lastChild() { return this.content.length ? this.content[this.content.length - 1] : null; }\n    /**\n    The number of child nodes in this fragment.\n    */\n    get childCount() { return this.content.length; }\n    /**\n    Get the child node at the given index. Raise an error when the\n    index is out of range.\n    */\n    child(index) {\n        let found = this.content[index];\n        if (!found)\n            throw new RangeError(\"Index \" + index + \" out of range for \" + this);\n        return found;\n    }\n    /**\n    Get the child node at the given index, if it exists.\n    */\n    maybeChild(index) {\n        return this.content[index] || null;\n    }\n    /**\n    Call `f` for every child node, passing the node, its offset\n    into this parent node, and its index.\n    */\n    forEach(f) {\n        for (let i = 0, p = 0; i < this.content.length; i++) {\n            let child = this.content[i];\n            f(child, p, i);\n            p += child.nodeSize;\n        }\n    }\n    /**\n    Find the first position at which this fragment and another\n    fragment differ, or `null` if they are the same.\n    */\n    findDiffStart(other, pos = 0) {\n        return findDiffStart(this, other, pos);\n    }\n    /**\n    Find the first position, searching from the end, at which this\n    fragment and the given fragment differ, or `null` if they are\n    the same. Since this position will not be the same in both\n    nodes, an object with two separate positions is returned.\n    */\n    findDiffEnd(other, pos = this.size, otherPos = other.size) {\n        return findDiffEnd(this, other, pos, otherPos);\n    }\n    /**\n    Find the index and inner offset corresponding to a given relative\n    position in this fragment. The result object will be reused\n    (overwritten) the next time the function is called. @internal\n    */\n    findIndex(pos) {\n        if (pos == 0)\n            return retIndex(0, pos);\n        if (pos == this.size)\n            return retIndex(this.content.length, pos);\n        if (pos > this.size || pos < 0)\n            throw new RangeError(`Position ${pos} outside of fragment (${this})`);\n        for (let i = 0, curPos = 0;; i++) {\n            let cur = this.child(i), end = curPos + cur.nodeSize;\n            if (end >= pos) {\n                if (end == pos)\n                    return retIndex(i + 1, end);\n                return retIndex(i, curPos);\n            }\n            curPos = end;\n        }\n    }\n    /**\n    Return a debugging string that describes this fragment.\n    */\n    toString() { return \"<\" + this.toStringInner() + \">\"; }\n    /**\n    @internal\n    */\n    toStringInner() { return this.content.join(\", \"); }\n    /**\n    Create a JSON-serializeable representation of this fragment.\n    */\n    toJSON() {\n        return this.content.length ? this.content.map(n => n.toJSON()) : null;\n    }\n    /**\n    Deserialize a fragment from its JSON representation.\n    */\n    static fromJSON(schema, value) {\n        if (!value)\n            return Fragment.empty;\n        if (!Array.isArray(value))\n            throw new RangeError(\"Invalid input for Fragment.fromJSON\");\n        return Fragment.fromArray(value.map(schema.nodeFromJSON));\n    }\n    /**\n    Build a fragment from an array of nodes. Ensures that adjacent\n    text nodes with the same marks are joined together.\n    */\n    static fromArray(array) {\n        if (!array.length)\n            return Fragment.empty;\n        let joined, size = 0;\n        for (let i = 0; i < array.length; i++) {\n            let node = array[i];\n            size += node.nodeSize;\n            if (i && node.isText && array[i - 1].sameMarkup(node)) {\n                if (!joined)\n                    joined = array.slice(0, i);\n                joined[joined.length - 1] = node\n                    .withText(joined[joined.length - 1].text + node.text);\n            }\n            else if (joined) {\n                joined.push(node);\n            }\n        }\n        return new Fragment(joined || array, size);\n    }\n    /**\n    Create a fragment from something that can be interpreted as a\n    set of nodes. For `null`, it returns the empty fragment. For a\n    fragment, the fragment itself. For a node or array of nodes, a\n    fragment containing those nodes.\n    */\n    static from(nodes) {\n        if (!nodes)\n            return Fragment.empty;\n        if (nodes instanceof Fragment)\n            return nodes;\n        if (Array.isArray(nodes))\n            return this.fromArray(nodes);\n        if (nodes.attrs)\n            return new Fragment([nodes], nodes.nodeSize);\n        throw new RangeError(\"Can not convert \" + nodes + \" to a Fragment\" +\n            (nodes.nodesBetween ? \" (looks like multiple versions of prosemirror-model were loaded)\" : \"\"));\n    }\n}\n/**\nAn empty fragment. Intended to be reused whenever a node doesn't\ncontain anything (rather than allocating a new empty fragment for\neach leaf node).\n*/\nFragment.empty = new Fragment([], 0);\nconst found = { index: 0, offset: 0 };\nfunction retIndex(index, offset) {\n    found.index = index;\n    found.offset = offset;\n    return found;\n}\n\nfunction compareDeep(a, b) {\n    if (a === b)\n        return true;\n    if (!(a && typeof a == \"object\") ||\n        !(b && typeof b == \"object\"))\n        return false;\n    let array = Array.isArray(a);\n    if (Array.isArray(b) != array)\n        return false;\n    if (array) {\n        if (a.length != b.length)\n            return false;\n        for (let i = 0; i < a.length; i++)\n            if (!compareDeep(a[i], b[i]))\n                return false;\n    }\n    else {\n        for (let p in a)\n            if (!(p in b) || !compareDeep(a[p], b[p]))\n                return false;\n        for (let p in b)\n            if (!(p in a))\n                return false;\n    }\n    return true;\n}\n\n/**\nA mark is a piece of information that can be attached to a node,\nsuch as it being emphasized, in code font, or a link. It has a\ntype and optionally a set of attributes that provide further\ninformation (such as the target of the link). Marks are created\nthrough a `Schema`, which controls which types exist and which\nattributes they have.\n*/\nclass Mark {\n    /**\n    @internal\n    */\n    constructor(\n    /**\n    The type of this mark.\n    */\n    type, \n    /**\n    The attributes associated with this mark.\n    */\n    attrs) {\n        this.type = type;\n        this.attrs = attrs;\n    }\n    /**\n    Given a set of marks, create a new set which contains this one as\n    well, in the right position. If this mark is already in the set,\n    the set itself is returned. If any marks that are set to be\n    [exclusive](https://prosemirror.net/docs/ref/#model.MarkSpec.excludes) with this mark are present,\n    those are replaced by this one.\n    */\n    addToSet(set) {\n        let copy, placed = false;\n        for (let i = 0; i < set.length; i++) {\n            let other = set[i];\n            if (this.eq(other))\n                return set;\n            if (this.type.excludes(other.type)) {\n                if (!copy)\n                    copy = set.slice(0, i);\n            }\n            else if (other.type.excludes(this.type)) {\n                return set;\n            }\n            else {\n                if (!placed && other.type.rank > this.type.rank) {\n                    if (!copy)\n                        copy = set.slice(0, i);\n                    copy.push(this);\n                    placed = true;\n                }\n                if (copy)\n                    copy.push(other);\n            }\n        }\n        if (!copy)\n            copy = set.slice();\n        if (!placed)\n            copy.push(this);\n        return copy;\n    }\n    /**\n    Remove this mark from the given set, returning a new set. If this\n    mark is not in the set, the set itself is returned.\n    */\n    removeFromSet(set) {\n        for (let i = 0; i < set.length; i++)\n            if (this.eq(set[i]))\n                return set.slice(0, i).concat(set.slice(i + 1));\n        return set;\n    }\n    /**\n    Test whether this mark is in the given set of marks.\n    */\n    isInSet(set) {\n        for (let i = 0; i < set.length; i++)\n            if (this.eq(set[i]))\n                return true;\n        return false;\n    }\n    /**\n    Test whether this mark has the same type and attributes as\n    another mark.\n    */\n    eq(other) {\n        return this == other ||\n            (this.type == other.type && compareDeep(this.attrs, other.attrs));\n    }\n    /**\n    Convert this mark to a JSON-serializeable representation.\n    */\n    toJSON() {\n        let obj = { type: this.type.name };\n        for (let _ in this.attrs) {\n            obj.attrs = this.attrs;\n            break;\n        }\n        return obj;\n    }\n    /**\n    Deserialize a mark from JSON.\n    */\n    static fromJSON(schema, json) {\n        if (!json)\n            throw new RangeError(\"Invalid input for Mark.fromJSON\");\n        let type = schema.marks[json.type];\n        if (!type)\n            throw new RangeError(`There is no mark type ${json.type} in this schema`);\n        let mark = type.create(json.attrs);\n        return mark;\n    }\n    /**\n    Test whether two sets of marks are identical.\n    */\n    static sameSet(a, b) {\n        if (a == b)\n            return true;\n        if (a.length != b.length)\n            return false;\n        for (let i = 0; i < a.length; i++)\n            if (!a[i].eq(b[i]))\n                return false;\n        return true;\n    }\n    /**\n    Create a properly sorted mark set from null, a single mark, or an\n    unsorted array of marks.\n    */\n    static setFrom(marks) {\n        if (!marks || Array.isArray(marks) && marks.length == 0)\n            return Mark.none;\n        if (marks instanceof Mark)\n            return [marks];\n        let copy = marks.slice();\n        copy.sort((a, b) => a.type.rank - b.type.rank);\n        return copy;\n    }\n}\n/**\nThe empty set of marks.\n*/\nMark.none = [];\n\n/**\nError type raised by [`Node.replace`](https://prosemirror.net/docs/ref/#model.Node.replace) when\ngiven an invalid replacement.\n*/\nclass ReplaceError extends Error {\n}\n/**\nA slice represents a piece cut out of a larger document. It\nstores not only a fragment, but also the depth up to which nodes on\nboth side are \u2018open\u2019 (cut through).\n*/\nclass Slice {\n    /**\n    Create a slice. When specifying a non-zero open depth, you must\n    make sure that there are nodes of at least that depth at the\n    appropriate side of the fragment\u2014i.e. if the fragment is an\n    empty paragraph node, `openStart` and `openEnd` can't be greater\n    than 1.\n    \n    It is not necessary for the content of open nodes to conform to\n    the schema's content constraints, though it should be a valid\n    start/end/middle for such a node, depending on which sides are\n    open.\n    */\n    constructor(\n    /**\n    The slice's content.\n    */\n    content, \n    /**\n    The open depth at the start of the fragment.\n    */\n    openStart, \n    /**\n    The open depth at the end.\n    */\n    openEnd) {\n        this.content = content;\n        this.openStart = openStart;\n        this.openEnd = openEnd;\n    }\n    /**\n    The size this slice would add when inserted into a document.\n    */\n    get size() {\n        return this.content.size - this.openStart - this.openEnd;\n    }\n    /**\n    @internal\n    */\n    insertAt(pos, fragment) {\n        let content = insertInto(this.content, pos + this.openStart, fragment, this.openStart + 1, this.openEnd + 1);\n        return content && new Slice(content, this.openStart, this.openEnd);\n    }\n    /**\n    @internal\n    */\n    removeBetween(from, to) {\n        return new Slice(removeRange(this.content, from + this.openStart, to + this.openStart), this.openStart, this.openEnd);\n    }\n    /**\n    Tests whether this slice is equal to another slice.\n    */\n    eq(other) {\n        return this.content.eq(other.content) && this.openStart == other.openStart && this.openEnd == other.openEnd;\n    }\n    /**\n    @internal\n    */\n    toString() {\n        return this.content + \"(\" + this.openStart + \",\" + this.openEnd + \")\";\n    }\n    /**\n    Convert a slice to a JSON-serializable representation.\n    */\n    toJSON() {\n        if (!this.content.size)\n            return null;\n        let json = { content: this.content.toJSON() };\n        if (this.openStart > 0)\n            json.openStart = this.openStart;\n        if (this.openEnd > 0)\n            json.openEnd = this.openEnd;\n        return json;\n    }\n    /**\n    Deserialize a slice from its JSON representation.\n    */\n    static fromJSON(schema, json) {\n        if (!json)\n            return Slice.empty;\n        let openStart = json.openStart || 0, openEnd = json.openEnd || 0;\n        if (typeof openStart != \"number\" || typeof openEnd != \"number\")\n            throw new RangeError(\"Invalid input for Slice.fromJSON\");\n        return new Slice(Fragment.fromJSON(schema, json.content), openStart, openEnd);\n    }\n    /**\n    Create a slice from a fragment by taking the maximum possible\n    open value on both side of the fragment.\n    */\n    static maxOpen(fragment, openIsolating = true) {\n        let openStart = 0, openEnd = 0;\n        for (let n = fragment.firstChild; n && !n.isLeaf && (openIsolating || !n.type.spec.isolating); n = n.firstChild)\n            openStart++;\n        for (let n = fragment.lastChild; n && !n.isLeaf && (openIsolating || !n.type.spec.isolating); n = n.lastChild)\n            openEnd++;\n        return new Slice(fragment, openStart, openEnd);\n    }\n}\n/**\nThe empty slice.\n*/\nSlice.empty = new Slice(Fragment.empty, 0, 0);\nfunction removeRange(content, from, to) {\n    let { index, offset } = content.findIndex(from), child = content.maybeChild(index);\n    let { index: indexTo, offset: offsetTo } = content.findIndex(to);\n    if (offset == from || child.isText) {\n        if (offsetTo != to && !content.child(indexTo).isText)\n            throw new RangeError(\"Removing non-flat range\");\n        return content.cut(0, from).append(content.cut(to));\n    }\n    if (index != indexTo)\n        throw new RangeError(\"Removing non-flat range\");\n    return content.replaceChild(index, child.copy(removeRange(child.content, from - offset - 1, to - offset - 1)));\n}\nfunction insertInto(content, dist, insert, openStart, openEnd, parent) {\n    let { index, offset } = content.findIndex(dist), child = content.maybeChild(index);\n    if (offset == dist || child.isText) {\n        if (parent && openStart <= 0 && openEnd <= 0 && !parent.canReplace(index, index, insert))\n            return null;\n        return content.cut(0, dist).append(insert).append(content.cut(dist));\n    }\n    let inner = insertInto(child.content, dist - offset - 1, insert, index == 0 ? openStart - 1 : 0, index == content.childCount - 1 ? openEnd - 1 : 0, child);\n    return inner && content.replaceChild(index, child.copy(inner));\n}\nfunction replace($from, $to, slice) {\n    if (slice.openStart > $from.depth)\n        throw new ReplaceError(\"Inserted content deeper than insertion position\");\n    if ($from.depth - slice.openStart != $to.depth - slice.openEnd)\n        throw new ReplaceError(\"Inconsistent open depths\");\n    return replaceOuter($from, $to, slice, 0);\n}\nfunction replaceOuter($from, $to, slice, depth) {\n    let index = $from.index(depth), node = $from.node(depth);\n    if (index == $to.index(depth) && depth < $from.depth - slice.openStart) {\n        let inner = replaceOuter($from, $to, slice, depth + 1);\n        return node.copy(node.content.replaceChild(index, inner));\n    }\n    else if (!slice.content.size) {\n        return close(node, replaceTwoWay($from, $to, depth));\n    }\n    else if (!slice.openStart && !slice.openEnd && $from.depth == depth && $to.depth == depth) { // Simple, flat case\n        let parent = $from.parent, content = parent.content;\n        return close(parent, content.cut(0, $from.parentOffset).append(slice.content).append(content.cut($to.parentOffset)));\n    }\n    else {\n        let { start, end } = prepareSliceForReplace(slice, $from);\n        return close(node, replaceThreeWay($from, start, end, $to, depth));\n    }\n}\nfunction checkJoin(main, sub) {\n    if (!sub.type.compatibleContent(main.type))\n        throw new ReplaceError(\"Cannot join \" + sub.type.name + \" onto \" + main.type.name);\n}\nfunction joinable($before, $after, depth) {\n    let node = $before.node(depth);\n    checkJoin(node, $after.node(depth));\n    return node;\n}\nfunction addNode(child, target) {\n    let last = target.length - 1;\n    if (last >= 0 && child.isText && child.sameMarkup(target[last]))\n        target[last] = child.withText(target[last].text + child.text);\n    else\n        target.push(child);\n}\nfunction addRange($start, $end, depth, target) {\n    let node = ($end || $start).node(depth);\n    let startIndex = 0, endIndex = $end ? $end.index(depth) : node.childCount;\n    if ($start) {\n        startIndex = $start.index(depth);\n        if ($start.depth > depth) {\n            startIndex++;\n        }\n        else if ($start.textOffset) {\n            addNode($start.nodeAfter, target);\n            startIndex++;\n        }\n    }\n    for (let i = startIndex; i < endIndex; i++)\n        addNode(node.child(i), target);\n    if ($end && $end.depth == depth && $end.textOffset)\n        addNode($end.nodeBefore, target);\n}\nfunction close(node, content) {\n    if (!node.type.validContent(content))\n        throw new ReplaceError(\"Invalid content for node \" + node.type.name);\n    return node.copy(content);\n}\nfunction replaceThreeWay($from, $start, $end, $to, depth) {\n    let openStart = $from.depth > depth && joinable($from, $start, depth + 1);\n    let openEnd = $to.depth > depth && joinable($end, $to, depth + 1);\n    let content = [];\n    addRange(null, $from, depth, content);\n    if (openStart && openEnd && $start.index(depth) == $end.index(depth)) {\n        checkJoin(openStart, openEnd);\n        addNode(close(openStart, replaceThreeWay($from, $start, $end, $to, depth + 1)), content);\n    }\n    else {\n        if (openStart)\n            addNode(close(openStart, replaceTwoWay($from, $start, depth + 1)), content);\n        addRange($start, $end, depth, content);\n        if (openEnd)\n            addNode(close(openEnd, replaceTwoWay($end, $to, depth + 1)), content);\n    }\n    addRange($to, null, depth, content);\n    return new Fragment(content);\n}\nfunction replaceTwoWay($from, $to, depth) {\n    let content = [];\n    addRange(null, $from, depth, content);\n    if ($from.depth > depth) {\n        let type = joinable($from, $to, depth + 1);\n        addNode(close(type, replaceTwoWay($from, $to, depth + 1)), content);\n    }\n    addRange($to, null, depth, content);\n    return new Fragment(content);\n}\nfunction prepareSliceForReplace(slice, $along) {\n    let extra = $along.depth - slice.openStart, parent = $along.node(extra);\n    let node = parent.copy(slice.content);\n    for (let i = extra - 1; i >= 0; i--)\n        node = $along.node(i).copy(Fragment.from(node));\n    return { start: node.resolveNoCache(slice.openStart + extra),\n        end: node.resolveNoCache(node.content.size - slice.openEnd - extra) };\n}\n\n/**\nYou can [_resolve_](https://prosemirror.net/docs/ref/#model.Node.resolve) a position to get more\ninformation about it. Objects of this class represent such a\nresolved position, providing various pieces of context\ninformation, and some helper methods.\n\nThroughout this interface, methods that take an optional `depth`\nparameter will interpret undefined as `this.depth` and negative\nnumbers as `this.depth + value`.\n*/\nclass ResolvedPos {\n    /**\n    @internal\n    */\n    constructor(\n    /**\n    The position that was resolved.\n    */\n    pos, \n    /**\n    @internal\n    */\n    path, \n    /**\n    The offset this position has into its parent node.\n    */\n    parentOffset) {\n        this.pos = pos;\n        this.path = path;\n        this.parentOffset = parentOffset;\n        this.depth = path.length / 3 - 1;\n    }\n    /**\n    @internal\n    */\n    resolveDepth(val) {\n        if (val == null)\n            return this.depth;\n        if (val < 0)\n            return this.depth + val;\n        return val;\n    }\n    /**\n    The parent node that the position points into. Note that even if\n    a position points into a text node, that node is not considered\n    the parent\u2014text nodes are \u2018flat\u2019 in this model, and have no content.\n    */\n    get parent() { return this.node(this.depth); }\n    /**\n    The root node in which the position was resolved.\n    */\n    get doc() { return this.node(0); }\n    /**\n    The ancestor node at the given level. `p.node(p.depth)` is the\n    same as `p.parent`.\n    */\n    node(depth) { return this.path[this.resolveDepth(depth) * 3]; }\n    /**\n    The index into the ancestor at the given level. If this points\n    at the 3rd node in the 2nd paragraph on the top level, for\n    example, `p.index(0)` is 1 and `p.index(1)` is 2.\n    */\n    index(depth) { return this.path[this.resolveDepth(depth) * 3 + 1]; }\n    /**\n    The index pointing after this position into the ancestor at the\n    given level.\n    */\n    indexAfter(depth) {\n        depth = this.resolveDepth(depth);\n        return this.index(depth) + (depth == this.depth && !this.textOffset ? 0 : 1);\n    }\n    /**\n    The (absolute) position at the start of the node at the given\n    level.\n    */\n    start(depth) {\n        depth = this.resolveDepth(depth);\n        return depth == 0 ? 0 : this.path[depth * 3 - 1] + 1;\n    }\n    /**\n    The (absolute) position at the end of the node at the given\n    level.\n    */\n    end(depth) {\n        depth = this.resolveDepth(depth);\n        return this.start(depth) + this.node(depth).content.size;\n    }\n    /**\n    The (absolute) position directly before the wrapping node at the\n    given level, or, when `depth` is `this.depth + 1`, the original\n    position.\n    */\n    before(depth) {\n        depth = this.resolveDepth(depth);\n        if (!depth)\n            throw new RangeError(\"There is no position before the top-level node\");\n        return depth == this.depth + 1 ? this.pos : this.path[depth * 3 - 1];\n    }\n    /**\n    The (absolute) position directly after the wrapping node at the\n    given level, or the original position when `depth` is `this.depth + 1`.\n    */\n    after(depth) {\n        depth = this.resolveDepth(depth);\n        if (!depth)\n            throw new RangeError(\"There is no position after the top-level node\");\n        return depth == this.depth + 1 ? this.pos : this.path[depth * 3 - 1] + this.path[depth * 3].nodeSize;\n    }\n    /**\n    When this position points into a text node, this returns the\n    distance between the position and the start of the text node.\n    Will be zero for positions that point between nodes.\n    */\n    get textOffset() { return this.pos - this.path[this.path.length - 1]; }\n    /**\n    Get the node directly after the position, if any. If the position\n    points into a text node, only the part of that node after the\n    position is returned.\n    */\n    get nodeAfter() {\n        let parent = this.parent, index = this.index(this.depth);\n        if (index == parent.childCount)\n            return null;\n        let dOff = this.pos - this.path[this.path.length - 1], child = parent.child(index);\n        return dOff ? parent.child(index).cut(dOff) : child;\n    }\n    /**\n    Get the node directly before the position, if any. If the\n    position points into a text node, only the part of that node\n    before the position is returned.\n    */\n    get nodeBefore() {\n        let index = this.index(this.depth);\n        let dOff = this.pos - this.path[this.path.length - 1];\n        if (dOff)\n            return this.parent.child(index).cut(0, dOff);\n        return index == 0 ? null : this.parent.child(index - 1);\n    }\n    /**\n    Get the position at the given index in the parent node at the\n    given depth (which defaults to `this.depth`).\n    */\n    posAtIndex(index, depth) {\n        depth = this.resolveDepth(depth);\n        let node = this.path[depth * 3], pos = depth == 0 ? 0 : this.path[depth * 3 - 1] + 1;\n        for (let i = 0; i < index; i++)\n            pos += node.child(i).nodeSize;\n        return pos;\n    }\n    /**\n    Get the marks at this position, factoring in the surrounding\n    marks' [`inclusive`](https://prosemirror.net/docs/ref/#model.MarkSpec.inclusive) property. If the\n    position is at the start of a non-empty node, the marks of the\n    node after it (if any) are returned.\n    */\n    marks() {\n        let parent = this.parent, index = this.index();\n        // In an empty parent, return the empty array\n        if (parent.content.size == 0)\n            return Mark.none;\n        // When inside a text node, just return the text node's marks\n        if (this.textOffset)\n            return parent.child(index).marks;\n        let main = parent.maybeChild(index - 1), other = parent.maybeChild(index);\n        // If the `after` flag is true of there is no node before, make\n        // the node after this position the main reference.\n        if (!main) {\n            let tmp = main;\n            main = other;\n            other = tmp;\n        }\n        // Use all marks in the main node, except those that have\n        // `inclusive` set to false and are not present in the other node.\n        let marks = main.marks;\n        for (var i = 0; i < marks.length; i++)\n            if (marks[i].type.spec.inclusive === false && (!other || !marks[i].isInSet(other.marks)))\n                marks = marks[i--].removeFromSet(marks);\n        return marks;\n    }\n    /**\n    Get the marks after the current position, if any, except those\n    that are non-inclusive and not present at position `$end`. This\n    is mostly useful for getting the set of marks to preserve after a\n    deletion. Will return `null` if this position is at the end of\n    its parent node or its parent node isn't a textblock (in which\n    case no marks should be preserved).\n    */\n    marksAcross($end) {\n        let after = this.parent.maybeChild(this.index());\n        if (!after || !after.isInline)\n            return null;\n        let marks = after.marks, next = $end.parent.maybeChild($end.index());\n        for (var i = 0; i < marks.length; i++)\n            if (marks[i].type.spec.inclusive === false && (!next || !marks[i].isInSet(next.marks)))\n                marks = marks[i--].removeFromSet(marks);\n        return marks;\n    }\n    /**\n    The depth up to which this position and the given (non-resolved)\n    position share the same parent nodes.\n    */\n    sharedDepth(pos) {\n        for (let depth = this.depth; depth > 0; depth--)\n            if (this.start(depth) <= pos && this.end(depth) >= pos)\n                return depth;\n        return 0;\n    }\n    /**\n    Returns a range based on the place where this position and the\n    given position diverge around block content. If both point into\n    the same textblock, for example, a range around that textblock\n    will be returned. If they point into different blocks, the range\n    around those blocks in their shared ancestor is returned. You can\n    pass in an optional predicate that will be called with a parent\n    node to see if a range into that parent is acceptable.\n    */\n    blockRange(other = this, pred) {\n        if (other.pos < this.pos)\n            return other.blockRange(this);\n        for (let d = this.depth - (this.parent.inlineContent || this.pos == other.pos ? 1 : 0); d >= 0; d--)\n            if (other.pos <= this.end(d) && (!pred || pred(this.node(d))))\n                return new NodeRange(this, other, d);\n        return null;\n    }\n    /**\n    Query whether the given position shares the same parent node.\n    */\n    sameParent(other) {\n        return this.pos - this.parentOffset == other.pos - other.parentOffset;\n    }\n    /**\n    Return the greater of this and the given position.\n    */\n    max(other) {\n        return other.pos > this.pos ? other : this;\n    }\n    /**\n    Return the smaller of this and the given position.\n    */\n    min(other) {\n        return other.pos < this.pos ? other : this;\n    }\n    /**\n    @internal\n    */\n    toString() {\n        let str = \"\";\n        for (let i = 1; i <= this.depth; i++)\n            str += (str ? \"/\" : \"\") + this.node(i).type.name + \"_\" + this.index(i - 1);\n        return str + \":\" + this.parentOffset;\n    }\n    /**\n    @internal\n    */\n    static resolve(doc, pos) {\n        if (!(pos >= 0 && pos <= doc.content.size))\n            throw new RangeError(\"Position \" + pos + \" out of range\");\n        let path = [];\n        let start = 0, parentOffset = pos;\n        for (let node = doc;;) {\n            let { index, offset } = node.content.findIndex(parentOffset);\n            let rem = parentOffset - offset;\n            path.push(node, index, start + offset);\n            if (!rem)\n                break;\n            node = node.child(index);\n            if (node.isText)\n                break;\n            parentOffset = rem - 1;\n            start += offset + 1;\n        }\n        return new ResolvedPos(pos, path, parentOffset);\n    }\n    /**\n    @internal\n    */\n    static resolveCached(doc, pos) {\n        let cache = resolveCache.get(doc);\n        if (cache) {\n            for (let i = 0; i < cache.elts.length; i++) {\n                let elt = cache.elts[i];\n                if (elt.pos == pos)\n                    return elt;\n            }\n        }\n        else {\n            resolveCache.set(doc, cache = new ResolveCache);\n        }\n        let result = cache.elts[cache.i] = ResolvedPos.resolve(doc, pos);\n        cache.i = (cache.i + 1) % resolveCacheSize;\n        return result;\n    }\n}\nclass ResolveCache {\n    constructor() {\n        this.elts = [];\n        this.i = 0;\n    }\n}\nconst resolveCacheSize = 12, resolveCache = new WeakMap();\n/**\nRepresents a flat range of content, i.e. one that starts and\nends in the same node.\n*/\nclass NodeRange {\n    /**\n    Construct a node range. `$from` and `$to` should point into the\n    same node until at least the given `depth`, since a node range\n    denotes an adjacent set of nodes in a single parent node.\n    */\n    constructor(\n    /**\n    A resolved position along the start of the content. May have a\n    `depth` greater than this object's `depth` property, since\n    these are the positions that were used to compute the range,\n    not re-resolved positions directly at its boundaries.\n    */\n    $from, \n    /**\n    A position along the end of the content. See\n    caveat for [`$from`](https://prosemirror.net/docs/ref/#model.NodeRange.$from).\n    */\n    $to, \n    /**\n    The depth of the node that this range points into.\n    */\n    depth) {\n        this.$from = $from;\n        this.$to = $to;\n        this.depth = depth;\n    }\n    /**\n    The position at the start of the range.\n    */\n    get start() { return this.$from.before(this.depth + 1); }\n    /**\n    The position at the end of the range.\n    */\n    get end() { return this.$to.after(this.depth + 1); }\n    /**\n    The parent node that the range points into.\n    */\n    get parent() { return this.$from.node(this.depth); }\n    /**\n    The start index of the range in the parent node.\n    */\n    get startIndex() { return this.$from.index(this.depth); }\n    /**\n    The end index of the range in the parent node.\n    */\n    get endIndex() { return this.$to.indexAfter(this.depth); }\n}\n\nconst emptyAttrs = Object.create(null);\n/**\nThis class represents a node in the tree that makes up a\nProseMirror document. So a document is an instance of `Node`, with\nchildren that are also instances of `Node`.\n\nNodes are persistent data structures. Instead of changing them, you\ncreate new ones with the content you want. Old ones keep pointing\nat the old document shape. This is made cheaper by sharing\nstructure between the old and new data as much as possible, which a\ntree shape like this (without back pointers) makes easy.\n\n**Do not** directly mutate the properties of a `Node` object. See\n[the guide](https://prosemirror.net/docs/guide/#doc) for more information.\n*/\nclass Node {\n    /**\n    @internal\n    */\n    constructor(\n    /**\n    The type of node that this is.\n    */\n    type, \n    /**\n    An object mapping attribute names to values. The kind of\n    attributes allowed and required are\n    [determined](https://prosemirror.net/docs/ref/#model.NodeSpec.attrs) by the node type.\n    */\n    attrs, \n    // A fragment holding the node's children.\n    content, \n    /**\n    The marks (things like whether it is emphasized or part of a\n    link) applied to this node.\n    */\n    marks = Mark.none) {\n        this.type = type;\n        this.attrs = attrs;\n        this.marks = marks;\n        this.content = content || Fragment.empty;\n    }\n    /**\n    The array of this node's child nodes.\n    */\n    get children() { return this.content.content; }\n    /**\n    The size of this node, as defined by the integer-based [indexing\n    scheme](https://prosemirror.net/docs/guide/#doc.indexing). For text nodes, this is the\n    amount of characters. For other leaf nodes, it is one. For\n    non-leaf nodes, it is the size of the content plus two (the\n    start and end token).\n    */\n    get nodeSize() { return this.isLeaf ? 1 : 2 + this.content.size; }\n    /**\n    The number of children that the node has.\n    */\n    get childCount() { return this.content.childCount; }\n    /**\n    Get the child node at the given index. Raises an error when the\n    index is out of range.\n    */\n    child(index) { return this.content.child(index); }\n    /**\n    Get the child node at the given index, if it exists.\n    */\n    maybeChild(index) { return this.content.maybeChild(index); }\n    /**\n    Call `f` for every child node, passing the node, its offset\n    into this parent node, and its index.\n    */\n    forEach(f) { this.content.forEach(f); }\n    /**\n    Invoke a callback for all descendant nodes recursively overlapping\n    the given two positions that are relative to start of this\n    node's content. This includes all ancestors of the nodes\n    containing the two positions. The callback is invoked with the\n    node, its position relative to the original node (method receiver),\n    its parent node, and its child index. When the callback returns\n    false for a given node, that node's children will not be\n    recursed over. The last parameter can be used to specify a\n    starting position to count from.\n    */\n    nodesBetween(from, to, f, startPos = 0) {\n        this.content.nodesBetween(from, to, f, startPos, this);\n    }\n    /**\n    Call the given callback for every descendant node. Doesn't\n    descend into a node when the callback returns `false`.\n    */\n    descendants(f) {\n        this.nodesBetween(0, this.content.size, f);\n    }\n    /**\n    Concatenates all the text nodes found in this fragment and its\n    children.\n    */\n    get textContent() {\n        return (this.isLeaf && this.type.spec.leafText)\n            ? this.type.spec.leafText(this)\n            : this.textBetween(0, this.content.size, \"\");\n    }\n    /**\n    Get all text between positions `from` and `to`. When\n    `blockSeparator` is given, it will be inserted to separate text\n    from different block nodes. If `leafText` is given, it'll be\n    inserted for every non-text leaf node encountered, otherwise\n    [`leafText`](https://prosemirror.net/docs/ref/#model.NodeSpec.leafText) will be used.\n    */\n    textBetween(from, to, blockSeparator, leafText) {\n        return this.content.textBetween(from, to, blockSeparator, leafText);\n    }\n    /**\n    Returns this node's first child, or `null` if there are no\n    children.\n    */\n    get firstChild() { return this.content.firstChild; }\n    /**\n    Returns this node's last child, or `null` if there are no\n    children.\n    */\n    get lastChild() { return this.content.lastChild; }\n    /**\n    Test whether two nodes represent the same piece of document.\n    */\n    eq(other) {\n        return this == other || (this.sameMarkup(other) && this.content.eq(other.content));\n    }\n    /**\n    Compare the markup (type, attributes, and marks) of this node to\n    those of another. Returns `true` if both have the same markup.\n    */\n    sameMarkup(other) {\n        return this.hasMarkup(other.type, other.attrs, other.marks);\n    }\n    /**\n    Check whether this node's markup correspond to the given type,\n    attributes, and marks.\n    */\n    hasMarkup(type, attrs, marks) {\n        return this.type == type &&\n            compareDeep(this.attrs, attrs || type.defaultAttrs || emptyAttrs) &&\n            Mark.sameSet(this.marks, marks || Mark.none);\n    }\n    /**\n    Create a new node with the same markup as this node, containing\n    the given content (or empty, if no content is given).\n    */\n    copy(content = null) {\n        if (content == this.content)\n            return this;\n        return new Node(this.type, this.attrs, content, this.marks);\n    }\n    /**\n    Create a copy of this node, with the given set of marks instead\n    of the node's own marks.\n    */\n    mark(marks) {\n        return marks == this.marks ? this : new Node(this.type, this.attrs, this.content, marks);\n    }\n    /**\n    Create a copy of this node with only the content between the\n    given positions. If `to` is not given, it defaults to the end of\n    the node.\n    */\n    cut(from, to = this.content.size) {\n        if (from == 0 && to == this.content.size)\n            return this;\n        return this.copy(this.content.cut(from, to));\n    }\n    /**\n    Cut out the part of the document between the given positions, and\n    return it as a `Slice` object.\n    */\n    slice(from, to = this.content.size, includeParents = false) {\n        if (from == to)\n            return Slice.empty;\n        let $from = this.resolve(from), $to = this.resolve(to);\n        let depth = includeParents ? 0 : $from.sharedDepth(to);\n        let start = $from.start(depth), node = $from.node(depth);\n        let content = node.content.cut($from.pos - start, $to.pos - start);\n        return new Slice(content, $from.depth - depth, $to.depth - depth);\n    }\n    /**\n    Replace the part of the document between the given positions with\n    the given slice. The slice must 'fit', meaning its open sides\n    must be able to connect to the surrounding content, and its\n    content nodes must be valid children for the node they are placed\n    into. If any of this is violated, an error of type\n    [`ReplaceError`](https://prosemirror.net/docs/ref/#model.ReplaceError) is thrown.\n    */\n    replace(from, to, slice) {\n        return replace(this.resolve(from), this.resolve(to), slice);\n    }\n    /**\n    Find the node directly after the given position.\n    */\n    nodeAt(pos) {\n        for (let node = this;;) {\n            let { index, offset } = node.content.findIndex(pos);\n            node = node.maybeChild(index);\n            if (!node)\n                return null;\n            if (offset == pos || node.isText)\n                return node;\n            pos -= offset + 1;\n        }\n    }\n    /**\n    Find the (direct) child node after the given offset, if any,\n    and return it along with its index and offset relative to this\n    node.\n    */\n    childAfter(pos) {\n        let { index, offset } = this.content.findIndex(pos);\n        return { node: this.content.maybeChild(index), index, offset };\n    }\n    /**\n    Find the (direct) child node before the given offset, if any,\n    and return it along with its index and offset relative to this\n    node.\n    */\n    childBefore(pos) {\n        if (pos == 0)\n            return { node: null, index: 0, offset: 0 };\n        let { index, offset } = this.content.findIndex(pos);\n        if (offset < pos)\n            return { node: this.content.child(index), index, offset };\n        let node = this.content.child(index - 1);\n        return { node, index: index - 1, offset: offset - node.nodeSize };\n    }\n    /**\n    Resolve the given position in the document, returning an\n    [object](https://prosemirror.net/docs/ref/#model.ResolvedPos) with information about its context.\n    */\n    resolve(pos) { return ResolvedPos.resolveCached(this, pos); }\n    /**\n    @internal\n    */\n    resolveNoCache(pos) { return ResolvedPos.resolve(this, pos); }\n    /**\n    Test whether a given mark or mark type occurs in this document\n    between the two given positions.\n    */\n    rangeHasMark(from, to, type) {\n        let found = false;\n        if (to > from)\n            this.nodesBetween(from, to, node => {\n                if (type.isInSet(node.marks))\n                    found = true;\n                return !found;\n            });\n        return found;\n    }\n    /**\n    True when this is a block (non-inline node)\n    */\n    get isBlock() { return this.type.isBlock; }\n    /**\n    True when this is a textblock node, a block node with inline\n    content.\n    */\n    get isTextblock() { return this.type.isTextblock; }\n    /**\n    True when this node allows inline content.\n    */\n    get inlineContent() { return this.type.inlineContent; }\n    /**\n    True when this is an inline node (a text node or a node that can\n    appear among text).\n    */\n    get isInline() { return this.type.isInline; }\n    /**\n    True when this is a text node.\n    */\n    get isText() { return this.type.isText; }\n    /**\n    True when this is a leaf node.\n    */\n    get isLeaf() { return this.type.isLeaf; }\n    /**\n    True when this is an atom, i.e. when it does not have directly\n    editable content. This is usually the same as `isLeaf`, but can\n    be configured with the [`atom` property](https://prosemirror.net/docs/ref/#model.NodeSpec.atom)\n    on a node's spec (typically used when the node is displayed as\n    an uneditable [node view](https://prosemirror.net/docs/ref/#view.NodeView)).\n    */\n    get isAtom() { return this.type.isAtom; }\n    /**\n    Return a string representation of this node for debugging\n    purposes.\n    */\n    toString() {\n        if (this.type.spec.toDebugString)\n            return this.type.spec.toDebugString(this);\n        let name = this.type.name;\n        if (this.content.size)\n            name += \"(\" + this.content.toStringInner() + \")\";\n        return wrapMarks(this.marks, name);\n    }\n    /**\n    Get the content match in this node at the given index.\n    */\n    contentMatchAt(index) {\n        let match = this.type.contentMatch.matchFragment(this.content, 0, index);\n        if (!match)\n            throw new Error(\"Called contentMatchAt on a node with invalid content\");\n        return match;\n    }\n    /**\n    Test whether replacing the range between `from` and `to` (by\n    child index) with the given replacement fragment (which defaults\n    to the empty fragment) would leave the node's content valid. You\n    can optionally pass `start` and `end` indices into the\n    replacement fragment.\n    */\n    canReplace(from, to, replacement = Fragment.empty, start = 0, end = replacement.childCount) {\n        let one = this.contentMatchAt(from).matchFragment(replacement, start, end);\n        let two = one && one.matchFragment(this.content, to);\n        if (!two || !two.validEnd)\n            return false;\n        for (let i = start; i < end; i++)\n            if (!this.type.allowsMarks(replacement.child(i).marks))\n                return false;\n        return true;\n    }\n    /**\n    Test whether replacing the range `from` to `to` (by index) with\n    a node of the given type would leave the node's content valid.\n    */\n    canReplaceWith(from, to, type, marks) {\n        if (marks && !this.type.allowsMarks(marks))\n            return false;\n        let start = this.contentMatchAt(from).matchType(type);\n        let end = start && start.matchFragment(this.content, to);\n        return end ? end.validEnd : false;\n    }\n    /**\n    Test whether the given node's content could be appended to this\n    node. If that node is empty, this will only return true if there\n    is at least one node type that can appear in both nodes (to avoid\n    merging completely incompatible nodes).\n    */\n    canAppend(other) {\n        if (other.content.size)\n            return this.canReplace(this.childCount, this.childCount, other.content);\n        else\n            return this.type.compatibleContent(other.type);\n    }\n    /**\n    Check whether this node and its descendants conform to the\n    schema, and raise an exception when they do not.\n    */\n    check() {\n        this.type.checkContent(this.content);\n        checkAttrs(this.type.attrs, this.attrs, \"node\", this.type.name);\n        let copy = Mark.none;\n        for (let i = 0; i < this.marks.length; i++) {\n            let mark = this.marks[i];\n            checkAttrs(mark.type.attrs, mark.attrs, \"mark\", mark.type.name);\n            copy = mark.addToSet(copy);\n        }\n        if (!Mark.sameSet(copy, this.marks))\n            throw new RangeError(`Invalid collection of marks for node ${this.type.name}: ${this.marks.map(m => m.type.name)}`);\n        this.content.forEach(node => node.check());\n    }\n    /**\n    Return a JSON-serializeable representation of this node.\n    */\n    toJSON() {\n        let obj = { type: this.type.name };\n        for (let _ in this.attrs) {\n            obj.attrs = this.attrs;\n            break;\n        }\n        if (this.content.size)\n            obj.content = this.content.toJSON();\n        if (this.marks.length)\n            obj.marks = this.marks.map(n => n.toJSON());\n        return obj;\n    }\n    /**\n    Deserialize a node from its JSON representation.\n    */\n    static fromJSON(schema, json) {\n        if (!json)\n            throw new RangeError(\"Invalid input for Node.fromJSON\");\n        let marks = undefined;\n        if (json.marks) {\n            if (!Array.isArray(json.marks))\n                throw new RangeError(\"Invalid mark data for Node.fromJSON\");\n            marks = json.marks.map(schema.markFromJSON);\n        }\n        if (json.type == \"text\") {\n            if (typeof json.text != \"string\")\n                throw new RangeError(\"Invalid text node in JSON\");\n            return schema.text(json.text, marks);\n        }\n        let content = Fragment.fromJSON(schema, json.content);\n        let node = schema.nodeType(json.type).create(json.attrs, content, marks);\n        return node;\n    }\n}\nNode.prototype.text = undefined;\n// V8 can leak big strings if you take a slice from them and hang on\n// to the slice (https://issues.chromium.org/issues/41480525). If it\n// looks like we're on V8 (by stack trace pattern), use such strings\n// as index to an object first to intern them to avoid leaking memory\n// in, for example, inverted steps stored in history. (#1609)\nconst v8InternHack = (() => {\n    let { stack } = new Error(\"/\");\n    if (!stack || !/\\n\\s*at\\s/.test(stack))\n        return s => s;\n    let obj = Object.create(null);\n    return s => { obj[s]; return s; };\n})();\nclass TextNode extends Node {\n    /**\n    @internal\n    */\n    constructor(type, attrs, content, marks) {\n        super(type, attrs, null, marks);\n        if (!content)\n            throw new RangeError(\"Empty text nodes are not allowed\");\n        this.text = content;\n    }\n    toString() {\n        if (this.type.spec.toDebugString)\n            return this.type.spec.toDebugString(this);\n        return wrapMarks(this.marks, JSON.stringify(this.text));\n    }\n    get textContent() { return this.text; }\n    textBetween(from, to) { return v8InternHack(this.text.slice(from, to)); }\n    get nodeSize() { return this.text.length; }\n    mark(marks) {\n        return marks == this.marks ? this : new TextNode(this.type, this.attrs, this.text, marks);\n    }\n    withText(text) {\n        if (text == this.text)\n            return this;\n        return new TextNode(this.type, this.attrs, text, this.marks);\n    }\n    cut(from = 0, to = this.text.length) {\n        if (from == 0 && to == this.text.length)\n            return this;\n        return this.withText(v8InternHack(this.text.slice(from, to)));\n    }\n    eq(other) {\n        return this.sameMarkup(other) && this.text == other.text;\n    }\n    toJSON() {\n        let base = super.toJSON();\n        base.text = this.text;\n        return base;\n    }\n}\nfunction wrapMarks(marks, str) {\n    for (let i = marks.length - 1; i >= 0; i--)\n        str = marks[i].type.name + \"(\" + str + \")\";\n    return str;\n}\nfunction checkAttrs(attrs, values, type, name) {\n    for (let attr in values)\n        if (!(attr in attrs))\n            throw new RangeError(`Unsupported attribute ${attr} for ${type} of type ${name}`);\n    for (let attr in attrs) {\n        if (attrs[attr].validate)\n            attrs[attr].validate(values[attr]);\n    }\n}\n\n/**\nInstances of this class represent a match state of a node type's\n[content expression](https://prosemirror.net/docs/ref/#model.NodeSpec.content), and can be used to\nfind out whether further content matches here, and whether a given\nposition is a valid end of the node.\n*/\nclass ContentMatch {\n    /**\n    @internal\n    */\n    constructor(\n    /**\n    True when this match state represents a valid end of the node.\n    */\n    validEnd) {\n        this.validEnd = validEnd;\n        /**\n        @internal\n        */\n        this.next = [];\n        /**\n        @internal\n        */\n        this.wrapCache = [];\n    }\n    /**\n    @internal\n    */\n    static parse(string, nodeTypes) {\n        let stream = new TokenStream(string, nodeTypes);\n        if (stream.next == null)\n            return ContentMatch.empty;\n        let expr = parseExpr(stream);\n        if (stream.next)\n            stream.err(\"Unexpected trailing text\");\n        let match = dfa(nfa(expr));\n        checkForDeadEnds(match, stream);\n        return match;\n    }\n    /**\n    Match a node type, returning a match after that node if\n    successful.\n    */\n    matchType(type) {\n        for (let i = 0; i < this.next.length; i++)\n            if (this.next[i].type == type)\n                return this.next[i].next;\n        return null;\n    }\n    /**\n    Try to match a fragment. Returns the resulting match when\n    successful.\n    */\n    matchFragment(frag, start = 0, end = frag.childCount) {\n        let cur = this;\n        for (let i = start; cur && i < end; i++)\n            cur = cur.matchType(frag.child(i).type);\n        return cur;\n    }\n    /**\n    @internal\n    */\n    get inlineContent() {\n        return this.next.length != 0 && this.next[0].type.isInline;\n    }\n    /**\n    Get the first matching node type at this match position that can\n    be generated.\n    */\n    get defaultType() {\n        for (let i = 0; i < this.next.length; i++) {\n            let { type } = this.next[i];\n            if (!(type.isText || type.hasRequiredAttrs()))\n                return type;\n        }\n        return null;\n    }\n    /**\n    @internal\n    */\n    compatible(other) {\n        for (let i = 0; i < this.next.length; i++)\n            for (let j = 0; j < other.next.length; j++)\n                if (this.next[i].type == other.next[j].type)\n                    return true;\n        return false;\n    }\n    /**\n    Try to match the given fragment, and if that fails, see if it can\n    be made to match by inserting nodes in front of it. When\n    successful, return a fragment of inserted nodes (which may be\n    empty if nothing had to be inserted). When `toEnd` is true, only\n    return a fragment if the resulting match goes to the end of the\n    content expression.\n    */\n    fillBefore(after, toEnd = false, startIndex = 0) {\n        let seen = [this];\n        function search(match, types) {\n            let finished = match.matchFragment(after, startIndex);\n            if (finished && (!toEnd || finished.validEnd))\n                return Fragment.from(types.map(tp => tp.createAndFill()));\n            for (let i = 0; i < match.next.length; i++) {\n                let { type, next } = match.next[i];\n                if (!(type.isText || type.hasRequiredAttrs()) && seen.indexOf(next) == -1) {\n                    seen.push(next);\n                    let found = search(next, types.concat(type));\n                    if (found)\n                        return found;\n                }\n            }\n            return null;\n        }\n        return search(this, []);\n    }\n    /**\n    Find a set of wrapping node types that would allow a node of the\n    given type to appear at this position. The result may be empty\n    (when it fits directly) and will be null when no such wrapping\n    exists.\n    */\n    findWrapping(target) {\n        for (let i = 0; i < this.wrapCache.length; i += 2)\n            if (this.wrapCache[i] == target)\n                return this.wrapCache[i + 1];\n        let computed = this.computeWrapping(target);\n        this.wrapCache.push(target, computed);\n        return computed;\n    }\n    /**\n    @internal\n    */\n    computeWrapping(target) {\n        let seen = Object.create(null), active = [{ match: this, type: null, via: null }];\n        while (active.length) {\n            let current = active.shift(), match = current.match;\n            if (match.matchType(target)) {\n                let result = [];\n                for (let obj = current; obj.type; obj = obj.via)\n                    result.push(obj.type);\n                return result.reverse();\n            }\n            for (let i = 0; i < match.next.length; i++) {\n                let { type, next } = match.next[i];\n                if (!type.isLeaf && !type.hasRequiredAttrs() && !(type.name in seen) && (!current.type || next.validEnd)) {\n                    active.push({ match: type.contentMatch, type, via: current });\n                    seen[type.name] = true;\n                }\n            }\n        }\n        return null;\n    }\n    /**\n    The number of outgoing edges this node has in the finite\n    automaton that describes the content expression.\n    */\n    get edgeCount() {\n        return this.next.length;\n    }\n    /**\n    Get the _n_\u200Bth outgoing edge from this node in the finite\n    automaton that describes the content expression.\n    */\n    edge(n) {\n        if (n >= this.next.length)\n            throw new RangeError(`There's no ${n}th edge in this content match`);\n        return this.next[n];\n    }\n    /**\n    @internal\n    */\n    toString() {\n        let seen = [];\n        function scan(m) {\n            seen.push(m);\n            for (let i = 0; i < m.next.length; i++)\n                if (seen.indexOf(m.next[i].next) == -1)\n                    scan(m.next[i].next);\n        }\n        scan(this);\n        return seen.map((m, i) => {\n            let out = i + (m.validEnd ? \"*\" : \" \") + \" \";\n            for (let i = 0; i < m.next.length; i++)\n                out += (i ? \", \" : \"\") + m.next[i].type.name + \"->\" + seen.indexOf(m.next[i].next);\n            return out;\n        }).join(\"\\n\");\n    }\n}\n/**\n@internal\n*/\nContentMatch.empty = new ContentMatch(true);\nclass TokenStream {\n    constructor(string, nodeTypes) {\n        this.string = string;\n        this.nodeTypes = nodeTypes;\n        this.inline = null;\n        this.pos = 0;\n        this.tokens = string.split(/\\s*(?=\\b|\\W|$)/);\n        if (this.tokens[this.tokens.length - 1] == \"\")\n            this.tokens.pop();\n        if (this.tokens[0] == \"\")\n            this.tokens.shift();\n    }\n    get next() { return this.tokens[this.pos]; }\n    eat(tok) { return this.next == tok && (this.pos++ || true); }\n    err(str) { throw new SyntaxError(str + \" (in content expression '\" + this.string + \"')\"); }\n}\nfunction parseExpr(stream) {\n    let exprs = [];\n    do {\n        exprs.push(parseExprSeq(stream));\n    } while (stream.eat(\"|\"));\n    return exprs.length == 1 ? exprs[0] : { type: \"choice\", exprs };\n}\nfunction parseExprSeq(stream) {\n    let exprs = [];\n    do {\n        exprs.push(parseExprSubscript(stream));\n    } while (stream.next && stream.next != \")\" && stream.next != \"|\");\n    return exprs.length == 1 ? exprs[0] : { type: \"seq\", exprs };\n}\nfunction parseExprSubscript(stream) {\n    let expr = parseExprAtom(stream);\n    for (;;) {\n        if (stream.eat(\"+\"))\n            expr = { type: \"plus\", expr };\n        else if (stream.eat(\"*\"))\n            expr = { type: \"star\", expr };\n        else if (stream.eat(\"?\"))\n            expr = { type: \"opt\", expr };\n        else if (stream.eat(\"{\"))\n            expr = parseExprRange(stream, expr);\n        else\n            break;\n    }\n    return expr;\n}\nfunction parseNum(stream) {\n    if (/\\D/.test(stream.next))\n        stream.err(\"Expected number, got '\" + stream.next + \"'\");\n    let result = Number(stream.next);\n    stream.pos++;\n    return result;\n}\nfunction parseExprRange(stream, expr) {\n    let min = parseNum(stream), max = min;\n    if (stream.eat(\",\")) {\n        if (stream.next != \"}\")\n            max = parseNum(stream);\n        else\n            max = -1;\n    }\n    if (!stream.eat(\"}\"))\n        stream.err(\"Unclosed braced range\");\n    return { type: \"range\", min, max, expr };\n}\nfunction resolveName(stream, name) {\n    let types = stream.nodeTypes, type = types[name];\n    if (type)\n        return [type];\n    let result = [];\n    for (let typeName in types) {\n        let type = types[typeName];\n        if (type.isInGroup(name))\n            result.push(type);\n    }\n    if (result.length == 0)\n        stream.err(\"No node type or group '\" + name + \"' found\");\n    return result;\n}\nfunction parseExprAtom(stream) {\n    if (stream.eat(\"(\")) {\n        let expr = parseExpr(stream);\n        if (!stream.eat(\")\"))\n            stream.err(\"Missing closing paren\");\n        return expr;\n    }\n    else if (!/\\W/.test(stream.next)) {\n        let exprs = resolveName(stream, stream.next).map(type => {\n            if (stream.inline == null)\n                stream.inline = type.isInline;\n            else if (stream.inline != type.isInline)\n                stream.err(\"Mixing inline and block content\");\n            return { type: \"name\", value: type };\n        });\n        stream.pos++;\n        return exprs.length == 1 ? exprs[0] : { type: \"choice\", exprs };\n    }\n    else {\n        stream.err(\"Unexpected token '\" + stream.next + \"'\");\n    }\n}\n// Construct an NFA from an expression as returned by the parser. The\n// NFA is represented as an array of states, which are themselves\n// arrays of edges, which are `{term, to}` objects. The first state is\n// the entry state and the last node is the success state.\n//\n// Note that unlike typical NFAs, the edge ordering in this one is\n// significant, in that it is used to contruct filler content when\n// necessary.\nfunction nfa(expr) {\n    let nfa = [[]];\n    connect(compile(expr, 0), node());\n    return nfa;\n    function node() { return nfa.push([]) - 1; }\n    function edge(from, to, term) {\n        let edge = { term, to };\n        nfa[from].push(edge);\n        return edge;\n    }\n    function connect(edges, to) {\n        edges.forEach(edge => edge.to = to);\n    }\n    function compile(expr, from) {\n        if (expr.type == \"choice\") {\n            return expr.exprs.reduce((out, expr) => out.concat(compile(expr, from)), []);\n        }\n        else if (expr.type == \"seq\") {\n            for (let i = 0;; i++) {\n                let next = compile(expr.exprs[i], from);\n                if (i == expr.exprs.length - 1)\n                    return next;\n                connect(next, from = node());\n            }\n        }\n        else if (expr.type == \"star\") {\n            let loop = node();\n            edge(from, loop);\n            connect(compile(expr.expr, loop), loop);\n            return [edge(loop)];\n        }\n        else if (expr.type == \"plus\") {\n            let loop = node();\n            connect(compile(expr.expr, from), loop);\n            connect(compile(expr.expr, loop), loop);\n            return [edge(loop)];\n        }\n        else if (expr.type == \"opt\") {\n            return [edge(from)].concat(compile(expr.expr, from));\n        }\n        else if (expr.type == \"range\") {\n            let cur = from;\n            for (let i = 0; i < expr.min; i++) {\n                let next = node();\n                connect(compile(expr.expr, cur), next);\n                cur = next;\n            }\n            if (expr.max == -1) {\n                connect(compile(expr.expr, cur), cur);\n            }\n            else {\n                for (let i = expr.min; i < expr.max; i++) {\n                    let next = node();\n                    edge(cur, next);\n                    connect(compile(expr.expr, cur), next);\n                    cur = next;\n                }\n            }\n            return [edge(cur)];\n        }\n        else if (expr.type == \"name\") {\n            return [edge(from, undefined, expr.value)];\n        }\n        else {\n            throw new Error(\"Unknown expr type\");\n        }\n    }\n}\nfunction cmp(a, b) { return b - a; }\n// Get the set of nodes reachable by null edges from `node`. Omit\n// nodes with only a single null-out-edge, since they may lead to\n// needless duplicated nodes.\nfunction nullFrom(nfa, node) {\n    let result = [];\n    scan(node);\n    return result.sort(cmp);\n    function scan(node) {\n        let edges = nfa[node];\n        if (edges.length == 1 && !edges[0].term)\n            return scan(edges[0].to);\n        result.push(node);\n        for (let i = 0; i < edges.length; i++) {\n            let { term, to } = edges[i];\n            if (!term && result.indexOf(to) == -1)\n                scan(to);\n        }\n    }\n}\n// Compiles an NFA as produced by `nfa` into a DFA, modeled as a set\n// of state objects (`ContentMatch` instances) with transitions\n// between them.\nfunction dfa(nfa) {\n    let labeled = Object.create(null);\n    return explore(nullFrom(nfa, 0));\n    function explore(states) {\n        let out = [];\n        states.forEach(node => {\n            nfa[node].forEach(({ term, to }) => {\n                if (!term)\n                    return;\n                let set;\n                for (let i = 0; i < out.length; i++)\n                    if (out[i][0] == term)\n                        set = out[i][1];\n                nullFrom(nfa, to).forEach(node => {\n                    if (!set)\n                        out.push([term, set = []]);\n                    if (set.indexOf(node) == -1)\n                        set.push(node);\n                });\n            });\n        });\n        let state = labeled[states.join(\",\")] = new ContentMatch(states.indexOf(nfa.length - 1) > -1);\n        for (let i = 0; i < out.length; i++) {\n            let states = out[i][1].sort(cmp);\n            state.next.push({ type: out[i][0], next: labeled[states.join(\",\")] || explore(states) });\n        }\n        return state;\n    }\n}\nfunction checkForDeadEnds(match, stream) {\n    for (let i = 0, work = [match]; i < work.length; i++) {\n        let state = work[i], dead = !state.validEnd, nodes = [];\n        for (let j = 0; j < state.next.length; j++) {\n            let { type, next } = state.next[j];\n            nodes.push(type.name);\n            if (dead && !(type.isText || type.hasRequiredAttrs()))\n                dead = false;\n            if (work.indexOf(next) == -1)\n                work.push(next);\n        }\n        if (dead)\n            stream.err(\"Only non-generatable nodes (\" + nodes.join(\", \") + \") in a required position (see https://prosemirror.net/docs/guide/#generatable)\");\n    }\n}\n\n// For node types where all attrs have a default value (or which don't\n// have any attributes), build up a single reusable default attribute\n// object, and use it for all nodes that don't specify specific\n// attributes.\nfunction defaultAttrs(attrs) {\n    let defaults = Object.create(null);\n    for (let attrName in attrs) {\n        let attr = attrs[attrName];\n        if (!attr.hasDefault)\n            return null;\n        defaults[attrName] = attr.default;\n    }\n    return defaults;\n}\nfunction computeAttrs(attrs, value) {\n    let built = Object.create(null);\n    for (let name in attrs) {\n        let attr = attrs[name];\n        let given = value && value[name];\n        if (given === undefined) {\n            if (attr.hasDefault)\n                given = attr.default;\n            else\n                throw new RangeError(\"No value supplied for attribute \" + name);\n        }\n        else if (attr.validate) {\n            attr.validate(given);\n        }\n        built[name] = given;\n    }\n    return built;\n}\nfunction initAttrs(typeName, attrs) {\n    let result = Object.create(null);\n    if (attrs)\n        for (let name in attrs)\n            result[name] = new Attribute(typeName, name, attrs[name]);\n    return result;\n}\n/**\nNode types are objects allocated once per `Schema` and used to\n[tag](https://prosemirror.net/docs/ref/#model.Node.type) `Node` instances. They contain information\nabout the node type, such as its name and what kind of node it\nrepresents.\n*/\nclass NodeType {\n    /**\n    @internal\n    */\n    constructor(\n    /**\n    The name the node type has in this schema.\n    */\n    name, \n    /**\n    A link back to the `Schema` the node type belongs to.\n    */\n    schema, \n    /**\n    The spec that this type is based on\n    */\n    spec) {\n        this.name = name;\n        this.schema = schema;\n        this.spec = spec;\n        /**\n        The set of marks allowed in this node. `null` means all marks\n        are allowed.\n        */\n        this.markSet = null;\n        this.groups = spec.group ? spec.group.split(\" \") : [];\n        this.attrs = initAttrs(name, spec.attrs);\n        this.defaultAttrs = defaultAttrs(this.attrs);\n        this.contentMatch = null;\n        this.inlineContent = null;\n        this.isBlock = !(spec.inline || name == \"text\");\n        this.isText = name == \"text\";\n    }\n    /**\n    True if this is an inline type.\n    */\n    get isInline() { return !this.isBlock; }\n    /**\n    True if this is a textblock type, a block that contains inline\n    content.\n    */\n    get isTextblock() { return this.isBlock && this.inlineContent; }\n    /**\n    True for node types that allow no content.\n    */\n    get isLeaf() { return this.contentMatch == ContentMatch.empty; }\n    /**\n    True when this node is an atom, i.e. when it does not have\n    directly editable content.\n    */\n    get isAtom() { return this.isLeaf || !!this.spec.atom; }\n    /**\n    Return true when this node type is part of the given\n    [group](https://prosemirror.net/docs/ref/#model.NodeSpec.group).\n    */\n    isInGroup(group) {\n        return this.groups.indexOf(group) > -1;\n    }\n    /**\n    The node type's [whitespace](https://prosemirror.net/docs/ref/#model.NodeSpec.whitespace) option.\n    */\n    get whitespace() {\n        return this.spec.whitespace || (this.spec.code ? \"pre\" : \"normal\");\n    }\n    /**\n    Tells you whether this node type has any required attributes.\n    */\n    hasRequiredAttrs() {\n        for (let n in this.attrs)\n            if (this.attrs[n].isRequired)\n                return true;\n        return false;\n    }\n    /**\n    Indicates whether this node allows some of the same content as\n    the given node type.\n    */\n    compatibleContent(other) {\n        return this == other || this.contentMatch.compatible(other.contentMatch);\n    }\n    /**\n    @internal\n    */\n    computeAttrs(attrs) {\n        if (!attrs && this.defaultAttrs)\n            return this.defaultAttrs;\n        else\n            return computeAttrs(this.attrs, attrs);\n    }\n    /**\n    Create a `Node` of this type. The given attributes are\n    checked and defaulted (you can pass `null` to use the type's\n    defaults entirely, if no required attributes exist). `content`\n    may be a `Fragment`, a node, an array of nodes, or\n    `null`. Similarly `marks` may be `null` to default to the empty\n    set of marks.\n    */\n    create(attrs = null, content, marks) {\n        if (this.isText)\n            throw new Error(\"NodeType.create can't construct text nodes\");\n        return new Node(this, this.computeAttrs(attrs), Fragment.from(content), Mark.setFrom(marks));\n    }\n    /**\n    Like [`create`](https://prosemirror.net/docs/ref/#model.NodeType.create), but check the given content\n    against the node type's content restrictions, and throw an error\n    if it doesn't match.\n    */\n    createChecked(attrs = null, content, marks) {\n        content = Fragment.from(content);\n        this.checkContent(content);\n        return new Node(this, this.computeAttrs(attrs), content, Mark.setFrom(marks));\n    }\n    /**\n    Like [`create`](https://prosemirror.net/docs/ref/#model.NodeType.create), but see if it is\n    necessary to add nodes to the start or end of the given fragment\n    to make it fit the node. If no fitting wrapping can be found,\n    return null. Note that, due to the fact that required nodes can\n    always be created, this will always succeed if you pass null or\n    `Fragment.empty` as content.\n    */\n    createAndFill(attrs = null, content, marks) {\n        attrs = this.computeAttrs(attrs);\n        content = Fragment.from(content);\n        if (content.size) {\n            let before = this.contentMatch.fillBefore(content);\n            if (!before)\n                return null;\n            content = before.append(content);\n        }\n        let matched = this.contentMatch.matchFragment(content);\n        let after = matched && matched.fillBefore(Fragment.empty, true);\n        if (!after)\n            return null;\n        return new Node(this, attrs, content.append(after), Mark.setFrom(marks));\n    }\n    /**\n    Returns true if the given fragment is valid content for this node\n    type.\n    */\n    validContent(content) {\n        let result = this.contentMatch.matchFragment(content);\n        if (!result || !result.validEnd)\n            return false;\n        for (let i = 0; i < content.childCount; i++)\n            if (!this.allowsMarks(content.child(i).marks))\n                return false;\n        return true;\n    }\n    /**\n    Throws a RangeError if the given fragment is not valid content for this\n    node type.\n    @internal\n    */\n    checkContent(content) {\n        if (!this.validContent(content))\n            throw new RangeError(`Invalid content for node ${this.name}: ${content.toString().slice(0, 50)}`);\n    }\n    /**\n    @internal no longer useful, but called by old prosemirror-view versions\n    */\n    checkAttrs(attrs) { }\n    /**\n    Check whether the given mark type is allowed in this node.\n    */\n    allowsMarkType(markType) {\n        return this.markSet == null || this.markSet.indexOf(markType) > -1;\n    }\n    /**\n    Test whether the given set of marks are allowed in this node.\n    */\n    allowsMarks(marks) {\n        if (this.markSet == null)\n            return true;\n        for (let i = 0; i < marks.length; i++)\n            if (!this.allowsMarkType(marks[i].type))\n                return false;\n        return true;\n    }\n    /**\n    Removes the marks that are not allowed in this node from the given set.\n    */\n    allowedMarks(marks) {\n        if (this.markSet == null)\n            return marks;\n        let copy;\n        for (let i = 0; i < marks.length; i++) {\n            if (!this.allowsMarkType(marks[i].type)) {\n                if (!copy)\n                    copy = marks.slice(0, i);\n            }\n            else if (copy) {\n                copy.push(marks[i]);\n            }\n        }\n        return !copy ? marks : copy.length ? copy : Mark.none;\n    }\n    /**\n    @internal\n    */\n    static compile(nodes, schema) {\n        let result = Object.create(null);\n        nodes.forEach((name, spec) => result[name] = new NodeType(name, schema, spec));\n        let topType = schema.spec.topNode || \"doc\";\n        if (!result[topType])\n            throw new RangeError(\"Schema is missing its top node type ('\" + topType + \"')\");\n        if (!result.text)\n            throw new RangeError(\"Every schema needs a 'text' type\");\n        for (let _ in result.text.attrs)\n            throw new RangeError(\"The text node type should not have attributes\");\n        return result;\n    }\n}\nfunction validateType(typeName, attrName, type) {\n    let types = type.split(\"|\");\n    return (value) => {\n        let name = value === null ? \"null\" : typeof value;\n        if (types.indexOf(name) < 0)\n            throw new RangeError(`Expected value of type ${types} for attribute ${attrName} on type ${typeName}, got ${name}`);\n    };\n}\n// Attribute descriptors\nclass Attribute {\n    constructor(typeName, attrName, options) {\n        this.hasDefault = Object.prototype.hasOwnProperty.call(options, \"default\");\n        this.default = options.default;\n        this.validate = typeof options.validate == \"string\" ? validateType(typeName, attrName, options.validate) : options.validate;\n    }\n    get isRequired() {\n        return !this.hasDefault;\n    }\n}\n// Marks\n/**\nLike nodes, marks (which are associated with nodes to signify\nthings like emphasis or being part of a link) are\n[tagged](https://prosemirror.net/docs/ref/#model.Mark.type) with type objects, which are\ninstantiated once per `Schema`.\n*/\nclass MarkType {\n    /**\n    @internal\n    */\n    constructor(\n    /**\n    The name of the mark type.\n    */\n    name, \n    /**\n    @internal\n    */\n    rank, \n    /**\n    The schema that this mark type instance is part of.\n    */\n    schema, \n    /**\n    The spec on which the type is based.\n    */\n    spec) {\n        this.name = name;\n        this.rank = rank;\n        this.schema = schema;\n        this.spec = spec;\n        this.attrs = initAttrs(name, spec.attrs);\n        this.excluded = null;\n        let defaults = defaultAttrs(this.attrs);\n        this.instance = defaults ? new Mark(this, defaults) : null;\n    }\n    /**\n    Create a mark of this type. `attrs` may be `null` or an object\n    containing only some of the mark's attributes. The others, if\n    they have defaults, will be added.\n    */\n    create(attrs = null) {\n        if (!attrs && this.instance)\n            return this.instance;\n        return new Mark(this, computeAttrs(this.attrs, attrs));\n    }\n    /**\n    @internal\n    */\n    static compile(marks, schema) {\n        let result = Object.create(null), rank = 0;\n        marks.forEach((name, spec) => result[name] = new MarkType(name, rank++, schema, spec));\n        return result;\n    }\n    /**\n    When there is a mark of this type in the given set, a new set\n    without it is returned. Otherwise, the input set is returned.\n    */\n    removeFromSet(set) {\n        for (var i = 0; i < set.length; i++)\n            if (set[i].type == this) {\n                set = set.slice(0, i).concat(set.slice(i + 1));\n                i--;\n            }\n        return set;\n    }\n    /**\n    Tests whether there is a mark of this type in the given set.\n    */\n    isInSet(set) {\n        for (let i = 0; i < set.length; i++)\n            if (set[i].type == this)\n                return set[i];\n    }\n    /**\n    Queries whether a given mark type is\n    [excluded](https://prosemirror.net/docs/ref/#model.MarkSpec.excludes) by this one.\n    */\n    excludes(other) {\n        return this.excluded.indexOf(other) > -1;\n    }\n}\n/**\nA document schema. Holds [node](https://prosemirror.net/docs/ref/#model.NodeType) and [mark\ntype](https://prosemirror.net/docs/ref/#model.MarkType) objects for the nodes and marks that may\noccur in conforming documents, and provides functionality for\ncreating and deserializing such documents.\n\nWhen given, the type parameters provide the names of the nodes and\nmarks in this schema.\n*/\nclass Schema {\n    /**\n    Construct a schema from a schema [specification](https://prosemirror.net/docs/ref/#model.SchemaSpec).\n    */\n    constructor(spec) {\n        /**\n        The [linebreak\n        replacement](https://prosemirror.net/docs/ref/#model.NodeSpec.linebreakReplacement) node defined\n        in this schema, if any.\n        */\n        this.linebreakReplacement = null;\n        /**\n        An object for storing whatever values modules may want to\n        compute and cache per schema. (If you want to store something\n        in it, try to use property names unlikely to clash.)\n        */\n        this.cached = Object.create(null);\n        let instanceSpec = this.spec = {};\n        for (let prop in spec)\n            instanceSpec[prop] = spec[prop];\n        instanceSpec.nodes = OrderedMap.from(spec.nodes),\n            instanceSpec.marks = OrderedMap.from(spec.marks || {}),\n            this.nodes = NodeType.compile(this.spec.nodes, this);\n        this.marks = MarkType.compile(this.spec.marks, this);\n        let contentExprCache = Object.create(null);\n        for (let prop in this.nodes) {\n            if (prop in this.marks)\n                throw new RangeError(prop + \" can not be both a node and a mark\");\n            let type = this.nodes[prop], contentExpr = type.spec.content || \"\", markExpr = type.spec.marks;\n            type.contentMatch = contentExprCache[contentExpr] ||\n                (contentExprCache[contentExpr] = ContentMatch.parse(contentExpr, this.nodes));\n            type.inlineContent = type.contentMatch.inlineContent;\n            if (type.spec.linebreakReplacement) {\n                if (this.linebreakReplacement)\n                    throw new RangeError(\"Multiple linebreak nodes defined\");\n                if (!type.isInline || !type.isLeaf)\n                    throw new RangeError(\"Linebreak replacement nodes must be inline leaf nodes\");\n                this.linebreakReplacement = type;\n            }\n            type.markSet = markExpr == \"_\" ? null :\n                markExpr ? gatherMarks(this, markExpr.split(\" \")) :\n                    markExpr == \"\" || !type.inlineContent ? [] : null;\n        }\n        for (let prop in this.marks) {\n            let type = this.marks[prop], excl = type.spec.excludes;\n            type.excluded = excl == null ? [type] : excl == \"\" ? [] : gatherMarks(this, excl.split(\" \"));\n        }\n        this.nodeFromJSON = json => Node.fromJSON(this, json);\n        this.markFromJSON = json => Mark.fromJSON(this, json);\n        this.topNodeType = this.nodes[this.spec.topNode || \"doc\"];\n        this.cached.wrappings = Object.create(null);\n    }\n    /**\n    Create a node in this schema. The `type` may be a string or a\n    `NodeType` instance. Attributes will be extended with defaults,\n    `content` may be a `Fragment`, `null`, a `Node`, or an array of\n    nodes.\n    */\n    node(type, attrs = null, content, marks) {\n        if (typeof type == \"string\")\n            type = this.nodeType(type);\n        else if (!(type instanceof NodeType))\n            throw new RangeError(\"Invalid node type: \" + type);\n        else if (type.schema != this)\n            throw new RangeError(\"Node type from different schema used (\" + type.name + \")\");\n        return type.createChecked(attrs, content, marks);\n    }\n    /**\n    Create a text node in the schema. Empty text nodes are not\n    allowed.\n    */\n    text(text, marks) {\n        let type = this.nodes.text;\n        return new TextNode(type, type.defaultAttrs, text, Mark.setFrom(marks));\n    }\n    /**\n    Create a mark with the given type and attributes.\n    */\n    mark(type, attrs) {\n        if (typeof type == \"string\")\n            type = this.marks[type];\n        return type.create(attrs);\n    }\n    /**\n    @internal\n    */\n    nodeType(name) {\n        let found = this.nodes[name];\n        if (!found)\n            throw new RangeError(\"Unknown node type: \" + name);\n        return found;\n    }\n}\nfunction gatherMarks(schema, marks) {\n    let found = [];\n    for (let i = 0; i < marks.length; i++) {\n        let name = marks[i], mark = schema.marks[name], ok = mark;\n        if (mark) {\n            found.push(mark);\n        }\n        else {\n            for (let prop in schema.marks) {\n                let mark = schema.marks[prop];\n                if (name == \"_\" || (mark.spec.group && mark.spec.group.split(\" \").indexOf(name) > -1))\n                    found.push(ok = mark);\n            }\n        }\n        if (!ok)\n            throw new SyntaxError(\"Unknown mark type: '\" + marks[i] + \"'\");\n    }\n    return found;\n}\n\nfunction isTagRule(rule) { return rule.tag != null; }\nfunction isStyleRule(rule) { return rule.style != null; }\n/**\nA DOM parser represents a strategy for parsing DOM content into a\nProseMirror document conforming to a given schema. Its behavior is\ndefined by an array of [rules](https://prosemirror.net/docs/ref/#model.ParseRule).\n*/\nclass DOMParser {\n    /**\n    Create a parser that targets the given schema, using the given\n    parsing rules.\n    */\n    constructor(\n    /**\n    The schema into which the parser parses.\n    */\n    schema, \n    /**\n    The set of [parse rules](https://prosemirror.net/docs/ref/#model.ParseRule) that the parser\n    uses, in order of precedence.\n    */\n    rules) {\n        this.schema = schema;\n        this.rules = rules;\n        /**\n        @internal\n        */\n        this.tags = [];\n        /**\n        @internal\n        */\n        this.styles = [];\n        let matchedStyles = this.matchedStyles = [];\n        rules.forEach(rule => {\n            if (isTagRule(rule)) {\n                this.tags.push(rule);\n            }\n            else if (isStyleRule(rule)) {\n                let prop = /[^=]*/.exec(rule.style)[0];\n                if (matchedStyles.indexOf(prop) < 0)\n                    matchedStyles.push(prop);\n                this.styles.push(rule);\n            }\n        });\n        // Only normalize list elements when lists in the schema can't directly contain themselves\n        this.normalizeLists = !this.tags.some(r => {\n            if (!/^(ul|ol)\\b/.test(r.tag) || !r.node)\n                return false;\n            let node = schema.nodes[r.node];\n            return node.contentMatch.matchType(node);\n        });\n    }\n    /**\n    Parse a document from the content of a DOM node.\n    */\n    parse(dom, options = {}) {\n        let context = new ParseContext(this, options, false);\n        context.addAll(dom, Mark.none, options.from, options.to);\n        return context.finish();\n    }\n    /**\n    Parses the content of the given DOM node, like\n    [`parse`](https://prosemirror.net/docs/ref/#model.DOMParser.parse), and takes the same set of\n    options. But unlike that method, which produces a whole node,\n    this one returns a slice that is open at the sides, meaning that\n    the schema constraints aren't applied to the start of nodes to\n    the left of the input and the end of nodes at the end.\n    */\n    parseSlice(dom, options = {}) {\n        let context = new ParseContext(this, options, true);\n        context.addAll(dom, Mark.none, options.from, options.to);\n        return Slice.maxOpen(context.finish());\n    }\n    /**\n    @internal\n    */\n    matchTag(dom, context, after) {\n        for (let i = after ? this.tags.indexOf(after) + 1 : 0; i < this.tags.length; i++) {\n            let rule = this.tags[i];\n            if (matches(dom, rule.tag) &&\n                (rule.namespace === undefined || dom.namespaceURI == rule.namespace) &&\n                (!rule.context || context.matchesContext(rule.context))) {\n                if (rule.getAttrs) {\n                    let result = rule.getAttrs(dom);\n                    if (result === false)\n                        continue;\n                    rule.attrs = result || undefined;\n                }\n                return rule;\n            }\n        }\n    }\n    /**\n    @internal\n    */\n    matchStyle(prop, value, context, after) {\n        for (let i = after ? this.styles.indexOf(after) + 1 : 0; i < this.styles.length; i++) {\n            let rule = this.styles[i], style = rule.style;\n            if (style.indexOf(prop) != 0 ||\n                rule.context && !context.matchesContext(rule.context) ||\n                // Test that the style string either precisely matches the prop,\n                // or has an '=' sign after the prop, followed by the given\n                // value.\n                style.length > prop.length &&\n                    (style.charCodeAt(prop.length) != 61 || style.slice(prop.length + 1) != value))\n                continue;\n            if (rule.getAttrs) {\n                let result = rule.getAttrs(value);\n                if (result === false)\n                    continue;\n                rule.attrs = result || undefined;\n            }\n            return rule;\n        }\n    }\n    /**\n    @internal\n    */\n    static schemaRules(schema) {\n        let result = [];\n        function insert(rule) {\n            let priority = rule.priority == null ? 50 : rule.priority, i = 0;\n            for (; i < result.length; i++) {\n                let next = result[i], nextPriority = next.priority == null ? 50 : next.priority;\n                if (nextPriority < priority)\n                    break;\n            }\n            result.splice(i, 0, rule);\n        }\n        for (let name in schema.marks) {\n            let rules = schema.marks[name].spec.parseDOM;\n            if (rules)\n                rules.forEach(rule => {\n                    insert(rule = copy(rule));\n                    if (!(rule.mark || rule.ignore || rule.clearMark))\n                        rule.mark = name;\n                });\n        }\n        for (let name in schema.nodes) {\n            let rules = schema.nodes[name].spec.parseDOM;\n            if (rules)\n                rules.forEach(rule => {\n                    insert(rule = copy(rule));\n                    if (!(rule.node || rule.ignore || rule.mark))\n                        rule.node = name;\n                });\n        }\n        return result;\n    }\n    /**\n    Construct a DOM parser using the parsing rules listed in a\n    schema's [node specs](https://prosemirror.net/docs/ref/#model.NodeSpec.parseDOM), reordered by\n    [priority](https://prosemirror.net/docs/ref/#model.GenericParseRule.priority).\n    */\n    static fromSchema(schema) {\n        return schema.cached.domParser ||\n            (schema.cached.domParser = new DOMParser(schema, DOMParser.schemaRules(schema)));\n    }\n}\nconst blockTags = {\n    address: true, article: true, aside: true, blockquote: true, body: true, canvas: true,\n    dd: true, div: true, dl: true, fieldset: true, figcaption: true, figure: true,\n    footer: true, form: true, h1: true, h2: true, h3: true, h4: true, h5: true,\n    h6: true, header: true, hgroup: true, hr: true, li: true, noscript: true, ol: true,\n    output: true, p: true, pre: true, section: true, table: true, tfoot: true, ul: true\n};\nconst ignoreTags = {\n    head: true, noscript: true, object: true, script: true, style: true, title: true\n};\nconst listTags = { ol: true, ul: true };\n// Using a bitfield for node context options\nconst OPT_PRESERVE_WS = 1, OPT_PRESERVE_WS_FULL = 2, OPT_OPEN_LEFT = 4;\nfunction wsOptionsFor(type, preserveWhitespace, base) {\n    if (preserveWhitespace != null)\n        return (preserveWhitespace ? OPT_PRESERVE_WS : 0) |\n            (preserveWhitespace === \"full\" ? OPT_PRESERVE_WS_FULL : 0);\n    return type && type.whitespace == \"pre\" ? OPT_PRESERVE_WS | OPT_PRESERVE_WS_FULL : base & ~OPT_OPEN_LEFT;\n}\nclass NodeContext {\n    constructor(type, attrs, marks, solid, match, options) {\n        this.type = type;\n        this.attrs = attrs;\n        this.marks = marks;\n        this.solid = solid;\n        this.options = options;\n        this.content = [];\n        // Marks applied to the node's children\n        this.activeMarks = Mark.none;\n        this.match = match || (options & OPT_OPEN_LEFT ? null : type.contentMatch);\n    }\n    findWrapping(node) {\n        if (!this.match) {\n            if (!this.type)\n                return [];\n            let fill = this.type.contentMatch.fillBefore(Fragment.from(node));\n            if (fill) {\n                this.match = this.type.contentMatch.matchFragment(fill);\n            }\n            else {\n                let start = this.type.contentMatch, wrap;\n                if (wrap = start.findWrapping(node.type)) {\n                    this.match = start;\n                    return wrap;\n                }\n                else {\n                    return null;\n                }\n            }\n        }\n        return this.match.findWrapping(node.type);\n    }\n    finish(openEnd) {\n        if (!(this.options & OPT_PRESERVE_WS)) { // Strip trailing whitespace\n            let last = this.content[this.content.length - 1], m;\n            if (last && last.isText && (m = /[ \\t\\r\\n\\u000c]+$/.exec(last.text))) {\n                let text = last;\n                if (last.text.length == m[0].length)\n                    this.content.pop();\n                else\n                    this.content[this.content.length - 1] = text.withText(text.text.slice(0, text.text.length - m[0].length));\n            }\n        }\n        let content = Fragment.from(this.content);\n        if (!openEnd && this.match)\n            content = content.append(this.match.fillBefore(Fragment.empty, true));\n        return this.type ? this.type.create(this.attrs, content, this.marks) : content;\n    }\n    inlineContext(node) {\n        if (this.type)\n            return this.type.inlineContent;\n        if (this.content.length)\n            return this.content[0].isInline;\n        return node.parentNode && !blockTags.hasOwnProperty(node.parentNode.nodeName.toLowerCase());\n    }\n}\nclass ParseContext {\n    constructor(\n    // The parser we are using.\n    parser, \n    // The options passed to this parse.\n    options, isOpen) {\n        this.parser = parser;\n        this.options = options;\n        this.isOpen = isOpen;\n        this.open = 0;\n        this.localPreserveWS = false;\n        let topNode = options.topNode, topContext;\n        let topOptions = wsOptionsFor(null, options.preserveWhitespace, 0) | (isOpen ? OPT_OPEN_LEFT : 0);\n        if (topNode)\n            topContext = new NodeContext(topNode.type, topNode.attrs, Mark.none, true, options.topMatch || topNode.type.contentMatch, topOptions);\n        else if (isOpen)\n            topContext = new NodeContext(null, null, Mark.none, true, null, topOptions);\n        else\n            topContext = new NodeContext(parser.schema.topNodeType, null, Mark.none, true, null, topOptions);\n        this.nodes = [topContext];\n        this.find = options.findPositions;\n        this.needsBlock = false;\n    }\n    get top() {\n        return this.nodes[this.open];\n    }\n    // Add a DOM node to the content. Text is inserted as text node,\n    // otherwise, the node is passed to `addElement` or, if it has a\n    // `style` attribute, `addElementWithStyles`.\n    addDOM(dom, marks) {\n        if (dom.nodeType == 3)\n            this.addTextNode(dom, marks);\n        else if (dom.nodeType == 1)\n            this.addElement(dom, marks);\n    }\n    addTextNode(dom, marks) {\n        let value = dom.nodeValue;\n        let top = this.top, preserveWS = (top.options & OPT_PRESERVE_WS_FULL) ? \"full\"\n            : this.localPreserveWS || (top.options & OPT_PRESERVE_WS) > 0;\n        let { schema } = this.parser;\n        if (preserveWS === \"full\" ||\n            top.inlineContext(dom) ||\n            /[^ \\t\\r\\n\\u000c]/.test(value)) {\n            if (!preserveWS) {\n                value = value.replace(/[ \\t\\r\\n\\u000c]+/g, \" \");\n                // If this starts with whitespace, and there is no node before it, or\n                // a hard break, or a text node that ends with whitespace, strip the\n                // leading space.\n                if (/^[ \\t\\r\\n\\u000c]/.test(value) && this.open == this.nodes.length - 1) {\n                    let nodeBefore = top.content[top.content.length - 1];\n                    let domNodeBefore = dom.previousSibling;\n                    if (!nodeBefore ||\n                        (domNodeBefore && domNodeBefore.nodeName == 'BR') ||\n                        (nodeBefore.isText && /[ \\t\\r\\n\\u000c]$/.test(nodeBefore.text)))\n                        value = value.slice(1);\n                }\n            }\n            else if (preserveWS === \"full\") {\n                value = value.replace(/\\r\\n?/g, \"\\n\");\n            }\n            else if (schema.linebreakReplacement && /[\\r\\n]/.test(value) && this.top.findWrapping(schema.linebreakReplacement.create())) {\n                let lines = value.split(/\\r?\\n|\\r/);\n                for (let i = 0; i < lines.length; i++) {\n                    if (i)\n                        this.insertNode(schema.linebreakReplacement.create(), marks, true);\n                    if (lines[i])\n                        this.insertNode(schema.text(lines[i]), marks, !/\\S/.test(lines[i]));\n                }\n                value = \"\";\n            }\n            else {\n                value = value.replace(/\\r?\\n|\\r/g, \" \");\n            }\n            if (value)\n                this.insertNode(schema.text(value), marks, !/\\S/.test(value));\n            this.findInText(dom);\n        }\n        else {\n            this.findInside(dom);\n        }\n    }\n    // Try to find a handler for the given tag and use that to parse. If\n    // none is found, the element's content nodes are added directly.\n    addElement(dom, marks, matchAfter) {\n        let outerWS = this.localPreserveWS, top = this.top;\n        if (dom.tagName == \"PRE\" || /pre/.test(dom.style && dom.style.whiteSpace))\n            this.localPreserveWS = true;\n        let name = dom.nodeName.toLowerCase(), ruleID;\n        if (listTags.hasOwnProperty(name) && this.parser.normalizeLists)\n            normalizeList(dom);\n        let rule = (this.options.ruleFromNode && this.options.ruleFromNode(dom)) ||\n            (ruleID = this.parser.matchTag(dom, this, matchAfter));\n        out: if (rule ? rule.ignore : ignoreTags.hasOwnProperty(name)) {\n            this.findInside(dom);\n            this.ignoreFallback(dom, marks);\n        }\n        else if (!rule || rule.skip || rule.closeParent) {\n            if (rule && rule.closeParent)\n                this.open = Math.max(0, this.open - 1);\n            else if (rule && rule.skip.nodeType)\n                dom = rule.skip;\n            let sync, oldNeedsBlock = this.needsBlock;\n            if (blockTags.hasOwnProperty(name)) {\n                if (top.content.length && top.content[0].isInline && this.open) {\n                    this.open--;\n                    top = this.top;\n                }\n                sync = true;\n                if (!top.type)\n                    this.needsBlock = true;\n            }\n            else if (!dom.firstChild) {\n                this.leafFallback(dom, marks);\n                break out;\n            }\n            let innerMarks = rule && rule.skip ? marks : this.readStyles(dom, marks);\n            if (innerMarks)\n                this.addAll(dom, innerMarks);\n            if (sync)\n                this.sync(top);\n            this.needsBlock = oldNeedsBlock;\n        }\n        else {\n            let innerMarks = this.readStyles(dom, marks);\n            if (innerMarks)\n                this.addElementByRule(dom, rule, innerMarks, rule.consuming === false ? ruleID : undefined);\n        }\n        this.localPreserveWS = outerWS;\n    }\n    // Called for leaf DOM nodes that would otherwise be ignored\n    leafFallback(dom, marks) {\n        if (dom.nodeName == \"BR\" && this.top.type && this.top.type.inlineContent)\n            this.addTextNode(dom.ownerDocument.createTextNode(\"\\n\"), marks);\n    }\n    // Called for ignored nodes\n    ignoreFallback(dom, marks) {\n        // Ignored BR nodes should at least create an inline context\n        if (dom.nodeName == \"BR\" && (!this.top.type || !this.top.type.inlineContent))\n            this.findPlace(this.parser.schema.text(\"-\"), marks, true);\n    }\n    // Run any style parser associated with the node's styles. Either\n    // return an updated array of marks, or null to indicate some of the\n    // styles had a rule with `ignore` set.\n    readStyles(dom, marks) {\n        let styles = dom.style;\n        // Because many properties will only show up in 'normalized' form\n        // in `style.item` (i.e. text-decoration becomes\n        // text-decoration-line, text-decoration-color, etc), we directly\n        // query the styles mentioned in our rules instead of iterating\n        // over the items.\n        if (styles && styles.length)\n            for (let i = 0; i < this.parser.matchedStyles.length; i++) {\n                let name = this.parser.matchedStyles[i], value = styles.getPropertyValue(name);\n                if (value)\n                    for (let after = undefined;;) {\n                        let rule = this.parser.matchStyle(name, value, this, after);\n                        if (!rule)\n                            break;\n                        if (rule.ignore)\n                            return null;\n                        if (rule.clearMark)\n                            marks = marks.filter(m => !rule.clearMark(m));\n                        else\n                            marks = marks.concat(this.parser.schema.marks[rule.mark].create(rule.attrs));\n                        if (rule.consuming === false)\n                            after = rule;\n                        else\n                            break;\n                    }\n            }\n        return marks;\n    }\n    // Look up a handler for the given node. If none are found, return\n    // false. Otherwise, apply it, use its return value to drive the way\n    // the node's content is wrapped, and return true.\n    addElementByRule(dom, rule, marks, continueAfter) {\n        let sync, nodeType;\n        if (rule.node) {\n            nodeType = this.parser.schema.nodes[rule.node];\n            if (!nodeType.isLeaf) {\n                let inner = this.enter(nodeType, rule.attrs || null, marks, rule.preserveWhitespace);\n                if (inner) {\n                    sync = true;\n                    marks = inner;\n                }\n            }\n            else if (!this.insertNode(nodeType.create(rule.attrs), marks, dom.nodeName == \"BR\")) {\n                this.leafFallback(dom, marks);\n            }\n        }\n        else {\n            let markType = this.parser.schema.marks[rule.mark];\n            marks = marks.concat(markType.create(rule.attrs));\n        }\n        let startIn = this.top;\n        if (nodeType && nodeType.isLeaf) {\n            this.findInside(dom);\n        }\n        else if (continueAfter) {\n            this.addElement(dom, marks, continueAfter);\n        }\n        else if (rule.getContent) {\n            this.findInside(dom);\n            rule.getContent(dom, this.parser.schema).forEach(node => this.insertNode(node, marks, false));\n        }\n        else {\n            let contentDOM = dom;\n            if (typeof rule.contentElement == \"string\")\n                contentDOM = dom.querySelector(rule.contentElement);\n            else if (typeof rule.contentElement == \"function\")\n                contentDOM = rule.contentElement(dom);\n            else if (rule.contentElement)\n                contentDOM = rule.contentElement;\n            this.findAround(dom, contentDOM, true);\n            this.addAll(contentDOM, marks);\n            this.findAround(dom, contentDOM, false);\n        }\n        if (sync && this.sync(startIn))\n            this.open--;\n    }\n    // Add all child nodes between `startIndex` and `endIndex` (or the\n    // whole node, if not given). If `sync` is passed, use it to\n    // synchronize after every block element.\n    addAll(parent, marks, startIndex, endIndex) {\n        let index = startIndex || 0;\n        for (let dom = startIndex ? parent.childNodes[startIndex] : parent.firstChild, end = endIndex == null ? null : parent.childNodes[endIndex]; dom != end; dom = dom.nextSibling, ++index) {\n            this.findAtPoint(parent, index);\n            this.addDOM(dom, marks);\n        }\n        this.findAtPoint(parent, index);\n    }\n    // Try to find a way to fit the given node type into the current\n    // context. May add intermediate wrappers and/or leave non-solid\n    // nodes that we're in.\n    findPlace(node, marks, cautious) {\n        let route, sync;\n        for (let depth = this.open, penalty = 0; depth >= 0; depth--) {\n            let cx = this.nodes[depth];\n            let found = cx.findWrapping(node);\n            if (found && (!route || route.length > found.length + penalty)) {\n                route = found;\n                sync = cx;\n                if (!found.length)\n                    break;\n            }\n            if (cx.solid) {\n                if (cautious)\n                    break;\n                penalty += 2;\n            }\n        }\n        if (!route)\n            return null;\n        this.sync(sync);\n        for (let i = 0; i < route.length; i++)\n            marks = this.enterInner(route[i], null, marks, false);\n        return marks;\n    }\n    // Try to insert the given node, adjusting the context when needed.\n    insertNode(node, marks, cautious) {\n        if (node.isInline && this.needsBlock && !this.top.type) {\n            let block = this.textblockFromContext();\n            if (block)\n                marks = this.enterInner(block, null, marks);\n        }\n        let innerMarks = this.findPlace(node, marks, cautious);\n        if (innerMarks) {\n            this.closeExtra();\n            let top = this.top;\n            if (top.match)\n                top.match = top.match.matchType(node.type);\n            let nodeMarks = Mark.none;\n            for (let m of innerMarks.concat(node.marks))\n                if (top.type ? top.type.allowsMarkType(m.type) : markMayApply(m.type, node.type))\n                    nodeMarks = m.addToSet(nodeMarks);\n            top.content.push(node.mark(nodeMarks));\n            return true;\n        }\n        return false;\n    }\n    // Try to start a node of the given type, adjusting the context when\n    // necessary.\n    enter(type, attrs, marks, preserveWS) {\n        let innerMarks = this.findPlace(type.create(attrs), marks, false);\n        if (innerMarks)\n            innerMarks = this.enterInner(type, attrs, marks, true, preserveWS);\n        return innerMarks;\n    }\n    // Open a node of the given type\n    enterInner(type, attrs, marks, solid = false, preserveWS) {\n        this.closeExtra();\n        let top = this.top;\n        top.match = top.match && top.match.matchType(type);\n        let options = wsOptionsFor(type, preserveWS, top.options);\n        if ((top.options & OPT_OPEN_LEFT) && top.content.length == 0)\n            options |= OPT_OPEN_LEFT;\n        let applyMarks = Mark.none;\n        marks = marks.filter(m => {\n            if (top.type ? top.type.allowsMarkType(m.type) : markMayApply(m.type, type)) {\n                applyMarks = m.addToSet(applyMarks);\n                return false;\n            }\n            return true;\n        });\n        this.nodes.push(new NodeContext(type, attrs, applyMarks, solid, null, options));\n        this.open++;\n        return marks;\n    }\n    // Make sure all nodes above this.open are finished and added to\n    // their parents\n    closeExtra(openEnd = false) {\n        let i = this.nodes.length - 1;\n        if (i > this.open) {\n            for (; i > this.open; i--)\n                this.nodes[i - 1].content.push(this.nodes[i].finish(openEnd));\n            this.nodes.length = this.open + 1;\n        }\n    }\n    finish() {\n        this.open = 0;\n        this.closeExtra(this.isOpen);\n        return this.nodes[0].finish(!!(this.isOpen || this.options.topOpen));\n    }\n    sync(to) {\n        for (let i = this.open; i >= 0; i--) {\n            if (this.nodes[i] == to) {\n                this.open = i;\n                return true;\n            }\n            else if (this.localPreserveWS) {\n                this.nodes[i].options |= OPT_PRESERVE_WS;\n            }\n        }\n        return false;\n    }\n    get currentPos() {\n        this.closeExtra();\n        let pos = 0;\n        for (let i = this.open; i >= 0; i--) {\n            let content = this.nodes[i].content;\n            for (let j = content.length - 1; j >= 0; j--)\n                pos += content[j].nodeSize;\n            if (i)\n                pos++;\n        }\n        return pos;\n    }\n    findAtPoint(parent, offset) {\n        if (this.find)\n            for (let i = 0; i < this.find.length; i++) {\n                if (this.find[i].node == parent && this.find[i].offset == offset)\n                    this.find[i].pos = this.currentPos;\n            }\n    }\n    findInside(parent) {\n        if (this.find)\n            for (let i = 0; i < this.find.length; i++) {\n                if (this.find[i].pos == null && parent.nodeType == 1 && parent.contains(this.find[i].node))\n                    this.find[i].pos = this.currentPos;\n            }\n    }\n    findAround(parent, content, before) {\n        if (parent != content && this.find)\n            for (let i = 0; i < this.find.length; i++) {\n                if (this.find[i].pos == null && parent.nodeType == 1 && parent.contains(this.find[i].node)) {\n                    let pos = content.compareDocumentPosition(this.find[i].node);\n                    if (pos & (before ? 2 : 4))\n                        this.find[i].pos = this.currentPos;\n                }\n            }\n    }\n    findInText(textNode) {\n        if (this.find)\n            for (let i = 0; i < this.find.length; i++) {\n                if (this.find[i].node == textNode)\n                    this.find[i].pos = this.currentPos - (textNode.nodeValue.length - this.find[i].offset);\n            }\n    }\n    // Determines whether the given context string matches this context.\n    matchesContext(context) {\n        if (context.indexOf(\"|\") > -1)\n            return context.split(/\\s*\\|\\s*/).some(this.matchesContext, this);\n        let parts = context.split(\"/\");\n        let option = this.options.context;\n        let useRoot = !this.isOpen && (!option || option.parent.type == this.nodes[0].type);\n        let minDepth = -(option ? option.depth + 1 : 0) + (useRoot ? 0 : 1);\n        let match = (i, depth) => {\n            for (; i >= 0; i--) {\n                let part = parts[i];\n                if (part == \"\") {\n                    if (i == parts.length - 1 || i == 0)\n                        continue;\n                    for (; depth >= minDepth; depth--)\n                        if (match(i - 1, depth))\n                            return true;\n                    return false;\n                }\n                else {\n                    let next = depth > 0 || (depth == 0 && useRoot) ? this.nodes[depth].type\n                        : option && depth >= minDepth ? option.node(depth - minDepth).type\n                            : null;\n                    if (!next || (next.name != part && !next.isInGroup(part)))\n                        return false;\n                    depth--;\n                }\n            }\n            return true;\n        };\n        return match(parts.length - 1, this.open);\n    }\n    textblockFromContext() {\n        let $context = this.options.context;\n        if ($context)\n            for (let d = $context.depth; d >= 0; d--) {\n                let deflt = $context.node(d).contentMatchAt($context.indexAfter(d)).defaultType;\n                if (deflt && deflt.isTextblock && deflt.defaultAttrs)\n                    return deflt;\n            }\n        for (let name in this.parser.schema.nodes) {\n            let type = this.parser.schema.nodes[name];\n            if (type.isTextblock && type.defaultAttrs)\n                return type;\n        }\n    }\n}\n// Kludge to work around directly nested list nodes produced by some\n// tools and allowed by browsers to mean that the nested list is\n// actually part of the list item above it.\nfunction normalizeList(dom) {\n    for (let child = dom.firstChild, prevItem = null; child; child = child.nextSibling) {\n        let name = child.nodeType == 1 ? child.nodeName.toLowerCase() : null;\n        if (name && listTags.hasOwnProperty(name) && prevItem) {\n            prevItem.appendChild(child);\n            child = prevItem;\n        }\n        else if (name == \"li\") {\n            prevItem = child;\n        }\n        else if (name) {\n            prevItem = null;\n        }\n    }\n}\n// Apply a CSS selector.\nfunction matches(dom, selector) {\n    return (dom.matches || dom.msMatchesSelector || dom.webkitMatchesSelector || dom.mozMatchesSelector).call(dom, selector);\n}\nfunction copy(obj) {\n    let copy = {};\n    for (let prop in obj)\n        copy[prop] = obj[prop];\n    return copy;\n}\n// Used when finding a mark at the top level of a fragment parse.\n// Checks whether it would be reasonable to apply a given mark type to\n// a given node, by looking at the way the mark occurs in the schema.\nfunction markMayApply(markType, nodeType) {\n    let nodes = nodeType.schema.nodes;\n    for (let name in nodes) {\n        let parent = nodes[name];\n        if (!parent.allowsMarkType(markType))\n            continue;\n        let seen = [], scan = (match) => {\n            seen.push(match);\n            for (let i = 0; i < match.edgeCount; i++) {\n                let { type, next } = match.edge(i);\n                if (type == nodeType)\n                    return true;\n                if (seen.indexOf(next) < 0 && scan(next))\n                    return true;\n            }\n        };\n        if (scan(parent.contentMatch))\n            return true;\n    }\n}\n\n/**\nA DOM serializer knows how to convert ProseMirror nodes and\nmarks of various types to DOM nodes.\n*/\nclass DOMSerializer {\n    /**\n    Create a serializer. `nodes` should map node names to functions\n    that take a node and return a description of the corresponding\n    DOM. `marks` does the same for mark names, but also gets an\n    argument that tells it whether the mark's content is block or\n    inline content (for typical use, it'll always be inline). A mark\n    serializer may be `null` to indicate that marks of that type\n    should not be serialized.\n    */\n    constructor(\n    /**\n    The node serialization functions.\n    */\n    nodes, \n    /**\n    The mark serialization functions.\n    */\n    marks) {\n        this.nodes = nodes;\n        this.marks = marks;\n    }\n    /**\n    Serialize the content of this fragment to a DOM fragment. When\n    not in the browser, the `document` option, containing a DOM\n    document, should be passed so that the serializer can create\n    nodes.\n    */\n    serializeFragment(fragment, options = {}, target) {\n        if (!target)\n            target = doc(options).createDocumentFragment();\n        let top = target, active = [];\n        fragment.forEach(node => {\n            if (active.length || node.marks.length) {\n                let keep = 0, rendered = 0;\n                while (keep < active.length && rendered < node.marks.length) {\n                    let next = node.marks[rendered];\n                    if (!this.marks[next.type.name]) {\n                        rendered++;\n                        continue;\n                    }\n                    if (!next.eq(active[keep][0]) || next.type.spec.spanning === false)\n                        break;\n                    keep++;\n                    rendered++;\n                }\n                while (keep < active.length)\n                    top = active.pop()[1];\n                while (rendered < node.marks.length) {\n                    let add = node.marks[rendered++];\n                    let markDOM = this.serializeMark(add, node.isInline, options);\n                    if (markDOM) {\n                        active.push([add, top]);\n                        top.appendChild(markDOM.dom);\n                        top = markDOM.contentDOM || markDOM.dom;\n                    }\n                }\n            }\n            top.appendChild(this.serializeNodeInner(node, options));\n        });\n        return target;\n    }\n    /**\n    @internal\n    */\n    serializeNodeInner(node, options) {\n        if (node.isText)\n            return doc(options).createTextNode(node.text);\n        let { dom, contentDOM } = renderSpec(doc(options), this.nodes[node.type.name](node), null, node.attrs);\n        if (contentDOM) {\n            if (node.isLeaf)\n                throw new RangeError(\"Content hole not allowed in a leaf node spec\");\n            this.serializeFragment(node.content, options, contentDOM);\n        }\n        return dom;\n    }\n    /**\n    Serialize this node to a DOM node. This can be useful when you\n    need to serialize a part of a document, as opposed to the whole\n    document. To serialize a whole document, use\n    [`serializeFragment`](https://prosemirror.net/docs/ref/#model.DOMSerializer.serializeFragment) on\n    its [content](https://prosemirror.net/docs/ref/#model.Node.content).\n    */\n    serializeNode(node, options = {}) {\n        let dom = this.serializeNodeInner(node, options);\n        for (let i = node.marks.length - 1; i >= 0; i--) {\n            let wrap = this.serializeMark(node.marks[i], node.isInline, options);\n            if (wrap) {\n                (wrap.contentDOM || wrap.dom).appendChild(dom);\n                dom = wrap.dom;\n            }\n        }\n        return dom;\n    }\n    /**\n    @internal\n    */\n    serializeMark(mark, inline, options = {}) {\n        let toDOM = this.marks[mark.type.name];\n        return toDOM && renderSpec(doc(options), toDOM(mark, inline), null, mark.attrs);\n    }\n    static renderSpec(doc, structure, xmlNS = null, blockArraysIn) {\n        // Kludge for backwards-compatibility with accidental original behavious\n        if (typeof structure == \"string\")\n            return { dom: doc.createTextNode(structure) };\n        return renderSpec(doc, structure, xmlNS, blockArraysIn);\n    }\n    /**\n    Build a serializer using the [`toDOM`](https://prosemirror.net/docs/ref/#model.NodeSpec.toDOM)\n    properties in a schema's node and mark specs.\n    */\n    static fromSchema(schema) {\n        return schema.cached.domSerializer ||\n            (schema.cached.domSerializer = new DOMSerializer(this.nodesFromSchema(schema), this.marksFromSchema(schema)));\n    }\n    /**\n    Gather the serializers in a schema's node specs into an object.\n    This can be useful as a base to build a custom serializer from.\n    */\n    static nodesFromSchema(schema) {\n        let result = gatherToDOM(schema.nodes);\n        if (!result.text)\n            result.text = node => node.text;\n        return result;\n    }\n    /**\n    Gather the serializers in a schema's mark specs into an object.\n    */\n    static marksFromSchema(schema) {\n        return gatherToDOM(schema.marks);\n    }\n}\nfunction gatherToDOM(obj) {\n    let result = {};\n    for (let name in obj) {\n        let toDOM = obj[name].spec.toDOM;\n        if (toDOM)\n            result[name] = toDOM;\n    }\n    return result;\n}\nfunction doc(options) {\n    return options.document || window.document;\n}\nconst suspiciousAttributeCache = new WeakMap();\nfunction suspiciousAttributes(attrs) {\n    let value = suspiciousAttributeCache.get(attrs);\n    if (value === undefined)\n        suspiciousAttributeCache.set(attrs, value = suspiciousAttributesInner(attrs));\n    return value;\n}\nfunction suspiciousAttributesInner(attrs) {\n    let result = null;\n    function scan(value) {\n        if (value && typeof value == \"object\") {\n            if (Array.isArray(value)) {\n                if (typeof value[0] == \"string\") {\n                    if (!result)\n                        result = [];\n                    result.push(value);\n                }\n                else {\n                    for (let i = 0; i < value.length; i++)\n                        scan(value[i]);\n                }\n            }\n            else {\n                for (let prop in value)\n                    scan(value[prop]);\n            }\n        }\n    }\n    scan(attrs);\n    return result;\n}\nfunction renderSpec(doc, structure, xmlNS, blockArraysIn) {\n    if (structure.nodeType == 1)\n        return { dom: structure };\n    if (structure.dom && structure.dom.nodeType == 1)\n        return structure;\n    let tagName = structure[0], suspicious;\n    if (typeof tagName != \"string\")\n        throw new RangeError(\"Invalid array passed to renderSpec\");\n    if (blockArraysIn && (suspicious = suspiciousAttributes(blockArraysIn)) &&\n        suspicious.indexOf(structure) > -1)\n        throw new RangeError(\"Using an array from an attribute object as a DOM spec. This may be an attempted cross site scripting attack.\");\n    let space = tagName.indexOf(\" \");\n    if (space > 0) {\n        xmlNS = tagName.slice(0, space);\n        tagName = tagName.slice(space + 1);\n    }\n    let contentDOM;\n    let dom = (xmlNS ? doc.createElementNS(xmlNS, tagName) : doc.createElement(tagName));\n    let attrs = structure[1], start = 1;\n    if (attrs && typeof attrs == \"object\" && attrs.nodeType == null && !Array.isArray(attrs)) {\n        start = 2;\n        for (let name in attrs)\n            if (attrs[name] != null) {\n                let space = name.indexOf(\" \");\n                if (space > 0)\n                    dom.setAttributeNS(name.slice(0, space), name.slice(space + 1), attrs[name]);\n                else if (name == \"style\" && dom.style)\n                    dom.style.cssText = attrs[name];\n                else\n                    dom.setAttribute(name, attrs[name]);\n            }\n    }\n    for (let i = start; i < structure.length; i++) {\n        let child = structure[i];\n        if (child === 0) {\n            if (i < structure.length - 1 || i > start)\n                throw new RangeError(\"Content hole must be the only child of its parent node\");\n            return { dom, contentDOM: dom };\n        }\n        else if (typeof child == \"string\") {\n            dom.appendChild(doc.createTextNode(child));\n        }\n        else {\n            let { dom: inner, contentDOM: innerContent } = renderSpec(doc, child, xmlNS, blockArraysIn);\n            dom.appendChild(inner);\n            if (innerContent) {\n                if (contentDOM)\n                    throw new RangeError(\"Multiple content holes\");\n                contentDOM = innerContent;\n            }\n        }\n    }\n    return { dom, contentDOM };\n}\n\nexport { ContentMatch, DOMParser, DOMSerializer, Fragment, Mark, MarkType, Node, NodeRange, NodeType, ReplaceError, ResolvedPos, Schema, Slice };\n", "import { ReplaceError, Slice, Mark, Fragment, MarkType } from 'prosemirror-model';\n\n// Recovery values encode a range index and an offset. They are\n// represented as numbers, because tons of them will be created when\n// mapping, for example, a large number of decorations. The number's\n// lower 16 bits provide the index, the remaining bits the offset.\n//\n// Note: We intentionally don't use bit shift operators to en- and\n// decode these, since those clip to 32 bits, which we might in rare\n// cases want to overflow. A 64-bit float can represent 48-bit\n// integers precisely.\nconst lower16 = 0xffff;\nconst factor16 = Math.pow(2, 16);\nfunction makeRecover(index, offset) { return index + offset * factor16; }\nfunction recoverIndex(value) { return value & lower16; }\nfunction recoverOffset(value) { return (value - (value & lower16)) / factor16; }\nconst DEL_BEFORE = 1, DEL_AFTER = 2, DEL_ACROSS = 4, DEL_SIDE = 8;\n/**\nAn object representing a mapped position with extra\ninformation.\n*/\nclass MapResult {\n    /**\n    @internal\n    */\n    constructor(\n    /**\n    The mapped version of the position.\n    */\n    pos, \n    /**\n    @internal\n    */\n    delInfo, \n    /**\n    @internal\n    */\n    recover) {\n        this.pos = pos;\n        this.delInfo = delInfo;\n        this.recover = recover;\n    }\n    /**\n    Tells you whether the position was deleted, that is, whether the\n    step removed the token on the side queried (via the `assoc`)\n    argument from the document.\n    */\n    get deleted() { return (this.delInfo & DEL_SIDE) > 0; }\n    /**\n    Tells you whether the token before the mapped position was deleted.\n    */\n    get deletedBefore() { return (this.delInfo & (DEL_BEFORE | DEL_ACROSS)) > 0; }\n    /**\n    True when the token after the mapped position was deleted.\n    */\n    get deletedAfter() { return (this.delInfo & (DEL_AFTER | DEL_ACROSS)) > 0; }\n    /**\n    Tells whether any of the steps mapped through deletes across the\n    position (including both the token before and after the\n    position).\n    */\n    get deletedAcross() { return (this.delInfo & DEL_ACROSS) > 0; }\n}\n/**\nA map describing the deletions and insertions made by a step, which\ncan be used to find the correspondence between positions in the\npre-step version of a document and the same position in the\npost-step version.\n*/\nclass StepMap {\n    /**\n    Create a position map. The modifications to the document are\n    represented as an array of numbers, in which each group of three\n    represents a modified chunk as `[start, oldSize, newSize]`.\n    */\n    constructor(\n    /**\n    @internal\n    */\n    ranges, \n    /**\n    @internal\n    */\n    inverted = false) {\n        this.ranges = ranges;\n        this.inverted = inverted;\n        if (!ranges.length && StepMap.empty)\n            return StepMap.empty;\n    }\n    /**\n    @internal\n    */\n    recover(value) {\n        let diff = 0, index = recoverIndex(value);\n        if (!this.inverted)\n            for (let i = 0; i < index; i++)\n                diff += this.ranges[i * 3 + 2] - this.ranges[i * 3 + 1];\n        return this.ranges[index * 3] + diff + recoverOffset(value);\n    }\n    mapResult(pos, assoc = 1) { return this._map(pos, assoc, false); }\n    map(pos, assoc = 1) { return this._map(pos, assoc, true); }\n    /**\n    @internal\n    */\n    _map(pos, assoc, simple) {\n        let diff = 0, oldIndex = this.inverted ? 2 : 1, newIndex = this.inverted ? 1 : 2;\n        for (let i = 0; i < this.ranges.length; i += 3) {\n            let start = this.ranges[i] - (this.inverted ? diff : 0);\n            if (start > pos)\n                break;\n            let oldSize = this.ranges[i + oldIndex], newSize = this.ranges[i + newIndex], end = start + oldSize;\n            if (pos <= end) {\n                let side = !oldSize ? assoc : pos == start ? -1 : pos == end ? 1 : assoc;\n                let result = start + diff + (side < 0 ? 0 : newSize);\n                if (simple)\n                    return result;\n                let recover = pos == (assoc < 0 ? start : end) ? null : makeRecover(i / 3, pos - start);\n                let del = 0;\n                if (oldSize) {\n                    del |= pos == start ? DEL_AFTER : pos == end ? DEL_BEFORE : DEL_ACROSS;\n                    if (assoc < 0 ? pos != start : pos != end)\n                        del |= DEL_SIDE;\n                }\n                return new MapResult(result, del, recover);\n            }\n            diff += newSize - oldSize;\n        }\n        return simple ? pos + diff : new MapResult(pos + diff, 0, null);\n    }\n    /**\n    @internal\n    */\n    touches(pos, recover) {\n        let diff = 0, index = recoverIndex(recover);\n        let oldIndex = this.inverted ? 2 : 1, newIndex = this.inverted ? 1 : 2;\n        for (let i = 0; i < this.ranges.length; i += 3) {\n            let start = this.ranges[i] - (this.inverted ? diff : 0);\n            if (start > pos)\n                break;\n            let oldSize = this.ranges[i + oldIndex], end = start + oldSize;\n            if (pos <= end && i == index * 3)\n                return true;\n            diff += this.ranges[i + newIndex] - oldSize;\n        }\n        return false;\n    }\n    /**\n    Calls the given function on each of the changed ranges included in\n    this map.\n    */\n    forEach(f) {\n        let oldIndex = this.inverted ? 2 : 1, newIndex = this.inverted ? 1 : 2;\n        for (let i = 0, diff = 0; i < this.ranges.length; i += 3) {\n            let start = this.ranges[i], oldStart = start - (this.inverted ? diff : 0), newStart = start + (this.inverted ? 0 : diff);\n            let oldSize = this.ranges[i + oldIndex], newSize = this.ranges[i + newIndex];\n            f(oldStart, oldStart + oldSize, newStart, newStart + newSize);\n            diff += newSize - oldSize;\n        }\n    }\n    /**\n    Create an inverted version of this map. The result can be used to\n    map positions in the post-step document to the pre-step document.\n    */\n    invert() {\n        return new StepMap(this.ranges, !this.inverted);\n    }\n    /**\n    @internal\n    */\n    toString() {\n        return (this.inverted ? \"-\" : \"\") + JSON.stringify(this.ranges);\n    }\n    /**\n    Create a map that moves all positions by offset `n` (which may be\n    negative). This can be useful when applying steps meant for a\n    sub-document to a larger document, or vice-versa.\n    */\n    static offset(n) {\n        return n == 0 ? StepMap.empty : new StepMap(n < 0 ? [0, -n, 0] : [0, 0, n]);\n    }\n}\n/**\nA StepMap that contains no changed ranges.\n*/\nStepMap.empty = new StepMap([]);\n/**\nA mapping represents a pipeline of zero or more [step\nmaps](https://prosemirror.net/docs/ref/#transform.StepMap). It has special provisions for losslessly\nhandling mapping positions through a series of steps in which some\nsteps are inverted versions of earlier steps. (This comes up when\n\u2018[rebasing](https://prosemirror.net/docs/guide/#transform.rebasing)\u2019 steps for\ncollaboration or history management.)\n*/\nclass Mapping {\n    /**\n    Create a new mapping with the given position maps.\n    */\n    constructor(maps, \n    /**\n    @internal\n    */\n    mirror, \n    /**\n    The starting position in the `maps` array, used when `map` or\n    `mapResult` is called.\n    */\n    from = 0, \n    /**\n    The end position in the `maps` array.\n    */\n    to = maps ? maps.length : 0) {\n        this.mirror = mirror;\n        this.from = from;\n        this.to = to;\n        this._maps = maps || [];\n        this.ownData = !(maps || mirror);\n    }\n    /**\n    The step maps in this mapping.\n    */\n    get maps() { return this._maps; }\n    /**\n    Create a mapping that maps only through a part of this one.\n    */\n    slice(from = 0, to = this.maps.length) {\n        return new Mapping(this._maps, this.mirror, from, to);\n    }\n    /**\n    Add a step map to the end of this mapping. If `mirrors` is\n    given, it should be the index of the step map that is the mirror\n    image of this one.\n    */\n    appendMap(map, mirrors) {\n        if (!this.ownData) {\n            this._maps = this._maps.slice();\n            this.mirror = this.mirror && this.mirror.slice();\n            this.ownData = true;\n        }\n        this.to = this._maps.push(map);\n        if (mirrors != null)\n            this.setMirror(this._maps.length - 1, mirrors);\n    }\n    /**\n    Add all the step maps in a given mapping to this one (preserving\n    mirroring information).\n    */\n    appendMapping(mapping) {\n        for (let i = mapping.from, startSize = this._maps.length; i < mapping.to; i++) {\n            let mirr = mapping.getMirror(i);\n            if (mirr != null)\n                mirr = mirr < i && mirr >= mapping.from ? startSize + (mirr - mapping.from) : undefined;\n            this.appendMap(mapping._maps[i], mirr);\n        }\n    }\n    /**\n    Finds the offset of the step map that mirrors the map at the\n    given offset, in this mapping (as per the second argument to\n    `appendMap`).\n    */\n    getMirror(n) {\n        if (this.mirror)\n            for (let i = 0; i < this.mirror.length; i++)\n                if (this.mirror[i] == n)\n                    return this.mirror[i + (i % 2 ? -1 : 1)];\n    }\n    /**\n    @internal\n    */\n    setMirror(n, m) {\n        if (!this.mirror)\n            this.mirror = [];\n        this.mirror.push(n, m);\n    }\n    /**\n    Append the inverse of the given mapping to this one.\n    */\n    appendMappingInverted(mapping) {\n        for (let i = mapping.to - 1, totalSize = this._maps.length + mapping._maps.length; i >= mapping.from; i--) {\n            let mirr = mapping.getMirror(i);\n            if (mirr != null)\n                mirr = mirr > i && mirr < mapping.to ? totalSize - (mirr - mapping.from) - 1 : undefined;\n            this.appendMap(mapping._maps[i].invert(), mirr);\n        }\n    }\n    /**\n    Create an inverted version of this mapping.\n    */\n    invert() {\n        let inverse = new Mapping;\n        inverse.appendMappingInverted(this);\n        return inverse;\n    }\n    /**\n    Map a position through this mapping.\n    */\n    map(pos, assoc = 1) {\n        if (this.mirror)\n            return this._map(pos, assoc, true);\n        for (let i = this.from; i < this.to; i++)\n            pos = this._maps[i].map(pos, assoc);\n        return pos;\n    }\n    /**\n    Map a position through this mapping, returning a mapping\n    result.\n    */\n    mapResult(pos, assoc = 1) { return this._map(pos, assoc, false); }\n    /**\n    @internal\n    */\n    _map(pos, assoc, simple) {\n        let delInfo = 0;\n        for (let i = this.from; i < this.to; i++) {\n            let map = this._maps[i], result = map.mapResult(pos, assoc);\n            if (result.recover != null) {\n                let corr = this.getMirror(i);\n                if (corr != null && corr > i && corr < this.to) {\n                    i = corr;\n                    pos = this._maps[corr].recover(result.recover);\n                    continue;\n                }\n            }\n            delInfo |= result.delInfo;\n            pos = result.pos;\n        }\n        return simple ? pos : new MapResult(pos, delInfo, null);\n    }\n}\n\nconst stepsByID = Object.create(null);\n/**\nA step object represents an atomic change. It generally applies\nonly to the document it was created for, since the positions\nstored in it will only make sense for that document.\n\nNew steps are defined by creating classes that extend `Step`,\noverriding the `apply`, `invert`, `map`, `getMap` and `fromJSON`\nmethods, and registering your class with a unique\nJSON-serialization identifier using\n[`Step.jsonID`](https://prosemirror.net/docs/ref/#transform.Step^jsonID).\n*/\nclass Step {\n    /**\n    Get the step map that represents the changes made by this step,\n    and which can be used to transform between positions in the old\n    and the new document.\n    */\n    getMap() { return StepMap.empty; }\n    /**\n    Try to merge this step with another one, to be applied directly\n    after it. Returns the merged step when possible, null if the\n    steps can't be merged.\n    */\n    merge(other) { return null; }\n    /**\n    Deserialize a step from its JSON representation. Will call\n    through to the step class' own implementation of this method.\n    */\n    static fromJSON(schema, json) {\n        if (!json || !json.stepType)\n            throw new RangeError(\"Invalid input for Step.fromJSON\");\n        let type = stepsByID[json.stepType];\n        if (!type)\n            throw new RangeError(`No step type ${json.stepType} defined`);\n        return type.fromJSON(schema, json);\n    }\n    /**\n    To be able to serialize steps to JSON, each step needs a string\n    ID to attach to its JSON representation. Use this method to\n    register an ID for your step classes. Try to pick something\n    that's unlikely to clash with steps from other modules.\n    */\n    static jsonID(id, stepClass) {\n        if (id in stepsByID)\n            throw new RangeError(\"Duplicate use of step JSON ID \" + id);\n        stepsByID[id] = stepClass;\n        stepClass.prototype.jsonID = id;\n        return stepClass;\n    }\n}\n/**\nThe result of [applying](https://prosemirror.net/docs/ref/#transform.Step.apply) a step. Contains either a\nnew document or a failure value.\n*/\nclass StepResult {\n    /**\n    @internal\n    */\n    constructor(\n    /**\n    The transformed document, if successful.\n    */\n    doc, \n    /**\n    The failure message, if unsuccessful.\n    */\n    failed) {\n        this.doc = doc;\n        this.failed = failed;\n    }\n    /**\n    Create a successful step result.\n    */\n    static ok(doc) { return new StepResult(doc, null); }\n    /**\n    Create a failed step result.\n    */\n    static fail(message) { return new StepResult(null, message); }\n    /**\n    Call [`Node.replace`](https://prosemirror.net/docs/ref/#model.Node.replace) with the given\n    arguments. Create a successful result if it succeeds, and a\n    failed one if it throws a `ReplaceError`.\n    */\n    static fromReplace(doc, from, to, slice) {\n        try {\n            return StepResult.ok(doc.replace(from, to, slice));\n        }\n        catch (e) {\n            if (e instanceof ReplaceError)\n                return StepResult.fail(e.message);\n            throw e;\n        }\n    }\n}\n\nfunction mapFragment(fragment, f, parent) {\n    let mapped = [];\n    for (let i = 0; i < fragment.childCount; i++) {\n        let child = fragment.child(i);\n        if (child.content.size)\n            child = child.copy(mapFragment(child.content, f, child));\n        if (child.isInline)\n            child = f(child, parent, i);\n        mapped.push(child);\n    }\n    return Fragment.fromArray(mapped);\n}\n/**\nAdd a mark to all inline content between two positions.\n*/\nclass AddMarkStep extends Step {\n    /**\n    Create a mark step.\n    */\n    constructor(\n    /**\n    The start of the marked range.\n    */\n    from, \n    /**\n    The end of the marked range.\n    */\n    to, \n    /**\n    The mark to add.\n    */\n    mark) {\n        super();\n        this.from = from;\n        this.to = to;\n        this.mark = mark;\n    }\n    apply(doc) {\n        let oldSlice = doc.slice(this.from, this.to), $from = doc.resolve(this.from);\n        let parent = $from.node($from.sharedDepth(this.to));\n        let slice = new Slice(mapFragment(oldSlice.content, (node, parent) => {\n            if (!node.isAtom || !parent.type.allowsMarkType(this.mark.type))\n                return node;\n            return node.mark(this.mark.addToSet(node.marks));\n        }, parent), oldSlice.openStart, oldSlice.openEnd);\n        return StepResult.fromReplace(doc, this.from, this.to, slice);\n    }\n    invert(doc) {\n        let steps = [];\n        doc.nodesBetween(this.from, this.to, (node, pos) => {\n            if (node.isInline && node.isAtom) {\n                let added = this.mark.addToSet(node.marks);\n                if (!Mark.sameSet(added, node.marks)) {\n                    let from = Math.max(this.from, pos), to = Math.min(this.to, pos + node.nodeSize);\n                    pushMarkStep(RemoveMarkStep, from, to, this.mark, steps);\n                    for (let mark of node.marks)\n                        if (!mark.isInSet(added))\n                            pushMarkStep(AddMarkStep, from, to, mark, steps);\n                }\n            }\n        });\n        return steps.length == 1 ? steps[0] : new MarkSetStep(steps);\n    }\n    map(mapping) {\n        let from = mapping.map(this.from, 1), to = mapping.map(this.to, -1);\n        if (from >= to)\n            return null;\n        return new AddMarkStep(from, to, this.mark);\n    }\n    merge(other) {\n        if (other instanceof AddMarkStep &&\n            other.mark.eq(this.mark) &&\n            this.from <= other.to && this.to >= other.from)\n            return new AddMarkStep(Math.min(this.from, other.from), Math.max(this.to, other.to), this.mark);\n        return null;\n    }\n    toJSON() {\n        return { stepType: \"addMark\", mark: this.mark.toJSON(),\n            from: this.from, to: this.to };\n    }\n    /**\n    @internal\n    */\n    static fromJSON(schema, json) {\n        if (typeof json.from != \"number\" || typeof json.to != \"number\")\n            throw new RangeError(\"Invalid input for AddMarkStep.fromJSON\");\n        return new AddMarkStep(json.from, json.to, schema.markFromJSON(json.mark));\n    }\n}\nStep.jsonID(\"addMark\", AddMarkStep);\n/**\nRemove a mark from all inline content between two positions.\n*/\nclass RemoveMarkStep extends Step {\n    /**\n    Create a mark-removing step.\n    */\n    constructor(\n    /**\n    The start of the unmarked range.\n    */\n    from, \n    /**\n    The end of the unmarked range.\n    */\n    to, \n    /**\n    The mark to remove.\n    */\n    mark) {\n        super();\n        this.from = from;\n        this.to = to;\n        this.mark = mark;\n    }\n    apply(doc) {\n        let oldSlice = doc.slice(this.from, this.to);\n        let slice = new Slice(mapFragment(oldSlice.content, node => {\n            return node.mark(this.mark.removeFromSet(node.marks));\n        }, doc), oldSlice.openStart, oldSlice.openEnd);\n        return StepResult.fromReplace(doc, this.from, this.to, slice);\n    }\n    invert(doc) {\n        let steps = [];\n        doc.nodesBetween(this.from, this.to, (node, pos) => {\n            if (node.isInline && node.isAtom && this.mark.isInSet(node.marks))\n                pushMarkStep(AddMarkStep, Math.max(this.from, pos), Math.min(this.to, pos + node.nodeSize), this.mark, steps);\n        });\n        return steps.length == 1 ? steps[0] : new MarkSetStep(steps);\n    }\n    map(mapping) {\n        let from = mapping.map(this.from, 1), to = mapping.map(this.to, -1);\n        if (from >= to)\n            return null;\n        return new RemoveMarkStep(from, to, this.mark);\n    }\n    merge(other) {\n        if (other instanceof RemoveMarkStep &&\n            other.mark.eq(this.mark) &&\n            this.from <= other.to && this.to >= other.from)\n            return new RemoveMarkStep(Math.min(this.from, other.from), Math.max(this.to, other.to), this.mark);\n        return null;\n    }\n    toJSON() {\n        return { stepType: \"removeMark\", mark: this.mark.toJSON(),\n            from: this.from, to: this.to };\n    }\n    /**\n    @internal\n    */\n    static fromJSON(schema, json) {\n        if (typeof json.from != \"number\" || typeof json.to != \"number\")\n            throw new RangeError(\"Invalid input for RemoveMarkStep.fromJSON\");\n        return new RemoveMarkStep(json.from, json.to, schema.markFromJSON(json.mark));\n    }\n}\nStep.jsonID(\"removeMark\", RemoveMarkStep);\nfunction pushMarkStep(cls, from, to, mark, target) {\n    let last = target.length ? target[target.length - 1] : null;\n    if (last && last instanceof cls && last.to == from && last.mark.eq(mark)) {\n        target[target.length - 1] = new cls(last.from, to, mark);\n    }\n    else {\n        target.push(new cls(from, to, mark));\n    }\n}\nclass MarkSetStep extends Step {\n    constructor(steps) {\n        super();\n        this.steps = steps;\n    }\n    apply(doc) {\n        for (let step of this.steps) {\n            let result = step.apply(doc);\n            if (!result.doc)\n                return result;\n            doc = result.doc;\n        }\n        return new StepResult(doc, null);\n    }\n    invert(doc) {\n        return new MarkSetStep(this.steps.map(s => s.invert(doc)));\n    }\n    map(mapping) {\n        let result = [];\n        for (let step of this.steps) {\n            let mapped = step.map(mapping);\n            if (mapped)\n                result.push(mapped);\n        }\n        return result.length ? new MarkSetStep(result) : null;\n    }\n    toJSON() {\n        return { stepType: \"markSet\", steps: this.steps.map(s => s.toJSON()) };\n    }\n    static fromJSON(schema, json) {\n        if (!Array.isArray(json.steps) || !json.steps.every((s) => s.stepType == \"addMark\" || s.stepType == \"removeMark\"))\n            throw new RangeError(\"Invalid JSON for MarkSetStep\");\n        return new MarkSetStep(json.steps.map((s) => Step.fromJSON(schema, s)));\n    }\n}\nStep.jsonID(\"markSet\", MarkSetStep);\n/**\nAdd a mark to a specific node.\n*/\nclass AddNodeMarkStep extends Step {\n    /**\n    Create a node mark step.\n    */\n    constructor(\n    /**\n    The position of the target node.\n    */\n    pos, \n    /**\n    The mark to add.\n    */\n    mark) {\n        super();\n        this.pos = pos;\n        this.mark = mark;\n    }\n    apply(doc) {\n        let node = doc.nodeAt(this.pos);\n        if (!node)\n            return StepResult.fail(\"No node at mark step's position\");\n        let updated = node.type.create(node.attrs, null, this.mark.addToSet(node.marks));\n        return StepResult.fromReplace(doc, this.pos, this.pos + 1, new Slice(Fragment.from(updated), 0, node.isLeaf ? 0 : 1));\n    }\n    invert(doc) {\n        let node = doc.nodeAt(this.pos);\n        if (node) {\n            let newSet = this.mark.addToSet(node.marks);\n            if (newSet.length == node.marks.length) {\n                for (let i = 0; i < node.marks.length; i++)\n                    if (!node.marks[i].isInSet(newSet))\n                        return new AddNodeMarkStep(this.pos, node.marks[i]);\n                return new AddNodeMarkStep(this.pos, this.mark);\n            }\n        }\n        return new RemoveNodeMarkStep(this.pos, this.mark);\n    }\n    map(mapping) {\n        let pos = mapping.mapResult(this.pos, 1);\n        return pos.deletedAfter ? null : new AddNodeMarkStep(pos.pos, this.mark);\n    }\n    toJSON() {\n        return { stepType: \"addNodeMark\", pos: this.pos, mark: this.mark.toJSON() };\n    }\n    /**\n    @internal\n    */\n    static fromJSON(schema, json) {\n        if (typeof json.pos != \"number\")\n            throw new RangeError(\"Invalid input for AddNodeMarkStep.fromJSON\");\n        return new AddNodeMarkStep(json.pos, schema.markFromJSON(json.mark));\n    }\n}\nStep.jsonID(\"addNodeMark\", AddNodeMarkStep);\n/**\nRemove a mark from a specific node.\n*/\nclass RemoveNodeMarkStep extends Step {\n    /**\n    Create a mark-removing step.\n    */\n    constructor(\n    /**\n    The position of the target node.\n    */\n    pos, \n    /**\n    The mark to remove.\n    */\n    mark) {\n        super();\n        this.pos = pos;\n        this.mark = mark;\n    }\n    apply(doc) {\n        let node = doc.nodeAt(this.pos);\n        if (!node)\n            return StepResult.fail(\"No node at mark step's position\");\n        let updated = node.type.create(node.attrs, null, this.mark.removeFromSet(node.marks));\n        return StepResult.fromReplace(doc, this.pos, this.pos + 1, new Slice(Fragment.from(updated), 0, node.isLeaf ? 0 : 1));\n    }\n    invert(doc) {\n        let node = doc.nodeAt(this.pos);\n        if (!node || !this.mark.isInSet(node.marks))\n            return this;\n        return new AddNodeMarkStep(this.pos, this.mark);\n    }\n    map(mapping) {\n        let pos = mapping.mapResult(this.pos, 1);\n        return pos.deletedAfter ? null : new RemoveNodeMarkStep(pos.pos, this.mark);\n    }\n    toJSON() {\n        return { stepType: \"removeNodeMark\", pos: this.pos, mark: this.mark.toJSON() };\n    }\n    /**\n    @internal\n    */\n    static fromJSON(schema, json) {\n        if (typeof json.pos != \"number\")\n            throw new RangeError(\"Invalid input for RemoveNodeMarkStep.fromJSON\");\n        return new RemoveNodeMarkStep(json.pos, schema.markFromJSON(json.mark));\n    }\n}\nStep.jsonID(\"removeNodeMark\", RemoveNodeMarkStep);\n\n/**\nReplace a part of the document with a slice of new content.\n*/\nclass ReplaceStep extends Step {\n    /**\n    The given `slice` should fit the 'gap' between `from` and\n    `to`\u2014the depths must line up, and the surrounding nodes must be\n    able to be joined with the open sides of the slice. When\n    `structure` is true, the step will fail if the content between\n    from and to is not just a sequence of closing and then opening\n    tokens (this is to guard against rebased replace steps\n    overwriting something they weren't supposed to).\n    */\n    constructor(\n    /**\n    The start position of the replaced range.\n    */\n    from, \n    /**\n    The end position of the replaced range.\n    */\n    to, \n    /**\n    The slice to insert.\n    */\n    slice, \n    /**\n    @internal\n    */\n    structure = false) {\n        super();\n        this.from = from;\n        this.to = to;\n        this.slice = slice;\n        this.structure = structure;\n    }\n    apply(doc) {\n        if (this.structure && contentBetween(doc, this.from, this.to))\n            return StepResult.fail(\"Structure replace would overwrite content\");\n        return StepResult.fromReplace(doc, this.from, this.to, this.slice);\n    }\n    getMap() {\n        return new StepMap([this.from, this.to - this.from, this.slice.size]);\n    }\n    invert(doc) {\n        return new ReplaceStep(this.from, this.from + this.slice.size, doc.slice(this.from, this.to));\n    }\n    map(mapping) {\n        let to = mapping.mapResult(this.to, -1);\n        let from = this.from == this.to && ReplaceStep.MAP_BIAS < 0 ? to : mapping.mapResult(this.from, 1);\n        if (from.deletedAcross && to.deletedAcross)\n            return null;\n        return new ReplaceStep(from.pos, Math.max(from.pos, to.pos), this.slice, this.structure);\n    }\n    merge(other) {\n        if (!(other instanceof ReplaceStep) || other.structure || this.structure)\n            return null;\n        if (this.from + this.slice.size == other.from && !this.slice.openEnd && !other.slice.openStart) {\n            let slice = this.slice.size + other.slice.size == 0 ? Slice.empty\n                : new Slice(this.slice.content.append(other.slice.content), this.slice.openStart, other.slice.openEnd);\n            return new ReplaceStep(this.from, this.to + (other.to - other.from), slice, this.structure);\n        }\n        else if (other.to == this.from && !this.slice.openStart && !other.slice.openEnd) {\n            let slice = this.slice.size + other.slice.size == 0 ? Slice.empty\n                : new Slice(other.slice.content.append(this.slice.content), other.slice.openStart, this.slice.openEnd);\n            return new ReplaceStep(other.from, this.to, slice, this.structure);\n        }\n        else {\n            return null;\n        }\n    }\n    toJSON() {\n        let json = { stepType: \"replace\", from: this.from, to: this.to };\n        if (this.slice.size)\n            json.slice = this.slice.toJSON();\n        if (this.structure)\n            json.structure = true;\n        return json;\n    }\n    /**\n    @internal\n    */\n    static fromJSON(schema, json) {\n        if (typeof json.from != \"number\" || typeof json.to != \"number\")\n            throw new RangeError(\"Invalid input for ReplaceStep.fromJSON\");\n        return new ReplaceStep(json.from, json.to, Slice.fromJSON(schema, json.slice), !!json.structure);\n    }\n}\n/**\nBy default, for backwards compatibility, an inserting step\nmapped over an insertion at that same position fill move after\nthe inserted content. In a collaborative editing situation, that\ncan make redone insertions appear in unexpected places. You can\nset this to -1 to make such mapping keep the step before the\ninsertion instead.\n*/\nReplaceStep.MAP_BIAS = 1;\nStep.jsonID(\"replace\", ReplaceStep);\n/**\nReplace a part of the document with a slice of content, but\npreserve a range of the replaced content by moving it into the\nslice.\n*/\nclass ReplaceAroundStep extends Step {\n    /**\n    Create a replace-around step with the given range and gap.\n    `insert` should be the point in the slice into which the content\n    of the gap should be moved. `structure` has the same meaning as\n    it has in the [`ReplaceStep`](https://prosemirror.net/docs/ref/#transform.ReplaceStep) class.\n    */\n    constructor(\n    /**\n    The start position of the replaced range.\n    */\n    from, \n    /**\n    The end position of the replaced range.\n    */\n    to, \n    /**\n    The start of preserved range.\n    */\n    gapFrom, \n    /**\n    The end of preserved range.\n    */\n    gapTo, \n    /**\n    The slice to insert.\n    */\n    slice, \n    /**\n    The position in the slice where the preserved range should be\n    inserted.\n    */\n    insert, \n    /**\n    @internal\n    */\n    structure = false) {\n        super();\n        this.from = from;\n        this.to = to;\n        this.gapFrom = gapFrom;\n        this.gapTo = gapTo;\n        this.slice = slice;\n        this.insert = insert;\n        this.structure = structure;\n    }\n    apply(doc) {\n        if (this.structure && (contentBetween(doc, this.from, this.gapFrom) ||\n            contentBetween(doc, this.gapTo, this.to)))\n            return StepResult.fail(\"Structure gap-replace would overwrite content\");\n        let gap = doc.slice(this.gapFrom, this.gapTo);\n        if (gap.openStart || gap.openEnd)\n            return StepResult.fail(\"Gap is not a flat range\");\n        let inserted = this.slice.insertAt(this.insert, gap.content);\n        if (!inserted)\n            return StepResult.fail(\"Content does not fit in gap\");\n        return StepResult.fromReplace(doc, this.from, this.to, inserted);\n    }\n    getMap() {\n        return new StepMap([this.from, this.gapFrom - this.from, this.insert,\n            this.gapTo, this.to - this.gapTo, this.slice.size - this.insert]);\n    }\n    invert(doc) {\n        let gap = this.gapTo - this.gapFrom;\n        return new ReplaceAroundStep(this.from, this.from + this.slice.size + gap, this.from + this.insert, this.from + this.insert + gap, doc.slice(this.from, this.to).removeBetween(this.gapFrom - this.from, this.gapTo - this.from), this.gapFrom - this.from, this.structure);\n    }\n    map(mapping) {\n        let from = mapping.mapResult(this.from, 1), to = mapping.mapResult(this.to, -1);\n        let gapFrom = this.from == this.gapFrom ? from.pos : mapping.map(this.gapFrom, -1);\n        let gapTo = this.to == this.gapTo ? to.pos : mapping.map(this.gapTo, 1);\n        if ((from.deletedAcross && to.deletedAcross) || gapFrom < from.pos || gapTo > to.pos || gapFrom > gapTo)\n            return null;\n        return new ReplaceAroundStep(from.pos, to.pos, gapFrom, gapTo, this.slice, this.insert, this.structure);\n    }\n    toJSON() {\n        let json = { stepType: \"replaceAround\", from: this.from, to: this.to,\n            gapFrom: this.gapFrom, gapTo: this.gapTo, insert: this.insert };\n        if (this.slice.size)\n            json.slice = this.slice.toJSON();\n        if (this.structure)\n            json.structure = true;\n        return json;\n    }\n    /**\n    @internal\n    */\n    static fromJSON(schema, json) {\n        if (typeof json.from != \"number\" || typeof json.to != \"number\" ||\n            typeof json.gapFrom != \"number\" || typeof json.gapTo != \"number\" || typeof json.insert != \"number\")\n            throw new RangeError(\"Invalid input for ReplaceAroundStep.fromJSON\");\n        return new ReplaceAroundStep(json.from, json.to, json.gapFrom, json.gapTo, Slice.fromJSON(schema, json.slice), json.insert, !!json.structure);\n    }\n}\nStep.jsonID(\"replaceAround\", ReplaceAroundStep);\nfunction contentBetween(doc, from, to) {\n    let $from = doc.resolve(from), dist = to - from, depth = $from.depth;\n    while (dist > 0 && depth > 0 && $from.indexAfter(depth) == $from.node(depth).childCount) {\n        depth--;\n        dist--;\n    }\n    if (dist > 0) {\n        let next = $from.node(depth).maybeChild($from.indexAfter(depth));\n        while (dist > 0) {\n            if (!next || next.isLeaf)\n                return true;\n            next = next.firstChild;\n            dist--;\n        }\n    }\n    return false;\n}\n\nfunction addMark(tr, from, to, mark) {\n    let added = [];\n    tr.doc.nodesBetween(from, to, (node, pos, parent) => {\n        if (!node.isInline)\n            return;\n        let marks = node.marks;\n        if (!mark.isInSet(marks) && parent.type.allowsMarkType(mark.type)) {\n            let start = Math.max(pos, from), end = Math.min(pos + node.nodeSize, to);\n            pushMarkStep(AddMarkStep, start, end, mark, added);\n        }\n    });\n    added.forEach(s => tr.step(s));\n}\nfunction removeMark(tr, from, to, mark) {\n    let matched = [], step = 0;\n    tr.doc.nodesBetween(from, to, (node, pos) => {\n        if (!node.isInline || !node.isAtom)\n            return;\n        step++;\n        let toRemove = null;\n        if (mark instanceof MarkType) {\n            let set = node.marks, found;\n            while (found = mark.isInSet(set)) {\n                (toRemove || (toRemove = [])).push(found);\n                set = found.removeFromSet(set);\n            }\n        }\n        else if (mark) {\n            if (mark.isInSet(node.marks))\n                toRemove = [mark];\n        }\n        else {\n            toRemove = node.marks;\n        }\n        if (toRemove && toRemove.length) {\n            let end = Math.min(pos + node.nodeSize, to);\n            for (let i = 0; i < toRemove.length; i++) {\n                let style = toRemove[i], found;\n                for (let j = 0; j < matched.length; j++) {\n                    let m = matched[j];\n                    if (m.step == step - 1 && style.eq(matched[j].style))\n                        found = m;\n                }\n                if (found) {\n                    found.to = end;\n                    found.step = step;\n                }\n                else {\n                    matched.push({ style, from: Math.max(pos, from), to: end, step });\n                }\n            }\n        }\n    });\n    matched.forEach(m => tr.step(new RemoveMarkStep(m.from, m.to, m.style)));\n}\nfunction clearIncompatible(tr, pos, parentType, match = parentType.contentMatch, clearNewlines = true) {\n    let node = tr.doc.nodeAt(pos);\n    let replSteps = [], cur = pos + 1;\n    for (let i = 0; i < node.childCount; i++) {\n        let child = node.child(i), end = cur + child.nodeSize;\n        let allowed = match.matchType(child.type);\n        if (!allowed) {\n            replSteps.push(new ReplaceStep(cur, end, Slice.empty));\n        }\n        else {\n            match = allowed;\n            for (let j = 0; j < child.marks.length; j++)\n                if (!parentType.allowsMarkType(child.marks[j].type))\n                    tr.step(new RemoveMarkStep(cur, end, child.marks[j]));\n            if (clearNewlines && child.isText && parentType.whitespace != \"pre\") {\n                let m, newline = /\\r?\\n|\\r/g, slice;\n                while (m = newline.exec(child.text)) {\n                    if (!slice)\n                        slice = new Slice(Fragment.from(parentType.schema.text(\" \", parentType.allowedMarks(child.marks))), 0, 0);\n                    replSteps.push(new ReplaceStep(cur + m.index, cur + m.index + m[0].length, slice));\n                }\n            }\n        }\n        cur = end;\n    }\n    if (!match.validEnd) {\n        let fill = match.fillBefore(Fragment.empty, true);\n        tr.replace(cur, cur, new Slice(fill, 0, 0));\n    }\n    for (let i = replSteps.length - 1; i >= 0; i--)\n        tr.step(replSteps[i]);\n}\n\nfunction canCut(node, start, end) {\n    return (start == 0 || node.canReplace(start, node.childCount)) &&\n        (end == node.childCount || node.canReplace(0, end));\n}\n/**\nTry to find a target depth to which the content in the given range\ncan be lifted. Will not go across\n[isolating](https://prosemirror.net/docs/ref/#model.NodeSpec.isolating) parent nodes.\n*/\nfunction liftTarget(range) {\n    let parent = range.parent;\n    let content = parent.content.cutByIndex(range.startIndex, range.endIndex);\n    for (let depth = range.depth, contentBefore = 0, contentAfter = 0;; --depth) {\n        let node = range.$from.node(depth);\n        let index = range.$from.index(depth) + contentBefore, endIndex = range.$to.indexAfter(depth) - contentAfter;\n        if (depth < range.depth && node.canReplace(index, endIndex, content))\n            return depth;\n        if (depth == 0 || node.type.spec.isolating || !canCut(node, index, endIndex))\n            break;\n        if (index)\n            contentBefore = 1;\n        if (endIndex < node.childCount)\n            contentAfter = 1;\n    }\n    return null;\n}\nfunction lift(tr, range, target) {\n    let { $from, $to, depth } = range;\n    let gapStart = $from.before(depth + 1), gapEnd = $to.after(depth + 1);\n    let start = gapStart, end = gapEnd;\n    let before = Fragment.empty, openStart = 0;\n    for (let d = depth, splitting = false; d > target; d--)\n        if (splitting || $from.index(d) > 0) {\n            splitting = true;\n            before = Fragment.from($from.node(d).copy(before));\n            openStart++;\n        }\n        else {\n            start--;\n        }\n    let after = Fragment.empty, openEnd = 0;\n    for (let d = depth, splitting = false; d > target; d--)\n        if (splitting || $to.after(d + 1) < $to.end(d)) {\n            splitting = true;\n            after = Fragment.from($to.node(d).copy(after));\n            openEnd++;\n        }\n        else {\n            end++;\n        }\n    tr.step(new ReplaceAroundStep(start, end, gapStart, gapEnd, new Slice(before.append(after), openStart, openEnd), before.size - openStart, true));\n}\n/**\nTry to find a valid way to wrap the content in the given range in a\nnode of the given type. May introduce extra nodes around and inside\nthe wrapper node, if necessary. Returns null if no valid wrapping\ncould be found. When `innerRange` is given, that range's content is\nused as the content to fit into the wrapping, instead of the\ncontent of `range`.\n*/\nfunction findWrapping(range, nodeType, attrs = null, innerRange = range) {\n    let around = findWrappingOutside(range, nodeType);\n    let inner = around && findWrappingInside(innerRange, nodeType);\n    if (!inner)\n        return null;\n    return around.map(withAttrs)\n        .concat({ type: nodeType, attrs }).concat(inner.map(withAttrs));\n}\nfunction withAttrs(type) { return { type, attrs: null }; }\nfunction findWrappingOutside(range, type) {\n    let { parent, startIndex, endIndex } = range;\n    let around = parent.contentMatchAt(startIndex).findWrapping(type);\n    if (!around)\n        return null;\n    let outer = around.length ? around[0] : type;\n    return parent.canReplaceWith(startIndex, endIndex, outer) ? around : null;\n}\nfunction findWrappingInside(range, type) {\n    let { parent, startIndex, endIndex } = range;\n    let inner = parent.child(startIndex);\n    let inside = type.contentMatch.findWrapping(inner.type);\n    if (!inside)\n        return null;\n    let lastType = inside.length ? inside[inside.length - 1] : type;\n    let innerMatch = lastType.contentMatch;\n    for (let i = startIndex; innerMatch && i < endIndex; i++)\n        innerMatch = innerMatch.matchType(parent.child(i).type);\n    if (!innerMatch || !innerMatch.validEnd)\n        return null;\n    return inside;\n}\nfunction wrap(tr, range, wrappers) {\n    let content = Fragment.empty;\n    for (let i = wrappers.length - 1; i >= 0; i--) {\n        if (content.size) {\n            let match = wrappers[i].type.contentMatch.matchFragment(content);\n            if (!match || !match.validEnd)\n                throw new RangeError(\"Wrapper type given to Transform.wrap does not form valid content of its parent wrapper\");\n        }\n        content = Fragment.from(wrappers[i].type.create(wrappers[i].attrs, content));\n    }\n    let start = range.start, end = range.end;\n    tr.step(new ReplaceAroundStep(start, end, start, end, new Slice(content, 0, 0), wrappers.length, true));\n}\nfunction setBlockType(tr, from, to, type, attrs) {\n    if (!type.isTextblock)\n        throw new RangeError(\"Type given to setBlockType should be a textblock\");\n    let mapFrom = tr.steps.length;\n    tr.doc.nodesBetween(from, to, (node, pos) => {\n        let attrsHere = typeof attrs == \"function\" ? attrs(node) : attrs;\n        if (node.isTextblock && !node.hasMarkup(type, attrsHere) &&\n            canChangeType(tr.doc, tr.mapping.slice(mapFrom).map(pos), type)) {\n            let convertNewlines = null;\n            if (type.schema.linebreakReplacement) {\n                let pre = type.whitespace == \"pre\", supportLinebreak = !!type.contentMatch.matchType(type.schema.linebreakReplacement);\n                if (pre && !supportLinebreak)\n                    convertNewlines = false;\n                else if (!pre && supportLinebreak)\n                    convertNewlines = true;\n            }\n            // Ensure all markup that isn't allowed in the new node type is cleared\n            if (convertNewlines === false)\n                replaceLinebreaks(tr, node, pos, mapFrom);\n            clearIncompatible(tr, tr.mapping.slice(mapFrom).map(pos, 1), type, undefined, convertNewlines === null);\n            let mapping = tr.mapping.slice(mapFrom);\n            let startM = mapping.map(pos, 1), endM = mapping.map(pos + node.nodeSize, 1);\n            tr.step(new ReplaceAroundStep(startM, endM, startM + 1, endM - 1, new Slice(Fragment.from(type.create(attrsHere, null, node.marks)), 0, 0), 1, true));\n            if (convertNewlines === true)\n                replaceNewlines(tr, node, pos, mapFrom);\n            return false;\n        }\n    });\n}\nfunction replaceNewlines(tr, node, pos, mapFrom) {\n    node.forEach((child, offset) => {\n        if (child.isText) {\n            let m, newline = /\\r?\\n|\\r/g;\n            while (m = newline.exec(child.text)) {\n                let start = tr.mapping.slice(mapFrom).map(pos + 1 + offset + m.index);\n                tr.replaceWith(start, start + 1, node.type.schema.linebreakReplacement.create());\n            }\n        }\n    });\n}\nfunction replaceLinebreaks(tr, node, pos, mapFrom) {\n    node.forEach((child, offset) => {\n        if (child.type == child.type.schema.linebreakReplacement) {\n            let start = tr.mapping.slice(mapFrom).map(pos + 1 + offset);\n            tr.replaceWith(start, start + 1, node.type.schema.text(\"\\n\"));\n        }\n    });\n}\nfunction canChangeType(doc, pos, type) {\n    let $pos = doc.resolve(pos), index = $pos.index();\n    return $pos.parent.canReplaceWith(index, index + 1, type);\n}\n/**\nChange the type, attributes, and/or marks of the node at `pos`.\nWhen `type` isn't given, the existing node type is preserved,\n*/\nfunction setNodeMarkup(tr, pos, type, attrs, marks) {\n    let node = tr.doc.nodeAt(pos);\n    if (!node)\n        throw new RangeError(\"No node at given position\");\n    if (!type)\n        type = node.type;\n    let newNode = type.create(attrs, null, marks || node.marks);\n    if (node.isLeaf)\n        return tr.replaceWith(pos, pos + node.nodeSize, newNode);\n    if (!type.validContent(node.content))\n        throw new RangeError(\"Invalid content for node type \" + type.name);\n    tr.step(new ReplaceAroundStep(pos, pos + node.nodeSize, pos + 1, pos + node.nodeSize - 1, new Slice(Fragment.from(newNode), 0, 0), 1, true));\n}\n/**\nCheck whether splitting at the given position is allowed.\n*/\nfunction canSplit(doc, pos, depth = 1, typesAfter) {\n    let $pos = doc.resolve(pos), base = $pos.depth - depth;\n    let innerType = (typesAfter && typesAfter[typesAfter.length - 1]) || $pos.parent;\n    if (base < 0 || $pos.parent.type.spec.isolating ||\n        !$pos.parent.canReplace($pos.index(), $pos.parent.childCount) ||\n        !innerType.type.validContent($pos.parent.content.cutByIndex($pos.index(), $pos.parent.childCount)))\n        return false;\n    for (let d = $pos.depth - 1, i = depth - 2; d > base; d--, i--) {\n        let node = $pos.node(d), index = $pos.index(d);\n        if (node.type.spec.isolating)\n            return false;\n        let rest = node.content.cutByIndex(index, node.childCount);\n        let overrideChild = typesAfter && typesAfter[i + 1];\n        if (overrideChild)\n            rest = rest.replaceChild(0, overrideChild.type.create(overrideChild.attrs));\n        let after = (typesAfter && typesAfter[i]) || node;\n        if (!node.canReplace(index + 1, node.childCount) || !after.type.validContent(rest))\n            return false;\n    }\n    let index = $pos.indexAfter(base);\n    let baseType = typesAfter && typesAfter[0];\n    return $pos.node(base).canReplaceWith(index, index, baseType ? baseType.type : $pos.node(base + 1).type);\n}\nfunction split(tr, pos, depth = 1, typesAfter) {\n    let $pos = tr.doc.resolve(pos), before = Fragment.empty, after = Fragment.empty;\n    for (let d = $pos.depth, e = $pos.depth - depth, i = depth - 1; d > e; d--, i--) {\n        before = Fragment.from($pos.node(d).copy(before));\n        let typeAfter = typesAfter && typesAfter[i];\n        after = Fragment.from(typeAfter ? typeAfter.type.create(typeAfter.attrs, after) : $pos.node(d).copy(after));\n    }\n    tr.step(new ReplaceStep(pos, pos, new Slice(before.append(after), depth, depth), true));\n}\n/**\nTest whether the blocks before and after a given position can be\njoined.\n*/\nfunction canJoin(doc, pos) {\n    let $pos = doc.resolve(pos), index = $pos.index();\n    return joinable($pos.nodeBefore, $pos.nodeAfter) &&\n        $pos.parent.canReplace(index, index + 1);\n}\nfunction canAppendWithSubstitutedLinebreaks(a, b) {\n    if (!b.content.size)\n        a.type.compatibleContent(b.type);\n    let match = a.contentMatchAt(a.childCount);\n    let { linebreakReplacement } = a.type.schema;\n    for (let i = 0; i < b.childCount; i++) {\n        let child = b.child(i);\n        let type = child.type == linebreakReplacement ? a.type.schema.nodes.text : child.type;\n        match = match.matchType(type);\n        if (!match)\n            return false;\n        if (!a.type.allowsMarks(child.marks))\n            return false;\n    }\n    return match.validEnd;\n}\nfunction joinable(a, b) {\n    return !!(a && b && !a.isLeaf && canAppendWithSubstitutedLinebreaks(a, b));\n}\n/**\nFind an ancestor of the given position that can be joined to the\nblock before (or after if `dir` is positive). Returns the joinable\npoint, if any.\n*/\nfunction joinPoint(doc, pos, dir = -1) {\n    let $pos = doc.resolve(pos);\n    for (let d = $pos.depth;; d--) {\n        let before, after, index = $pos.index(d);\n        if (d == $pos.depth) {\n            before = $pos.nodeBefore;\n            after = $pos.nodeAfter;\n        }\n        else if (dir > 0) {\n            before = $pos.node(d + 1);\n            index++;\n            after = $pos.node(d).maybeChild(index);\n        }\n        else {\n            before = $pos.node(d).maybeChild(index - 1);\n            after = $pos.node(d + 1);\n        }\n        if (before && !before.isTextblock && joinable(before, after) &&\n            $pos.node(d).canReplace(index, index + 1))\n            return pos;\n        if (d == 0)\n            break;\n        pos = dir < 0 ? $pos.before(d) : $pos.after(d);\n    }\n}\nfunction join(tr, pos, depth) {\n    let convertNewlines = null;\n    let { linebreakReplacement } = tr.doc.type.schema;\n    let $before = tr.doc.resolve(pos - depth), beforeType = $before.node().type;\n    if (linebreakReplacement && beforeType.inlineContent) {\n        let pre = beforeType.whitespace == \"pre\";\n        let supportLinebreak = !!beforeType.contentMatch.matchType(linebreakReplacement);\n        if (pre && !supportLinebreak)\n            convertNewlines = false;\n        else if (!pre && supportLinebreak)\n            convertNewlines = true;\n    }\n    let mapFrom = tr.steps.length;\n    if (convertNewlines === false) {\n        let $after = tr.doc.resolve(pos + depth);\n        replaceLinebreaks(tr, $after.node(), $after.before(), mapFrom);\n    }\n    if (beforeType.inlineContent)\n        clearIncompatible(tr, pos + depth - 1, beforeType, $before.node().contentMatchAt($before.index()), convertNewlines == null);\n    let mapping = tr.mapping.slice(mapFrom), start = mapping.map(pos - depth);\n    tr.step(new ReplaceStep(start, mapping.map(pos + depth, -1), Slice.empty, true));\n    if (convertNewlines === true) {\n        let $full = tr.doc.resolve(start);\n        replaceNewlines(tr, $full.node(), $full.before(), tr.steps.length);\n    }\n    return tr;\n}\n/**\nTry to find a point where a node of the given type can be inserted\nnear `pos`, by searching up the node hierarchy when `pos` itself\nisn't a valid place but is at the start or end of a node. Return\nnull if no position was found.\n*/\nfunction insertPoint(doc, pos, nodeType) {\n    let $pos = doc.resolve(pos);\n    if ($pos.parent.canReplaceWith($pos.index(), $pos.index(), nodeType))\n        return pos;\n    if ($pos.parentOffset == 0)\n        for (let d = $pos.depth - 1; d >= 0; d--) {\n            let index = $pos.index(d);\n            if ($pos.node(d).canReplaceWith(index, index, nodeType))\n                return $pos.before(d + 1);\n            if (index > 0)\n                return null;\n        }\n    if ($pos.parentOffset == $pos.parent.content.size)\n        for (let d = $pos.depth - 1; d >= 0; d--) {\n            let index = $pos.indexAfter(d);\n            if ($pos.node(d).canReplaceWith(index, index, nodeType))\n                return $pos.after(d + 1);\n            if (index < $pos.node(d).childCount)\n                return null;\n        }\n    return null;\n}\n/**\nFinds a position at or around the given position where the given\nslice can be inserted. Will look at parent nodes' nearest boundary\nand try there, even if the original position wasn't directly at the\nstart or end of that node. Returns null when no position was found.\n*/\nfunction dropPoint(doc, pos, slice) {\n    let $pos = doc.resolve(pos);\n    if (!slice.content.size)\n        return pos;\n    let content = slice.content;\n    for (let i = 0; i < slice.openStart; i++)\n        content = content.firstChild.content;\n    for (let pass = 1; pass <= (slice.openStart == 0 && slice.size ? 2 : 1); pass++) {\n        for (let d = $pos.depth; d >= 0; d--) {\n            let bias = d == $pos.depth ? 0 : $pos.pos <= ($pos.start(d + 1) + $pos.end(d + 1)) / 2 ? -1 : 1;\n            for (let attempt = 0; attempt < 2; attempt++) {\n                if (attempt) {\n                    if (!bias)\n                        break;\n                    bias = -bias;\n                }\n                let insertPos = $pos.index(d) + (bias > 0 ? 1 : 0);\n                let parent = $pos.node(d), fits = false;\n                if (pass == 1) {\n                    fits = parent.canReplace(insertPos, insertPos, content);\n                }\n                else {\n                    let wrapping = parent.contentMatchAt(insertPos).findWrapping(content.firstChild.type);\n                    fits = wrapping && parent.canReplaceWith(insertPos, insertPos, wrapping[0]);\n                }\n                if (fits)\n                    return bias == 0 ? $pos.pos : bias < 0 ? $pos.before(d + 1) : $pos.after(d + 1);\n            }\n        }\n    }\n    return null;\n}\n\n/**\n\u2018Fit\u2019 a slice into a given position in the document, producing a\n[step](https://prosemirror.net/docs/ref/#transform.Step) that inserts it. Will return null if\nthere's no meaningful way to insert the slice here, or inserting it\nwould be a no-op (an empty slice over an empty range).\n*/\nfunction replaceStep(doc, from, to = from, slice = Slice.empty) {\n    if (from == to && !slice.size)\n        return null;\n    let $from = doc.resolve(from), $to = doc.resolve(to);\n    // Optimization -- avoid work if it's obvious that it's not needed.\n    if (fitsTrivially($from, $to, slice))\n        return new ReplaceStep(from, to, slice);\n    return new Fitter($from, $to, slice).fit();\n}\nfunction fitsTrivially($from, $to, slice) {\n    return !slice.openStart && !slice.openEnd && $from.start() == $to.start() &&\n        $from.parent.canReplace($from.index(), $to.index(), slice.content);\n}\n// Algorithm for 'placing' the elements of a slice into a gap:\n//\n// We consider the content of each node that is open to the left to be\n// independently placeable. I.e. in <p(\"foo\"), p(\"bar\")>, when the\n// paragraph on the left is open, \"foo\" can be placed (somewhere on\n// the left side of the replacement gap) independently from p(\"bar\").\n//\n// This class tracks the state of the placement progress in the\n// following properties:\n//\n//  - `frontier` holds a stack of `{type, match}` objects that\n//    represent the open side of the replacement. It starts at\n//    `$from`, then moves forward as content is placed, and is finally\n//    reconciled with `$to`.\n//\n//  - `unplaced` is a slice that represents the content that hasn't\n//    been placed yet.\n//\n//  - `placed` is a fragment of placed content. Its open-start value\n//    is implicit in `$from`, and its open-end value in `frontier`.\nclass Fitter {\n    constructor($from, $to, unplaced) {\n        this.$from = $from;\n        this.$to = $to;\n        this.unplaced = unplaced;\n        this.frontier = [];\n        this.placed = Fragment.empty;\n        for (let i = 0; i <= $from.depth; i++) {\n            let node = $from.node(i);\n            this.frontier.push({\n                type: node.type,\n                match: node.contentMatchAt($from.indexAfter(i))\n            });\n        }\n        for (let i = $from.depth; i > 0; i--)\n            this.placed = Fragment.from($from.node(i).copy(this.placed));\n    }\n    get depth() { return this.frontier.length - 1; }\n    fit() {\n        // As long as there's unplaced content, try to place some of it.\n        // If that fails, either increase the open score of the unplaced\n        // slice, or drop nodes from it, and then try again.\n        while (this.unplaced.size) {\n            let fit = this.findFittable();\n            if (fit)\n                this.placeNodes(fit);\n            else\n                this.openMore() || this.dropNode();\n        }\n        // When there's inline content directly after the frontier _and_\n        // directly after `this.$to`, we must generate a `ReplaceAround`\n        // step that pulls that content into the node after the frontier.\n        // That means the fitting must be done to the end of the textblock\n        // node after `this.$to`, not `this.$to` itself.\n        let moveInline = this.mustMoveInline(), placedSize = this.placed.size - this.depth - this.$from.depth;\n        let $from = this.$from, $to = this.close(moveInline < 0 ? this.$to : $from.doc.resolve(moveInline));\n        if (!$to)\n            return null;\n        // If closing to `$to` succeeded, create a step\n        let content = this.placed, openStart = $from.depth, openEnd = $to.depth;\n        while (openStart && openEnd && content.childCount == 1) { // Normalize by dropping open parent nodes\n            content = content.firstChild.content;\n            openStart--;\n            openEnd--;\n        }\n        let slice = new Slice(content, openStart, openEnd);\n        if (moveInline > -1)\n            return new ReplaceAroundStep($from.pos, moveInline, this.$to.pos, this.$to.end(), slice, placedSize);\n        if (slice.size || $from.pos != this.$to.pos) // Don't generate no-op steps\n            return new ReplaceStep($from.pos, $to.pos, slice);\n        return null;\n    }\n    // Find a position on the start spine of `this.unplaced` that has\n    // content that can be moved somewhere on the frontier. Returns two\n    // depths, one for the slice and one for the frontier.\n    findFittable() {\n        let startDepth = this.unplaced.openStart;\n        for (let cur = this.unplaced.content, d = 0, openEnd = this.unplaced.openEnd; d < startDepth; d++) {\n            let node = cur.firstChild;\n            if (cur.childCount > 1)\n                openEnd = 0;\n            if (node.type.spec.isolating && openEnd <= d) {\n                startDepth = d;\n                break;\n            }\n            cur = node.content;\n        }\n        // Only try wrapping nodes (pass 2) after finding a place without\n        // wrapping failed.\n        for (let pass = 1; pass <= 2; pass++) {\n            for (let sliceDepth = pass == 1 ? startDepth : this.unplaced.openStart; sliceDepth >= 0; sliceDepth--) {\n                let fragment, parent = null;\n                if (sliceDepth) {\n                    parent = contentAt(this.unplaced.content, sliceDepth - 1).firstChild;\n                    fragment = parent.content;\n                }\n                else {\n                    fragment = this.unplaced.content;\n                }\n                let first = fragment.firstChild;\n                for (let frontierDepth = this.depth; frontierDepth >= 0; frontierDepth--) {\n                    let { type, match } = this.frontier[frontierDepth], wrap, inject = null;\n                    // In pass 1, if the next node matches, or there is no next\n                    // node but the parents look compatible, we've found a\n                    // place.\n                    if (pass == 1 && (first ? match.matchType(first.type) || (inject = match.fillBefore(Fragment.from(first), false))\n                        : parent && type.compatibleContent(parent.type)))\n                        return { sliceDepth, frontierDepth, parent, inject };\n                    // In pass 2, look for a set of wrapping nodes that make\n                    // `first` fit here.\n                    else if (pass == 2 && first && (wrap = match.findWrapping(first.type)))\n                        return { sliceDepth, frontierDepth, parent, wrap };\n                    // Don't continue looking further up if the parent node\n                    // would fit here.\n                    if (parent && match.matchType(parent.type))\n                        break;\n                }\n            }\n        }\n    }\n    openMore() {\n        let { content, openStart, openEnd } = this.unplaced;\n        if (maxOpen(content, -1) <= openStart)\n            return false;\n        if (this.unplaced.size > 1 && maxOpen(content, 1) > openEnd)\n            openEnd++;\n        this.unplaced = new Slice(content, openStart + 1, openEnd);\n        return true;\n    }\n    dropNode() {\n        let { content, openStart, openEnd } = this.unplaced;\n        let inner = contentAt(content, openStart);\n        if (inner.childCount <= 1 && openStart > 0) {\n            let openAtEnd = content.size - openStart <= openStart + inner.size;\n            this.unplaced = new Slice(dropFromFragment(content, openStart - 1, 1), openStart - 1, openAtEnd ? openStart - 1 : openEnd);\n        }\n        else {\n            this.unplaced = new Slice(dropFromFragment(content, openStart, 1), openStart, openEnd);\n        }\n    }\n    // Move content from the unplaced slice at `sliceDepth` to the\n    // frontier node at `frontierDepth`. Close that frontier node when\n    // applicable.\n    placeNodes({ sliceDepth, frontierDepth, parent, inject, wrap }) {\n        while (this.depth > frontierDepth)\n            this.closeFrontierNode();\n        if (wrap)\n            for (let i = 0; i < wrap.length; i++)\n                this.openFrontierNode(wrap[i]);\n        let slice = this.unplaced, fragment = parent ? parent.content : slice.content;\n        let openStart = slice.openStart - sliceDepth;\n        let taken = 0, add = [];\n        let { match, type } = this.frontier[frontierDepth];\n        if (inject) {\n            for (let i = 0; i < inject.childCount; i++)\n                add.push(inject.child(i));\n            match = match.matchFragment(inject);\n        }\n        // Computes the amount of (end) open nodes at the end of the\n        // fragment. When 0, the parent is open, but no more. When\n        // negative, nothing is open.\n        let openEndCount = (fragment.size + sliceDepth) - (slice.content.size - slice.openEnd);\n        // Scan over the fragment, fitting as many child nodes as\n        // possible.\n        while (taken < fragment.childCount) {\n            let next = fragment.child(taken), matches = match.matchType(next.type);\n            if (!matches)\n                break;\n            taken++;\n            if (taken > 1 || openStart == 0 || next.content.size) { // Drop empty open nodes\n                match = matches;\n                add.push(closeNodeStart(next.mark(type.allowedMarks(next.marks)), taken == 1 ? openStart : 0, taken == fragment.childCount ? openEndCount : -1));\n            }\n        }\n        let toEnd = taken == fragment.childCount;\n        if (!toEnd)\n            openEndCount = -1;\n        this.placed = addToFragment(this.placed, frontierDepth, Fragment.from(add));\n        this.frontier[frontierDepth].match = match;\n        // If the parent types match, and the entire node was moved, and\n        // it's not open, close this frontier node right away.\n        if (toEnd && openEndCount < 0 && parent && parent.type == this.frontier[this.depth].type && this.frontier.length > 1)\n            this.closeFrontierNode();\n        // Add new frontier nodes for any open nodes at the end.\n        for (let i = 0, cur = add[add.length - 1]; cur && i < openEndCount; i++) {\n            this.frontier.push({ type: cur.type, match: cur.contentMatchAt(cur.childCount) });\n            cur = cur.lastChild;\n        }\n        // Update `this.unplaced`. Drop the entire node from which we\n        // placed it we got to its end, otherwise just drop the placed\n        // nodes.\n        this.unplaced = !toEnd ? new Slice(dropFromFragment(slice.content, sliceDepth, taken), sliceDepth, slice.openEnd)\n            : sliceDepth == 0 ? Slice.empty\n                : new Slice(dropFromFragment(slice.content, sliceDepth - 1, 1), sliceDepth - 1, openEndCount < 0 ? slice.openEnd : sliceDepth - 1);\n    }\n    mustMoveInline() {\n        if (!this.$to.parent.isTextblock)\n            return -1;\n        let top = this.frontier[this.depth], level;\n        if (!top.type.isTextblock || !contentAfterFits(this.$to, this.$to.depth, top.type, top.match, false) ||\n            (this.$to.depth == this.depth && (level = this.findCloseLevel(this.$to)) && level.depth == this.depth))\n            return -1;\n        let { depth } = this.$to, after = this.$to.after(depth);\n        while (depth > 1 && after == this.$to.end(--depth))\n            ++after;\n        return after;\n    }\n    findCloseLevel($to) {\n        scan: for (let i = Math.min(this.depth, $to.depth); i >= 0; i--) {\n            let { match, type } = this.frontier[i];\n            let dropInner = i < $to.depth && $to.end(i + 1) == $to.pos + ($to.depth - (i + 1));\n            let fit = contentAfterFits($to, i, type, match, dropInner);\n            if (!fit)\n                continue;\n            for (let d = i - 1; d >= 0; d--) {\n                let { match, type } = this.frontier[d];\n                let matches = contentAfterFits($to, d, type, match, true);\n                if (!matches || matches.childCount)\n                    continue scan;\n            }\n            return { depth: i, fit, move: dropInner ? $to.doc.resolve($to.after(i + 1)) : $to };\n        }\n    }\n    close($to) {\n        let close = this.findCloseLevel($to);\n        if (!close)\n            return null;\n        while (this.depth > close.depth)\n            this.closeFrontierNode();\n        if (close.fit.childCount)\n            this.placed = addToFragment(this.placed, close.depth, close.fit);\n        $to = close.move;\n        for (let d = close.depth + 1; d <= $to.depth; d++) {\n            let node = $to.node(d), add = node.type.contentMatch.fillBefore(node.content, true, $to.index(d));\n            this.openFrontierNode(node.type, node.attrs, add);\n        }\n        return $to;\n    }\n    openFrontierNode(type, attrs = null, content) {\n        let top = this.frontier[this.depth];\n        top.match = top.match.matchType(type);\n        this.placed = addToFragment(this.placed, this.depth, Fragment.from(type.create(attrs, content)));\n        this.frontier.push({ type, match: type.contentMatch });\n    }\n    closeFrontierNode() {\n        let open = this.frontier.pop();\n        let add = open.match.fillBefore(Fragment.empty, true);\n        if (add.childCount)\n            this.placed = addToFragment(this.placed, this.frontier.length, add);\n    }\n}\nfunction dropFromFragment(fragment, depth, count) {\n    if (depth == 0)\n        return fragment.cutByIndex(count, fragment.childCount);\n    return fragment.replaceChild(0, fragment.firstChild.copy(dropFromFragment(fragment.firstChild.content, depth - 1, count)));\n}\nfunction addToFragment(fragment, depth, content) {\n    if (depth == 0)\n        return fragment.append(content);\n    return fragment.replaceChild(fragment.childCount - 1, fragment.lastChild.copy(addToFragment(fragment.lastChild.content, depth - 1, content)));\n}\nfunction contentAt(fragment, depth) {\n    for (let i = 0; i < depth; i++)\n        fragment = fragment.firstChild.content;\n    return fragment;\n}\nfunction closeNodeStart(node, openStart, openEnd) {\n    if (openStart <= 0)\n        return node;\n    let frag = node.content;\n    if (openStart > 1)\n        frag = frag.replaceChild(0, closeNodeStart(frag.firstChild, openStart - 1, frag.childCount == 1 ? openEnd - 1 : 0));\n    if (openStart > 0) {\n        frag = node.type.contentMatch.fillBefore(frag).append(frag);\n        if (openEnd <= 0)\n            frag = frag.append(node.type.contentMatch.matchFragment(frag).fillBefore(Fragment.empty, true));\n    }\n    return node.copy(frag);\n}\nfunction contentAfterFits($to, depth, type, match, open) {\n    let node = $to.node(depth), index = open ? $to.indexAfter(depth) : $to.index(depth);\n    if (index == node.childCount && !type.compatibleContent(node.type))\n        return null;\n    let fit = match.fillBefore(node.content, true, index);\n    return fit && !invalidMarks(type, node.content, index) ? fit : null;\n}\nfunction invalidMarks(type, fragment, start) {\n    for (let i = start; i < fragment.childCount; i++)\n        if (!type.allowsMarks(fragment.child(i).marks))\n            return true;\n    return false;\n}\nfunction definesContent(type) {\n    return type.spec.defining || type.spec.definingForContent;\n}\nfunction maxOpen(frag, side) {\n    for (let count = 0;; count++) {\n        let ch = side < 0 ? frag.firstChild : frag.lastChild;\n        if (!ch || ch.isAtom)\n            return count;\n        frag = ch.content;\n    }\n}\nfunction replaceRange(tr, from, to, slice) {\n    if (!slice.size)\n        return tr.deleteRange(from, to);\n    let $from = tr.doc.resolve(from), $to = tr.doc.resolve(to);\n    if (fitsTrivially($from, $to, slice))\n        return tr.step(new ReplaceStep(from, to, slice));\n    let targetDepths = coveredDepths($from, $to);\n    // Can't replace the whole document, so remove 0 if it's present\n    if (targetDepths[targetDepths.length - 1] == 0)\n        targetDepths.pop();\n    // Negative numbers represent not expansion over the whole node at\n    // that depth, but replacing from $from.before(-D) to $to.pos.\n    let preferredTarget = -($from.depth + 1);\n    targetDepths.unshift(preferredTarget);\n    // This loop picks a preferred target depth, if one of the covering\n    // depths is not outside of a defining node, and adds negative\n    // depths for any depth that has $from at its start and does not\n    // cross a defining node.\n    for (let d = $from.depth, pos = $from.pos - 1; d > 0; d--, pos--) {\n        let spec = $from.node(d).type.spec;\n        if (spec.defining || spec.definingAsContext || spec.isolating)\n            break;\n        if (targetDepths.indexOf(d) > -1)\n            preferredTarget = d;\n        else if ($from.before(d) == pos)\n            targetDepths.splice(1, 0, -d);\n    }\n    // Try to fit each possible depth of the slice into each possible\n    // target depth, starting with the preferred depths.\n    let preferredTargetIndex = targetDepths.indexOf(preferredTarget);\n    let leftNodes = [], preferredDepth = slice.openStart;\n    for (let content = slice.content, i = 0;; i++) {\n        let node = content.firstChild;\n        leftNodes.push(node);\n        if (i == slice.openStart)\n            break;\n        content = node.content;\n    }\n    // Back up preferredDepth to cover defining textblocks directly\n    // above it, possibly skipping a non-defining textblock.\n    for (let d = preferredDepth - 1; d >= 0; d--) {\n        let leftNode = leftNodes[d], def = definesContent(leftNode.type);\n        if (def && !leftNode.sameMarkup($from.node(Math.abs(preferredTarget) - 1)))\n            preferredDepth = d;\n        else if (def || !leftNode.type.isTextblock)\n            break;\n    }\n    for (let j = slice.openStart; j >= 0; j--) {\n        let openDepth = (j + preferredDepth + 1) % (slice.openStart + 1);\n        let insert = leftNodes[openDepth];\n        if (!insert)\n            continue;\n        for (let i = 0; i < targetDepths.length; i++) {\n            // Loop over possible expansion levels, starting with the\n            // preferred one\n            let targetDepth = targetDepths[(i + preferredTargetIndex) % targetDepths.length], expand = true;\n            if (targetDepth < 0) {\n                expand = false;\n                targetDepth = -targetDepth;\n            }\n            let parent = $from.node(targetDepth - 1), index = $from.index(targetDepth - 1);\n            if (parent.canReplaceWith(index, index, insert.type, insert.marks))\n                return tr.replace($from.before(targetDepth), expand ? $to.after(targetDepth) : to, new Slice(closeFragment(slice.content, 0, slice.openStart, openDepth), openDepth, slice.openEnd));\n        }\n    }\n    let startSteps = tr.steps.length;\n    for (let i = targetDepths.length - 1; i >= 0; i--) {\n        tr.replace(from, to, slice);\n        if (tr.steps.length > startSteps)\n            break;\n        let depth = targetDepths[i];\n        if (depth < 0)\n            continue;\n        from = $from.before(depth);\n        to = $to.after(depth);\n    }\n}\nfunction closeFragment(fragment, depth, oldOpen, newOpen, parent) {\n    if (depth < oldOpen) {\n        let first = fragment.firstChild;\n        fragment = fragment.replaceChild(0, first.copy(closeFragment(first.content, depth + 1, oldOpen, newOpen, first)));\n    }\n    if (depth > newOpen) {\n        let match = parent.contentMatchAt(0);\n        let start = match.fillBefore(fragment).append(fragment);\n        fragment = start.append(match.matchFragment(start).fillBefore(Fragment.empty, true));\n    }\n    return fragment;\n}\nfunction replaceRangeWith(tr, from, to, node) {\n    if (!node.isInline && from == to && tr.doc.resolve(from).parent.content.size) {\n        let point = insertPoint(tr.doc, from, node.type);\n        if (point != null)\n            from = to = point;\n    }\n    tr.replaceRange(from, to, new Slice(Fragment.from(node), 0, 0));\n}\nfunction deleteRange(tr, from, to) {\n    let $from = tr.doc.resolve(from), $to = tr.doc.resolve(to);\n    // When the deleted range spans from the start of one textblock to\n    // the start of another one, move out of the start of both blocks.\n    if ($from.parent.isTextblock && $to.parent.isTextblock && $from.start() != $to.start() &&\n        $from.parentOffset == 0 && $to.parentOffset == 0) {\n        let shared = $from.sharedDepth(to), isolated = false;\n        for (let d = $from.depth; d > shared; d--)\n            if ($from.node(d).type.spec.isolating)\n                isolated = true;\n        for (let d = $to.depth; d > shared; d--)\n            if ($to.node(d).type.spec.isolating)\n                isolated = true;\n        if (!isolated) {\n            for (let d = $from.depth; d > 0 && from == $from.start(d); d--)\n                from = $from.before(d);\n            for (let d = $to.depth; d > 0 && to == $to.start(d); d--)\n                to = $to.before(d);\n            $from = tr.doc.resolve(from);\n            $to = tr.doc.resolve(to);\n        }\n    }\n    let covered = coveredDepths($from, $to);\n    for (let i = 0; i < covered.length; i++) {\n        let depth = covered[i], last = i == covered.length - 1;\n        if ((last && depth == 0) || $from.node(depth).type.contentMatch.validEnd)\n            return tr.delete($from.start(depth), $to.end(depth));\n        if (depth > 0 && (last || $from.node(depth - 1).canReplace($from.index(depth - 1), $to.indexAfter(depth - 1))))\n            return tr.delete($from.before(depth), $to.after(depth));\n    }\n    for (let d = 1; d <= $from.depth && d <= $to.depth; d++) {\n        if (from - $from.start(d) == $from.depth - d && to > $from.end(d) && $to.end(d) - to != $to.depth - d &&\n            $from.start(d - 1) == $to.start(d - 1) && $from.node(d - 1).canReplace($from.index(d - 1), $to.index(d - 1)))\n            return tr.delete($from.before(d), to);\n    }\n    tr.delete(from, to);\n}\n// Returns an array of all depths for which $from - $to spans the\n// whole content of the nodes at that depth.\nfunction coveredDepths($from, $to) {\n    let result = [], minDepth = Math.min($from.depth, $to.depth);\n    for (let d = minDepth; d >= 0; d--) {\n        let start = $from.start(d);\n        if (start < $from.pos - ($from.depth - d) ||\n            $to.end(d) > $to.pos + ($to.depth - d) ||\n            $from.node(d).type.spec.isolating ||\n            $to.node(d).type.spec.isolating)\n            break;\n        if (start == $to.start(d) ||\n            (d == $from.depth && d == $to.depth && $from.parent.inlineContent && $to.parent.inlineContent &&\n                d && $to.start(d - 1) == start - 1))\n            result.push(d);\n    }\n    return result;\n}\n\n/**\nUpdate an attribute in a specific node.\n*/\nclass AttrStep extends Step {\n    /**\n    Construct an attribute step.\n    */\n    constructor(\n    /**\n    The position of the target node.\n    */\n    pos, \n    /**\n    The attribute to set.\n    */\n    attr, \n    // The attribute's new value.\n    value) {\n        super();\n        this.pos = pos;\n        this.attr = attr;\n        this.value = value;\n    }\n    apply(doc) {\n        let node = doc.nodeAt(this.pos);\n        if (!node)\n            return StepResult.fail(\"No node at attribute step's position\");\n        let attrs = Object.create(null);\n        for (let name in node.attrs)\n            attrs[name] = node.attrs[name];\n        attrs[this.attr] = this.value;\n        let updated = node.type.create(attrs, null, node.marks);\n        return StepResult.fromReplace(doc, this.pos, this.pos + 1, new Slice(Fragment.from(updated), 0, node.isLeaf ? 0 : 1));\n    }\n    getMap() {\n        return StepMap.empty;\n    }\n    invert(doc) {\n        return new AttrStep(this.pos, this.attr, doc.nodeAt(this.pos).attrs[this.attr]);\n    }\n    map(mapping) {\n        let pos = mapping.mapResult(this.pos, 1);\n        return pos.deletedAfter ? null : new AttrStep(pos.pos, this.attr, this.value);\n    }\n    toJSON() {\n        return { stepType: \"attr\", pos: this.pos, attr: this.attr, value: this.value };\n    }\n    static fromJSON(schema, json) {\n        if (typeof json.pos != \"number\" || typeof json.attr != \"string\")\n            throw new RangeError(\"Invalid input for AttrStep.fromJSON\");\n        return new AttrStep(json.pos, json.attr, json.value);\n    }\n}\nStep.jsonID(\"attr\", AttrStep);\n/**\nUpdate an attribute in the doc node.\n*/\nclass DocAttrStep extends Step {\n    /**\n    Construct an attribute step.\n    */\n    constructor(\n    /**\n    The attribute to set.\n    */\n    attr, \n    // The attribute's new value.\n    value) {\n        super();\n        this.attr = attr;\n        this.value = value;\n    }\n    apply(doc) {\n        let attrs = Object.create(null);\n        for (let name in doc.attrs)\n            attrs[name] = doc.attrs[name];\n        attrs[this.attr] = this.value;\n        let updated = doc.type.create(attrs, doc.content, doc.marks);\n        return StepResult.ok(updated);\n    }\n    getMap() {\n        return StepMap.empty;\n    }\n    invert(doc) {\n        return new DocAttrStep(this.attr, doc.attrs[this.attr]);\n    }\n    map(mapping) {\n        return this;\n    }\n    toJSON() {\n        return { stepType: \"docAttr\", attr: this.attr, value: this.value };\n    }\n    static fromJSON(schema, json) {\n        if (typeof json.attr != \"string\")\n            throw new RangeError(\"Invalid input for DocAttrStep.fromJSON\");\n        return new DocAttrStep(json.attr, json.value);\n    }\n}\nStep.jsonID(\"docAttr\", DocAttrStep);\n\n/**\n@internal\n*/\nlet TransformError = class extends Error {\n};\nTransformError = function TransformError(message) {\n    let err = Error.call(this, message);\n    err.__proto__ = TransformError.prototype;\n    return err;\n};\nTransformError.prototype = Object.create(Error.prototype);\nTransformError.prototype.constructor = TransformError;\nTransformError.prototype.name = \"TransformError\";\n/**\nAbstraction to build up and track an array of\n[steps](https://prosemirror.net/docs/ref/#transform.Step) representing a document transformation.\n\nMost transforming methods return the `Transform` object itself, so\nthat they can be chained.\n*/\nclass Transform {\n    /**\n    Create a transform that starts with the given document.\n    */\n    constructor(\n    /**\n    The current document (the result of applying the steps in the\n    transform).\n    */\n    doc) {\n        this.doc = doc;\n        /**\n        The steps in this transform.\n        */\n        this.steps = [];\n        /**\n        The documents before each of the steps.\n        */\n        this.docs = [];\n        /**\n        A mapping with the maps for each of the steps in this transform.\n        */\n        this.mapping = new Mapping;\n    }\n    /**\n    The starting document.\n    */\n    get before() { return this.docs.length ? this.docs[0] : this.doc; }\n    /**\n    Apply a new step in this transform, saving the result. Throws an\n    error when the step fails.\n    */\n    step(step) {\n        let result = this.maybeStep(step);\n        if (result.failed)\n            throw new TransformError(result.failed);\n        return this;\n    }\n    /**\n    Try to apply a step in this transformation, ignoring it if it\n    fails. Returns the step result.\n    */\n    maybeStep(step) {\n        let result = step.apply(this.doc);\n        if (!result.failed)\n            this.addStep(step, result.doc);\n        return result;\n    }\n    /**\n    True when the document has been changed (when there are any\n    steps).\n    */\n    get docChanged() {\n        return this.steps.length > 0;\n    }\n    /**\n    Return a single range, in post-transform document positions,\n    that covers all content changed by this transform. Returns null\n    if no replacements are made. Note that this will ignore changes\n    that add/remove marks without replacing the underlying content.\n    */\n    changedRange() {\n        let from = 1e9, to = -1e9;\n        for (let i = 0; i < this.mapping.maps.length; i++) {\n            let map = this.mapping.maps[i];\n            if (i) {\n                from = map.map(from, 1);\n                to = map.map(to, -1);\n            }\n            map.forEach((_f, _t, fromB, toB) => {\n                from = Math.min(from, fromB);\n                to = Math.max(to, toB);\n            });\n        }\n        return from == 1e9 ? null : { from, to };\n    }\n    /**\n    @internal\n    */\n    addStep(step, doc) {\n        this.docs.push(this.doc);\n        this.steps.push(step);\n        this.mapping.appendMap(step.getMap());\n        this.doc = doc;\n    }\n    /**\n    Replace the part of the document between `from` and `to` with the\n    given `slice`.\n    */\n    replace(from, to = from, slice = Slice.empty) {\n        let step = replaceStep(this.doc, from, to, slice);\n        if (step)\n            this.step(step);\n        return this;\n    }\n    /**\n    Replace the given range with the given content, which may be a\n    fragment, node, or array of nodes.\n    */\n    replaceWith(from, to, content) {\n        return this.replace(from, to, new Slice(Fragment.from(content), 0, 0));\n    }\n    /**\n    Delete the content between the given positions.\n    */\n    delete(from, to) {\n        return this.replace(from, to, Slice.empty);\n    }\n    /**\n    Insert the given content at the given position.\n    */\n    insert(pos, content) {\n        return this.replaceWith(pos, pos, content);\n    }\n    /**\n    Replace a range of the document with a given slice, using\n    `from`, `to`, and the slice's\n    [`openStart`](https://prosemirror.net/docs/ref/#model.Slice.openStart) property as hints, rather\n    than fixed start and end points. This method may grow the\n    replaced area or close open nodes in the slice in order to get a\n    fit that is more in line with WYSIWYG expectations, by dropping\n    fully covered parent nodes of the replaced region when they are\n    marked [non-defining as\n    context](https://prosemirror.net/docs/ref/#model.NodeSpec.definingAsContext), or including an\n    open parent node from the slice that _is_ marked as [defining\n    its content](https://prosemirror.net/docs/ref/#model.NodeSpec.definingForContent).\n    \n    This is the method, for example, to handle paste. The similar\n    [`replace`](https://prosemirror.net/docs/ref/#transform.Transform.replace) method is a more\n    primitive tool which will _not_ move the start and end of its given\n    range, and is useful in situations where you need more precise\n    control over what happens.\n    */\n    replaceRange(from, to, slice) {\n        replaceRange(this, from, to, slice);\n        return this;\n    }\n    /**\n    Replace the given range with a node, but use `from` and `to` as\n    hints, rather than precise positions. When from and to are the same\n    and are at the start or end of a parent node in which the given\n    node doesn't fit, this method may _move_ them out towards a parent\n    that does allow the given node to be placed. When the given range\n    completely covers a parent node, this method may completely replace\n    that parent node.\n    */\n    replaceRangeWith(from, to, node) {\n        replaceRangeWith(this, from, to, node);\n        return this;\n    }\n    /**\n    Delete the given range, expanding it to cover fully covered\n    parent nodes until a valid replace is found.\n    */\n    deleteRange(from, to) {\n        deleteRange(this, from, to);\n        return this;\n    }\n    /**\n    Split the content in the given range off from its parent, if there\n    is sibling content before or after it, and move it up the tree to\n    the depth specified by `target`. You'll probably want to use\n    [`liftTarget`](https://prosemirror.net/docs/ref/#transform.liftTarget) to compute `target`, to make\n    sure the lift is valid.\n    */\n    lift(range, target) {\n        lift(this, range, target);\n        return this;\n    }\n    /**\n    Join the blocks around the given position. If depth is 2, their\n    last and first siblings are also joined, and so on.\n    */\n    join(pos, depth = 1) {\n        join(this, pos, depth);\n        return this;\n    }\n    /**\n    Wrap the given [range](https://prosemirror.net/docs/ref/#model.NodeRange) in the given set of wrappers.\n    The wrappers are assumed to be valid in this position, and should\n    probably be computed with [`findWrapping`](https://prosemirror.net/docs/ref/#transform.findWrapping).\n    */\n    wrap(range, wrappers) {\n        wrap(this, range, wrappers);\n        return this;\n    }\n    /**\n    Set the type of all textblocks (partly) between `from` and `to` to\n    the given node type with the given attributes.\n    */\n    setBlockType(from, to = from, type, attrs = null) {\n        setBlockType(this, from, to, type, attrs);\n        return this;\n    }\n    /**\n    Change the type, attributes, and/or marks of the node at `pos`.\n    When `type` isn't given, the existing node type is preserved,\n    */\n    setNodeMarkup(pos, type, attrs = null, marks) {\n        setNodeMarkup(this, pos, type, attrs, marks);\n        return this;\n    }\n    /**\n    Set a single attribute on a given node to a new value.\n    The `pos` addresses the document content. Use `setDocAttribute`\n    to set attributes on the document itself.\n    */\n    setNodeAttribute(pos, attr, value) {\n        this.step(new AttrStep(pos, attr, value));\n        return this;\n    }\n    /**\n    Set a single attribute on the document to a new value.\n    */\n    setDocAttribute(attr, value) {\n        this.step(new DocAttrStep(attr, value));\n        return this;\n    }\n    /**\n    Add a mark to the node at position `pos`.\n    */\n    addNodeMark(pos, mark) {\n        this.step(new AddNodeMarkStep(pos, mark));\n        return this;\n    }\n    /**\n    Remove a mark (or all marks of the given type) from the node at\n    position `pos`.\n    */\n    removeNodeMark(pos, mark) {\n        let node = this.doc.nodeAt(pos);\n        if (!node)\n            throw new RangeError(\"No node at position \" + pos);\n        if (mark instanceof Mark) {\n            if (mark.isInSet(node.marks))\n                this.step(new RemoveNodeMarkStep(pos, mark));\n        }\n        else {\n            let set = node.marks, found, steps = [];\n            while (found = mark.isInSet(set)) {\n                steps.push(new RemoveNodeMarkStep(pos, found));\n                set = found.removeFromSet(set);\n            }\n            for (let i = steps.length - 1; i >= 0; i--)\n                this.step(steps[i]);\n        }\n        return this;\n    }\n    /**\n    Split the node at the given position, and optionally, if `depth` is\n    greater than one, any number of nodes above that. By default, the\n    parts split off will inherit the node type of the original node.\n    This can be changed by passing an array of types and attributes to\n    use after the split (with the outermost nodes coming first).\n    */\n    split(pos, depth = 1, typesAfter) {\n        split(this, pos, depth, typesAfter);\n        return this;\n    }\n    /**\n    Add the given mark to the inline content between `from` and `to`.\n    */\n    addMark(from, to, mark) {\n        addMark(this, from, to, mark);\n        return this;\n    }\n    /**\n    Remove marks from inline nodes between `from` and `to`. When\n    `mark` is a single mark, remove precisely that mark. When it is\n    a mark type, remove all marks of that type. When it is null,\n    remove all marks of any type.\n    */\n    removeMark(from, to, mark) {\n        removeMark(this, from, to, mark);\n        return this;\n    }\n    /**\n    Removes all marks and nodes from the content of the node at\n    `pos` that don't match the given new parent node type. Accepts\n    an optional starting [content match](https://prosemirror.net/docs/ref/#model.ContentMatch) as\n    third argument.\n    */\n    clearIncompatible(pos, parentType, match) {\n        clearIncompatible(this, pos, parentType, match);\n        return this;\n    }\n}\n\nexport { AddMarkStep, AddNodeMarkStep, AttrStep, DocAttrStep, MapResult, Mapping, RemoveMarkStep, RemoveNodeMarkStep, ReplaceAroundStep, ReplaceStep, Step, StepMap, StepResult, Transform, TransformError, canJoin, canSplit, dropPoint, findWrapping, insertPoint, joinPoint, liftTarget, replaceStep };\n", "import { Slice, Fragment, Mark, Node } from 'prosemirror-model';\nimport { ReplaceStep, ReplaceAroundStep, Transform } from 'prosemirror-transform';\n\nconst classesById = Object.create(null);\n/**\nSuperclass for editor selections. Every selection type should\nextend this. Should not be instantiated directly.\n*/\nclass Selection {\n    /**\n    Initialize a selection with the head and anchor and ranges. If no\n    ranges are given, constructs a single range across `$anchor` and\n    `$head`.\n    */\n    constructor(\n    /**\n    The resolved anchor of the selection (the side that stays in\n    place when the selection is modified).\n    */\n    $anchor, \n    /**\n    The resolved head of the selection (the side that moves when\n    the selection is modified).\n    */\n    $head, ranges) {\n        this.$anchor = $anchor;\n        this.$head = $head;\n        this.ranges = ranges || [new SelectionRange($anchor.min($head), $anchor.max($head))];\n    }\n    /**\n    The selection's anchor, as an unresolved position.\n    */\n    get anchor() { return this.$anchor.pos; }\n    /**\n    The selection's head.\n    */\n    get head() { return this.$head.pos; }\n    /**\n    The lower bound of the selection's main range.\n    */\n    get from() { return this.$from.pos; }\n    /**\n    The upper bound of the selection's main range.\n    */\n    get to() { return this.$to.pos; }\n    /**\n    The resolved lower  bound of the selection's main range.\n    */\n    get $from() {\n        return this.ranges[0].$from;\n    }\n    /**\n    The resolved upper bound of the selection's main range.\n    */\n    get $to() {\n        return this.ranges[0].$to;\n    }\n    /**\n    Indicates whether the selection contains any content.\n    */\n    get empty() {\n        let ranges = this.ranges;\n        for (let i = 0; i < ranges.length; i++)\n            if (ranges[i].$from.pos != ranges[i].$to.pos)\n                return false;\n        return true;\n    }\n    /**\n    Get the content of this selection as a slice.\n    */\n    content() {\n        return this.$from.doc.slice(this.from, this.to, true);\n    }\n    /**\n    Replace the selection with a slice or, if no slice is given,\n    delete the selection. Will append to the given transaction.\n    */\n    replace(tr, content = Slice.empty) {\n        // Put the new selection at the position after the inserted\n        // content. When that ended in an inline node, search backwards,\n        // to get the position after that node. If not, search forward.\n        let lastNode = content.content.lastChild, lastParent = null;\n        for (let i = 0; i < content.openEnd; i++) {\n            lastParent = lastNode;\n            lastNode = lastNode.lastChild;\n        }\n        let mapFrom = tr.steps.length, ranges = this.ranges;\n        for (let i = 0; i < ranges.length; i++) {\n            let { $from, $to } = ranges[i], mapping = tr.mapping.slice(mapFrom);\n            tr.replaceRange(mapping.map($from.pos), mapping.map($to.pos), i ? Slice.empty : content);\n            if (i == 0)\n                selectionToInsertionEnd(tr, mapFrom, (lastNode ? lastNode.isInline : lastParent && lastParent.isTextblock) ? -1 : 1);\n        }\n    }\n    /**\n    Replace the selection with the given node, appending the changes\n    to the given transaction.\n    */\n    replaceWith(tr, node) {\n        let mapFrom = tr.steps.length, ranges = this.ranges;\n        for (let i = 0; i < ranges.length; i++) {\n            let { $from, $to } = ranges[i], mapping = tr.mapping.slice(mapFrom);\n            let from = mapping.map($from.pos), to = mapping.map($to.pos);\n            if (i) {\n                tr.deleteRange(from, to);\n            }\n            else {\n                tr.replaceRangeWith(from, to, node);\n                selectionToInsertionEnd(tr, mapFrom, node.isInline ? -1 : 1);\n            }\n        }\n    }\n    /**\n    Find a valid cursor or leaf node selection starting at the given\n    position and searching back if `dir` is negative, and forward if\n    positive. When `textOnly` is true, only consider cursor\n    selections. Will return null when no valid selection position is\n    found.\n    */\n    static findFrom($pos, dir, textOnly = false) {\n        let inner = $pos.parent.inlineContent ? new TextSelection($pos)\n            : findSelectionIn($pos.node(0), $pos.parent, $pos.pos, $pos.index(), dir, textOnly);\n        if (inner)\n            return inner;\n        for (let depth = $pos.depth - 1; depth >= 0; depth--) {\n            let found = dir < 0\n                ? findSelectionIn($pos.node(0), $pos.node(depth), $pos.before(depth + 1), $pos.index(depth), dir, textOnly)\n                : findSelectionIn($pos.node(0), $pos.node(depth), $pos.after(depth + 1), $pos.index(depth) + 1, dir, textOnly);\n            if (found)\n                return found;\n        }\n        return null;\n    }\n    /**\n    Find a valid cursor or leaf node selection near the given\n    position. Searches forward first by default, but if `bias` is\n    negative, it will search backwards first.\n    */\n    static near($pos, bias = 1) {\n        return this.findFrom($pos, bias) || this.findFrom($pos, -bias) || new AllSelection($pos.node(0));\n    }\n    /**\n    Find the cursor or leaf node selection closest to the start of\n    the given document. Will return an\n    [`AllSelection`](https://prosemirror.net/docs/ref/#state.AllSelection) if no valid position\n    exists.\n    */\n    static atStart(doc) {\n        return findSelectionIn(doc, doc, 0, 0, 1) || new AllSelection(doc);\n    }\n    /**\n    Find the cursor or leaf node selection closest to the end of the\n    given document.\n    */\n    static atEnd(doc) {\n        return findSelectionIn(doc, doc, doc.content.size, doc.childCount, -1) || new AllSelection(doc);\n    }\n    /**\n    Deserialize the JSON representation of a selection. Must be\n    implemented for custom classes (as a static class method).\n    */\n    static fromJSON(doc, json) {\n        if (!json || !json.type)\n            throw new RangeError(\"Invalid input for Selection.fromJSON\");\n        let cls = classesById[json.type];\n        if (!cls)\n            throw new RangeError(`No selection type ${json.type} defined`);\n        return cls.fromJSON(doc, json);\n    }\n    /**\n    To be able to deserialize selections from JSON, custom selection\n    classes must register themselves with an ID string, so that they\n    can be disambiguated. Try to pick something that's unlikely to\n    clash with classes from other modules.\n    */\n    static jsonID(id, selectionClass) {\n        if (id in classesById)\n            throw new RangeError(\"Duplicate use of selection JSON ID \" + id);\n        classesById[id] = selectionClass;\n        selectionClass.prototype.jsonID = id;\n        return selectionClass;\n    }\n    /**\n    Get a [bookmark](https://prosemirror.net/docs/ref/#state.SelectionBookmark) for this selection,\n    which is a value that can be mapped without having access to a\n    current document, and later resolved to a real selection for a\n    given document again. (This is used mostly by the history to\n    track and restore old selections.) The default implementation of\n    this method just converts the selection to a text selection and\n    returns the bookmark for that.\n    */\n    getBookmark() {\n        return TextSelection.between(this.$anchor, this.$head).getBookmark();\n    }\n}\nSelection.prototype.visible = true;\n/**\nRepresents a selected range in a document.\n*/\nclass SelectionRange {\n    /**\n    Create a range.\n    */\n    constructor(\n    /**\n    The lower bound of the range.\n    */\n    $from, \n    /**\n    The upper bound of the range.\n    */\n    $to) {\n        this.$from = $from;\n        this.$to = $to;\n    }\n}\nlet warnedAboutTextSelection = false;\nfunction checkTextSelection($pos) {\n    if (!warnedAboutTextSelection && !$pos.parent.inlineContent) {\n        warnedAboutTextSelection = true;\n        console[\"warn\"](\"TextSelection endpoint not pointing into a node with inline content (\" + $pos.parent.type.name + \")\");\n    }\n}\n/**\nA text selection represents a classical editor selection, with a\nhead (the moving side) and anchor (immobile side), both of which\npoint into textblock nodes. It can be empty (a regular cursor\nposition).\n*/\nclass TextSelection extends Selection {\n    /**\n    Construct a text selection between the given points.\n    */\n    constructor($anchor, $head = $anchor) {\n        checkTextSelection($anchor);\n        checkTextSelection($head);\n        super($anchor, $head);\n    }\n    /**\n    Returns a resolved position if this is a cursor selection (an\n    empty text selection), and null otherwise.\n    */\n    get $cursor() { return this.$anchor.pos == this.$head.pos ? this.$head : null; }\n    map(doc, mapping) {\n        let $head = doc.resolve(mapping.map(this.head));\n        if (!$head.parent.inlineContent)\n            return Selection.near($head);\n        let $anchor = doc.resolve(mapping.map(this.anchor));\n        return new TextSelection($anchor.parent.inlineContent ? $anchor : $head, $head);\n    }\n    replace(tr, content = Slice.empty) {\n        super.replace(tr, content);\n        if (content == Slice.empty) {\n            let marks = this.$from.marksAcross(this.$to);\n            if (marks)\n                tr.ensureMarks(marks);\n        }\n    }\n    eq(other) {\n        return other instanceof TextSelection && other.anchor == this.anchor && other.head == this.head;\n    }\n    getBookmark() {\n        return new TextBookmark(this.anchor, this.head);\n    }\n    toJSON() {\n        return { type: \"text\", anchor: this.anchor, head: this.head };\n    }\n    /**\n    @internal\n    */\n    static fromJSON(doc, json) {\n        if (typeof json.anchor != \"number\" || typeof json.head != \"number\")\n            throw new RangeError(\"Invalid input for TextSelection.fromJSON\");\n        return new TextSelection(doc.resolve(json.anchor), doc.resolve(json.head));\n    }\n    /**\n    Create a text selection from non-resolved positions.\n    */\n    static create(doc, anchor, head = anchor) {\n        let $anchor = doc.resolve(anchor);\n        return new this($anchor, head == anchor ? $anchor : doc.resolve(head));\n    }\n    /**\n    Return a text selection that spans the given positions or, if\n    they aren't text positions, find a text selection near them.\n    `bias` determines whether the method searches forward (default)\n    or backwards (negative number) first. Will fall back to calling\n    [`Selection.near`](https://prosemirror.net/docs/ref/#state.Selection^near) when the document\n    doesn't contain a valid text position.\n    */\n    static between($anchor, $head, bias) {\n        let dPos = $anchor.pos - $head.pos;\n        if (!bias || dPos)\n            bias = dPos >= 0 ? 1 : -1;\n        if (!$head.parent.inlineContent) {\n            let found = Selection.findFrom($head, bias, true) || Selection.findFrom($head, -bias, true);\n            if (found)\n                $head = found.$head;\n            else\n                return Selection.near($head, bias);\n        }\n        if (!$anchor.parent.inlineContent) {\n            if (dPos == 0) {\n                $anchor = $head;\n            }\n            else {\n                $anchor = (Selection.findFrom($anchor, -bias, true) || Selection.findFrom($anchor, bias, true)).$anchor;\n                if (($anchor.pos < $head.pos) != (dPos < 0))\n                    $anchor = $head;\n            }\n        }\n        return new TextSelection($anchor, $head);\n    }\n}\nSelection.jsonID(\"text\", TextSelection);\nclass TextBookmark {\n    constructor(anchor, head) {\n        this.anchor = anchor;\n        this.head = head;\n    }\n    map(mapping) {\n        return new TextBookmark(mapping.map(this.anchor), mapping.map(this.head));\n    }\n    resolve(doc) {\n        return TextSelection.between(doc.resolve(this.anchor), doc.resolve(this.head));\n    }\n}\n/**\nA node selection is a selection that points at a single node. All\nnodes marked [selectable](https://prosemirror.net/docs/ref/#model.NodeSpec.selectable) can be the\ntarget of a node selection. In such a selection, `from` and `to`\npoint directly before and after the selected node, `anchor` equals\n`from`, and `head` equals `to`..\n*/\nclass NodeSelection extends Selection {\n    /**\n    Create a node selection. Does not verify the validity of its\n    argument.\n    */\n    constructor($pos) {\n        let node = $pos.nodeAfter;\n        let $end = $pos.node(0).resolve($pos.pos + node.nodeSize);\n        super($pos, $end);\n        this.node = node;\n    }\n    map(doc, mapping) {\n        let { deleted, pos } = mapping.mapResult(this.anchor);\n        let $pos = doc.resolve(pos);\n        if (deleted)\n            return Selection.near($pos);\n        return new NodeSelection($pos);\n    }\n    content() {\n        return new Slice(Fragment.from(this.node), 0, 0);\n    }\n    eq(other) {\n        return other instanceof NodeSelection && other.anchor == this.anchor;\n    }\n    toJSON() {\n        return { type: \"node\", anchor: this.anchor };\n    }\n    getBookmark() { return new NodeBookmark(this.anchor); }\n    /**\n    @internal\n    */\n    static fromJSON(doc, json) {\n        if (typeof json.anchor != \"number\")\n            throw new RangeError(\"Invalid input for NodeSelection.fromJSON\");\n        return new NodeSelection(doc.resolve(json.anchor));\n    }\n    /**\n    Create a node selection from non-resolved positions.\n    */\n    static create(doc, from) {\n        return new NodeSelection(doc.resolve(from));\n    }\n    /**\n    Determines whether the given node may be selected as a node\n    selection.\n    */\n    static isSelectable(node) {\n        return !node.isText && node.type.spec.selectable !== false;\n    }\n}\nNodeSelection.prototype.visible = false;\nSelection.jsonID(\"node\", NodeSelection);\nclass NodeBookmark {\n    constructor(anchor) {\n        this.anchor = anchor;\n    }\n    map(mapping) {\n        let { deleted, pos } = mapping.mapResult(this.anchor);\n        return deleted ? new TextBookmark(pos, pos) : new NodeBookmark(pos);\n    }\n    resolve(doc) {\n        let $pos = doc.resolve(this.anchor), node = $pos.nodeAfter;\n        if (node && NodeSelection.isSelectable(node))\n            return new NodeSelection($pos);\n        return Selection.near($pos);\n    }\n}\n/**\nA selection type that represents selecting the whole document\n(which can not necessarily be expressed with a text selection, when\nthere are for example leaf block nodes at the start or end of the\ndocument).\n*/\nclass AllSelection extends Selection {\n    /**\n    Create an all-selection over the given document.\n    */\n    constructor(doc) {\n        super(doc.resolve(0), doc.resolve(doc.content.size));\n    }\n    replace(tr, content = Slice.empty) {\n        if (content == Slice.empty) {\n            tr.delete(0, tr.doc.content.size);\n            let sel = Selection.atStart(tr.doc);\n            if (!sel.eq(tr.selection))\n                tr.setSelection(sel);\n        }\n        else {\n            super.replace(tr, content);\n        }\n    }\n    toJSON() { return { type: \"all\" }; }\n    /**\n    @internal\n    */\n    static fromJSON(doc) { return new AllSelection(doc); }\n    map(doc) { return new AllSelection(doc); }\n    eq(other) { return other instanceof AllSelection; }\n    getBookmark() { return AllBookmark; }\n}\nSelection.jsonID(\"all\", AllSelection);\nconst AllBookmark = {\n    map() { return this; },\n    resolve(doc) { return new AllSelection(doc); }\n};\n// FIXME we'll need some awareness of text direction when scanning for selections\n// Try to find a selection inside the given node. `pos` points at the\n// position where the search starts. When `text` is true, only return\n// text selections.\nfunction findSelectionIn(doc, node, pos, index, dir, text = false) {\n    if (node.inlineContent)\n        return TextSelection.create(doc, pos);\n    for (let i = index - (dir > 0 ? 0 : 1); dir > 0 ? i < node.childCount : i >= 0; i += dir) {\n        let child = node.child(i);\n        if (!child.isAtom) {\n            let inner = findSelectionIn(doc, child, pos + dir, dir < 0 ? child.childCount : 0, dir, text);\n            if (inner)\n                return inner;\n        }\n        else if (!text && NodeSelection.isSelectable(child)) {\n            return NodeSelection.create(doc, pos - (dir < 0 ? child.nodeSize : 0));\n        }\n        pos += child.nodeSize * dir;\n    }\n    return null;\n}\nfunction selectionToInsertionEnd(tr, startLen, bias) {\n    let last = tr.steps.length - 1;\n    if (last < startLen)\n        return;\n    let step = tr.steps[last];\n    if (!(step instanceof ReplaceStep || step instanceof ReplaceAroundStep))\n        return;\n    let map = tr.mapping.maps[last], end;\n    map.forEach((_from, _to, _newFrom, newTo) => { if (end == null)\n        end = newTo; });\n    tr.setSelection(Selection.near(tr.doc.resolve(end), bias));\n}\n\nconst UPDATED_SEL = 1, UPDATED_MARKS = 2, UPDATED_SCROLL = 4;\n/**\nAn editor state transaction, which can be applied to a state to\ncreate an updated state. Use\n[`EditorState.tr`](https://prosemirror.net/docs/ref/#state.EditorState.tr) to create an instance.\n\nTransactions track changes to the document (they are a subclass of\n[`Transform`](https://prosemirror.net/docs/ref/#transform.Transform)), but also other state changes,\nlike selection updates and adjustments of the set of [stored\nmarks](https://prosemirror.net/docs/ref/#state.EditorState.storedMarks). In addition, you can store\nmetadata properties in a transaction, which are extra pieces of\ninformation that client code or plugins can use to describe what a\ntransaction represents, so that they can update their [own\nstate](https://prosemirror.net/docs/ref/#state.StateField) accordingly.\n\nThe [editor view](https://prosemirror.net/docs/ref/#view.EditorView) uses a few metadata\nproperties: it will attach a property `\"pointer\"` with the value\n`true` to selection transactions directly caused by mouse or touch\ninput, a `\"composition\"` property holding an ID identifying the\ncomposition that caused it to transactions caused by composed DOM\ninput, and a `\"uiEvent\"` property of that may be `\"paste\"`,\n`\"cut\"`, or `\"drop\"`.\n*/\nclass Transaction extends Transform {\n    /**\n    @internal\n    */\n    constructor(state) {\n        super(state.doc);\n        // The step count for which the current selection is valid.\n        this.curSelectionFor = 0;\n        // Bitfield to track which aspects of the state were updated by\n        // this transaction.\n        this.updated = 0;\n        // Object used to store metadata properties for the transaction.\n        this.meta = Object.create(null);\n        this.time = Date.now();\n        this.curSelection = state.selection;\n        this.storedMarks = state.storedMarks;\n    }\n    /**\n    The transaction's current selection. This defaults to the editor\n    selection [mapped](https://prosemirror.net/docs/ref/#state.Selection.map) through the steps in the\n    transaction, but can be overwritten with\n    [`setSelection`](https://prosemirror.net/docs/ref/#state.Transaction.setSelection).\n    */\n    get selection() {\n        if (this.curSelectionFor < this.steps.length) {\n            this.curSelection = this.curSelection.map(this.doc, this.mapping.slice(this.curSelectionFor));\n            this.curSelectionFor = this.steps.length;\n        }\n        return this.curSelection;\n    }\n    /**\n    Update the transaction's current selection. Will determine the\n    selection that the editor gets when the transaction is applied.\n    */\n    setSelection(selection) {\n        if (selection.$from.doc != this.doc)\n            throw new RangeError(\"Selection passed to setSelection must point at the current document\");\n        this.curSelection = selection;\n        this.curSelectionFor = this.steps.length;\n        this.updated = (this.updated | UPDATED_SEL) & ~UPDATED_MARKS;\n        this.storedMarks = null;\n        return this;\n    }\n    /**\n    Whether the selection was explicitly updated by this transaction.\n    */\n    get selectionSet() {\n        return (this.updated & UPDATED_SEL) > 0;\n    }\n    /**\n    Set the current stored marks.\n    */\n    setStoredMarks(marks) {\n        this.storedMarks = marks;\n        this.updated |= UPDATED_MARKS;\n        return this;\n    }\n    /**\n    Make sure the current stored marks or, if that is null, the marks\n    at the selection, match the given set of marks. Does nothing if\n    this is already the case.\n    */\n    ensureMarks(marks) {\n        if (!Mark.sameSet(this.storedMarks || this.selection.$from.marks(), marks))\n            this.setStoredMarks(marks);\n        return this;\n    }\n    /**\n    Add a mark to the set of stored marks.\n    */\n    addStoredMark(mark) {\n        return this.ensureMarks(mark.addToSet(this.storedMarks || this.selection.$head.marks()));\n    }\n    /**\n    Remove a mark or mark type from the set of stored marks.\n    */\n    removeStoredMark(mark) {\n        return this.ensureMarks(mark.removeFromSet(this.storedMarks || this.selection.$head.marks()));\n    }\n    /**\n    Whether the stored marks were explicitly set for this transaction.\n    */\n    get storedMarksSet() {\n        return (this.updated & UPDATED_MARKS) > 0;\n    }\n    /**\n    @internal\n    */\n    addStep(step, doc) {\n        super.addStep(step, doc);\n        this.updated = this.updated & ~UPDATED_MARKS;\n        this.storedMarks = null;\n    }\n    /**\n    Update the timestamp for the transaction.\n    */\n    setTime(time) {\n        this.time = time;\n        return this;\n    }\n    /**\n    Replace the current selection with the given slice.\n    */\n    replaceSelection(slice) {\n        this.selection.replace(this, slice);\n        return this;\n    }\n    /**\n    Replace the selection with the given node. When `inheritMarks` is\n    true and the content is inline, it inherits the marks from the\n    place where it is inserted.\n    */\n    replaceSelectionWith(node, inheritMarks = true) {\n        let selection = this.selection;\n        if (inheritMarks)\n            node = node.mark(this.storedMarks || (selection.empty ? selection.$from.marks() : (selection.$from.marksAcross(selection.$to) || Mark.none)));\n        selection.replaceWith(this, node);\n        return this;\n    }\n    /**\n    Delete the selection.\n    */\n    deleteSelection() {\n        this.selection.replace(this);\n        return this;\n    }\n    /**\n    Replace the given range, or the selection if no range is given,\n    with a text node containing the given string.\n    */\n    insertText(text, from, to) {\n        let schema = this.doc.type.schema;\n        if (from == null) {\n            if (!text)\n                return this.deleteSelection();\n            return this.replaceSelectionWith(schema.text(text), true);\n        }\n        else {\n            if (to == null)\n                to = from;\n            if (!text)\n                return this.deleteRange(from, to);\n            let marks = this.storedMarks;\n            if (!marks) {\n                let $from = this.doc.resolve(from);\n                marks = to == from ? $from.marks() : $from.marksAcross(this.doc.resolve(to));\n            }\n            this.replaceRangeWith(from, to, schema.text(text, marks));\n            if (!this.selection.empty && this.selection.to == from + text.length)\n                this.setSelection(Selection.near(this.selection.$to));\n            return this;\n        }\n    }\n    /**\n    Store a metadata property in this transaction, keyed either by\n    name or by plugin.\n    */\n    setMeta(key, value) {\n        this.meta[typeof key == \"string\" ? key : key.key] = value;\n        return this;\n    }\n    /**\n    Retrieve a metadata property for a given name or plugin.\n    */\n    getMeta(key) {\n        return this.meta[typeof key == \"string\" ? key : key.key];\n    }\n    /**\n    Returns true if this transaction doesn't contain any metadata,\n    and can thus safely be extended.\n    */\n    get isGeneric() {\n        for (let _ in this.meta)\n            return false;\n        return true;\n    }\n    /**\n    Indicate that the editor should scroll the selection into view\n    when updated to the state produced by this transaction.\n    */\n    scrollIntoView() {\n        this.updated |= UPDATED_SCROLL;\n        return this;\n    }\n    /**\n    True when this transaction has had `scrollIntoView` called on it.\n    */\n    get scrolledIntoView() {\n        return (this.updated & UPDATED_SCROLL) > 0;\n    }\n}\n\nfunction bind(f, self) {\n    return !self || !f ? f : f.bind(self);\n}\nclass FieldDesc {\n    constructor(name, desc, self) {\n        this.name = name;\n        this.init = bind(desc.init, self);\n        this.apply = bind(desc.apply, self);\n    }\n}\nconst baseFields = [\n    new FieldDesc(\"doc\", {\n        init(config) { return config.doc || config.schema.topNodeType.createAndFill(); },\n        apply(tr) { return tr.doc; }\n    }),\n    new FieldDesc(\"selection\", {\n        init(config, instance) { return config.selection || Selection.atStart(instance.doc); },\n        apply(tr) { return tr.selection; }\n    }),\n    new FieldDesc(\"storedMarks\", {\n        init(config) { return config.storedMarks || null; },\n        apply(tr, _marks, _old, state) { return state.selection.$cursor ? tr.storedMarks : null; }\n    }),\n    new FieldDesc(\"scrollToSelection\", {\n        init() { return 0; },\n        apply(tr, prev) { return tr.scrolledIntoView ? prev + 1 : prev; }\n    })\n];\n// Object wrapping the part of a state object that stays the same\n// across transactions. Stored in the state's `config` property.\nclass Configuration {\n    constructor(schema, plugins) {\n        this.schema = schema;\n        this.plugins = [];\n        this.pluginsByKey = Object.create(null);\n        this.fields = baseFields.slice();\n        if (plugins)\n            plugins.forEach(plugin => {\n                if (this.pluginsByKey[plugin.key])\n                    throw new RangeError(\"Adding different instances of a keyed plugin (\" + plugin.key + \")\");\n                this.plugins.push(plugin);\n                this.pluginsByKey[plugin.key] = plugin;\n                if (plugin.spec.state)\n                    this.fields.push(new FieldDesc(plugin.key, plugin.spec.state, plugin));\n            });\n    }\n}\n/**\nThe state of a ProseMirror editor is represented by an object of\nthis type. A state is a persistent data structure\u2014it isn't\nupdated, but rather a new state value is computed from an old one\nusing the [`apply`](https://prosemirror.net/docs/ref/#state.EditorState.apply) method.\n\nA state holds a number of built-in fields, and plugins can\n[define](https://prosemirror.net/docs/ref/#state.PluginSpec.state) additional fields.\n*/\nclass EditorState {\n    /**\n    @internal\n    */\n    constructor(\n    /**\n    @internal\n    */\n    config) {\n        this.config = config;\n    }\n    /**\n    The schema of the state's document.\n    */\n    get schema() {\n        return this.config.schema;\n    }\n    /**\n    The plugins that are active in this state.\n    */\n    get plugins() {\n        return this.config.plugins;\n    }\n    /**\n    Apply the given transaction to produce a new state.\n    */\n    apply(tr) {\n        return this.applyTransaction(tr).state;\n    }\n    /**\n    @internal\n    */\n    filterTransaction(tr, ignore = -1) {\n        for (let i = 0; i < this.config.plugins.length; i++)\n            if (i != ignore) {\n                let plugin = this.config.plugins[i];\n                if (plugin.spec.filterTransaction && !plugin.spec.filterTransaction.call(plugin, tr, this))\n                    return false;\n            }\n        return true;\n    }\n    /**\n    Verbose variant of [`apply`](https://prosemirror.net/docs/ref/#state.EditorState.apply) that\n    returns the precise transactions that were applied (which might\n    be influenced by the [transaction\n    hooks](https://prosemirror.net/docs/ref/#state.PluginSpec.filterTransaction) of\n    plugins) along with the new state.\n    */\n    applyTransaction(rootTr) {\n        if (!this.filterTransaction(rootTr))\n            return { state: this, transactions: [] };\n        let trs = [rootTr], newState = this.applyInner(rootTr), seen = null;\n        // This loop repeatedly gives plugins a chance to respond to\n        // transactions as new transactions are added, making sure to only\n        // pass the transactions the plugin did not see before.\n        for (;;) {\n            let haveNew = false;\n            for (let i = 0; i < this.config.plugins.length; i++) {\n                let plugin = this.config.plugins[i];\n                if (plugin.spec.appendTransaction) {\n                    let n = seen ? seen[i].n : 0, oldState = seen ? seen[i].state : this;\n                    let tr = n < trs.length &&\n                        plugin.spec.appendTransaction.call(plugin, n ? trs.slice(n) : trs, oldState, newState);\n                    if (tr && newState.filterTransaction(tr, i)) {\n                        tr.setMeta(\"appendedTransaction\", rootTr);\n                        if (!seen) {\n                            seen = [];\n                            for (let j = 0; j < this.config.plugins.length; j++)\n                                seen.push(j < i ? { state: newState, n: trs.length } : { state: this, n: 0 });\n                        }\n                        trs.push(tr);\n                        newState = newState.applyInner(tr);\n                        haveNew = true;\n                    }\n                    if (seen)\n                        seen[i] = { state: newState, n: trs.length };\n                }\n            }\n            if (!haveNew)\n                return { state: newState, transactions: trs };\n        }\n    }\n    /**\n    @internal\n    */\n    applyInner(tr) {\n        if (!tr.before.eq(this.doc))\n            throw new RangeError(\"Applying a mismatched transaction\");\n        let newInstance = new EditorState(this.config), fields = this.config.fields;\n        for (let i = 0; i < fields.length; i++) {\n            let field = fields[i];\n            newInstance[field.name] = field.apply(tr, this[field.name], this, newInstance);\n        }\n        return newInstance;\n    }\n    /**\n    Accessor that constructs and returns a new [transaction](https://prosemirror.net/docs/ref/#state.Transaction) from this state.\n    */\n    get tr() { return new Transaction(this); }\n    /**\n    Create a new state.\n    */\n    static create(config) {\n        let $config = new Configuration(config.doc ? config.doc.type.schema : config.schema, config.plugins);\n        let instance = new EditorState($config);\n        for (let i = 0; i < $config.fields.length; i++)\n            instance[$config.fields[i].name] = $config.fields[i].init(config, instance);\n        return instance;\n    }\n    /**\n    Create a new state based on this one, but with an adjusted set\n    of active plugins. State fields that exist in both sets of\n    plugins are kept unchanged. Those that no longer exist are\n    dropped, and those that are new are initialized using their\n    [`init`](https://prosemirror.net/docs/ref/#state.StateField.init) method, passing in the new\n    configuration object..\n    */\n    reconfigure(config) {\n        let $config = new Configuration(this.schema, config.plugins);\n        let fields = $config.fields, instance = new EditorState($config);\n        for (let i = 0; i < fields.length; i++) {\n            let name = fields[i].name;\n            instance[name] = this.hasOwnProperty(name) ? this[name] : fields[i].init(config, instance);\n        }\n        return instance;\n    }\n    /**\n    Serialize this state to JSON. If you want to serialize the state\n    of plugins, pass an object mapping property names to use in the\n    resulting JSON object to plugin objects. The argument may also be\n    a string or number, in which case it is ignored, to support the\n    way `JSON.stringify` calls `toString` methods.\n    */\n    toJSON(pluginFields) {\n        let result = { doc: this.doc.toJSON(), selection: this.selection.toJSON() };\n        if (this.storedMarks)\n            result.storedMarks = this.storedMarks.map(m => m.toJSON());\n        if (pluginFields && typeof pluginFields == 'object')\n            for (let prop in pluginFields) {\n                if (prop == \"doc\" || prop == \"selection\")\n                    throw new RangeError(\"The JSON fields `doc` and `selection` are reserved\");\n                let plugin = pluginFields[prop], state = plugin.spec.state;\n                if (state && state.toJSON)\n                    result[prop] = state.toJSON.call(plugin, this[plugin.key]);\n            }\n        return result;\n    }\n    /**\n    Deserialize a JSON representation of a state. `config` should\n    have at least a `schema` field, and should contain array of\n    plugins to initialize the state with. `pluginFields` can be used\n    to deserialize the state of plugins, by associating plugin\n    instances with the property names they use in the JSON object.\n    */\n    static fromJSON(config, json, pluginFields) {\n        if (!json)\n            throw new RangeError(\"Invalid input for EditorState.fromJSON\");\n        if (!config.schema)\n            throw new RangeError(\"Required config field 'schema' missing\");\n        let $config = new Configuration(config.schema, config.plugins);\n        let instance = new EditorState($config);\n        $config.fields.forEach(field => {\n            if (field.name == \"doc\") {\n                instance.doc = Node.fromJSON(config.schema, json.doc);\n            }\n            else if (field.name == \"selection\") {\n                instance.selection = Selection.fromJSON(instance.doc, json.selection);\n            }\n            else if (field.name == \"storedMarks\") {\n                if (json.storedMarks)\n                    instance.storedMarks = json.storedMarks.map(config.schema.markFromJSON);\n            }\n            else {\n                if (pluginFields)\n                    for (let prop in pluginFields) {\n                        let plugin = pluginFields[prop], state = plugin.spec.state;\n                        if (plugin.key == field.name && state && state.fromJSON &&\n                            Object.prototype.hasOwnProperty.call(json, prop)) {\n                            instance[field.name] = state.fromJSON.call(plugin, config, json[prop], instance);\n                            return;\n                        }\n                    }\n                instance[field.name] = field.init(config, instance);\n            }\n        });\n        return instance;\n    }\n}\n\nfunction bindProps(obj, self, target) {\n    for (let prop in obj) {\n        let val = obj[prop];\n        if (val instanceof Function)\n            val = val.bind(self);\n        else if (prop == \"handleDOMEvents\")\n            val = bindProps(val, self, {});\n        target[prop] = val;\n    }\n    return target;\n}\n/**\nPlugins bundle functionality that can be added to an editor.\nThey are part of the [editor state](https://prosemirror.net/docs/ref/#state.EditorState) and\nmay influence that state and the view that contains it.\n*/\nclass Plugin {\n    /**\n    Create a plugin.\n    */\n    constructor(\n    /**\n    The plugin's [spec object](https://prosemirror.net/docs/ref/#state.PluginSpec).\n    */\n    spec) {\n        this.spec = spec;\n        /**\n        The [props](https://prosemirror.net/docs/ref/#view.EditorProps) exported by this plugin.\n        */\n        this.props = {};\n        if (spec.props)\n            bindProps(spec.props, this, this.props);\n        this.key = spec.key ? spec.key.key : createKey(\"plugin\");\n    }\n    /**\n    Extract the plugin's state field from an editor state.\n    */\n    getState(state) { return state[this.key]; }\n}\nconst keys = Object.create(null);\nfunction createKey(name) {\n    if (name in keys)\n        return name + \"$\" + ++keys[name];\n    keys[name] = 0;\n    return name + \"$\";\n}\n/**\nA key is used to [tag](https://prosemirror.net/docs/ref/#state.PluginSpec.key) plugins in a way\nthat makes it possible to find them, given an editor state.\nAssigning a key does mean only one plugin of that type can be\nactive in a state.\n*/\nclass PluginKey {\n    /**\n    Create a plugin key.\n    */\n    constructor(name = \"key\") { this.key = createKey(name); }\n    /**\n    Get the active plugin with this key, if any, from an editor\n    state.\n    */\n    get(state) { return state.config.pluginsByKey[this.key]; }\n    /**\n    Get the plugin's state from an editor state.\n    */\n    getState(state) { return state[this.key]; }\n}\n\nexport { AllSelection, EditorState, NodeSelection, Plugin, PluginKey, Selection, SelectionRange, TextSelection, Transaction };\n", "import { liftTarget, replaceStep, ReplaceStep, canJoin, joinPoint, canSplit, ReplaceAroundStep, findWrapping } from 'prosemirror-transform';\nimport { Slice, Fragment } from 'prosemirror-model';\nimport { NodeSelection, Selection, TextSelection, AllSelection, SelectionRange } from 'prosemirror-state';\n\n/**\nDelete the selection, if there is one.\n*/\nconst deleteSelection = (state, dispatch) => {\n    if (state.selection.empty)\n        return false;\n    if (dispatch)\n        dispatch(state.tr.deleteSelection().scrollIntoView());\n    return true;\n};\nfunction atBlockStart(state, view) {\n    let { $cursor } = state.selection;\n    if (!$cursor || (view ? !view.endOfTextblock(\"backward\", state)\n        : $cursor.parentOffset > 0))\n        return null;\n    return $cursor;\n}\n/**\nIf the selection is empty and at the start of a textblock, try to\nreduce the distance between that block and the one before it\u2014if\nthere's a block directly before it that can be joined, join them.\nIf not, try to move the selected block closer to the next one in\nthe document structure by lifting it out of its parent or moving it\ninto a parent of the previous block. Will use the view for accurate\n(bidi-aware) start-of-textblock detection if given.\n*/\nconst joinBackward = (state, dispatch, view) => {\n    let $cursor = atBlockStart(state, view);\n    if (!$cursor)\n        return false;\n    let $cut = findCutBefore($cursor);\n    // If there is no node before this, try to lift\n    if (!$cut) {\n        let range = $cursor.blockRange(), target = range && liftTarget(range);\n        if (target == null)\n            return false;\n        if (dispatch)\n            dispatch(state.tr.lift(range, target).scrollIntoView());\n        return true;\n    }\n    let before = $cut.nodeBefore;\n    // Apply the joining algorithm\n    if (deleteBarrier(state, $cut, dispatch, -1))\n        return true;\n    // If the node below has no content and the node above is\n    // selectable, delete the node below and select the one above.\n    if ($cursor.parent.content.size == 0 &&\n        (textblockAt(before, \"end\") || NodeSelection.isSelectable(before))) {\n        for (let depth = $cursor.depth;; depth--) {\n            let delStep = replaceStep(state.doc, $cursor.before(depth), $cursor.after(depth), Slice.empty);\n            if (delStep && delStep.slice.size < delStep.to - delStep.from) {\n                if (dispatch) {\n                    let tr = state.tr.step(delStep);\n                    tr.setSelection(textblockAt(before, \"end\")\n                        ? Selection.findFrom(tr.doc.resolve(tr.mapping.map($cut.pos, -1)), -1)\n                        : NodeSelection.create(tr.doc, $cut.pos - before.nodeSize));\n                    dispatch(tr.scrollIntoView());\n                }\n                return true;\n            }\n            if (depth == 1 || $cursor.node(depth - 1).childCount > 1)\n                break;\n        }\n    }\n    // If the node before is an atom, delete it\n    if (before.isAtom && $cut.depth == $cursor.depth - 1) {\n        if (dispatch)\n            dispatch(state.tr.delete($cut.pos - before.nodeSize, $cut.pos).scrollIntoView());\n        return true;\n    }\n    return false;\n};\n/**\nA more limited form of [`joinBackward`](https://prosemirror.net/docs/ref/#commands.joinBackward)\nthat only tries to join the current textblock to the one before\nit, if the cursor is at the start of a textblock.\n*/\nconst joinTextblockBackward = (state, dispatch, view) => {\n    let $cursor = atBlockStart(state, view);\n    if (!$cursor)\n        return false;\n    let $cut = findCutBefore($cursor);\n    return $cut ? joinTextblocksAround(state, $cut, dispatch) : false;\n};\n/**\nA more limited form of [`joinForward`](https://prosemirror.net/docs/ref/#commands.joinForward)\nthat only tries to join the current textblock to the one after\nit, if the cursor is at the end of a textblock.\n*/\nconst joinTextblockForward = (state, dispatch, view) => {\n    let $cursor = atBlockEnd(state, view);\n    if (!$cursor)\n        return false;\n    let $cut = findCutAfter($cursor);\n    return $cut ? joinTextblocksAround(state, $cut, dispatch) : false;\n};\nfunction joinTextblocksAround(state, $cut, dispatch) {\n    let before = $cut.nodeBefore, beforeText = before, beforePos = $cut.pos - 1;\n    for (; !beforeText.isTextblock; beforePos--) {\n        if (beforeText.type.spec.isolating)\n            return false;\n        let child = beforeText.lastChild;\n        if (!child)\n            return false;\n        beforeText = child;\n    }\n    let after = $cut.nodeAfter, afterText = after, afterPos = $cut.pos + 1;\n    for (; !afterText.isTextblock; afterPos++) {\n        if (afterText.type.spec.isolating)\n            return false;\n        let child = afterText.firstChild;\n        if (!child)\n            return false;\n        afterText = child;\n    }\n    let step = replaceStep(state.doc, beforePos, afterPos, Slice.empty);\n    if (!step || step.from != beforePos ||\n        step instanceof ReplaceStep && step.slice.size >= afterPos - beforePos)\n        return false;\n    if (dispatch) {\n        let tr = state.tr.step(step);\n        tr.setSelection(TextSelection.create(tr.doc, beforePos));\n        dispatch(tr.scrollIntoView());\n    }\n    return true;\n}\nfunction textblockAt(node, side, only = false) {\n    for (let scan = node; scan; scan = (side == \"start\" ? scan.firstChild : scan.lastChild)) {\n        if (scan.isTextblock)\n            return true;\n        if (only && scan.childCount != 1)\n            return false;\n    }\n    return false;\n}\n/**\nWhen the selection is empty and at the start of a textblock, select\nthe node before that textblock, if possible. This is intended to be\nbound to keys like backspace, after\n[`joinBackward`](https://prosemirror.net/docs/ref/#commands.joinBackward) or other deleting\ncommands, as a fall-back behavior when the schema doesn't allow\ndeletion at the selected point.\n*/\nconst selectNodeBackward = (state, dispatch, view) => {\n    let { $head, empty } = state.selection, $cut = $head;\n    if (!empty)\n        return false;\n    if ($head.parent.isTextblock) {\n        if (view ? !view.endOfTextblock(\"backward\", state) : $head.parentOffset > 0)\n            return false;\n        $cut = findCutBefore($head);\n    }\n    let node = $cut && $cut.nodeBefore;\n    if (!node || !NodeSelection.isSelectable(node))\n        return false;\n    if (dispatch)\n        dispatch(state.tr.setSelection(NodeSelection.create(state.doc, $cut.pos - node.nodeSize)).scrollIntoView());\n    return true;\n};\nfunction findCutBefore($pos) {\n    if (!$pos.parent.type.spec.isolating)\n        for (let i = $pos.depth - 1; i >= 0; i--) {\n            if ($pos.index(i) > 0)\n                return $pos.doc.resolve($pos.before(i + 1));\n            if ($pos.node(i).type.spec.isolating)\n                break;\n        }\n    return null;\n}\nfunction atBlockEnd(state, view) {\n    let { $cursor } = state.selection;\n    if (!$cursor || (view ? !view.endOfTextblock(\"forward\", state)\n        : $cursor.parentOffset < $cursor.parent.content.size))\n        return null;\n    return $cursor;\n}\n/**\nIf the selection is empty and the cursor is at the end of a\ntextblock, try to reduce or remove the boundary between that block\nand the one after it, either by joining them or by moving the other\nblock closer to this one in the tree structure. Will use the view\nfor accurate start-of-textblock detection if given.\n*/\nconst joinForward = (state, dispatch, view) => {\n    let $cursor = atBlockEnd(state, view);\n    if (!$cursor)\n        return false;\n    let $cut = findCutAfter($cursor);\n    // If there is no node after this, there's nothing to do\n    if (!$cut)\n        return false;\n    let after = $cut.nodeAfter;\n    // Try the joining algorithm\n    if (deleteBarrier(state, $cut, dispatch, 1))\n        return true;\n    // If the node above has no content and the node below is\n    // selectable, delete the node above and select the one below.\n    if ($cursor.parent.content.size == 0 &&\n        (textblockAt(after, \"start\") || NodeSelection.isSelectable(after))) {\n        let delStep = replaceStep(state.doc, $cursor.before(), $cursor.after(), Slice.empty);\n        if (delStep && delStep.slice.size < delStep.to - delStep.from) {\n            if (dispatch) {\n                let tr = state.tr.step(delStep);\n                tr.setSelection(textblockAt(after, \"start\") ? Selection.findFrom(tr.doc.resolve(tr.mapping.map($cut.pos)), 1)\n                    : NodeSelection.create(tr.doc, tr.mapping.map($cut.pos)));\n                dispatch(tr.scrollIntoView());\n            }\n            return true;\n        }\n    }\n    // If the next node is an atom, delete it\n    if (after.isAtom && $cut.depth == $cursor.depth - 1) {\n        if (dispatch)\n            dispatch(state.tr.delete($cut.pos, $cut.pos + after.nodeSize).scrollIntoView());\n        return true;\n    }\n    return false;\n};\n/**\nWhen the selection is empty and at the end of a textblock, select\nthe node coming after that textblock, if possible. This is intended\nto be bound to keys like delete, after\n[`joinForward`](https://prosemirror.net/docs/ref/#commands.joinForward) and similar deleting\ncommands, to provide a fall-back behavior when the schema doesn't\nallow deletion at the selected point.\n*/\nconst selectNodeForward = (state, dispatch, view) => {\n    let { $head, empty } = state.selection, $cut = $head;\n    if (!empty)\n        return false;\n    if ($head.parent.isTextblock) {\n        if (view ? !view.endOfTextblock(\"forward\", state) : $head.parentOffset < $head.parent.content.size)\n            return false;\n        $cut = findCutAfter($head);\n    }\n    let node = $cut && $cut.nodeAfter;\n    if (!node || !NodeSelection.isSelectable(node))\n        return false;\n    if (dispatch)\n        dispatch(state.tr.setSelection(NodeSelection.create(state.doc, $cut.pos)).scrollIntoView());\n    return true;\n};\nfunction findCutAfter($pos) {\n    if (!$pos.parent.type.spec.isolating)\n        for (let i = $pos.depth - 1; i >= 0; i--) {\n            let parent = $pos.node(i);\n            if ($pos.index(i) + 1 < parent.childCount)\n                return $pos.doc.resolve($pos.after(i + 1));\n            if (parent.type.spec.isolating)\n                break;\n        }\n    return null;\n}\n/**\nJoin the selected block or, if there is a text selection, the\nclosest ancestor block of the selection that can be joined, with\nthe sibling above it.\n*/\nconst joinUp = (state, dispatch) => {\n    let sel = state.selection, nodeSel = sel instanceof NodeSelection, point;\n    if (nodeSel) {\n        if (sel.node.isTextblock || !canJoin(state.doc, sel.from))\n            return false;\n        point = sel.from;\n    }\n    else {\n        point = joinPoint(state.doc, sel.from, -1);\n        if (point == null)\n            return false;\n    }\n    if (dispatch) {\n        let tr = state.tr.join(point);\n        if (nodeSel)\n            tr.setSelection(NodeSelection.create(tr.doc, point - state.doc.resolve(point).nodeBefore.nodeSize));\n        dispatch(tr.scrollIntoView());\n    }\n    return true;\n};\n/**\nJoin the selected block, or the closest ancestor of the selection\nthat can be joined, with the sibling after it.\n*/\nconst joinDown = (state, dispatch) => {\n    let sel = state.selection, point;\n    if (sel instanceof NodeSelection) {\n        if (sel.node.isTextblock || !canJoin(state.doc, sel.to))\n            return false;\n        point = sel.to;\n    }\n    else {\n        point = joinPoint(state.doc, sel.to, 1);\n        if (point == null)\n            return false;\n    }\n    if (dispatch)\n        dispatch(state.tr.join(point).scrollIntoView());\n    return true;\n};\n/**\nLift the selected block, or the closest ancestor block of the\nselection that can be lifted, out of its parent node.\n*/\nconst lift = (state, dispatch) => {\n    let { $from, $to } = state.selection;\n    let range = $from.blockRange($to), target = range && liftTarget(range);\n    if (target == null)\n        return false;\n    if (dispatch)\n        dispatch(state.tr.lift(range, target).scrollIntoView());\n    return true;\n};\n/**\nIf the selection is in a node whose type has a truthy\n[`code`](https://prosemirror.net/docs/ref/#model.NodeSpec.code) property in its spec, replace the\nselection with a newline character.\n*/\nconst newlineInCode = (state, dispatch) => {\n    let { $head, $anchor } = state.selection;\n    if (!$head.parent.type.spec.code || !$head.sameParent($anchor))\n        return false;\n    if (dispatch)\n        dispatch(state.tr.insertText(\"\\n\").scrollIntoView());\n    return true;\n};\nfunction defaultBlockAt(match) {\n    for (let i = 0; i < match.edgeCount; i++) {\n        let { type } = match.edge(i);\n        if (type.isTextblock && !type.hasRequiredAttrs())\n            return type;\n    }\n    return null;\n}\n/**\nWhen the selection is in a node with a truthy\n[`code`](https://prosemirror.net/docs/ref/#model.NodeSpec.code) property in its spec, create a\ndefault block after the code block, and move the cursor there.\n*/\nconst exitCode = (state, dispatch) => {\n    let { $head, $anchor } = state.selection;\n    if (!$head.parent.type.spec.code || !$head.sameParent($anchor))\n        return false;\n    let above = $head.node(-1), after = $head.indexAfter(-1), type = defaultBlockAt(above.contentMatchAt(after));\n    if (!type || !above.canReplaceWith(after, after, type))\n        return false;\n    if (dispatch) {\n        let pos = $head.after(), tr = state.tr.replaceWith(pos, pos, type.createAndFill());\n        tr.setSelection(Selection.near(tr.doc.resolve(pos), 1));\n        dispatch(tr.scrollIntoView());\n    }\n    return true;\n};\n/**\nIf a block node is selected, create an empty paragraph before (if\nit is its parent's first child) or after it.\n*/\nconst createParagraphNear = (state, dispatch) => {\n    let sel = state.selection, { $from, $to } = sel;\n    if (sel instanceof AllSelection || $from.parent.inlineContent || $to.parent.inlineContent)\n        return false;\n    let type = defaultBlockAt($to.parent.contentMatchAt($to.indexAfter()));\n    if (!type || !type.isTextblock)\n        return false;\n    if (dispatch) {\n        let side = (!$from.parentOffset && $to.index() < $to.parent.childCount ? $from : $to).pos;\n        let tr = state.tr.insert(side, type.createAndFill());\n        tr.setSelection(TextSelection.create(tr.doc, side + 1));\n        dispatch(tr.scrollIntoView());\n    }\n    return true;\n};\n/**\nIf the cursor is in an empty textblock that can be lifted, lift the\nblock.\n*/\nconst liftEmptyBlock = (state, dispatch) => {\n    let { $cursor } = state.selection;\n    if (!$cursor || $cursor.parent.content.size)\n        return false;\n    if ($cursor.depth > 1 && $cursor.after() != $cursor.end(-1)) {\n        let before = $cursor.before();\n        if (canSplit(state.doc, before)) {\n            if (dispatch)\n                dispatch(state.tr.split(before).scrollIntoView());\n            return true;\n        }\n    }\n    let range = $cursor.blockRange(), target = range && liftTarget(range);\n    if (target == null)\n        return false;\n    if (dispatch)\n        dispatch(state.tr.lift(range, target).scrollIntoView());\n    return true;\n};\n/**\nCreate a variant of [`splitBlock`](https://prosemirror.net/docs/ref/#commands.splitBlock) that uses\na custom function to determine the type of the newly split off block.\n*/\nfunction splitBlockAs(splitNode) {\n    return (state, dispatch) => {\n        if (state.selection instanceof NodeSelection && state.selection.node.isBlock) {\n            let { $from } = state.selection;\n            if (!$from.parentOffset || !canSplit(state.doc, $from.pos))\n                return false;\n            if (dispatch)\n                dispatch(state.tr.split($from.pos).scrollIntoView());\n            return true;\n        }\n        if (!state.selection.$from.depth)\n            return false;\n        let tr = state.tr;\n        if (!state.selection.empty && (state.selection instanceof TextSelection || state.selection instanceof AllSelection))\n            tr.deleteSelection();\n        let { $from } = tr.selection, mapFrom = tr.steps.length;\n        let types = [];\n        let splitDepth, deflt, atEnd = false, atStart = false;\n        for (let d = $from.depth;; d--) {\n            let node = $from.node(d);\n            if (node.isBlock) {\n                atEnd = $from.end(d) == $from.pos + ($from.depth - d);\n                atStart = $from.start(d) == $from.pos - ($from.depth - d);\n                deflt = defaultBlockAt($from.node(d - 1).contentMatchAt($from.indexAfter(d - 1)));\n                let splitType = splitNode && splitNode($from.parent, atEnd, $from);\n                types.unshift(splitType || (atEnd && deflt ? { type: deflt } : null));\n                splitDepth = d;\n                break;\n            }\n            else {\n                if (d == 1)\n                    return false;\n                types.unshift(null);\n            }\n        }\n        let splitPos = $from.pos;\n        let can = canSplit(tr.doc, splitPos, types.length, types);\n        if (!can) {\n            types[0] = deflt ? { type: deflt } : null;\n            can = canSplit(tr.doc, splitPos, types.length, types);\n        }\n        if (!can)\n            return false;\n        tr.split(splitPos, types.length, types);\n        if (!atEnd && atStart && $from.node(splitDepth).type != deflt) {\n            let mapping = tr.mapping.slice(mapFrom);\n            let first = mapping.map($from.before(splitDepth)), $first = tr.doc.resolve(first);\n            if (deflt && $from.node(splitDepth - 1).canReplaceWith($first.index(), $first.index() + 1, deflt))\n                tr.setNodeMarkup(mapping.map($from.before(splitDepth)), deflt);\n        }\n        if (dispatch)\n            dispatch(tr.scrollIntoView());\n        return true;\n    };\n}\n/**\nSplit the parent block of the selection. If the selection is a text\nselection, also delete its content.\n*/\nconst splitBlock = splitBlockAs();\n/**\nActs like [`splitBlock`](https://prosemirror.net/docs/ref/#commands.splitBlock), but without\nresetting the set of active marks at the cursor.\n*/\nconst splitBlockKeepMarks = (state, dispatch) => {\n    return splitBlock(state, dispatch && (tr => {\n        let marks = state.storedMarks || (state.selection.$to.parentOffset && state.selection.$from.marks());\n        if (marks)\n            tr.ensureMarks(marks);\n        dispatch(tr);\n    }));\n};\n/**\nMove the selection to the node wrapping the current selection, if\nany. (Will not select the document node.)\n*/\nconst selectParentNode = (state, dispatch) => {\n    let { $from, to } = state.selection, pos;\n    let same = $from.sharedDepth(to);\n    if (same == 0)\n        return false;\n    pos = $from.before(same);\n    if (dispatch)\n        dispatch(state.tr.setSelection(NodeSelection.create(state.doc, pos)));\n    return true;\n};\n/**\nSelect the whole document.\n*/\nconst selectAll = (state, dispatch) => {\n    if (dispatch)\n        dispatch(state.tr.setSelection(new AllSelection(state.doc)));\n    return true;\n};\nfunction joinMaybeClear(state, $pos, dispatch) {\n    let before = $pos.nodeBefore, after = $pos.nodeAfter, index = $pos.index();\n    if (!before || !after || !before.type.compatibleContent(after.type))\n        return false;\n    if (!before.content.size && $pos.parent.canReplace(index - 1, index)) {\n        if (dispatch)\n            dispatch(state.tr.delete($pos.pos - before.nodeSize, $pos.pos).scrollIntoView());\n        return true;\n    }\n    if (!$pos.parent.canReplace(index, index + 1) || !(after.isTextblock || canJoin(state.doc, $pos.pos)))\n        return false;\n    if (dispatch)\n        dispatch(state.tr.join($pos.pos).scrollIntoView());\n    return true;\n}\nfunction deleteBarrier(state, $cut, dispatch, dir) {\n    let before = $cut.nodeBefore, after = $cut.nodeAfter, conn, match;\n    let isolated = before.type.spec.isolating || after.type.spec.isolating;\n    if (!isolated && joinMaybeClear(state, $cut, dispatch))\n        return true;\n    let canDelAfter = !isolated && $cut.parent.canReplace($cut.index(), $cut.index() + 1);\n    if (canDelAfter &&\n        (conn = (match = before.contentMatchAt(before.childCount)).findWrapping(after.type)) &&\n        match.matchType(conn[0] || after.type).validEnd) {\n        if (dispatch) {\n            let end = $cut.pos + after.nodeSize, wrap = Fragment.empty;\n            for (let i = conn.length - 1; i >= 0; i--)\n                wrap = Fragment.from(conn[i].create(null, wrap));\n            wrap = Fragment.from(before.copy(wrap));\n            let tr = state.tr.step(new ReplaceAroundStep($cut.pos - 1, end, $cut.pos, end, new Slice(wrap, 1, 0), conn.length, true));\n            let $joinAt = tr.doc.resolve(end + 2 * conn.length);\n            if ($joinAt.nodeAfter && $joinAt.nodeAfter.type == before.type &&\n                canJoin(tr.doc, $joinAt.pos))\n                tr.join($joinAt.pos);\n            dispatch(tr.scrollIntoView());\n        }\n        return true;\n    }\n    let selAfter = after.type.spec.isolating || (dir > 0 && isolated) ? null : Selection.findFrom($cut, 1);\n    let range = selAfter && selAfter.$from.blockRange(selAfter.$to), target = range && liftTarget(range);\n    if (target != null && target >= $cut.depth) {\n        if (dispatch)\n            dispatch(state.tr.lift(range, target).scrollIntoView());\n        return true;\n    }\n    if (canDelAfter && textblockAt(after, \"start\", true) && textblockAt(before, \"end\")) {\n        let at = before, wrap = [];\n        for (;;) {\n            wrap.push(at);\n            if (at.isTextblock)\n                break;\n            at = at.lastChild;\n        }\n        let afterText = after, afterDepth = 1;\n        for (; !afterText.isTextblock; afterText = afterText.firstChild)\n            afterDepth++;\n        if (at.canReplace(at.childCount, at.childCount, afterText.content)) {\n            if (dispatch) {\n                let end = Fragment.empty;\n                for (let i = wrap.length - 1; i >= 0; i--)\n                    end = Fragment.from(wrap[i].copy(end));\n                let tr = state.tr.step(new ReplaceAroundStep($cut.pos - wrap.length, $cut.pos + after.nodeSize, $cut.pos + afterDepth, $cut.pos + after.nodeSize - afterDepth, new Slice(end, wrap.length, 0), 0, true));\n                dispatch(tr.scrollIntoView());\n            }\n            return true;\n        }\n    }\n    return false;\n}\nfunction selectTextblockSide(side) {\n    return function (state, dispatch) {\n        let sel = state.selection, $pos = side < 0 ? sel.$from : sel.$to;\n        let depth = $pos.depth;\n        while ($pos.node(depth).isInline) {\n            if (!depth)\n                return false;\n            depth--;\n        }\n        if (!$pos.node(depth).isTextblock)\n            return false;\n        if (dispatch)\n            dispatch(state.tr.setSelection(TextSelection.create(state.doc, side < 0 ? $pos.start(depth) : $pos.end(depth))));\n        return true;\n    };\n}\n/**\nMoves the cursor to the start of current text block.\n*/\nconst selectTextblockStart = selectTextblockSide(-1);\n/**\nMoves the cursor to the end of current text block.\n*/\nconst selectTextblockEnd = selectTextblockSide(1);\n// Parameterized commands\n/**\nWrap the selection in a node of the given type with the given\nattributes.\n*/\nfunction wrapIn(nodeType, attrs = null) {\n    return function (state, dispatch) {\n        let { $from, $to } = state.selection;\n        let range = $from.blockRange($to), wrapping = range && findWrapping(range, nodeType, attrs);\n        if (!wrapping)\n            return false;\n        if (dispatch)\n            dispatch(state.tr.wrap(range, wrapping).scrollIntoView());\n        return true;\n    };\n}\n/**\nReturns a command that tries to set the selected textblocks to the\ngiven node type with the given attributes.\n*/\nfunction setBlockType(nodeType, attrs = null) {\n    return function (state, dispatch) {\n        let applicable = false;\n        for (let i = 0; i < state.selection.ranges.length && !applicable; i++) {\n            let { $from: { pos: from }, $to: { pos: to } } = state.selection.ranges[i];\n            state.doc.nodesBetween(from, to, (node, pos) => {\n                if (applicable)\n                    return false;\n                if (!node.isTextblock || node.hasMarkup(nodeType, attrs))\n                    return;\n                if (node.type == nodeType) {\n                    applicable = true;\n                }\n                else {\n                    let $pos = state.doc.resolve(pos), index = $pos.index();\n                    applicable = $pos.parent.canReplaceWith(index, index + 1, nodeType);\n                }\n            });\n        }\n        if (!applicable)\n            return false;\n        if (dispatch) {\n            let tr = state.tr;\n            for (let i = 0; i < state.selection.ranges.length; i++) {\n                let { $from: { pos: from }, $to: { pos: to } } = state.selection.ranges[i];\n                tr.setBlockType(from, to, nodeType, attrs);\n            }\n            dispatch(tr.scrollIntoView());\n        }\n        return true;\n    };\n}\nfunction markApplies(doc, ranges, type, enterAtoms) {\n    for (let i = 0; i < ranges.length; i++) {\n        let { $from, $to } = ranges[i];\n        let can = $from.depth == 0 ? doc.inlineContent && doc.type.allowsMarkType(type) : false;\n        doc.nodesBetween($from.pos, $to.pos, (node, pos) => {\n            if (can || !enterAtoms && node.isAtom && node.isInline && pos >= $from.pos && pos + node.nodeSize <= $to.pos)\n                return false;\n            can = node.inlineContent && node.type.allowsMarkType(type);\n        });\n        if (can)\n            return true;\n    }\n    return false;\n}\nfunction removeInlineAtoms(ranges) {\n    let result = [];\n    for (let i = 0; i < ranges.length; i++) {\n        let { $from, $to } = ranges[i];\n        $from.doc.nodesBetween($from.pos, $to.pos, (node, pos) => {\n            if (node.isAtom && node.content.size && node.isInline && pos >= $from.pos && pos + node.nodeSize <= $to.pos) {\n                if (pos + 1 > $from.pos)\n                    result.push(new SelectionRange($from, $from.doc.resolve(pos + 1)));\n                $from = $from.doc.resolve(pos + 1 + node.content.size);\n                return false;\n            }\n        });\n        if ($from.pos < $to.pos)\n            result.push(new SelectionRange($from, $to));\n    }\n    return result;\n}\n/**\nCreate a command function that toggles the given mark with the\ngiven attributes. Will return `false` when the current selection\ndoesn't support that mark. This will remove the mark if any marks\nof that type exist in the selection, or add it otherwise. If the\nselection is empty, this applies to the [stored\nmarks](https://prosemirror.net/docs/ref/#state.EditorState.storedMarks) instead of a range of the\ndocument.\n*/\nfunction toggleMark(markType, attrs = null, options) {\n    let removeWhenPresent = (options && options.removeWhenPresent) !== false;\n    let enterAtoms = (options && options.enterInlineAtoms) !== false;\n    let dropSpace = !(options && options.includeWhitespace);\n    return function (state, dispatch) {\n        let { empty, $cursor, ranges } = state.selection;\n        if ((empty && !$cursor) || !markApplies(state.doc, ranges, markType, enterAtoms))\n            return false;\n        if (dispatch) {\n            if ($cursor) {\n                if (markType.isInSet(state.storedMarks || $cursor.marks()))\n                    dispatch(state.tr.removeStoredMark(markType));\n                else\n                    dispatch(state.tr.addStoredMark(markType.create(attrs)));\n            }\n            else {\n                let add, tr = state.tr;\n                if (!enterAtoms)\n                    ranges = removeInlineAtoms(ranges);\n                if (removeWhenPresent) {\n                    add = !ranges.some(r => state.doc.rangeHasMark(r.$from.pos, r.$to.pos, markType));\n                }\n                else {\n                    add = !ranges.every(r => {\n                        let missing = false;\n                        tr.doc.nodesBetween(r.$from.pos, r.$to.pos, (node, pos, parent) => {\n                            if (missing)\n                                return false;\n                            missing = !markType.isInSet(node.marks) && !!parent && parent.type.allowsMarkType(markType) &&\n                                !(node.isText && /^\\s*$/.test(node.textBetween(Math.max(0, r.$from.pos - pos), Math.min(node.nodeSize, r.$to.pos - pos))));\n                        });\n                        return !missing;\n                    });\n                }\n                for (let i = 0; i < ranges.length; i++) {\n                    let { $from, $to } = ranges[i];\n                    if (!add) {\n                        tr.removeMark($from.pos, $to.pos, markType);\n                    }\n                    else {\n                        let from = $from.pos, to = $to.pos, start = $from.nodeAfter, end = $to.nodeBefore;\n                        let spaceStart = dropSpace && start && start.isText ? /^\\s*/.exec(start.text)[0].length : 0;\n                        let spaceEnd = dropSpace && end && end.isText ? /\\s*$/.exec(end.text)[0].length : 0;\n                        if (from + spaceStart < to) {\n                            from += spaceStart;\n                            to -= spaceEnd;\n                        }\n                        tr.addMark(from, to, markType.create(attrs));\n                    }\n                }\n                dispatch(tr.scrollIntoView());\n            }\n        }\n        return true;\n    };\n}\nfunction wrapDispatchForJoin(dispatch, isJoinable) {\n    return (tr) => {\n        if (!tr.isGeneric)\n            return dispatch(tr);\n        let ranges = [];\n        for (let i = 0; i < tr.mapping.maps.length; i++) {\n            let map = tr.mapping.maps[i];\n            for (let j = 0; j < ranges.length; j++)\n                ranges[j] = map.map(ranges[j]);\n            map.forEach((_s, _e, from, to) => ranges.push(from, to));\n        }\n        // Figure out which joinable points exist inside those ranges,\n        // by checking all node boundaries in their parent nodes.\n        let joinable = [];\n        for (let i = 0; i < ranges.length; i += 2) {\n            let from = ranges[i], to = ranges[i + 1];\n            let $from = tr.doc.resolve(from), depth = $from.sharedDepth(to), parent = $from.node(depth);\n            for (let index = $from.indexAfter(depth), pos = $from.after(depth + 1); pos <= to; ++index) {\n                let after = parent.maybeChild(index);\n                if (!after)\n                    break;\n                if (index && joinable.indexOf(pos) == -1) {\n                    let before = parent.child(index - 1);\n                    if (before.type == after.type && isJoinable(before, after))\n                        joinable.push(pos);\n                }\n                pos += after.nodeSize;\n            }\n        }\n        // Join the joinable points\n        joinable.sort((a, b) => a - b);\n        for (let i = joinable.length - 1; i >= 0; i--) {\n            if (canJoin(tr.doc, joinable[i]))\n                tr.join(joinable[i]);\n        }\n        dispatch(tr);\n    };\n}\n/**\nWrap a command so that, when it produces a transform that causes\ntwo joinable nodes to end up next to each other, those are joined.\nNodes are considered joinable when they are of the same type and\nwhen the `isJoinable` predicate returns true for them or, if an\narray of strings was passed, if their node type name is in that\narray.\n*/\nfunction autoJoin(command, isJoinable) {\n    let canJoin = Array.isArray(isJoinable) ? (node) => isJoinable.indexOf(node.type.name) > -1\n        : isJoinable;\n    return (state, dispatch, view) => command(state, dispatch && wrapDispatchForJoin(dispatch, canJoin), view);\n}\n/**\nCombine a number of command functions into a single function (which\ncalls them one by one until one returns true).\n*/\nfunction chainCommands(...commands) {\n    return function (state, dispatch, view) {\n        for (let i = 0; i < commands.length; i++)\n            if (commands[i](state, dispatch, view))\n                return true;\n        return false;\n    };\n}\nlet backspace = chainCommands(deleteSelection, joinBackward, selectNodeBackward);\nlet del = chainCommands(deleteSelection, joinForward, selectNodeForward);\n/**\nA basic keymap containing bindings not specific to any schema.\nBinds the following keys (when multiple commands are listed, they\nare chained with [`chainCommands`](https://prosemirror.net/docs/ref/#commands.chainCommands)):\n\n* **Enter** to `newlineInCode`, `createParagraphNear`, `liftEmptyBlock`, `splitBlock`\n* **Mod-Enter** to `exitCode`\n* **Backspace** and **Mod-Backspace** to `deleteSelection`, `joinBackward`, `selectNodeBackward`\n* **Delete** and **Mod-Delete** to `deleteSelection`, `joinForward`, `selectNodeForward`\n* **Mod-Delete** to `deleteSelection`, `joinForward`, `selectNodeForward`\n* **Mod-a** to `selectAll`\n*/\nconst pcBaseKeymap = {\n    \"Enter\": chainCommands(newlineInCode, createParagraphNear, liftEmptyBlock, splitBlock),\n    \"Mod-Enter\": exitCode,\n    \"Backspace\": backspace,\n    \"Mod-Backspace\": backspace,\n    \"Shift-Backspace\": backspace,\n    \"Delete\": del,\n    \"Mod-Delete\": del,\n    \"Mod-a\": selectAll\n};\n/**\nA copy of `pcBaseKeymap` that also binds **Ctrl-h** like Backspace,\n**Ctrl-d** like Delete, **Alt-Backspace** like Ctrl-Backspace, and\n**Ctrl-Alt-Backspace**, **Alt-Delete**, and **Alt-d** like\nCtrl-Delete.\n*/\nconst macBaseKeymap = {\n    \"Ctrl-h\": pcBaseKeymap[\"Backspace\"],\n    \"Alt-Backspace\": pcBaseKeymap[\"Mod-Backspace\"],\n    \"Ctrl-d\": pcBaseKeymap[\"Delete\"],\n    \"Ctrl-Alt-Backspace\": pcBaseKeymap[\"Mod-Delete\"],\n    \"Alt-Delete\": pcBaseKeymap[\"Mod-Delete\"],\n    \"Alt-d\": pcBaseKeymap[\"Mod-Delete\"],\n    \"Ctrl-a\": selectTextblockStart,\n    \"Ctrl-e\": selectTextblockEnd\n};\nfor (let key in pcBaseKeymap)\n    macBaseKeymap[key] = pcBaseKeymap[key];\nconst mac = typeof navigator != \"undefined\" ? /Mac|iP(hone|[oa]d)/.test(navigator.platform)\n    // @ts-ignore\n    : typeof os != \"undefined\" && os.platform ? os.platform() == \"darwin\" : false;\n/**\nDepending on the detected platform, this will hold\n[`pcBasekeymap`](https://prosemirror.net/docs/ref/#commands.pcBaseKeymap) or\n[`macBaseKeymap`](https://prosemirror.net/docs/ref/#commands.macBaseKeymap).\n*/\nconst baseKeymap = mac ? macBaseKeymap : pcBaseKeymap;\n\nexport { autoJoin, baseKeymap, chainCommands, createParagraphNear, deleteSelection, exitCode, joinBackward, joinDown, joinForward, joinTextblockBackward, joinTextblockForward, joinUp, lift, liftEmptyBlock, macBaseKeymap, newlineInCode, pcBaseKeymap, selectAll, selectNodeBackward, selectNodeForward, selectParentNode, selectTextblockEnd, selectTextblockStart, setBlockType, splitBlock, splitBlockAs, splitBlockKeepMarks, toggleMark, wrapIn };\n", "import { findWrapping, ReplaceAroundStep, canSplit, liftTarget, canJoin } from 'prosemirror-transform';\nimport { NodeRange, Fragment, Slice, NodeType } from 'prosemirror-model';\nimport { Selection } from 'prosemirror-state';\n\nconst olDOM = [\"ol\", 0], ulDOM = [\"ul\", 0], liDOM = [\"li\", 0];\n/**\nAn ordered list [node spec](https://prosemirror.net/docs/ref/#model.NodeSpec). Has a single\nattribute, `order`, which determines the number at which the list\nstarts counting, and defaults to 1. Represented as an `<ol>`\nelement.\n*/\nconst orderedList = {\n    attrs: { order: { default: 1, validate: \"number\" } },\n    parseDOM: [{ tag: \"ol\", getAttrs(dom) {\n                return { order: dom.hasAttribute(\"start\") ? +dom.getAttribute(\"start\") : 1 };\n            } }],\n    toDOM(node) {\n        return node.attrs.order == 1 ? olDOM : [\"ol\", { start: node.attrs.order }, 0];\n    }\n};\n/**\nA bullet list node spec, represented in the DOM as `<ul>`.\n*/\nconst bulletList = {\n    parseDOM: [{ tag: \"ul\" }],\n    toDOM() { return ulDOM; }\n};\n/**\nA list item (`<li>`) spec.\n*/\nconst listItem = {\n    parseDOM: [{ tag: \"li\" }],\n    toDOM() { return liDOM; },\n    defining: true\n};\nfunction add(obj, props) {\n    let copy = {};\n    for (let prop in obj)\n        copy[prop] = obj[prop];\n    for (let prop in props)\n        copy[prop] = props[prop];\n    return copy;\n}\n/**\nConvenience function for adding list-related node types to a map\nspecifying the nodes for a schema. Adds\n[`orderedList`](https://prosemirror.net/docs/ref/#schema-list.orderedList) as `\"ordered_list\"`,\n[`bulletList`](https://prosemirror.net/docs/ref/#schema-list.bulletList) as `\"bullet_list\"`, and\n[`listItem`](https://prosemirror.net/docs/ref/#schema-list.listItem) as `\"list_item\"`.\n\n`itemContent` determines the content expression for the list items.\nIf you want the commands defined in this module to apply to your\nlist structure, it should have a shape like `\"paragraph block*\"` or\n`\"paragraph (ordered_list | bullet_list)*\"`. `listGroup` can be\ngiven to assign a group name to the list node types, for example\n`\"block\"`.\n*/\nfunction addListNodes(nodes, itemContent, listGroup) {\n    return nodes.append({\n        ordered_list: add(orderedList, { content: \"list_item+\", group: listGroup }),\n        bullet_list: add(bulletList, { content: \"list_item+\", group: listGroup }),\n        list_item: add(listItem, { content: itemContent })\n    });\n}\n/**\nReturns a command function that wraps the selection in a list with\nthe given type an attributes. If `dispatch` is null, only return a\nvalue to indicate whether this is possible, but don't actually\nperform the change.\n*/\nfunction wrapInList(listType, attrs = null) {\n    return function (state, dispatch) {\n        let { $from, $to } = state.selection;\n        let range = $from.blockRange($to);\n        if (!range)\n            return false;\n        let tr = dispatch ? state.tr : null;\n        if (!wrapRangeInList(tr, range, listType, attrs))\n            return false;\n        if (dispatch)\n            dispatch(tr.scrollIntoView());\n        return true;\n    };\n}\n/**\nTry to wrap the given node range in a list of the given type.\nReturn `true` when this is possible, `false` otherwise. When `tr`\nis non-null, the wrapping is added to that transaction. When it is\n`null`, the function only queries whether the wrapping is\npossible.\n*/\nfunction wrapRangeInList(tr, range, listType, attrs = null) {\n    let doJoin = false, outerRange = range, doc = range.$from.doc;\n    // This is at the top of an existing list item\n    if (range.depth >= 2 && range.$from.node(range.depth - 1).type.compatibleContent(listType) && range.startIndex == 0) {\n        // Don't do anything if this is the top of the list\n        if (range.$from.index(range.depth - 1) == 0)\n            return false;\n        let $insert = doc.resolve(range.start - 2);\n        outerRange = new NodeRange($insert, $insert, range.depth);\n        if (range.endIndex < range.parent.childCount)\n            range = new NodeRange(range.$from, doc.resolve(range.$to.end(range.depth)), range.depth);\n        doJoin = true;\n    }\n    let wrap = findWrapping(outerRange, listType, attrs, range);\n    if (!wrap)\n        return false;\n    if (tr)\n        doWrapInList(tr, range, wrap, doJoin, listType);\n    return true;\n}\nfunction doWrapInList(tr, range, wrappers, joinBefore, listType) {\n    let content = Fragment.empty;\n    for (let i = wrappers.length - 1; i >= 0; i--)\n        content = Fragment.from(wrappers[i].type.create(wrappers[i].attrs, content));\n    tr.step(new ReplaceAroundStep(range.start - (joinBefore ? 2 : 0), range.end, range.start, range.end, new Slice(content, 0, 0), wrappers.length, true));\n    let found = 0;\n    for (let i = 0; i < wrappers.length; i++)\n        if (wrappers[i].type == listType)\n            found = i + 1;\n    let splitDepth = wrappers.length - found;\n    let splitPos = range.start + wrappers.length - (joinBefore ? 2 : 0), parent = range.parent;\n    for (let i = range.startIndex, e = range.endIndex, first = true; i < e; i++, first = false) {\n        if (!first && splitDepth && canSplit(tr.doc, splitPos, splitDepth)) {\n            tr.split(splitPos, splitDepth);\n            splitPos += 2 * splitDepth;\n        }\n        splitPos += parent.child(i).nodeSize;\n    }\n    return tr;\n}\nfunction isItem(itemType, type) {\n    return itemType instanceof NodeType ? type == itemType : itemType.indexOf(type) > -1;\n}\n/**\nBuild a command that splits a non-empty textblock at the top level\nof a list item by also splitting that list item. `itemType` may be\nan array, when there are multiple node types that act as list\nitems. The new item gets the same type as the item that was split.\n*/\nfunction splitListItem(itemType, itemAttrs) {\n    return function (state, dispatch) {\n        let { $from, $to, node } = state.selection;\n        if ((node && node.isBlock) || $from.depth < 2 || !$from.sameParent($to))\n            return false;\n        let grandParent = $from.node(-1);\n        if (!isItem(itemType, grandParent.type))\n            return false;\n        if ($from.parent.content.size == 0 && $from.node(-1).childCount == $from.indexAfter(-1)) {\n            // In an empty block. If this is a nested list, the wrapping\n            // list item should be split. Otherwise, bail out and let next\n            // command handle lifting.\n            if ($from.depth == 3 || !isItem(itemType, $from.node(-3).type) ||\n                $from.index(-2) != $from.node(-2).childCount - 1)\n                return false;\n            if (dispatch) {\n                let wrap = Fragment.empty;\n                let depthBefore = $from.index(-1) ? 1 : $from.index(-2) ? 2 : 3;\n                // Build a fragment containing empty versions of the structure\n                // from the outer list item to the parent node of the cursor\n                for (let d = $from.depth - depthBefore; d >= $from.depth - 3; d--)\n                    wrap = Fragment.from($from.node(d).copy(wrap));\n                let depthAfter = $from.indexAfter(-1) < $from.node(-2).childCount ? 1\n                    : $from.indexAfter(-2) < $from.node(-3).childCount ? 2 : 3;\n                // Add a second list item with an empty default start node\n                wrap = wrap.append(Fragment.from($from.node(-3).type.createAndFill()));\n                let start = $from.before($from.depth - (depthBefore - 1));\n                let tr = state.tr.replace(start, $from.after(-depthAfter), new Slice(wrap, 4 - depthBefore, 0));\n                let sel = -1;\n                tr.doc.nodesBetween(start, tr.doc.content.size, (node, pos) => {\n                    if (sel > -1)\n                        return false;\n                    if (node.isTextblock && node.content.size == 0)\n                        sel = pos + 1;\n                });\n                if (sel > -1)\n                    tr.setSelection(Selection.near(tr.doc.resolve(sel)));\n                dispatch(tr.scrollIntoView());\n            }\n            return true;\n        }\n        let nextType = $to.pos == $from.end() ? grandParent.contentMatchAt(0).defaultType : null;\n        let tr = state.tr.delete($from.pos, $to.pos);\n        let types = nextType || itemAttrs ? [\n            itemAttrs ? { type: grandParent.type, attrs: itemAttrs } : null,\n            nextType ? { type: nextType } : null\n        ] : undefined;\n        if (!canSplit(tr.doc, $from.pos, 2, types))\n            return false;\n        if (dispatch)\n            dispatch(tr.split($from.pos, 2, types).scrollIntoView());\n        return true;\n    };\n}\n/**\nActs like [`splitListItem`](https://prosemirror.net/docs/ref/#schema-list.splitListItem), but\nwithout resetting the set of active marks at the cursor.\n*/\nfunction splitListItemKeepMarks(itemType, itemAttrs) {\n    let split = splitListItem(itemType, itemAttrs);\n    return (state, dispatch) => {\n        return split(state, dispatch && (tr => {\n            let marks = state.storedMarks || (state.selection.$to.parentOffset && state.selection.$from.marks());\n            if (marks)\n                tr.ensureMarks(marks);\n            dispatch(tr);\n        }));\n    };\n}\n/**\nCreate a command to lift the list item around the selection up into\na wrapping list. `itemType` may be an array of list item types.\n*/\nfunction liftListItem(itemType) {\n    return function (state, dispatch) {\n        let { $from, $to } = state.selection;\n        let range = $from.blockRange($to, node => node.childCount > 0 && isItem(itemType, node.firstChild.type));\n        if (!range)\n            return false;\n        if (!dispatch)\n            return true;\n        if (isItem(itemType, $from.node(range.depth - 1).type)) // Inside a parent list\n            return liftToOuterList(state, dispatch, range);\n        else // Outer list node\n            return liftOutOfList(state, dispatch, range);\n    };\n}\nfunction liftToOuterList(state, dispatch, range) {\n    let tr = state.tr, end = range.end, endOfList = range.$to.end(range.depth);\n    let itemType = range.parent.child(range.endIndex - 1).type;\n    if (end < endOfList) {\n        // There are siblings after the lifted items, which must become\n        // children of the last item\n        tr.step(new ReplaceAroundStep(end - 1, endOfList, end, endOfList, new Slice(Fragment.from(itemType.create(null, range.parent.copy())), 1, 0), 1, true));\n        range = new NodeRange(tr.doc.resolve(range.$from.pos), tr.doc.resolve(endOfList), range.depth);\n    }\n    const target = liftTarget(range);\n    if (target == null)\n        return false;\n    tr.lift(range, target);\n    let $after = tr.doc.resolve(tr.mapping.map(end, -1) - 1);\n    if (canJoin(tr.doc, $after.pos) && $after.nodeBefore.type == $after.nodeAfter.type)\n        tr.join($after.pos);\n    dispatch(tr.scrollIntoView());\n    return true;\n}\nfunction liftOutOfList(state, dispatch, range) {\n    let tr = state.tr, list = range.parent;\n    // Merge the list items into a single big item\n    for (let pos = range.end, i = range.endIndex - 1, e = range.startIndex; i > e; i--) {\n        pos -= list.child(i).nodeSize;\n        tr.delete(pos - 1, pos + 1);\n    }\n    let $start = tr.doc.resolve(range.start), item = $start.nodeAfter;\n    if (tr.mapping.map(range.end) != range.start + $start.nodeAfter.nodeSize)\n        return false;\n    let atStart = range.startIndex == 0, atEnd = range.endIndex == list.childCount;\n    let parent = $start.node(-1), indexBefore = $start.index(-1);\n    if (!parent.canReplace(indexBefore + (atStart ? 0 : 1), indexBefore + 1, item.content.append(atEnd ? Fragment.empty : Fragment.from(list))))\n        return false;\n    let start = $start.pos, end = start + item.nodeSize;\n    // Strip off the surrounding list. At the sides where we're not at\n    // the end of the list, the existing list is closed. At sides where\n    // this is the end, it is overwritten to its end.\n    tr.step(new ReplaceAroundStep(start - (atStart ? 1 : 0), end + (atEnd ? 1 : 0), start + 1, end - 1, new Slice((atStart ? Fragment.empty : Fragment.from(list.copy(Fragment.empty)))\n        .append(atEnd ? Fragment.empty : Fragment.from(list.copy(Fragment.empty))), atStart ? 0 : 1, atEnd ? 0 : 1), atStart ? 0 : 1));\n    dispatch(tr.scrollIntoView());\n    return true;\n}\n/**\nCreate a command to sink the list item around the selection down\ninto an inner list. `itemType` may be an array of list item types.\n*/\nfunction sinkListItem(itemType) {\n    return function (state, dispatch) {\n        let { $from, $to } = state.selection;\n        let range = $from.blockRange($to, node => node.childCount > 0 && isItem(itemType, node.firstChild.type));\n        if (!range)\n            return false;\n        let startIndex = range.startIndex;\n        if (startIndex == 0)\n            return false;\n        let parent = range.parent, nodeBefore = parent.child(startIndex - 1);\n        if (!isItem(itemType, nodeBefore.type))\n            return false;\n        if (dispatch) {\n            let nestedBefore = nodeBefore.lastChild && nodeBefore.lastChild.type == parent.type;\n            let inner = Fragment.from(nestedBefore ? nodeBefore.lastChild.lastChild.type.create() : null);\n            let slice = new Slice(Fragment.from(nodeBefore.type.create(null, Fragment.from(parent.type.create(null, inner)))), nestedBefore ? 3 : 1, 0);\n            let before = range.start, after = range.end;\n            dispatch(state.tr.step(new ReplaceAroundStep(before - (nestedBefore ? 3 : 1), after, before, after, slice, 1, true))\n                .scrollIntoView());\n        }\n        return true;\n    };\n}\n\nexport { addListNodes, bulletList, liftListItem, listItem, orderedList, sinkListItem, splitListItem, splitListItemKeepMarks, wrapInList, wrapRangeInList };\n", "import { TextSelection, NodeSelection, AllSelection, Selection } from 'prosemirror-state';\nimport { DOMSerializer, Fragment, Mark, Slice, DOMParser } from 'prosemirror-model';\nimport { dropPoint } from 'prosemirror-transform';\n\nconst domIndex = function (node) {\n    for (var index = 0;; index++) {\n        node = node.previousSibling;\n        if (!node)\n            return index;\n    }\n};\nfunction parentNode(node) {\n    let parent = node.assignedSlot || node.parentNode;\n    return parent && parent.nodeType == 11 ? parent.host : parent;\n}\nlet reusedRange = null;\n// Note that this will always return the same range, because DOM range\n// objects are every expensive, and keep slowing down subsequent DOM\n// updates, for some reason.\nfunction textRange(node, from, to) {\n    let range = reusedRange || (reusedRange = document.createRange());\n    range.setEnd(node, to == null ? node.nodeValue.length : to);\n    range.setStart(node, from || 0);\n    return range;\n}\nfunction clearReusedRange() {\n    reusedRange = null;\n}\n// Scans forward and backward through DOM positions equivalent to the\n// given one to see if the two are in the same place (i.e. after a\n// text node vs at the end of that text node)\nfunction isEquivalentPosition(node, off, targetNode, targetOff) {\n    return targetNode && (scanFor(node, off, targetNode, targetOff, -1) ||\n        scanFor(node, off, targetNode, targetOff, 1));\n}\nconst atomElements = /^(img|br|input|textarea|hr)$/i;\nfunction scanFor(node, off, targetNode, targetOff, dir) {\n    var _a;\n    for (;;) {\n        if (node == targetNode && off == targetOff)\n            return true;\n        if (off == (dir < 0 ? 0 : nodeSize(node))) {\n            let parent = node.parentNode;\n            if (!parent || !isElt(parent) || hasNodeDesc(node) || atomElements.test(node.nodeName) ||\n                node.contentEditable == \"false\")\n                return false;\n            off = domIndex(node) + (dir < 0 ? 0 : 1);\n            node = parent;\n        }\n        else if (isElt(node)) {\n            let child = node.childNodes[off + (dir < 0 ? -1 : 0)];\n            if (isElt(child) && child.contentEditable == \"false\") {\n                if ((_a = child.pmViewDesc) === null || _a === void 0 ? void 0 : _a.ignoreForSelection)\n                    off += dir;\n                else\n                    return false;\n            }\n            else if (hasNodeDesc(child) || atomElements.test(child.nodeName)) {\n                return false;\n            }\n            else {\n                node = child;\n                off = dir < 0 ? nodeSize(node) : 0;\n            }\n        }\n        else {\n            return false;\n        }\n    }\n}\nfunction nodeSize(node) {\n    return node.nodeType == 3 ? node.nodeValue.length : node.childNodes.length;\n}\nfunction isElt(node) { return node.nodeType == 1; }\nfunction isText(node) { return node.nodeType == 3; }\nfunction contains(parent, child) {\n    return child ? parent.contains(isElt(child) ? child : child.parentNode) : false;\n}\nfunction textNodeBefore(node, offset) {\n    for (;;) {\n        if (isText(node) && offset)\n            return node;\n        if (isElt(node) && offset > 0) {\n            if (node.contentEditable == \"false\")\n                return null;\n            node = node.childNodes[offset - 1];\n            offset = nodeSize(node);\n        }\n        else if (node.parentNode && !hasNodeDesc(node, true)) {\n            offset = domIndex(node);\n            node = node.parentNode;\n        }\n        else {\n            return null;\n        }\n    }\n}\nfunction textNodeAfter(node, offset) {\n    for (;;) {\n        if (isText(node) && offset < node.nodeValue.length)\n            return node;\n        if (isElt(node) && offset < node.childNodes.length) {\n            if (node.contentEditable == \"false\")\n                return null;\n            node = node.childNodes[offset];\n            offset = 0;\n        }\n        else if (node.parentNode && !hasNodeDesc(node, true)) {\n            offset = domIndex(node) + 1;\n            node = node.parentNode;\n        }\n        else {\n            return null;\n        }\n    }\n}\nfunction isOnEdge(node, offset, parent) {\n    for (let atStart = offset == 0, atEnd = offset == nodeSize(node); atStart || atEnd;) {\n        if (node == parent)\n            return true;\n        let index = domIndex(node);\n        node = node.parentNode;\n        if (!node)\n            return false;\n        atStart = atStart && index == 0;\n        atEnd = atEnd && index == nodeSize(node);\n    }\n}\nfunction hasNodeDesc(dom, isBlock = false) {\n    let desc;\n    for (let cur = dom; cur; cur = cur.parentNode)\n        if (desc = cur.pmViewDesc)\n            break;\n    return desc && desc.node && (!isBlock || desc.node.isBlock) && (desc.dom == dom || desc.contentDOM == dom);\n}\n// Work around Chrome issue https://bugs.chromium.org/p/chromium/issues/detail?id=447523\n// (isCollapsed inappropriately returns true in shadow dom)\nfunction selectionCollapsed(domSel) {\n    return domSel.focusNode && isEquivalentPosition(domSel.focusNode, domSel.focusOffset, domSel.anchorNode, domSel.anchorOffset);\n}\nfunction writeSelection(sel, range) {\n    sel.collapse(range.anchorNode, range.anchorOffset);\n    if (range.focusNode != range.anchorNode || range.focusOffset != range.anchorOffset)\n        sel.extend(range.focusNode, range.focusOffset);\n}\nfunction keyEvent(keyCode, key) {\n    let event = document.createEvent(\"Event\");\n    event.initEvent(\"keydown\", true, true);\n    event.keyCode = keyCode;\n    event.key = event.code = key;\n    return event;\n}\nfunction deepActiveElement(doc) {\n    let elt = doc.activeElement;\n    while (elt && elt.shadowRoot)\n        elt = elt.shadowRoot.activeElement;\n    return elt;\n}\nfunction caretFromPoint(doc, x, y) {\n    if (doc.caretPositionFromPoint) {\n        try { // Firefox throws for this call in hard-to-predict circumstances (#994)\n            let pos = doc.caretPositionFromPoint(x, y);\n            // Clip the offset, because Chrome will return a text offset\n            // into <input> nodes, which can't be treated as a regular DOM\n            // offset\n            if (pos)\n                return { node: pos.offsetNode, offset: Math.min(nodeSize(pos.offsetNode), pos.offset) };\n        }\n        catch (_) { }\n    }\n    if (doc.caretRangeFromPoint) {\n        let range = doc.caretRangeFromPoint(x, y);\n        if (range)\n            return { node: range.startContainer, offset: Math.min(nodeSize(range.startContainer), range.startOffset) };\n    }\n}\n\nconst nav = typeof navigator != \"undefined\" ? navigator : null;\nconst doc = typeof document != \"undefined\" ? document : null;\nconst agent = (nav && nav.userAgent) || \"\";\nconst gecko = /gecko\\/(\\d+)/i.test(agent) && !/edge?\\//i.test(agent);\ngecko && +(/Firefox\\/(\\d+)/.exec(agent) || [0, 0])[1];\nconst _chrome = /Chrome\\/(\\d+)/.exec(agent);\nconst chrome = !!_chrome;\nconst chrome_version = _chrome ? +_chrome[1] : 0;\nconst safari = !!nav && /Apple Computer/.test(nav.vendor);\n// Is true for both iOS and iPadOS for convenience\nconst ios = safari && (/Mobile\\/\\w+/.test(agent) || !!nav && nav.maxTouchPoints > 2);\nconst mac = ios || (nav ? /Mac/.test(nav.platform) : false);\nconst windows = nav ? /Win/.test(nav.platform) : false;\nconst android = /Android \\d/.test(agent);\nconst webkit = !!doc && \"webkitFontSmoothing\" in doc.documentElement.style;\nconst webkit_version = webkit ? +(/\\bAppleWebKit\\/(\\d+)/.exec(navigator.userAgent) || [0, 0])[1] : 0;\n\nfunction windowRect(doc) {\n    let vp = doc.defaultView && doc.defaultView.visualViewport;\n    if (vp)\n        return {\n            left: 0, right: vp.width,\n            top: 0, bottom: vp.height\n        };\n    return { left: 0, right: doc.documentElement.clientWidth,\n        top: 0, bottom: doc.documentElement.clientHeight };\n}\nfunction getSide(value, side) {\n    return typeof value == \"number\" ? value : value[side];\n}\nfunction clientRect(node) {\n    let rect = node.getBoundingClientRect();\n    // Adjust for elements with style \"transform: scale()\"\n    let scaleX = (rect.width / node.offsetWidth) || 1;\n    let scaleY = (rect.height / node.offsetHeight) || 1;\n    // Make sure scrollbar width isn't included in the rectangle\n    return { left: rect.left, right: rect.left + node.clientWidth * scaleX,\n        top: rect.top, bottom: rect.top + node.clientHeight * scaleY };\n}\nfunction rectNextTo(node, offset, dir) {\n    for (;;) {\n        if (dir < 0 ? offset : offset < nodeSize(node)) {\n            if (isText(node))\n                return singleRect(textRange(node, offset + (dir < 0 ? -1 : 0), offset + (dir > 0 ? 1 : 0)), -dir);\n            let next = node.childNodes[dir < 0 ? offset - 1 : offset];\n            if (isText(next)) {\n                node = next;\n                offset = dir < 0 ? next.nodeValue.length : 0;\n            }\n            else if (isElt(next))\n                return singleRect(next, -dir);\n            else\n                return null;\n        }\n        else if (hasNodeDesc(node, true) || !node.parentNode) {\n            return null;\n        }\n        else {\n            offset = domIndex(node) + (dir < 0 ? 0 : 1);\n            node = node.parentNode;\n        }\n    }\n}\nfunction scrollRectIntoView(view, rect, startDOM) {\n    // Skip empty rects with all sides at 0, for example, when the element has no CSS box (display: none)\n    if (!nonZero(rect) && rect.left == 0)\n        return;\n    let scrollThreshold = view.someProp(\"scrollThreshold\") || 0, scrollMargin = view.someProp(\"scrollMargin\") || 5;\n    let doc = view.dom.ownerDocument;\n    for (let parent = startDOM || view.dom;;) {\n        if (!parent)\n            break;\n        if (!isElt(parent)) {\n            parent = parentNode(parent);\n            continue;\n        }\n        let atTop = parent == doc.body;\n        let bounding = atTop ? windowRect(doc) : clientRect(parent);\n        let moveX = 0, moveY = 0;\n        if (rect.top < bounding.top + getSide(scrollThreshold, \"top\"))\n            moveY = -(bounding.top - rect.top + getSide(scrollMargin, \"top\"));\n        else if (rect.bottom > bounding.bottom - getSide(scrollThreshold, \"bottom\"))\n            moveY = rect.bottom - rect.top > bounding.bottom - bounding.top\n                ? rect.top + getSide(scrollMargin, \"top\") - bounding.top\n                : rect.bottom - bounding.bottom + getSide(scrollMargin, \"bottom\");\n        if (rect.left < bounding.left + getSide(scrollThreshold, \"left\"))\n            moveX = -(bounding.left - rect.left + getSide(scrollMargin, \"left\"));\n        else if (rect.right > bounding.right - getSide(scrollThreshold, \"right\"))\n            moveX = rect.right - bounding.right + getSide(scrollMargin, \"right\");\n        if (moveX || moveY) {\n            if (atTop) {\n                doc.defaultView.scrollBy(moveX, moveY);\n            }\n            else {\n                let startX = parent.scrollLeft, startY = parent.scrollTop;\n                if (moveY)\n                    parent.scrollTop += moveY;\n                if (moveX)\n                    parent.scrollLeft += moveX;\n                let dX = parent.scrollLeft - startX, dY = parent.scrollTop - startY;\n                rect = { left: rect.left - dX, top: rect.top - dY, right: rect.right - dX, bottom: rect.bottom - dY };\n            }\n        }\n        let pos = atTop ? \"fixed\" : getComputedStyle(parent).position;\n        if (/^(fixed|sticky)$/.test(pos))\n            break;\n        parent = pos == \"absolute\" ? parent.offsetParent : parentNode(parent);\n    }\n}\n// Store the scroll position of the editor's parent nodes, along with\n// the top position of an element near the top of the editor, which\n// will be used to make sure the visible viewport remains stable even\n// when the size of the content above changes.\nfunction storeScrollPos(view) {\n    let rect = view.dom.getBoundingClientRect(), startY = Math.max(0, rect.top);\n    let refDOM, refTop;\n    for (let x = (rect.left + rect.right) / 2, y = startY + 1; y < Math.min(innerHeight, rect.bottom); y += 5) {\n        let dom = view.root.elementFromPoint(x, y);\n        if (!dom || dom == view.dom || !view.dom.contains(dom))\n            continue;\n        let localRect = dom.getBoundingClientRect();\n        if (localRect.top >= startY - 20) {\n            refDOM = dom;\n            refTop = localRect.top;\n            break;\n        }\n    }\n    return { refDOM: refDOM, refTop: refTop, stack: scrollStack(view.dom) };\n}\nfunction scrollStack(dom) {\n    let stack = [], doc = dom.ownerDocument;\n    for (let cur = dom; cur; cur = parentNode(cur)) {\n        stack.push({ dom: cur, top: cur.scrollTop, left: cur.scrollLeft });\n        if (dom == doc)\n            break;\n    }\n    return stack;\n}\n// Reset the scroll position of the editor's parent nodes to that what\n// it was before, when storeScrollPos was called.\nfunction resetScrollPos({ refDOM, refTop, stack }) {\n    let newRefTop = refDOM ? refDOM.getBoundingClientRect().top : 0;\n    restoreScrollStack(stack, newRefTop == 0 ? 0 : newRefTop - refTop);\n}\nfunction restoreScrollStack(stack, dTop) {\n    for (let i = 0; i < stack.length; i++) {\n        let { dom, top, left } = stack[i];\n        if (dom.scrollTop != top + dTop)\n            dom.scrollTop = top + dTop;\n        if (dom.scrollLeft != left)\n            dom.scrollLeft = left;\n    }\n}\nlet preventScrollSupported = null;\n// Feature-detects support for .focus({preventScroll: true}), and uses\n// a fallback kludge when not supported.\nfunction focusPreventScroll(dom) {\n    if (dom.setActive)\n        return dom.setActive(); // in IE\n    if (preventScrollSupported)\n        return dom.focus(preventScrollSupported);\n    let stored = scrollStack(dom);\n    dom.focus(preventScrollSupported == null ? {\n        get preventScroll() {\n            preventScrollSupported = { preventScroll: true };\n            return true;\n        }\n    } : undefined);\n    if (!preventScrollSupported) {\n        preventScrollSupported = false;\n        restoreScrollStack(stored, 0);\n    }\n}\nfunction findOffsetInNode(node, coords) {\n    let closest;\n    let dxClosest = 2e8, coordsClosest, offset = 0;\n    let rowBot = coords.top, rowTop = coords.top;\n    let firstBelow, coordsBelow;\n    for (let child = node.firstChild, childIndex = 0; child; child = child.nextSibling, childIndex++) {\n        let rects;\n        if (isElt(child))\n            rects = child.getClientRects();\n        else if (isText(child))\n            rects = textRange(child).getClientRects();\n        else\n            continue;\n        for (let i = 0; i < rects.length; i++) {\n            let rect = rects[i];\n            if (rect.top <= rowBot && rect.bottom >= rowTop) {\n                rowBot = Math.max(rect.bottom, rowBot);\n                rowTop = Math.min(rect.top, rowTop);\n                let dx = rect.left > coords.left ? rect.left - coords.left\n                    : rect.right < coords.left ? coords.left - rect.right : 0;\n                if (dx < dxClosest) {\n                    closest = child;\n                    dxClosest = dx;\n                    coordsClosest = dx && isText(closest) ? {\n                        left: rect.right < coords.left ? rect.right : rect.left,\n                        top: coords.top\n                    } : coords;\n                    if (isElt(child) && dx)\n                        offset = childIndex + (coords.left >= (rect.left + rect.right) / 2 ? 1 : 0);\n                    continue;\n                }\n            }\n            else if (rect.top > coords.top && !firstBelow && rect.left <= coords.left && rect.right >= coords.left) {\n                firstBelow = child;\n                coordsBelow = { left: Math.max(rect.left, Math.min(rect.right, coords.left)), top: rect.top };\n            }\n            if (!closest && (coords.left >= rect.right && coords.top >= rect.top ||\n                coords.left >= rect.left && coords.top >= rect.bottom))\n                offset = childIndex + 1;\n        }\n    }\n    if (!closest && firstBelow) {\n        closest = firstBelow;\n        coordsClosest = coordsBelow;\n        dxClosest = 0;\n    }\n    if (closest && isText(closest))\n        return findOffsetInText(closest, coordsClosest);\n    if (!closest || dxClosest)\n        return { node, offset };\n    return findOffsetInNode(closest, coordsClosest);\n}\nfunction findOffsetInText(node, coords) {\n    let len = node.nodeValue.length;\n    let range = document.createRange(), result;\n    for (let i = 0; i < len; i++) {\n        range.setEnd(node, i + 1);\n        range.setStart(node, i);\n        let rect = singleRect(range, 1);\n        if (rect.top == rect.bottom)\n            continue;\n        if (inRect(coords, rect)) {\n            result = { node, offset: i + (coords.left >= (rect.left + rect.right) / 2 ? 1 : 0) };\n            break;\n        }\n    }\n    range.detach();\n    return result || { node, offset: 0 };\n}\nfunction inRect(coords, rect) {\n    return coords.left >= rect.left - 1 && coords.left <= rect.right + 1 &&\n        coords.top >= rect.top - 1 && coords.top <= rect.bottom + 1;\n}\nfunction targetKludge(dom, coords) {\n    let parent = dom.parentNode;\n    if (parent && /^li$/i.test(parent.nodeName) && coords.left < dom.getBoundingClientRect().left)\n        return parent;\n    return dom;\n}\nfunction posFromElement(view, elt, coords) {\n    let { node, offset } = findOffsetInNode(elt, coords), bias = -1;\n    if (isElt(node) && !node.firstChild) {\n        let rect = node.getBoundingClientRect();\n        bias = rect.left != rect.right && coords.left > (rect.left + rect.right) / 2 ? 1 : -1;\n    }\n    return { pos: view.docView.posFromDOM(node, offset, bias), affinity: affinityFromCoords(node, offset, coords) };\n}\nfunction horizDist(x, rect) {\n    return x < rect.left ? rect.left - x : x > rect.right ? x - rect.right : 0;\n}\nfunction affinityFromCoords(node, offset, coords) {\n    let before = rectNextTo(node, offset, -1), after = rectNextTo(node, offset, 1);\n    if (!before)\n        return 1;\n    if (!after)\n        return -1;\n    if (before.bottom <= after.top) // Different lines\n        return coords.top > (before.bottom + after.top) / 2 ? 1 : -1;\n    // Same line\n    return horizDist(coords.left, before) < horizDist(coords.left, after) ? -1 : 1;\n}\nfunction posFromCaret(view, node, offset, coords) {\n    // Browser (in caretPosition/RangeFromPoint) will agressively\n    // normalize towards nearby inline nodes. Since we are interested in\n    // positions between block nodes too, we first walk up the hierarchy\n    // of nodes to see if there are parent block nodes that the\n    // coordinates fall vertically outside of.\n    let outsideBlock = -1;\n    for (let cur = node; cur != view.dom;) {\n        let desc = view.docView.nearestDesc(cur, true), rect;\n        if (!desc)\n            return null;\n        // Ignore elements with zero-size bounding rectangles\n        if (isElt(desc.dom) && ((rect = desc.dom.getBoundingClientRect()).width || rect.height)) {\n            if (!desc.contentDOM && !desc.node.isText &&\n                coords.left >= rect.left && coords.left <= rect.right &&\n                coords.top >= rect.top && coords.top <= rect.bottom) {\n                // If we are inside a leaf, return the side of the leaf closer to the coords\n                let before = desc.node.isBlock ? coords.top < (rect.top + rect.bottom) / 2\n                    : coords.left < (rect.left + rect.right) / 2;\n                return { pos: before ? desc.posBefore : desc.posAfter, affinity: before ? 1 : -1 };\n            }\n            if (desc.node.isBlock && desc.parent && !/^T(R|BODY|HEAD|FOOT)$/.test(desc.dom.nodeName) &&\n                (coords.top < rect.top || coords.top > rect.bottom)) {\n                outsideBlock = coords.top < rect.top ? desc.posBefore : desc.posAfter;\n            }\n        }\n        cur = desc.dom.parentNode;\n    }\n    if (outsideBlock > -1)\n        return { pos: outsideBlock, affinity: 0 };\n    return { pos: view.docView.posFromDOM(node, offset, -1),\n        affinity: affinityFromCoords(node, offset, coords) };\n}\nfunction elementFromPoint(element, coords, box) {\n    let len = element.childNodes.length;\n    if (len && box.top < box.bottom) {\n        for (let startI = Math.max(0, Math.min(len - 1, Math.floor(len * (coords.top - box.top) / (box.bottom - box.top)) - 2)), i = startI;;) {\n            let child = element.childNodes[i];\n            if (isElt(child)) {\n                let rects = child.getClientRects();\n                for (let j = 0; j < rects.length; j++) {\n                    let rect = rects[j];\n                    if (inRect(coords, rect))\n                        return elementFromPoint(child, coords, rect);\n                }\n            }\n            if ((i = (i + 1) % len) == startI)\n                break;\n        }\n    }\n    return element;\n}\n// Given an x,y position on the editor, get the position in the document.\nfunction posAtCoords(view, coords) {\n    let doc = view.dom.ownerDocument, node, offset = 0;\n    let caret = caretFromPoint(doc, coords.left, coords.top);\n    if (caret)\n        ({ node, offset } = caret);\n    let elt = (view.root.elementFromPoint ? view.root : doc)\n        .elementFromPoint(coords.left, coords.top);\n    let pos, affinity = 0;\n    if (!elt || !view.dom.contains(elt)) {\n        let box = view.dom.getBoundingClientRect();\n        if (!inRect(coords, box))\n            return null;\n        elt = elementFromPoint(view.dom, coords, box);\n        if (!elt)\n            return null;\n    }\n    // Safari's caretRangeFromPoint returns nonsense when on a draggable element\n    if (safari) {\n        for (let p = elt; node && p; p = parentNode(p))\n            if (p.draggable)\n                node = undefined;\n    }\n    elt = targetKludge(elt, coords);\n    if (node) {\n        if (gecko && isElt(node)) {\n            // Firefox will sometimes return offsets into <input> nodes, which\n            // have no actual children, from caretPositionFromPoint (#953)\n            offset = Math.min(offset, node.childNodes.length);\n            // It'll also move the returned position before image nodes,\n            // even if those are behind it.\n            if (offset < node.childNodes.length) {\n                let next = node.childNodes[offset], box;\n                if (next.nodeName == \"IMG\" && (box = next.getBoundingClientRect()).right <= coords.left &&\n                    box.bottom > coords.top)\n                    offset++;\n            }\n        }\n        let prev;\n        // When clicking above the right side of an uneditable node, Chrome will report a cursor position after that node.\n        if (webkit && offset && isElt(node) && isElt(prev = node.childNodes[offset - 1]) &&\n            prev.contentEditable == \"false\" && prev.getBoundingClientRect().top >= coords.top)\n            offset--;\n        // Suspiciously specific kludge to work around caret*FromPoint\n        // never returning a position at the end of the document\n        if (node == view.dom && offset == node.childNodes.length - 1 && isElt(node.lastChild) &&\n            coords.top > node.lastChild.getBoundingClientRect().bottom) {\n            pos = view.state.doc.content.size;\n            // Ignore positions directly after a BR, since caret*FromPoint\n            // 'round up' positions that would be more accurately placed\n            // before the BR node.\n        }\n        else if (offset == 0 || !isElt(node) || node.childNodes[offset - 1].nodeName != \"BR\") {\n            let found = posFromCaret(view, node, offset, coords);\n            if (found)\n                ({ pos, affinity } = found);\n        }\n    }\n    if (pos == null)\n        ({ pos, affinity } = posFromElement(view, elt, coords));\n    let desc = view.docView.nearestDesc(elt, true);\n    return { pos, inside: desc ? desc.posAtStart - desc.border : -1, affinity };\n}\nfunction nonZero(rect) {\n    return rect.top < rect.bottom || rect.left < rect.right;\n}\nfunction singleRect(target, bias) {\n    let rects = target.getClientRects();\n    if (rects.length) {\n        let first = rects[bias < 0 ? 0 : rects.length - 1];\n        if (nonZero(first))\n            return first;\n    }\n    return Array.prototype.find.call(rects, nonZero) || target.getBoundingClientRect();\n}\nconst BIDI = /[\\u0590-\\u05f4\\u0600-\\u06ff\\u0700-\\u08ac]/;\n// Given a position in the document model, get a bounding box of the\n// character at that position, relative to the window.\nfunction coordsAtPos(view, pos, side) {\n    let { node, offset, atom } = view.docView.domFromPos(pos, side < 0 ? -1 : 1);\n    let supportEmptyRange = webkit || gecko;\n    if (isText(node)) {\n        // These browsers support querying empty text ranges. Prefer that in\n        // bidi context or when at the end of a node.\n        if (supportEmptyRange && (BIDI.test(node.nodeValue) || (side < 0 ? !offset : offset == node.nodeValue.length))) {\n            let rect = singleRect(textRange(node, offset, offset), side);\n            // Firefox returns bad results (the position before the space)\n            // when querying a position directly after line-broken\n            // whitespace. Detect this situation and and kludge around it\n            if (gecko && offset && /\\s/.test(node.nodeValue[offset - 1]) && offset < node.nodeValue.length) {\n                let rectBefore = singleRect(textRange(node, offset - 1, offset - 1), -1);\n                if (rectBefore.top == rect.top) {\n                    let rectAfter = singleRect(textRange(node, offset, offset + 1), -1);\n                    if (rectAfter.top != rect.top)\n                        return flattenV(rectAfter, rectAfter.left < rectBefore.left);\n                }\n            }\n            return rect;\n        }\n        else {\n            let from = offset, to = offset, takeSide = side < 0 ? 1 : -1;\n            if (side < 0 && !offset) {\n                to++;\n                takeSide = -1;\n            }\n            else if (side >= 0 && offset == node.nodeValue.length) {\n                from--;\n                takeSide = 1;\n            }\n            else if (side < 0) {\n                from--;\n            }\n            else {\n                to++;\n            }\n            return flattenV(singleRect(textRange(node, from, to), takeSide), takeSide < 0);\n        }\n    }\n    let $dom = view.state.doc.resolve(pos - (atom || 0));\n    // Return a horizontal line in block context\n    if (!$dom.parent.inlineContent) {\n        if (atom == null && offset && (side < 0 || offset == nodeSize(node))) {\n            let before = node.childNodes[offset - 1];\n            if (isElt(before))\n                return flattenH(before.getBoundingClientRect(), false);\n        }\n        if (atom == null && offset < nodeSize(node)) {\n            let after = node.childNodes[offset];\n            if (isElt(after))\n                return flattenH(after.getBoundingClientRect(), true);\n        }\n        return flattenH(node.getBoundingClientRect(), side >= 0);\n    }\n    // Inline, not in text node (this is not Bidi-safe)\n    if (atom == null && offset && (side < 0 || offset == nodeSize(node))) {\n        let before = node.childNodes[offset - 1];\n        let target = isText(before) ? textRange(before, nodeSize(before) - (supportEmptyRange ? 0 : 1))\n            // BR nodes tend to only return the rectangle before them.\n            // Only use them if they are the last element in their parent\n            : isElt(before) && (before.nodeName != \"BR\" || !before.nextSibling) ? before : null;\n        if (target)\n            return flattenV(singleRect(target, 1), false);\n    }\n    if (atom == null && offset < nodeSize(node)) {\n        let after = node.childNodes[offset];\n        while (after.pmViewDesc && after.pmViewDesc.ignoreForCoords)\n            after = after.nextSibling;\n        let target = !after ? null : isText(after) ? textRange(after, 0, (supportEmptyRange ? 0 : 1))\n            : isElt(after) ? after : null;\n        if (target)\n            return flattenV(singleRect(target, -1), true);\n    }\n    // All else failed, just try to get a rectangle for the target node\n    return flattenV(singleRect(isText(node) ? textRange(node) : node, -side), side >= 0);\n}\nfunction flattenV(rect, left) {\n    if (rect.width == 0)\n        return rect;\n    let x = left ? rect.left : rect.right;\n    return { top: rect.top, bottom: rect.bottom, left: x, right: x };\n}\nfunction flattenH(rect, top) {\n    if (rect.height == 0)\n        return rect;\n    let y = top ? rect.top : rect.bottom;\n    return { top: y, bottom: y, left: rect.left, right: rect.right };\n}\nfunction withFlushedState(view, state, f) {\n    let viewState = view.state, active = view.root.activeElement;\n    if (viewState != state)\n        view.updateState(state);\n    if (active != view.dom)\n        view.focus();\n    try {\n        return f();\n    }\n    finally {\n        if (viewState != state)\n            view.updateState(viewState);\n        if (active != view.dom && active)\n            active.focus();\n    }\n}\n// Whether vertical position motion in a given direction\n// from a position would leave a text block.\nfunction endOfTextblockVertical(view, state, dir) {\n    let sel = state.selection;\n    let $pos = dir == \"up\" ? sel.$from : sel.$to;\n    return withFlushedState(view, state, () => {\n        let { node: dom } = view.docView.domFromPos($pos.pos, dir == \"up\" ? -1 : 1);\n        for (;;) {\n            let nearest = view.docView.nearestDesc(dom, true);\n            if (!nearest)\n                break;\n            if (nearest.node.isBlock) {\n                dom = nearest.contentDOM || nearest.dom;\n                break;\n            }\n            dom = nearest.dom.parentNode;\n        }\n        let coords = coordsAtPos(view, $pos.pos, 1);\n        for (let child = dom.firstChild; child; child = child.nextSibling) {\n            let boxes;\n            if (isElt(child))\n                boxes = child.getClientRects();\n            else if (isText(child))\n                boxes = textRange(child, 0, child.nodeValue.length).getClientRects();\n            else\n                continue;\n            for (let i = 0; i < boxes.length; i++) {\n                let box = boxes[i];\n                if (box.bottom > box.top + 1 &&\n                    (dir == \"up\" ? coords.top - box.top > (box.bottom - coords.top) * 2\n                        : box.bottom - coords.bottom > (coords.bottom - box.top) * 2))\n                    return false;\n            }\n        }\n        return true;\n    });\n}\nconst maybeRTL = /[\\u0590-\\u08ac]/;\nfunction endOfTextblockHorizontal(view, state, dir) {\n    let { $head } = state.selection;\n    if (!$head.parent.isTextblock)\n        return false;\n    let offset = $head.parentOffset, atStart = !offset, atEnd = offset == $head.parent.content.size;\n    let sel = view.domSelection();\n    if (!sel)\n        return $head.pos == $head.start() || $head.pos == $head.end();\n    // If the textblock is all LTR, or the browser doesn't support\n    // Selection.modify (Edge), fall back to a primitive approach\n    if (!maybeRTL.test($head.parent.textContent) || !sel.modify)\n        return dir == \"left\" || dir == \"backward\" ? atStart : atEnd;\n    return withFlushedState(view, state, () => {\n        // This is a huge hack, but appears to be the best we can\n        // currently do: use `Selection.modify` to move the selection by\n        // one character, and see if that moves the cursor out of the\n        // textblock (or doesn't move it at all, when at the start/end of\n        // the document).\n        let range = view.domSel.readRange();\n        let oldBidiLevel = sel.caretBidiLevel // Only for Firefox\n        ;\n        sel.modify(\"move\", dir, \"character\");\n        let parentDOM = $head.depth ? view.docView.domAfterPos($head.before()) : view.dom;\n        let { focusNode: newNode, focusOffset: newOff } = view.domSel.readRange();\n        let result = newNode && !contains(parentDOM, newNode) || (range.focusNode == newNode && range.focusOffset == newOff);\n        // Restore the previous selection\n        writeSelection(sel, range);\n        if (oldBidiLevel != null)\n            sel.caretBidiLevel = oldBidiLevel;\n        return result;\n    });\n}\nlet cachedState = null;\nlet cachedDir = null;\nlet cachedResult = false;\nfunction endOfTextblock(view, state, dir) {\n    if (cachedState == state && cachedDir == dir)\n        return cachedResult;\n    cachedState = state;\n    cachedDir = dir;\n    return cachedResult = dir == \"up\" || dir == \"down\"\n        ? endOfTextblockVertical(view, state, dir)\n        : endOfTextblockHorizontal(view, state, dir);\n}\n\n// Superclass for the various kinds of descriptions. Defines their\n// basic structure and shared methods.\nclass ViewDesc {\n    constructor(parent, children, dom, \n    // This is the node that holds the child views. It may be null for\n    // descs that don't have children.\n    contentDOM) {\n        this.parent = parent;\n        this.children = children;\n        this.dom = dom;\n        this.contentDOM = contentDOM;\n        this.damage = 0 /* Damage.None */;\n        // An expando property on the DOM node provides a link back to its\n        // description.\n        dom.pmViewDesc = this;\n    }\n    // Used to check whether a given description corresponds to a\n    // widget/mark/node.\n    matchesWidget(widget) { return false; }\n    matchesMark(mark) { return false; }\n    matchesNode(node, outerDeco, innerDeco) { return false; }\n    matchesHack(nodeName) { return false; }\n    // When parsing in-editor content (in domchange.js), we allow\n    // descriptions to determine the parse rules that should be used to\n    // parse them.\n    parseRule(addedNodes) { return null; }\n    // Used by the editor's event handler to ignore events that come\n    // from certain descs.\n    stopEvent(event) { return false; }\n    // The size of the content represented by this desc.\n    get size() {\n        let size = 0;\n        for (let i = 0; i < this.children.length; i++)\n            size += this.children[i].size;\n        return size;\n    }\n    // For block nodes, this represents the space taken up by their\n    // start/end tokens.\n    get border() { return 0; }\n    destroy() {\n        this.parent = undefined;\n        if (this.dom.pmViewDesc == this)\n            this.dom.pmViewDesc = undefined;\n        for (let i = 0; i < this.children.length; i++)\n            this.children[i].destroy();\n    }\n    posBeforeChild(child) {\n        for (let i = 0, pos = this.posAtStart;; i++) {\n            let cur = this.children[i];\n            if (cur == child)\n                return pos;\n            pos += cur.size;\n        }\n    }\n    get posBefore() {\n        return this.parent.posBeforeChild(this);\n    }\n    get posAtStart() {\n        return this.parent ? this.parent.posBeforeChild(this) + this.border : 0;\n    }\n    get posAfter() {\n        return this.posBefore + this.size;\n    }\n    get posAtEnd() {\n        return this.posAtStart + this.size - 2 * this.border;\n    }\n    localPosFromDOM(dom, offset, bias) {\n        // If the DOM position is in the content, use the child desc after\n        // it to figure out a position.\n        if (this.contentDOM && contains(this.contentDOM, dom)) {\n            if (bias < 0) {\n                let domBefore, desc;\n                if (dom == this.contentDOM) {\n                    domBefore = dom.childNodes[offset - 1];\n                }\n                else {\n                    while (dom.parentNode != this.contentDOM)\n                        dom = dom.parentNode;\n                    domBefore = dom.previousSibling;\n                }\n                while (domBefore && !((desc = domBefore.pmViewDesc) && desc.parent == this))\n                    domBefore = domBefore.previousSibling;\n                return domBefore ? this.posBeforeChild(desc) + desc.size : this.posAtStart;\n            }\n            else {\n                let domAfter, desc;\n                if (dom == this.contentDOM) {\n                    domAfter = dom.childNodes[offset];\n                }\n                else {\n                    while (dom.parentNode != this.contentDOM)\n                        dom = dom.parentNode;\n                    domAfter = dom.nextSibling;\n                }\n                while (domAfter && !((desc = domAfter.pmViewDesc) && desc.parent == this))\n                    domAfter = domAfter.nextSibling;\n                return domAfter ? this.posBeforeChild(desc) : this.posAtEnd;\n            }\n        }\n        // Otherwise, use various heuristics, falling back on the bias\n        // parameter, to determine whether to return the position at the\n        // start or at the end of this view desc.\n        let atEnd;\n        if (dom == this.dom && this.contentDOM) {\n            atEnd = offset > domIndex(this.contentDOM);\n        }\n        else if (this.contentDOM && this.contentDOM != this.dom && this.dom.contains(this.contentDOM)) {\n            let rel = dom.compareDocumentPosition(this.contentDOM);\n            if (rel & 16) { // this.contentDOM is inside dom\n                atEnd = offset > Array.from(dom.childNodes).findIndex(n => n.contains(this.contentDOM));\n            }\n            else { // Check if after or before\n                atEnd = !(rel & 4);\n            }\n        }\n        else if (this.dom.firstChild) {\n            if (offset == 0)\n                for (let search = dom;; search = search.parentNode) {\n                    if (search == this.dom) {\n                        atEnd = false;\n                        break;\n                    }\n                    if (search.previousSibling)\n                        break;\n                }\n            if (atEnd == null && offset == dom.childNodes.length)\n                for (let search = dom;; search = search.parentNode) {\n                    if (search == this.dom) {\n                        atEnd = true;\n                        break;\n                    }\n                    if (search.nextSibling)\n                        break;\n                }\n        }\n        return (atEnd == null ? bias > 0 : atEnd) ? this.posAtEnd : this.posAtStart;\n    }\n    nearestDesc(dom, onlyNodes = false) {\n        for (let first = true, cur = dom; cur; cur = cur.parentNode) {\n            let desc = this.getDesc(cur), nodeDOM;\n            if (desc && (!onlyNodes || desc.node)) {\n                // If dom is outside of this desc's nodeDOM, don't count it.\n                if (first && (nodeDOM = desc.nodeDOM) &&\n                    !(isElt(nodeDOM) ? contains(nodeDOM, dom) : nodeDOM == dom))\n                    first = false;\n                else\n                    return desc;\n            }\n        }\n    }\n    getDesc(dom) {\n        let desc = dom.pmViewDesc;\n        for (let cur = desc; cur; cur = cur.parent)\n            if (cur == this)\n                return desc;\n    }\n    posFromDOM(dom, offset, bias) {\n        for (let scan = dom; scan; scan = scan.parentNode) {\n            let desc = this.getDesc(scan);\n            if (desc)\n                return desc.localPosFromDOM(dom, offset, bias);\n        }\n        return -1;\n    }\n    // Find the desc for the node after the given pos, if any. (When a\n    // parent node overrode rendering, there might not be one.)\n    descAt(pos) {\n        for (let i = 0, offset = 0; i < this.children.length; i++) {\n            let child = this.children[i], end = offset + child.size;\n            if (offset == pos && end != offset) {\n                while (!child.border && child.children.length) {\n                    for (let i = 0; i < child.children.length; i++) {\n                        let inner = child.children[i];\n                        if (inner.size) {\n                            child = inner;\n                            break;\n                        }\n                    }\n                }\n                return child;\n            }\n            if (pos < end)\n                return child.descAt(pos - offset - child.border);\n            offset = end;\n        }\n    }\n    domFromPos(pos, side) {\n        if (!this.contentDOM)\n            return { node: this.dom, offset: 0, atom: pos + 1 };\n        // First find the position in the child array\n        let i = 0, offset = 0;\n        for (let curPos = 0; i < this.children.length; i++) {\n            let child = this.children[i], end = curPos + child.size;\n            if (end > pos) {\n                offset = pos - curPos;\n                break;\n            }\n            curPos = end;\n        }\n        // If this points into the middle of a child, call through\n        if (offset)\n            return this.children[i].domFromPos(offset - this.children[i].border, side);\n        // Go back if there were any zero-length widgets with side >= 0 before this point\n        for (; i > 0; i--) {\n            let prev = this.children[i - 1];\n            if (prev.size || !(prev instanceof BufferHackViewDesc || prev instanceof WidgetViewDesc && prev.side >= 0))\n                break;\n        }\n        // Scan towards the first useable node\n        if (side <= 0) {\n            let prev, enter = true;\n            for (;; i--, enter = false) {\n                prev = i ? this.children[i - 1] : null;\n                if (!prev || prev.dom.parentNode == this.contentDOM)\n                    break;\n            }\n            if (prev && side && enter && !prev.border && !prev.domAtom)\n                return prev.domFromPos(prev.size, side);\n            return { node: this.contentDOM, offset: prev ? domIndex(prev.dom) + 1 : 0 };\n        }\n        else {\n            let next, enter = true;\n            for (;; i++, enter = false) {\n                next = i < this.children.length ? this.children[i] : null;\n                if (!next || next.dom.parentNode == this.contentDOM)\n                    break;\n            }\n            if (next && enter && !next.border && !next.domAtom)\n                return next.domFromPos(0, side);\n            return { node: this.contentDOM, offset: next ? domIndex(next.dom) : this.contentDOM.childNodes.length };\n        }\n    }\n    // Used to find a DOM range in a single parent for a given changed\n    // range.\n    parseRange(from, to, base = 0) {\n        if (this.children.length == 0)\n            return { node: this.contentDOM, from, to, fromOffset: 0, toOffset: this.contentDOM.childNodes.length };\n        let fromOffset = -1, toOffset = -1;\n        for (let offset = base, i = 0;; i++) {\n            let child = this.children[i], end = offset + child.size;\n            if (fromOffset == -1 && from <= end) {\n                let childBase = offset + child.border;\n                // FIXME maybe descend mark views to parse a narrower range?\n                if (from >= childBase && to <= end - child.border && child.node &&\n                    child.contentDOM && this.contentDOM.contains(child.contentDOM))\n                    return child.parseRange(from, to, childBase);\n                from = offset;\n                for (let j = i; j > 0; j--) {\n                    let prev = this.children[j - 1];\n                    if (prev.size && prev.dom.parentNode == this.contentDOM && !prev.emptyChildAt(1)) {\n                        fromOffset = domIndex(prev.dom) + 1;\n                        break;\n                    }\n                    from -= prev.size;\n                }\n                if (fromOffset == -1)\n                    fromOffset = 0;\n            }\n            if (fromOffset > -1 && (end > to || i == this.children.length - 1)) {\n                to = end;\n                for (let j = i + 1; j < this.children.length; j++) {\n                    let next = this.children[j];\n                    if (next.size && next.dom.parentNode == this.contentDOM && !next.emptyChildAt(-1)) {\n                        toOffset = domIndex(next.dom);\n                        break;\n                    }\n                    to += next.size;\n                }\n                if (toOffset == -1)\n                    toOffset = this.contentDOM.childNodes.length;\n                break;\n            }\n            offset = end;\n        }\n        return { node: this.contentDOM, from, to, fromOffset, toOffset };\n    }\n    emptyChildAt(side) {\n        if (this.border || !this.contentDOM || !this.children.length)\n            return false;\n        let child = this.children[side < 0 ? 0 : this.children.length - 1];\n        return child.size == 0 || child.emptyChildAt(side);\n    }\n    domAfterPos(pos) {\n        let { node, offset } = this.domFromPos(pos, 0);\n        if (!isElt(node) || offset == node.childNodes.length)\n            throw new RangeError(\"No node after pos \" + pos);\n        return node.childNodes[offset];\n    }\n    ignoreMutation(mutation) {\n        return !this.contentDOM && mutation.type != \"selection\";\n    }\n    get contentLost() {\n        return this.contentDOM && this.contentDOM != this.dom && !this.dom.contains(this.contentDOM);\n    }\n    markDamage(damage) {\n        if (damage) {\n            this.damage |= damage;\n            this.markParentDamage();\n        }\n    }\n    markParentDamage() {\n        for (let cur = this;;) {\n            let { parent } = cur;\n            if (!parent || (parent.damage & 1 /* Damage.Child */))\n                break;\n            parent.damage |= 1 /* Damage.Child */;\n            cur = parent;\n        }\n    }\n    get domAtom() { return false; }\n    get ignoreForCoords() { return false; }\n    get ignoreForSelection() { return false; }\n    isText(text) { return false; }\n}\n// A widget desc represents a widget decoration, which is a DOM node\n// drawn between the document nodes.\nclass WidgetViewDesc extends ViewDesc {\n    constructor(parent, widget, view, pos) {\n        let self, dom = widget.type.toDOM;\n        if (typeof dom == \"function\")\n            dom = dom(view, () => {\n                if (!self)\n                    return pos;\n                if (self.parent)\n                    return self.parent.posBeforeChild(self);\n            });\n        if (!widget.type.spec.raw) {\n            let elt = isElt(dom) ? dom : document.createElement(\"span\");\n            if (elt != dom) {\n                elt.appendChild(dom);\n                dom = elt;\n            }\n            if (!elt.hasAttribute(\"contenteditable\"))\n                elt.contentEditable = \"false\";\n            elt.classList.add(\"ProseMirror-widget\");\n        }\n        super(parent, [], dom, null);\n        this.widget = widget;\n        this.widget = widget;\n        self = this;\n    }\n    matchesWidget(widget) {\n        return !this.damage && widget.type.eq(this.widget.type);\n    }\n    parseRule() { return { ignore: true }; }\n    stopEvent(event) {\n        let stop = this.widget.spec.stopEvent;\n        return stop ? stop(event) : false;\n    }\n    ignoreMutation(mutation) {\n        return mutation.type != \"selection\" || this.widget.spec.ignoreSelection;\n    }\n    destroy() {\n        this.widget.type.destroy(this.dom);\n        super.destroy();\n    }\n    get domAtom() { return true; }\n    get ignoreForSelection() { return !!this.widget.type.spec.relaxedSide; }\n    get side() { return this.widget.type.side; }\n}\nclass CompositionViewDesc extends ViewDesc {\n    constructor(parent, dom, textDOM, text) {\n        super(parent, [], dom, null);\n        this.textDOM = textDOM;\n        this.text = text;\n    }\n    get size() { return this.text.length; }\n    localPosFromDOM(dom, offset) {\n        if (dom != this.textDOM)\n            return this.posAtStart + (offset ? this.size : 0);\n        return this.posAtStart + offset;\n    }\n    domFromPos(pos) {\n        return { node: this.textDOM, offset: pos };\n    }\n    ignoreMutation(mut) {\n        return mut.type === \"characterData\" && mut.target.nodeValue == mut.oldValue;\n    }\n}\n// A mark desc represents a mark. May have multiple children,\n// depending on how the mark is split. Note that marks are drawn using\n// a fixed nesting order, for simplicity and predictability, so in\n// some cases they will be split more often than would appear\n// necessary.\nclass MarkViewDesc extends ViewDesc {\n    constructor(parent, mark, dom, contentDOM, spec) {\n        super(parent, [], dom, contentDOM);\n        this.mark = mark;\n        this.spec = spec;\n    }\n    static create(parent, mark, inline, view) {\n        let custom = view.nodeViews[mark.type.name];\n        let spec = custom && custom(mark, view, inline);\n        if (!spec || !spec.dom)\n            spec = DOMSerializer.renderSpec(document, mark.type.spec.toDOM(mark, inline), null, mark.attrs);\n        return new MarkViewDesc(parent, mark, spec.dom, spec.contentDOM || spec.dom, spec);\n    }\n    parseRule() {\n        if ((this.damage & 4 /* Damage.Structure */) || this.mark.type.spec.reparseInView)\n            return null;\n        return { mark: this.mark.type.name, attrs: this.mark.attrs, contentElement: this.contentDOM };\n    }\n    matchesMark(mark) { return !(this.damage & 4 /* Damage.Structure */) && this.mark.eq(mark); }\n    markDamage(damage) {\n        var _a;\n        this.damage |= damage;\n        (_a = this.parent) === null || _a === void 0 ? void 0 : _a.markDamage(2 /* Damage.ChildList */);\n    }\n    slice(from, to, view) {\n        let copy = MarkViewDesc.create(this.parent, this.mark, true, view);\n        let nodes = this.children, size = this.size;\n        if (to < size)\n            nodes = replaceNodes(nodes, to, size, view);\n        if (from > 0)\n            nodes = replaceNodes(nodes, 0, from, view);\n        for (let i = 0; i < nodes.length; i++)\n            nodes[i].parent = copy;\n        copy.children = nodes;\n        return copy;\n    }\n    ignoreMutation(mutation) {\n        return this.spec.ignoreMutation ? this.spec.ignoreMutation(mutation) : super.ignoreMutation(mutation);\n    }\n    destroy() {\n        if (this.spec.destroy)\n            this.spec.destroy();\n        super.destroy();\n    }\n}\n// Node view descs are the main, most common type of view desc, and\n// correspond to an actual node in the document. Unlike mark descs,\n// they populate their child array themselves.\nclass NodeViewDesc extends ViewDesc {\n    constructor(parent, node, outerDeco, innerDeco, dom, contentDOM, nodeDOM) {\n        super(parent, [], dom, contentDOM);\n        this.node = node;\n        this.outerDeco = outerDeco;\n        this.innerDeco = innerDeco;\n        this.nodeDOM = nodeDOM;\n    }\n    // By default, a node is rendered using the `toDOM` method from the\n    // node type spec. But client code can use the `nodeViews` spec to\n    // supply a custom node view, which can influence various aspects of\n    // the way the node works.\n    //\n    // (Using subclassing for this was intentionally decided against,\n    // since it'd require exposing a whole slew of finicky\n    // implementation details to the user code that they probably will\n    // never need.)\n    static create(parent, node, outerDeco, innerDeco, view, pos) {\n        let custom = view.nodeViews[node.type.name], descObj;\n        let spec = custom && custom(node, view, () => {\n            // (This is a function that allows the custom view to find its\n            // own position)\n            if (!descObj)\n                return pos;\n            if (descObj.parent)\n                return descObj.parent.posBeforeChild(descObj);\n        }, outerDeco, innerDeco);\n        let dom = spec && spec.dom, contentDOM = spec && spec.contentDOM;\n        if (node.isText) {\n            if (!dom)\n                dom = document.createTextNode(node.text);\n            else if (!isText(dom))\n                throw new RangeError(\"Text must be rendered as a DOM text node\");\n        }\n        else if (!dom) {\n            let spec = DOMSerializer.renderSpec(document, node.type.spec.toDOM(node), null, node.attrs);\n            ({ dom, contentDOM } = spec);\n        }\n        if (!contentDOM && !node.isText && dom.nodeName != \"BR\") { // Chrome gets confused by <br contenteditable=false>\n            if (!dom.hasAttribute(\"contenteditable\"))\n                dom.contentEditable = \"false\";\n            if (node.type.spec.draggable)\n                dom.draggable = true;\n        }\n        let nodeDOM = dom;\n        dom = applyOuterDeco(dom, outerDeco, node);\n        if (spec)\n            return descObj = new CustomNodeViewDesc(parent, node, outerDeco, innerDeco, dom, contentDOM || null, nodeDOM, spec);\n        else if (node.isText)\n            return new TextViewDesc(parent, node, outerDeco, innerDeco, dom, nodeDOM);\n        else\n            return new NodeViewDesc(parent, node, outerDeco, innerDeco, dom, contentDOM || null, nodeDOM);\n    }\n    parseRule(addedNodes) {\n        // Experimental kludge to allow opt-in re-parsing of nodes\n        if (this.node.type.spec.reparseInView)\n            return null;\n        // FIXME the assumption that this can always return the current\n        // attrs means that if the user somehow manages to change the\n        // attrs in the dom, that won't be picked up. Not entirely sure\n        // whether this is a problem\n        let rule = { node: this.node.type.name, attrs: this.node.attrs };\n        if (this.node.type.whitespace == \"pre\")\n            rule.preserveWhitespace = \"full\";\n        if (!this.contentDOM) {\n            rule.getContent = () => this.node.content;\n        }\n        else if (!this.contentLost) {\n            rule.contentElement = this.contentDOM;\n        }\n        else {\n            // Chrome likes to randomly recreate parent nodes when\n            // backspacing things. When that happens, this tries to find the\n            // new parent.\n            for (let i = this.children.length - 1; i >= 0; i--) {\n                let child = this.children[i];\n                if (this.dom.contains(child.dom.parentNode)) {\n                    rule.contentElement = child.dom.parentNode;\n                    break;\n                }\n            }\n            if (!rule.contentElement) {\n                let found = addedNodes &&\n                    addedNodes.find(n => isElt(n) && addedNodes.indexOf(n.parentNode) < 0 && this.dom.contains(n));\n                if (found)\n                    rule.contentElement = found;\n                else\n                    rule.getContent = () => Fragment.empty;\n            }\n        }\n        return rule;\n    }\n    matchesNode(node, outerDeco, innerDeco) {\n        return !this.damage && node.eq(this.node) &&\n            sameOuterDeco(outerDeco, this.outerDeco) && innerDeco.eq(this.innerDeco);\n    }\n    get size() { return this.node.nodeSize; }\n    get border() { return this.node.isLeaf ? 0 : 1; }\n    // Syncs `this.children` to match `this.node.content` and the local\n    // decorations, possibly introducing nesting for marks. Then, in a\n    // separate step, syncs the DOM inside `this.contentDOM` to\n    // `this.children`.\n    updateChildren(view, pos) {\n        let inline = this.node.inlineContent, off = pos;\n        let composition = view.composing ? this.localCompositionInfo(view, pos) : null;\n        let localComposition = composition && composition.pos > -1 ? composition : null;\n        let compositionInChild = composition && composition.pos < 0;\n        let updater = new ViewTreeUpdater(this, localComposition && localComposition.node, view);\n        let addBuffers = this.node.inlineContent, atBufferPos = addBuffers && this.node.isBlock;\n        iterDeco(this.node, this.innerDeco, (widget, i, insideNode) => {\n            if (widget.spec.marks)\n                updater.syncToMarks(widget.spec.marks, inline, view, i);\n            else if (widget.type.side >= 0 && !insideNode)\n                updater.syncToMarks(i == this.node.childCount ? Mark.none : this.node.child(i).marks, inline, view, i);\n            // If the next node is a desc matching this widget, reuse it,\n            // otherwise insert the widget as a new view desc.\n            updater.placeWidget(widget, view, off);\n        }, (child, outerDeco, innerDeco, i) => {\n            // Make sure the wrapping mark descs match the node's marks.\n            updater.syncToMarks(child.marks, inline, view, i);\n            if (atBufferPos && child.isAtom && !child.isText)\n                updater.addHackNode(\"IMG\", updater.top);\n            // Try several strategies for drawing this node\n            let compIndex;\n            if (updater.findNodeMatch(child, outerDeco, innerDeco, i)) ;\n            else if (compositionInChild && view.state.selection.from > off &&\n                view.state.selection.to < off + child.nodeSize &&\n                (compIndex = updater.findIndexWithChild(composition.node)) > -1 &&\n                updater.updateNodeAt(child, outerDeco, innerDeco, compIndex, view, off)) ;\n            else if (updater.updateNextNode(child, outerDeco, innerDeco, view, i, off)) ;\n            else {\n                // Add it as a new view\n                updater.addNode(child, outerDeco, innerDeco, view, off);\n            }\n            off += child.nodeSize;\n            if (addBuffers)\n                atBufferPos = child.isAtom && !child.isText;\n        });\n        // Drop all remaining descs after the current position.\n        updater.syncToMarks([], inline, view, 0);\n        if (this.node.isTextblock)\n            updater.addTextblockHacks();\n        updater.destroyRest();\n        // Sync the DOM if anything changed\n        if (updater.changed || (this.damage & 2 /* Damage.ChildList */)) {\n            // May have to protect focused DOM from being changed if a composition is active\n            if (localComposition)\n                this.protectLocalComposition(view, localComposition);\n            renderDescs(this.contentDOM, this.children, view);\n            if (ios)\n                iosHacks(this.dom);\n        }\n    }\n    localCompositionInfo(view, pos) {\n        // Only do something if both the selection and a focused text node\n        // are inside of this node\n        let { from, to } = view.state.selection;\n        if (!(view.state.selection instanceof TextSelection) || from < pos || to > pos + this.node.content.size)\n            return null;\n        let textNode = view.input.compositionNode;\n        if (!textNode || !this.dom.contains(textNode.parentNode))\n            return null;\n        if (this.node.inlineContent) {\n            // Find the text in the focused node in the node, stop if it's not\n            // there (may have been modified through other means, in which\n            // case it should overwritten)\n            let text = textNode.nodeValue;\n            let textPos = findTextInFragment(this.node.content, text, from - pos, to - pos);\n            return textPos < 0 ? null : { node: textNode, pos: textPos, text };\n        }\n        else {\n            return { node: textNode, pos: -1, text: \"\" };\n        }\n    }\n    protectLocalComposition(view, { node, pos, text }) {\n        // The node is already part of a local view desc, leave it there\n        if (this.getDesc(node))\n            return;\n        // Create a composition view for the orphaned nodes\n        let topNode = node;\n        for (;; topNode = topNode.parentNode) {\n            if (topNode.parentNode == this.contentDOM)\n                break;\n            while (topNode.previousSibling)\n                topNode.parentNode.removeChild(topNode.previousSibling);\n            while (topNode.nextSibling)\n                topNode.parentNode.removeChild(topNode.nextSibling);\n            if (topNode.pmViewDesc)\n                topNode.pmViewDesc = undefined;\n        }\n        let desc = new CompositionViewDesc(this, topNode, node, text);\n        view.input.compositionNodes.push(desc);\n        // Patch up this.children to contain the composition view\n        this.children = replaceNodes(this.children, pos, pos + text.length, view, desc);\n    }\n    // If this desc must be updated to match the given node decoration,\n    // do so and return true. pos is the position before the node, or -1\n    // for the document.\n    update(node, outerDeco, innerDeco, view, pos) {\n        if ((this.damage & 4 /* Damage.Structure */) || !node.sameMarkup(this.node))\n            return false;\n        this.updateInner(node, outerDeco, innerDeco, view, pos);\n        return true;\n    }\n    updateInner(node, outerDeco, innerDeco, view, pos) {\n        this.updateOuterDeco(outerDeco);\n        this.node = node;\n        this.innerDeco = innerDeco;\n        if (this.contentDOM)\n            this.updateChildren(view, pos + 1);\n        this.damage = 0 /* Damage.None */;\n    }\n    updateOuterDeco(outerDeco) {\n        if (sameOuterDeco(outerDeco, this.outerDeco))\n            return;\n        let needsWrap = !isElt(this.nodeDOM);\n        let oldDOM = this.dom;\n        this.dom = patchOuterDeco(this.dom, this.nodeDOM, computeOuterDeco(this.outerDeco, this.node, needsWrap), computeOuterDeco(outerDeco, this.node, needsWrap));\n        if (this.dom != oldDOM) {\n            oldDOM.pmViewDesc = undefined;\n            this.dom.pmViewDesc = this;\n        }\n        this.outerDeco = outerDeco;\n    }\n    // Mark this node as being the selected node.\n    selectNode() {\n        if (isElt(this.nodeDOM)) {\n            this.nodeDOM.classList.add(\"ProseMirror-selectednode\");\n            if (this.contentDOM || !this.node.type.spec.draggable)\n                this.nodeDOM.draggable = true;\n        }\n    }\n    // Remove selected node marking from this node.\n    deselectNode() {\n        if (isElt(this.nodeDOM)) {\n            this.nodeDOM.classList.remove(\"ProseMirror-selectednode\");\n            if (this.contentDOM || !this.node.type.spec.draggable)\n                this.nodeDOM.removeAttribute(\"draggable\");\n        }\n    }\n    get domAtom() { return this.node.isAtom; }\n}\n// Create a view desc for the top-level document node, to be exported\n// and used by the view class.\nfunction docViewDesc(doc, outerDeco, innerDeco, dom, view, prevOuterDeco) {\n    if (!prevOuterDeco)\n        applyOuterDeco(dom, outerDeco, doc);\n    else\n        patchOuterDeco(dom, dom, computeOuterDeco(prevOuterDeco, doc, false), computeOuterDeco(outerDeco, doc, false));\n    let docView = new NodeViewDesc(undefined, doc, outerDeco, innerDeco, dom, dom, dom);\n    if (docView.contentDOM)\n        docView.updateChildren(view, 0);\n    return docView;\n}\nclass TextViewDesc extends NodeViewDesc {\n    constructor(parent, node, outerDeco, innerDeco, dom, nodeDOM) {\n        super(parent, node, outerDeco, innerDeco, dom, null, nodeDOM);\n    }\n    parseRule() {\n        let skip = this.nodeDOM.parentNode;\n        while (skip && skip != this.dom && !skip.pmIsDeco)\n            skip = skip.parentNode;\n        return { skip: (skip || true) };\n    }\n    update(node, outerDeco, innerDeco, view) {\n        if ((this.damage & 4 /* Damage.Structure */) || (this.damage && !this.inParent()) ||\n            !node.sameMarkup(this.node))\n            return false;\n        this.updateOuterDeco(outerDeco);\n        if (((this.damage & 8 /* Damage.Text */) || node.text != this.node.text) && node.text != this.nodeDOM.nodeValue) {\n            this.nodeDOM.nodeValue = node.text;\n            if (view.trackWrites == this.nodeDOM)\n                view.trackWrites = null;\n        }\n        this.node = node;\n        this.damage = 0 /* Damage.None */;\n        return true;\n    }\n    inParent() {\n        let parentDOM = this.parent.contentDOM;\n        for (let n = this.nodeDOM; n; n = n.parentNode)\n            if (n == parentDOM)\n                return true;\n        return false;\n    }\n    domFromPos(pos) {\n        return { node: this.nodeDOM, offset: pos };\n    }\n    localPosFromDOM(dom, offset, bias) {\n        if (dom == this.nodeDOM)\n            return this.posAtStart + Math.min(offset, this.node.text.length);\n        return super.localPosFromDOM(dom, offset, bias);\n    }\n    ignoreMutation(mutation) {\n        return false;\n    }\n    slice(from, to, _view) {\n        let node = this.node.cut(from, to), dom = document.createTextNode(node.text);\n        return new TextViewDesc(this.parent, node, this.outerDeco, this.innerDeco, dom, dom);\n    }\n    get domAtom() { return false; }\n    isText(text) { return this.node.text == text; }\n}\n// A dummy desc used to tag extra BR or IMG nodes created to work\n// around contentEditable terribleness.\nclass BufferHackViewDesc extends ViewDesc {\n    parseRule() { return { ignore: true }; }\n    matchesHack(nodeName) { return !this.damage && this.dom.nodeName == nodeName; }\n    get domAtom() { return true; }\n    get ignoreForCoords() { return this.dom.nodeName == \"IMG\"; }\n}\n// A separate subclass is used for customized node views, so that the\n// extra checks only have to be made for nodes that are actually\n// customized.\nclass CustomNodeViewDesc extends NodeViewDesc {\n    constructor(parent, node, outerDeco, innerDeco, dom, contentDOM, nodeDOM, spec) {\n        super(parent, node, outerDeco, innerDeco, dom, contentDOM, nodeDOM);\n        this.spec = spec;\n    }\n    // A custom `update` method gets to decide whether the update goes\n    // through. If it does, and there's a `contentDOM` node, our logic\n    // updates the children.\n    update(node, outerDeco, innerDeco, view, pos) {\n        if (this.damage & 4 /* Damage.Structure */)\n            return false;\n        if (this.spec.update && (this.node.type == node.type || this.spec.multiType)) {\n            let result = this.spec.update(node, outerDeco, innerDeco);\n            if (result)\n                this.updateInner(node, outerDeco, innerDeco, view, pos);\n            return result;\n        }\n        else if (!this.contentDOM && !node.isLeaf) {\n            return false;\n        }\n        else {\n            return super.update(node, outerDeco, innerDeco, view, pos);\n        }\n    }\n    selectNode() {\n        this.spec.selectNode ? this.spec.selectNode() : super.selectNode();\n    }\n    deselectNode() {\n        this.spec.deselectNode ? this.spec.deselectNode() : super.deselectNode();\n    }\n    destroy() {\n        if (this.spec.destroy)\n            this.spec.destroy();\n        super.destroy();\n    }\n    stopEvent(event) {\n        return this.spec.stopEvent ? this.spec.stopEvent(event) : false;\n    }\n    ignoreMutation(mutation) {\n        return this.spec.ignoreMutation ? this.spec.ignoreMutation(mutation) : super.ignoreMutation(mutation);\n    }\n}\n// Sync the content of the given DOM node with the nodes associated\n// with the given array of view descs, recursing into mark descs\n// because this should sync the subtree for a whole node at a time.\nfunction renderDescs(parentDOM, descs, view) {\n    let dom = parentDOM.firstChild, written = false;\n    for (let i = 0; i < descs.length; i++) {\n        let desc = descs[i], childDOM = desc.dom;\n        if (childDOM.parentNode == parentDOM) {\n            while (childDOM != dom) {\n                dom = rm(dom);\n                written = true;\n            }\n            dom = dom.nextSibling;\n        }\n        else {\n            written = true;\n            parentDOM.insertBefore(childDOM, dom);\n        }\n        if (desc instanceof MarkViewDesc) {\n            let pos = dom ? dom.previousSibling : parentDOM.lastChild;\n            renderDescs(desc.contentDOM, desc.children, view);\n            dom = pos ? pos.nextSibling : parentDOM.firstChild;\n        }\n    }\n    while (dom) {\n        dom = rm(dom);\n        written = true;\n    }\n    if (written && view.trackWrites == parentDOM)\n        view.trackWrites = null;\n}\nconst OuterDecoLevel = function (nodeName) {\n    if (nodeName)\n        this.nodeName = nodeName;\n};\nOuterDecoLevel.prototype = Object.create(null);\nconst noDeco = [new OuterDecoLevel];\nfunction computeOuterDeco(outerDeco, node, needsWrap) {\n    if (outerDeco.length == 0)\n        return noDeco;\n    let top = needsWrap ? noDeco[0] : new OuterDecoLevel, result = [top];\n    for (let i = 0; i < outerDeco.length; i++) {\n        let attrs = outerDeco[i].type.attrs;\n        if (!attrs)\n            continue;\n        if (attrs.nodeName)\n            result.push(top = new OuterDecoLevel(attrs.nodeName));\n        for (let name in attrs) {\n            let val = attrs[name];\n            if (val == null)\n                continue;\n            if (needsWrap && result.length == 1)\n                result.push(top = new OuterDecoLevel(node.isInline ? \"span\" : \"div\"));\n            if (name == \"class\")\n                top.class = (top.class ? top.class + \" \" : \"\") + val;\n            else if (name == \"style\")\n                top.style = (top.style ? top.style + \";\" : \"\") + val;\n            else if (name != \"nodeName\")\n                top[name] = val;\n        }\n    }\n    return result;\n}\nfunction patchOuterDeco(outerDOM, nodeDOM, prevComputed, curComputed) {\n    // Shortcut for trivial case\n    if (prevComputed == noDeco && curComputed == noDeco)\n        return nodeDOM;\n    let curDOM = nodeDOM;\n    for (let i = 0; i < curComputed.length; i++) {\n        let deco = curComputed[i], prev = prevComputed[i];\n        if (i) {\n            let parent;\n            if (prev && prev.nodeName == deco.nodeName && curDOM != outerDOM &&\n                (parent = curDOM.parentNode) && parent.nodeName.toLowerCase() == deco.nodeName) {\n                curDOM = parent;\n            }\n            else {\n                parent = document.createElement(deco.nodeName);\n                parent.pmIsDeco = true;\n                parent.appendChild(curDOM);\n                prev = noDeco[0];\n                curDOM = parent;\n            }\n        }\n        patchAttributes(curDOM, prev || noDeco[0], deco);\n    }\n    return curDOM;\n}\nfunction patchAttributes(dom, prev, cur) {\n    for (let name in prev)\n        if (name != \"class\" && name != \"style\" && name != \"nodeName\" && !(name in cur))\n            dom.removeAttribute(name);\n    for (let name in cur)\n        if (name != \"class\" && name != \"style\" && name != \"nodeName\" && cur[name] != prev[name])\n            dom.setAttribute(name, cur[name]);\n    if (prev.class != cur.class) {\n        let prevList = prev.class ? prev.class.split(\" \").filter(Boolean) : [];\n        let curList = cur.class ? cur.class.split(\" \").filter(Boolean) : [];\n        for (let i = 0; i < prevList.length; i++)\n            if (curList.indexOf(prevList[i]) == -1)\n                dom.classList.remove(prevList[i]);\n        for (let i = 0; i < curList.length; i++)\n            if (prevList.indexOf(curList[i]) == -1)\n                dom.classList.add(curList[i]);\n        if (dom.classList.length == 0)\n            dom.removeAttribute(\"class\");\n    }\n    if (prev.style != cur.style) {\n        if (prev.style) {\n            let prop = /\\s*([\\w\\-\\xa1-\\uffff]+)\\s*:(?:\"(?:\\\\.|[^\"])*\"|'(?:\\\\.|[^'])*'|\\(.*?\\)|[^;])*/g, m;\n            while (m = prop.exec(prev.style))\n                dom.style.removeProperty(m[1]);\n        }\n        if (cur.style)\n            dom.style.cssText += cur.style;\n    }\n}\nfunction applyOuterDeco(dom, deco, node) {\n    return patchOuterDeco(dom, dom, noDeco, computeOuterDeco(deco, node, !isElt(dom)));\n}\nfunction sameOuterDeco(a, b) {\n    if (a.length != b.length)\n        return false;\n    for (let i = 0; i < a.length; i++)\n        if (!a[i].type.eq(b[i].type))\n            return false;\n    return true;\n}\n// Remove a DOM node and return its next sibling.\nfunction rm(dom) {\n    let next = dom.nextSibling;\n    dom.parentNode.removeChild(dom);\n    return next;\n}\n// Helper class for incrementally updating a tree of mark descs and\n// the widget and node descs inside of them.\nclass ViewTreeUpdater {\n    constructor(top, lock, view) {\n        this.lock = lock;\n        this.view = view;\n        // Index into `this.top`'s child array, represents the current\n        // update position.\n        this.index = 0;\n        // When entering a mark, the current top and index are pushed\n        // onto this.\n        this.stack = [];\n        // Tracks whether anything was changed\n        this.changed = false;\n        this.top = top;\n        this.preMatch = preMatch(top.node.content, top);\n    }\n    // Destroy and remove the children between the given indices in\n    // `this.top`.\n    destroyBetween(start, end) {\n        if (start == end)\n            return;\n        for (let i = start; i < end; i++)\n            this.top.children[i].destroy();\n        this.top.children.splice(start, end - start);\n        this.changed = true;\n    }\n    // Destroy all remaining children in `this.top`.\n    destroyRest() {\n        this.destroyBetween(this.index, this.top.children.length);\n    }\n    // Sync the current stack of mark descs with the given array of\n    // marks, reusing existing mark descs when possible.\n    syncToMarks(marks, inline, view, parentIndex) {\n        let keep = 0, depth = this.stack.length >> 1;\n        let maxKeep = Math.min(depth, marks.length);\n        while (keep < maxKeep &&\n            (keep == depth - 1 ? this.top : this.stack[(keep + 1) << 1])\n                .matchesMark(marks[keep]) && marks[keep].type.spec.spanning !== false)\n            keep++;\n        while (keep < depth) {\n            this.destroyRest();\n            this.top.damage = 0 /* Damage.None */;\n            this.index = this.stack.pop();\n            this.top = this.stack.pop();\n            depth--;\n        }\n        while (depth < marks.length) {\n            this.stack.push(this.top, this.index + 1);\n            let found = -1, scanTo = this.top.children.length;\n            if (parentIndex < this.preMatch.index)\n                scanTo = Math.min(this.index + 3, scanTo);\n            for (let i = this.index; i < scanTo; i++) {\n                let next = this.top.children[i];\n                if (next.matchesMark(marks[depth]) && !this.isLocked(next.dom)) {\n                    found = i;\n                    break;\n                }\n            }\n            // When nothing matches, try to update the mark view at this position\n            // in place, so a custom mark view can adapt to a changed mark without\n            // re-creating its DOM.\n            if (found < 0 && this.index < this.top.children.length) {\n                let cur = this.top.children[this.index];\n                if (cur instanceof MarkViewDesc && !(cur.damage & 4 /* Damage.Structure */) &&\n                    cur.mark.type == marks[depth].type && cur.spec.update &&\n                    !this.isLocked(cur.dom) && cur.spec.update(marks[depth])) {\n                    cur.mark = marks[depth];\n                    found = this.index;\n                    this.changed = true;\n                }\n            }\n            if (found > -1) {\n                if (found > this.index) {\n                    this.changed = true;\n                    this.destroyBetween(this.index, found);\n                }\n                this.top = this.top.children[this.index];\n            }\n            else {\n                let markDesc = MarkViewDesc.create(this.top, marks[depth], inline, view);\n                this.top.children.splice(this.index, 0, markDesc);\n                this.top = markDesc;\n                this.changed = true;\n            }\n            this.index = 0;\n            depth++;\n        }\n    }\n    // Try to find a node desc matching the given data. Skip over it and\n    // return true when successful.\n    findNodeMatch(node, outerDeco, innerDeco, index) {\n        let found = -1, targetDesc;\n        if (index >= this.preMatch.index &&\n            (targetDesc = this.preMatch.matches[index - this.preMatch.index]).parent == this.top &&\n            targetDesc.matchesNode(node, outerDeco, innerDeco)) {\n            found = this.top.children.indexOf(targetDesc, this.index);\n        }\n        else {\n            for (let i = this.index, e = Math.min(this.top.children.length, i + 5); i < e; i++) {\n                let child = this.top.children[i];\n                if (child.matchesNode(node, outerDeco, innerDeco) && !this.preMatch.matched.has(child)) {\n                    found = i;\n                    break;\n                }\n            }\n        }\n        if (found < 0)\n            return false;\n        this.destroyBetween(this.index, found);\n        this.index++;\n        return true;\n    }\n    updateNodeAt(node, outerDeco, innerDeco, index, view, pos) {\n        let child = this.top.children[index];\n        if ((child.damage & 4 /* Damage.Structure */) && child.dom == child.contentDOM)\n            child.damage = 2 /* Damage.ChildList */;\n        if (!child.update(node, outerDeco, innerDeco, view, pos))\n            return false;\n        this.destroyBetween(this.index, index);\n        this.index++;\n        return true;\n    }\n    findIndexWithChild(domNode) {\n        for (;;) {\n            let parent = domNode.parentNode;\n            if (!parent)\n                return -1;\n            if (parent == this.top.contentDOM) {\n                let desc = domNode.pmViewDesc;\n                if (desc)\n                    for (let i = this.index; i < this.top.children.length; i++) {\n                        if (this.top.children[i] == desc)\n                            return i;\n                    }\n                return -1;\n            }\n            domNode = parent;\n        }\n    }\n    // Try to update the next node, if any, to the given data. Checks\n    // pre-matches to avoid overwriting nodes that could still be used.\n    updateNextNode(node, outerDeco, innerDeco, view, index, pos) {\n        for (let i = this.index; i < this.top.children.length; i++) {\n            let next = this.top.children[i];\n            if (next instanceof NodeViewDesc) {\n                let preMatch = this.preMatch.matched.get(next);\n                if (preMatch != null && preMatch != index)\n                    return false;\n                let nextDOM = next.dom, updated;\n                // Can't update if nextDOM is or contains this.lock, except if\n                // it's a text node whose content already matches the new text\n                // and whose decorations match the new ones.\n                let locked = this.isLocked(nextDOM) &&\n                    !(node.isText && next.node && next.node.isText && next.nodeDOM.nodeValue == node.text &&\n                        !(next.damage & 4 /* Damage.Structure */) && sameOuterDeco(outerDeco, next.outerDeco));\n                if (!locked && next.update(node, outerDeco, innerDeco, view, pos)) {\n                    this.destroyBetween(this.index, i);\n                    if (next.dom != nextDOM)\n                        this.changed = true;\n                    this.index++;\n                    return true;\n                }\n                else if (!locked && (updated = this.recreateWrapper(next, node, outerDeco, innerDeco, view, pos))) {\n                    this.destroyBetween(this.index, i);\n                    this.top.children[this.index] = updated;\n                    if (updated.contentDOM) {\n                        updated.damage |= 2 /* Damage.ChildList */;\n                        updated.updateChildren(view, pos + 1);\n                        updated.damage = 0 /* Damage.None */;\n                    }\n                    this.changed = true;\n                    this.index++;\n                    return true;\n                }\n                break;\n            }\n        }\n        return false;\n    }\n    // When a node with content is replaced by a different node with\n    // identical content, move over its children.\n    recreateWrapper(next, node, outerDeco, innerDeco, view, pos) {\n        if ((next.damage & (2 /* Damage.ChildList */ | 1 /* Damage.Child */)) || node.isAtom || !next.children.length ||\n            !next.node.content.eq(node.content) ||\n            !sameOuterDeco(outerDeco, next.outerDeco) || !innerDeco.eq(next.innerDeco))\n            return null;\n        let wrapper = NodeViewDesc.create(this.top, node, outerDeco, innerDeco, view, pos);\n        if (wrapper.contentDOM) {\n            wrapper.children = next.children;\n            next.children = [];\n            for (let ch of wrapper.children)\n                ch.parent = wrapper;\n        }\n        next.destroy();\n        return wrapper;\n    }\n    // Insert the node as a newly created node desc.\n    addNode(node, outerDeco, innerDeco, view, pos) {\n        let desc = NodeViewDesc.create(this.top, node, outerDeco, innerDeco, view, pos);\n        if (desc.contentDOM)\n            desc.updateChildren(view, pos + 1);\n        this.top.children.splice(this.index++, 0, desc);\n        this.changed = true;\n    }\n    placeWidget(widget, view, pos) {\n        let next = this.index < this.top.children.length ? this.top.children[this.index] : null;\n        if (next && next.matchesWidget(widget) &&\n            (widget == next.widget || !next.widget.type.toDOM.parentNode)) {\n            this.index++;\n        }\n        else {\n            let desc = new WidgetViewDesc(this.top, widget, view, pos);\n            this.top.children.splice(this.index++, 0, desc);\n            this.changed = true;\n        }\n    }\n    // Make sure a textblock looks and behaves correctly in\n    // contentEditable.\n    addTextblockHacks() {\n        let lastChild = this.top.children[this.index - 1], parent = this.top;\n        while (lastChild instanceof MarkViewDesc) {\n            parent = lastChild;\n            lastChild = parent.children[parent.children.length - 1];\n        }\n        if (!lastChild || // Empty textblock\n            !(lastChild instanceof TextViewDesc) ||\n            /\\n$/.test(lastChild.node.text) ||\n            (this.view.requiresGeckoHackNode && /\\s$/.test(lastChild.node.text))) {\n            // Avoid bugs in Safari's cursor drawing (#1165) and Chrome's mouse selection (#1152)\n            if ((safari || chrome) && lastChild && lastChild.dom.contentEditable == \"false\")\n                this.addHackNode(\"IMG\", parent);\n            this.addHackNode(\"BR\", this.top);\n        }\n    }\n    addHackNode(nodeName, parent) {\n        if (parent == this.top && this.index < parent.children.length && parent.children[this.index].matchesHack(nodeName)) {\n            this.index++;\n        }\n        else {\n            let dom = document.createElement(nodeName);\n            if (nodeName == \"IMG\") {\n                dom.className = \"ProseMirror-separator\";\n                dom.alt = \"\";\n            }\n            if (nodeName == \"BR\")\n                dom.className = \"ProseMirror-trailingBreak\";\n            let hack = new BufferHackViewDesc(this.top, [], dom, null);\n            if (parent != this.top)\n                parent.children.push(hack);\n            else\n                parent.children.splice(this.index++, 0, hack);\n            this.changed = true;\n        }\n    }\n    isLocked(node) {\n        return this.lock && (node == this.lock || isElt(node) && node.contains(this.lock.parentNode));\n    }\n}\n// Iterate from the end of the fragment and array of descs to find\n// directly matching ones, in order to avoid overeagerly reusing those\n// for other nodes.\nfunction preMatch(frag, parentDesc) {\n    let curDesc = parentDesc, descI = curDesc.children.length, stack = [];\n    let fI = frag.childCount, matched = new Map, matches = [];\n    outer: while (fI > 0) {\n        let desc;\n        for (;;) {\n            if (descI) {\n                let next = curDesc.children[descI - 1];\n                if (next instanceof MarkViewDesc) {\n                    stack.push(descI - 1);\n                    curDesc = next;\n                    descI = next.children.length;\n                }\n                else {\n                    desc = next;\n                    descI--;\n                    break;\n                }\n            }\n            else if (curDesc == parentDesc) {\n                break outer;\n            }\n            else {\n                descI = stack.pop();\n                curDesc = curDesc.parent;\n            }\n        }\n        let node = desc.node;\n        if (!node)\n            continue;\n        if (node != frag.child(fI - 1))\n            break;\n        --fI;\n        matched.set(desc, fI);\n        matches.push(desc);\n    }\n    return { index: fI, matched, matches: matches.reverse() };\n}\nfunction compareSide(a, b) {\n    return a.type.side - b.type.side;\n}\n// This function abstracts iterating over the nodes and decorations in\n// a fragment. Calls `onNode` for each node, with its local and child\n// decorations. Splits text nodes when there is a decoration starting\n// or ending inside of them. Calls `onWidget` for each widget.\nfunction iterDeco(parent, deco, onWidget, onNode) {\n    let locals = deco.locals(parent), offset = 0;\n    // Simple, cheap variant for when there are no local decorations\n    if (locals.length == 0) {\n        for (let i = 0; i < parent.childCount; i++) {\n            let child = parent.child(i);\n            onNode(child, locals, deco.forChild(offset, child), i);\n            offset += child.nodeSize;\n        }\n        return;\n    }\n    let decoIndex = 0, active = [], restNode = null;\n    for (let parentIndex = 0;;) {\n        let widget, widgets;\n        while (decoIndex < locals.length && locals[decoIndex].to == offset) {\n            let next = locals[decoIndex++];\n            if (next.widget) {\n                if (!widget)\n                    widget = next;\n                else\n                    (widgets || (widgets = [widget])).push(next);\n            }\n        }\n        if (widget) {\n            if (widgets) {\n                widgets.sort(compareSide);\n                for (let i = 0; i < widgets.length; i++)\n                    onWidget(widgets[i], parentIndex, !!restNode);\n            }\n            else {\n                onWidget(widget, parentIndex, !!restNode);\n            }\n        }\n        let child, index;\n        if (restNode) {\n            index = -1;\n            child = restNode;\n            restNode = null;\n        }\n        else if (parentIndex < parent.childCount) {\n            index = parentIndex;\n            child = parent.child(parentIndex++);\n        }\n        else {\n            break;\n        }\n        for (let i = 0; i < active.length; i++)\n            if (active[i].to <= offset)\n                active.splice(i--, 1);\n        while (decoIndex < locals.length && locals[decoIndex].from <= offset && locals[decoIndex].to > offset)\n            active.push(locals[decoIndex++]);\n        let end = offset + child.nodeSize;\n        if (child.isText) {\n            let cutAt = end;\n            if (decoIndex < locals.length && locals[decoIndex].from < cutAt)\n                cutAt = locals[decoIndex].from;\n            for (let i = 0; i < active.length; i++)\n                if (active[i].to < cutAt)\n                    cutAt = active[i].to;\n            if (cutAt < end) {\n                restNode = child.cut(cutAt - offset);\n                child = child.cut(0, cutAt - offset);\n                end = cutAt;\n                index = -1;\n            }\n        }\n        else {\n            while (decoIndex < locals.length && locals[decoIndex].to < end)\n                decoIndex++;\n        }\n        let outerDeco = child.isInline && !child.isLeaf ? active.filter(d => !d.inline) : active.slice();\n        onNode(child, outerDeco, deco.forChild(offset, child), index);\n        offset = end;\n    }\n}\n// List markers in Mobile Safari will mysteriously disappear\n// sometimes. This works around that.\nfunction iosHacks(dom) {\n    if (dom.nodeName == \"UL\" || dom.nodeName == \"OL\") {\n        let oldCSS = dom.style.cssText;\n        dom.style.cssText = oldCSS + \"; list-style: square !important\";\n        window.getComputedStyle(dom).listStyle;\n        dom.style.cssText = oldCSS;\n    }\n}\n// Find a piece of text in an inline fragment, overlapping from-to\nfunction findTextInFragment(frag, text, from, to) {\n    for (let i = 0, pos = 0; i < frag.childCount && pos <= to;) {\n        let child = frag.child(i++), childStart = pos;\n        pos += child.nodeSize;\n        if (!child.isText)\n            continue;\n        let str = child.text;\n        while (i < frag.childCount) {\n            let next = frag.child(i++);\n            pos += next.nodeSize;\n            if (!next.isText)\n                break;\n            str += next.text;\n        }\n        if (pos >= from) {\n            if (pos >= to && str.slice(to - text.length - childStart, to - childStart) == text)\n                return to - text.length;\n            let found = childStart < to ? str.lastIndexOf(text, to - childStart - 1) : -1;\n            if (found >= 0 && found + text.length + childStart >= from)\n                return childStart + found;\n            if (from == to && str.length >= (to + text.length) - childStart &&\n                str.slice(to - childStart, to - childStart + text.length) == text)\n                return to;\n        }\n    }\n    return -1;\n}\n// Replace range from-to in an array of view descs with replacement\n// (may be null to just delete). This goes very much against the grain\n// of the rest of this code, which tends to create nodes with the\n// right shape in one go, rather than messing with them after\n// creation, but is necessary in the composition hack.\nfunction replaceNodes(nodes, from, to, view, replacement) {\n    let result = [];\n    for (let i = 0, off = 0; i < nodes.length; i++) {\n        let child = nodes[i], start = off, end = off += child.size;\n        if (start >= to || end <= from) {\n            result.push(child);\n        }\n        else {\n            if (start < from)\n                result.push(child.slice(0, from - start, view));\n            if (replacement) {\n                result.push(replacement);\n                replacement = undefined;\n            }\n            if (end > to)\n                result.push(child.slice(to - start, child.size, view));\n        }\n    }\n    return result;\n}\n\nfunction moveSelectionBlock(state, dir) {\n    let { $anchor, $head } = state.selection;\n    let $side = dir > 0 ? $anchor.max($head) : $anchor.min($head);\n    let $start = !$side.parent.inlineContent ? $side : $side.depth ? state.doc.resolve(dir > 0 ? $side.after() : $side.before()) : null;\n    return $start && Selection.findFrom($start, dir);\n}\nfunction apply(view, sel) {\n    view.dispatch(view.state.tr.setSelection(sel).scrollIntoView());\n    return true;\n}\nfunction selectHorizontally(view, dir, mods) {\n    let sel = view.state.selection;\n    if (sel instanceof TextSelection) {\n        if (mods.indexOf(\"s\") > -1) {\n            let { $head } = sel, node = $head.textOffset ? null : dir < 0 ? $head.nodeBefore : $head.nodeAfter;\n            if (!node || node.isText || !node.isLeaf)\n                return false;\n            let $newHead = view.state.doc.resolve($head.pos + node.nodeSize * (dir < 0 ? -1 : 1));\n            return apply(view, new TextSelection(sel.$anchor, $newHead));\n        }\n        else if (!sel.empty) {\n            return false;\n        }\n        else if (view.endOfTextblock(dir > 0 ? \"forward\" : \"backward\")) {\n            let next = moveSelectionBlock(view.state, dir);\n            if (next && (next instanceof NodeSelection))\n                return apply(view, next);\n            return false;\n        }\n        else if (!mac || mods.indexOf(\"m\") < 0) {\n            let $head = sel.$head, node = $head.textOffset ? null : dir < 0 ? $head.nodeBefore : $head.nodeAfter, desc;\n            if (!node || node.isText)\n                return false;\n            let nodePos = dir < 0 ? $head.pos - node.nodeSize : $head.pos;\n            if (!(node.isAtom || (desc = view.docView.descAt(nodePos)) && !desc.contentDOM))\n                return false;\n            if (NodeSelection.isSelectable(node)) {\n                return apply(view, new NodeSelection(dir < 0 ? view.state.doc.resolve($head.pos - node.nodeSize) : $head));\n            }\n            else {\n                // Chrome and Safari will introduce extra pointless cursor\n                // positions around inline uneditable nodes (#937), and\n                // Firefox will sometimes just plain refuse to move across\n                // them (#1592), so in this situation we move the cursor\n                // ourselves.\n                return apply(view, new TextSelection(view.state.doc.resolve(dir < 0 ? nodePos : nodePos + node.nodeSize)));\n            }\n        }\n    }\n    else if (sel instanceof NodeSelection && sel.node.isInline) {\n        return apply(view, new TextSelection(dir > 0 ? sel.$to : sel.$from));\n    }\n    else {\n        let next = moveSelectionBlock(view.state, dir);\n        if (next)\n            return apply(view, next);\n        return false;\n    }\n}\nfunction isIgnorable(dom, dir) {\n    let desc = dom.pmViewDesc;\n    return desc ? desc.size == 0 && (dir < 0 || dom.nextSibling || dom.nodeName != \"BR\")\n        : isElt(dom) && dom.contentEditable == \"false\";\n}\nfunction skipIgnoredNodes(view, dir) {\n    return dir < 0 ? skipIgnoredNodesBefore(view) : skipIgnoredNodesAfter(view);\n}\n// Make sure the cursor isn't directly after one or more ignored\n// nodes, which will confuse the browser's cursor motion logic.\nfunction skipIgnoredNodesBefore(view) {\n    let sel = view.domSel.readRange();\n    let node = sel.focusNode, offset = sel.focusOffset;\n    if (!node)\n        return;\n    let moveNode, moveOffset, force = false;\n    // Gecko will do odd things when the selection is directly in front\n    // of a non-editable node, so in that case, move it into the next\n    // node if possible. Issue prosemirror/prosemirror#832.\n    if (gecko && isElt(node) && offset < nodeSize(node) && isIgnorable(node.childNodes[offset], -1))\n        force = true;\n    for (;;) {\n        if (offset > 0) {\n            if (!isElt(node))\n                break;\n            let before = node.childNodes[offset - 1];\n            if (isIgnorable(before, -1)) {\n                moveNode = node;\n                moveOffset = --offset;\n            }\n            else if (isText(before)) {\n                node = before;\n                offset = node.nodeValue.length;\n            }\n            else {\n                break;\n            }\n        }\n        else if (isBlockNode(node)) {\n            break;\n        }\n        else {\n            let prev = node.previousSibling;\n            while (prev && isIgnorable(prev, -1)) {\n                moveNode = node.parentNode;\n                moveOffset = domIndex(prev);\n                prev = prev.previousSibling;\n            }\n            if (!prev) {\n                node = node.parentNode;\n                if (node == view.dom)\n                    break;\n                offset = 0;\n            }\n            else {\n                node = prev;\n                offset = nodeSize(node);\n            }\n        }\n    }\n    if (force)\n        setSelFocus(view, node, offset);\n    else if (moveNode)\n        setSelFocus(view, moveNode, moveOffset);\n}\n// Make sure the cursor isn't directly before one or more ignored\n// nodes.\nfunction skipIgnoredNodesAfter(view) {\n    let sel = view.domSel.readRange();\n    let node = sel.focusNode, offset = sel.focusOffset;\n    if (!node)\n        return;\n    let len = nodeSize(node);\n    let moveNode, moveOffset;\n    for (;;) {\n        if (offset < len) {\n            if (!isElt(node))\n                break;\n            let after = node.childNodes[offset];\n            if (isIgnorable(after, 1)) {\n                moveNode = node;\n                moveOffset = ++offset;\n            }\n            else {\n                break;\n            }\n        }\n        else if (isBlockNode(node)) {\n            break;\n        }\n        else {\n            let next = node.nextSibling;\n            while (next && isIgnorable(next, 1)) {\n                moveNode = next.parentNode;\n                moveOffset = domIndex(next) + 1;\n                next = next.nextSibling;\n            }\n            if (!next) {\n                node = node.parentNode;\n                if (node == view.dom)\n                    break;\n                offset = len = 0;\n            }\n            else {\n                node = next;\n                offset = 0;\n                len = nodeSize(node);\n            }\n        }\n    }\n    if (moveNode)\n        setSelFocus(view, moveNode, moveOffset);\n}\nfunction isBlockNode(dom) {\n    for (let scan = dom; scan; scan = scan.parentNode) {\n        let desc = scan.pmViewDesc;\n        if (desc)\n            return desc.node ? desc.node.isBlock : false;\n    }\n    return false;\n}\nfunction setSelFocus(view, node, offset) {\n    if (!isText(node)) {\n        let before, after;\n        if (after = textNodeAfter(node, offset)) {\n            node = after;\n            offset = 0;\n        }\n        else if (before = textNodeBefore(node, offset)) {\n            node = before;\n            offset = before.nodeValue.length;\n        }\n    }\n    let sel = view.domSelection(), range = view.domSel.readRange();\n    if (!sel)\n        return;\n    if (selectionCollapsed(range)) {\n        sel.collapse(node, offset);\n    }\n    else if (sel.extend) {\n        sel.collapse(range.anchorNode, range.anchorOffset);\n        sel.extend(node, offset);\n    }\n    view.domSel.ignore();\n    let { state } = view;\n    // If no state update ends up happening, reset the selection.\n    setTimeout(() => {\n        if (view.state == state)\n            view.domSel.sync();\n    }, 50);\n}\nfunction findDirection(view, pos) {\n    let $pos = view.state.doc.resolve(pos);\n    if (!(chrome || windows) && $pos.parent.inlineContent) {\n        let coords = view.coordsAtPos(pos);\n        if (pos > $pos.start()) {\n            let before = view.coordsAtPos(pos - 1);\n            let mid = (before.top + before.bottom) / 2;\n            if (mid > coords.top && mid < coords.bottom && Math.abs(before.left - coords.left) > 1)\n                return before.left < coords.left ? \"ltr\" : \"rtl\";\n        }\n        if (pos < $pos.end()) {\n            let after = view.coordsAtPos(pos + 1);\n            let mid = (after.top + after.bottom) / 2;\n            if (mid > coords.top && mid < coords.bottom && Math.abs(after.left - coords.left) > 1)\n                return after.left > coords.left ? \"ltr\" : \"rtl\";\n        }\n    }\n    let block = view.dom;\n    for (let d = $pos.depth; d > 0; d--)\n        if ($pos.node(d).isBlock) {\n            block = view.nodeDOM($pos.before(d)) || block;\n            break;\n        }\n    let computed = getComputedStyle(block).direction;\n    return computed == \"rtl\" ? \"rtl\" : \"ltr\";\n}\n// Check whether vertical selection motion would involve node\n// selections. If so, apply it (if not, the result is left to the\n// browser)\nfunction selectVertically(view, dir, mods) {\n    let sel = view.state.selection;\n    if (sel instanceof TextSelection && !sel.empty || mods.indexOf(\"s\") > -1)\n        return false;\n    if (mac && mods.indexOf(\"m\") > -1)\n        return false;\n    let { $from, $to } = sel;\n    if (!$from.parent.inlineContent || view.endOfTextblock(dir < 0 ? \"up\" : \"down\")) {\n        let next = moveSelectionBlock(view.state, dir);\n        if (next && (next instanceof NodeSelection))\n            return apply(view, next);\n    }\n    if (!$from.parent.inlineContent) {\n        let side = dir < 0 ? $from : $to;\n        let beyond = sel instanceof AllSelection ? Selection.near(side, dir) : Selection.findFrom(side, dir);\n        return beyond ? apply(view, beyond) : false;\n    }\n    return false;\n}\nfunction stopNativeHorizontalDelete(view, dir) {\n    if (!(view.state.selection instanceof TextSelection))\n        return true;\n    let { $head, $anchor, empty } = view.state.selection;\n    if (!$head.sameParent($anchor))\n        return true;\n    if (!empty)\n        return false;\n    if (view.endOfTextblock(dir > 0 ? \"forward\" : \"backward\"))\n        return true;\n    let nextNode = !$head.textOffset && (dir < 0 ? $head.nodeBefore : $head.nodeAfter);\n    if (nextNode && !nextNode.isText) {\n        let tr = view.state.tr;\n        if (dir < 0)\n            tr.delete($head.pos - nextNode.nodeSize, $head.pos);\n        else\n            tr.delete($head.pos, $head.pos + nextNode.nodeSize);\n        view.dispatch(tr);\n        return true;\n    }\n    return false;\n}\nfunction switchEditable(view, node, state) {\n    view.domObserver.stopped(() => node.contentEditable = state);\n}\n// Issue #867 / #1090 / https://bugs.chromium.org/p/chromium/issues/detail?id=903821\n// In which Safari (and at some point in the past, Chrome) does really\n// wrong things when the down arrow is pressed when the cursor is\n// directly at the start of a textblock and has an uneditable node\n// after it\nfunction safariDownArrowBug(view) {\n    if (!safari || view.state.selection.$head.parentOffset > 0)\n        return false;\n    let { focusNode, focusOffset } = view.domSel.readRange();\n    if (focusNode && isElt(focusNode) && focusOffset == 0 &&\n        focusNode.firstChild && isElt(focusNode.firstChild) && focusNode.firstChild.contentEditable == \"false\") {\n        let child = focusNode.firstChild;\n        switchEditable(view, child, \"true\");\n        setTimeout(() => switchEditable(view, child, \"false\"), 20);\n    }\n    return false;\n}\n// A backdrop key mapping used to make sure we always suppress keys\n// that have a dangerous default effect, even if the commands they are\n// bound to return false, and to make sure that cursor-motion keys\n// find a cursor (as opposed to a node selection) when pressed. For\n// cursor-motion keys, the code in the handlers also takes care of\n// block selections.\nfunction getMods(event) {\n    let result = \"\";\n    if (event.ctrlKey)\n        result += \"c\";\n    if (event.metaKey)\n        result += \"m\";\n    if (event.altKey)\n        result += \"a\";\n    if (event.shiftKey)\n        result += \"s\";\n    return result;\n}\nfunction captureKeyDown(view, event) {\n    let code = event.keyCode, mods = getMods(event);\n    if (code == 8 || (mac && code == 72 && mods == \"c\")) { // Backspace, Ctrl-h on Mac\n        return stopNativeHorizontalDelete(view, -1) || skipIgnoredNodes(view, -1);\n    }\n    else if ((code == 46 && !event.shiftKey) || (mac && code == 68 && mods == \"c\")) { // Delete, Ctrl-d on Mac\n        return stopNativeHorizontalDelete(view, 1) || skipIgnoredNodes(view, 1);\n    }\n    else if (code == 13 || code == 27) { // Enter, Esc\n        return true;\n    }\n    else if (code == 37 || (mac && code == 66 && mods == \"c\")) { // Left arrow, Ctrl-b on Mac\n        let dir = code == 37 ? (findDirection(view, view.state.selection.from) == \"ltr\" ? -1 : 1) : -1;\n        return selectHorizontally(view, dir, mods) || skipIgnoredNodes(view, dir);\n    }\n    else if (code == 39 || (mac && code == 70 && mods == \"c\")) { // Right arrow, Ctrl-f on Mac\n        let dir = code == 39 ? (findDirection(view, view.state.selection.from) == \"ltr\" ? 1 : -1) : 1;\n        return selectHorizontally(view, dir, mods) || skipIgnoredNodes(view, dir);\n    }\n    else if (code == 38 || (mac && code == 80 && mods == \"c\")) { // Up arrow, Ctrl-p on Mac\n        return selectVertically(view, -1, mods) || skipIgnoredNodes(view, -1);\n    }\n    else if (code == 40 || (mac && code == 78 && mods == \"c\")) { // Down arrow, Ctrl-n on Mac\n        return safariDownArrowBug(view) || selectVertically(view, 1, mods) || skipIgnoredNodes(view, 1);\n    }\n    else if (mods == (mac ? \"m\" : \"c\") &&\n        (code == 66 || code == 73 || code == 89 || code == 90)) { // Mod-[biyz]\n        return true;\n    }\n    return false;\n}\n\nfunction serializeForClipboard(view, slice) {\n    view.someProp(\"transformCopied\", f => { slice = f(slice, view); });\n    let context = [], { content, openStart, openEnd } = slice;\n    while (openStart > 1 && openEnd > 1 && content.childCount == 1 && content.firstChild.childCount == 1) {\n        openStart--;\n        openEnd--;\n        let node = content.firstChild;\n        context.push(node.type.name, node.attrs != node.type.defaultAttrs ? node.attrs : null);\n        content = node.content;\n    }\n    let serializer = view.someProp(\"clipboardSerializer\") || DOMSerializer.fromSchema(view.state.schema);\n    let doc = detachedDoc(), wrap = doc.createElement(\"div\");\n    wrap.appendChild(serializer.serializeFragment(content, { document: doc }));\n    let firstChild = wrap.firstChild, needsWrap, wrappers = 0;\n    while (firstChild && isElt(firstChild) && (needsWrap = wrapMap[firstChild.nodeName.toLowerCase()])) {\n        for (let i = needsWrap.length - 1; i >= 0; i--) {\n            let wrapper = doc.createElement(needsWrap[i]);\n            while (wrap.firstChild)\n                wrapper.appendChild(wrap.firstChild);\n            wrap.appendChild(wrapper);\n            wrappers++;\n        }\n        firstChild = wrap.firstChild;\n    }\n    if (firstChild && isElt(firstChild))\n        firstChild.setAttribute(\"data-pm-slice\", `${openStart} ${openEnd}${wrappers ? ` -${wrappers}` : \"\"} ${JSON.stringify(context)}`);\n    let text = view.someProp(\"clipboardTextSerializer\", f => f(slice, view)) ||\n        slice.content.textBetween(0, slice.content.size, \"\\n\\n\");\n    return { dom: wrap, text, slice };\n}\n// Read a slice of content from the clipboard (or drop data).\nfunction parseFromClipboard(view, text, html, plainText, $context) {\n    let inCode = $context.parent.type.spec.code;\n    let dom, slice;\n    if (!html && !text)\n        return null;\n    let asText = !!text && (plainText || inCode || !html);\n    if (asText) {\n        view.someProp(\"transformPastedText\", f => { text = f(text, inCode || plainText, view); });\n        if (inCode) {\n            slice = new Slice(Fragment.from(view.state.schema.text(text.replace(/\\r\\n?/g, \"\\n\"))), 0, 0);\n            view.someProp(\"transformPasted\", f => { slice = f(slice, view, true); });\n            return slice;\n        }\n        let parsed = view.someProp(\"clipboardTextParser\", f => f(text, $context, plainText, view));\n        if (parsed) {\n            slice = parsed;\n        }\n        else {\n            let marks = $context.marks();\n            let { schema } = view.state, serializer = DOMSerializer.fromSchema(schema);\n            dom = document.createElement(\"div\");\n            text.split(/(?:\\r\\n?|\\n)+/).forEach(block => {\n                let p = dom.appendChild(document.createElement(\"p\"));\n                if (block)\n                    p.appendChild(serializer.serializeNode(schema.text(block, marks)));\n            });\n        }\n    }\n    else {\n        view.someProp(\"transformPastedHTML\", f => { html = f(html, view); });\n        dom = readHTML(html);\n        if (webkit)\n            restoreReplacedSpaces(dom);\n    }\n    let contextNode = dom && dom.querySelector(\"[data-pm-slice]\");\n    let sliceData = contextNode && /^(\\d+) (\\d+)(?: -(\\d+))? (.*)/.exec(contextNode.getAttribute(\"data-pm-slice\") || \"\");\n    if (sliceData && sliceData[3])\n        for (let i = +sliceData[3]; i > 0; i--) {\n            let child = dom.firstChild;\n            while (child && !isElt(child))\n                child = child.nextSibling;\n            if (!child)\n                break;\n            dom = child;\n        }\n    if (!slice) {\n        let parser = view.someProp(\"clipboardParser\") || view.someProp(\"domParser\") || DOMParser.fromSchema(view.state.schema);\n        slice = parser.parseSlice(dom, {\n            preserveWhitespace: !!(asText || sliceData),\n            context: $context,\n            ruleFromNode(dom) {\n                if (dom.nodeName == \"BR\" && !dom.nextSibling &&\n                    dom.parentNode && !inlineParents.test(dom.parentNode.nodeName))\n                    return { ignore: true };\n                return null;\n            }\n        });\n    }\n    if (sliceData) {\n        slice = addContext(closeSlice(slice, +sliceData[1], +sliceData[2]), sliceData[4]);\n    }\n    else { // HTML wasn't created by ProseMirror. Make sure top-level siblings are coherent\n        slice = Slice.maxOpen(normalizeSiblings(slice.content, $context), true);\n        if (slice.openStart || slice.openEnd) {\n            let openStart = 0, openEnd = 0;\n            for (let node = slice.content.firstChild; openStart < slice.openStart && !node.type.spec.isolating; openStart++, node = node.firstChild) { }\n            for (let node = slice.content.lastChild; openEnd < slice.openEnd && !node.type.spec.isolating; openEnd++, node = node.lastChild) { }\n            slice = closeSlice(slice, openStart, openEnd);\n        }\n    }\n    view.someProp(\"transformPasted\", f => { slice = f(slice, view, plainText); });\n    return slice;\n}\nconst inlineParents = /^(a|abbr|acronym|b|cite|code|del|em|i|ins|kbd|label|output|q|ruby|s|samp|span|strong|sub|sup|time|u|tt|var)$/i;\n// Takes a slice parsed with parseSlice, which means there hasn't been\n// any content-expression checking done on the top nodes, tries to\n// find a parent node in the current context that might fit the nodes,\n// and if successful, rebuilds the slice so that it fits into that parent.\n//\n// This addresses the problem that Transform.replace expects a\n// coherent slice, and will fail to place a set of siblings that don't\n// fit anywhere in the schema.\nfunction normalizeSiblings(fragment, $context) {\n    if (fragment.childCount < 2)\n        return fragment;\n    for (let d = $context.depth; d >= 0; d--) {\n        let parent = $context.node(d);\n        let match = parent.contentMatchAt($context.index(d));\n        let lastWrap, result = [];\n        fragment.forEach(node => {\n            if (!result)\n                return;\n            let wrap = match.findWrapping(node.type), inLast;\n            if (!wrap)\n                return result = null;\n            if (inLast = result.length && lastWrap.length && addToSibling(wrap, lastWrap, node, result[result.length - 1], 0)) {\n                result[result.length - 1] = inLast;\n            }\n            else {\n                if (result.length)\n                    result[result.length - 1] = closeRight(result[result.length - 1], lastWrap.length);\n                let wrapped = withWrappers(node, wrap);\n                result.push(wrapped);\n                match = match.matchType(wrapped.type);\n                lastWrap = wrap;\n            }\n        });\n        if (result)\n            return Fragment.from(result);\n    }\n    return fragment;\n}\nfunction withWrappers(node, wrap, from = 0) {\n    for (let i = wrap.length - 1; i >= from; i--)\n        node = wrap[i].create(null, Fragment.from(node));\n    return node;\n}\n// Used to group adjacent nodes wrapped in similar parents by\n// normalizeSiblings into the same parent node\nfunction addToSibling(wrap, lastWrap, node, sibling, depth) {\n    if (depth < wrap.length && depth < lastWrap.length && wrap[depth] == lastWrap[depth]) {\n        let inner = addToSibling(wrap, lastWrap, node, sibling.lastChild, depth + 1);\n        if (inner)\n            return sibling.copy(sibling.content.replaceChild(sibling.childCount - 1, inner));\n        let match = sibling.contentMatchAt(sibling.childCount);\n        if (match.matchType(depth == wrap.length - 1 ? node.type : wrap[depth + 1]))\n            return sibling.copy(sibling.content.append(Fragment.from(withWrappers(node, wrap, depth + 1))));\n    }\n}\nfunction closeRight(node, depth) {\n    if (depth == 0)\n        return node;\n    let fragment = node.content.replaceChild(node.childCount - 1, closeRight(node.lastChild, depth - 1));\n    let fill = node.contentMatchAt(node.childCount).fillBefore(Fragment.empty, true);\n    return node.copy(fragment.append(fill));\n}\nfunction closeRange(fragment, side, from, to, depth, openEnd) {\n    let node = side < 0 ? fragment.firstChild : fragment.lastChild, inner = node.content;\n    if (fragment.childCount > 1)\n        openEnd = 0;\n    if (depth < to - 1)\n        inner = closeRange(inner, side, from, to, depth + 1, openEnd);\n    if (depth >= from)\n        inner = side < 0 ? node.contentMatchAt(0).fillBefore(inner, openEnd <= depth).append(inner)\n            : inner.append(node.contentMatchAt(node.childCount).fillBefore(Fragment.empty, true));\n    return fragment.replaceChild(side < 0 ? 0 : fragment.childCount - 1, node.copy(inner));\n}\nfunction closeSlice(slice, openStart, openEnd) {\n    if (openStart < slice.openStart)\n        slice = new Slice(closeRange(slice.content, -1, openStart, slice.openStart, 0, slice.openEnd), openStart, slice.openEnd);\n    if (openEnd < slice.openEnd)\n        slice = new Slice(closeRange(slice.content, 1, openEnd, slice.openEnd, 0, 0), slice.openStart, openEnd);\n    return slice;\n}\n// Trick from jQuery -- some elements must be wrapped in other\n// elements for innerHTML to work. I.e. if you do `div.innerHTML =\n// \"<td>..</td>\"` the table cells are ignored.\nconst wrapMap = {\n    thead: [\"table\"],\n    tbody: [\"table\"],\n    tfoot: [\"table\"],\n    caption: [\"table\"],\n    colgroup: [\"table\"],\n    col: [\"table\", \"colgroup\"],\n    tr: [\"table\", \"tbody\"],\n    td: [\"table\", \"tbody\", \"tr\"],\n    th: [\"table\", \"tbody\", \"tr\"]\n};\nfunction detachedDoc() {\n    return document.implementation.createHTMLDocument(\"title\");\n}\nlet _policy = null;\nfunction maybeWrapTrusted(html) {\n    let trustedTypes = window.trustedTypes;\n    if (!trustedTypes)\n        return html;\n    // With the require-trusted-types-for CSP, Chrome will block\n    // innerHTML, even on a detached document. This wraps the string in\n    // a way that makes the browser allow us to use its parser again.\n    if (!_policy) {\n        if (_policy = trustedTypes.defaultPolicy)\n            try {\n                return _policy.createHTML(html);\n            }\n            catch (_a) { }\n        _policy = trustedTypes.createPolicy(\"ProseMirrorClipboard\", { createHTML: (s) => s });\n    }\n    return _policy.createHTML(html);\n}\nfunction readHTML(html) {\n    let metas = /^(\\s*<meta [^>]*>)*/.exec(html);\n    if (metas)\n        html = html.slice(metas[0].length);\n    let doc = detachedDoc(), elt = doc.body;\n    let firstTag = /<([a-z][^>\\s]+)/i.exec(html), wrap;\n    if (wrap = firstTag && wrapMap[firstTag[1].toLowerCase()])\n        html = wrap.map(n => \"<\" + n + \">\").join(\"\") + html + wrap.map(n => \"</\" + n + \">\").reverse().join(\"\");\n    elt.innerHTML = maybeWrapTrusted(html);\n    if (wrap)\n        for (let i = 0; i < wrap.length; i++)\n            elt = elt.querySelector(wrap[i]) || elt;\n    // Inline styles defined in the pasted content, so that parse rules pick them up\n    for (let i = 0; i < doc.styleSheets.length; i++) {\n        let style = doc.styleSheets[i];\n        for (let j = 0; j < style.rules.length; j++) {\n            let rule = style.rules[j];\n            if (rule instanceof CSSStyleRule) {\n                let matches = elt.querySelectorAll(rule.selectorText);\n                for (let k = 0; k < matches.length; k++)\n                    matches[k].style.cssText += rule.style.cssText;\n            }\n        }\n    }\n    return elt;\n}\n// Webkit browsers do some hard-to-predict replacement of regular\n// spaces with non-breaking spaces when putting content on the\n// clipboard. This tries to convert such non-breaking spaces (which\n// will be wrapped in a plain span on Chrome, a span with class\n// Apple-converted-space on Safari) back to regular spaces.\nfunction restoreReplacedSpaces(dom) {\n    let nodes = dom.querySelectorAll(chrome ? \"span:not([class]):not([style])\" : \"span.Apple-converted-space\");\n    for (let i = 0; i < nodes.length; i++) {\n        let node = nodes[i];\n        if (node.childNodes.length == 1 && node.textContent == \"\\u00a0\" && node.parentNode)\n            node.parentNode.replaceChild(dom.ownerDocument.createTextNode(\" \"), node);\n    }\n}\nfunction addContext(slice, context) {\n    if (!slice.size)\n        return slice;\n    let schema = slice.content.firstChild.type.schema, array;\n    try {\n        array = JSON.parse(context);\n    }\n    catch (e) {\n        return slice;\n    }\n    let { content, openStart, openEnd } = slice;\n    for (let i = array.length - 2; i >= 0; i -= 2) {\n        let type = schema.nodes[array[i]];\n        if (!type || type.hasRequiredAttrs() || !type.createAndFill(null, content))\n            break;\n        try {\n            content = Fragment.from(type.create(array[i + 1], content));\n        }\n        catch (e) {\n            break;\n        }\n        openStart++;\n        openEnd++;\n    }\n    return new Slice(content, openStart, openEnd);\n}\n\nclass StoredDOMSel {\n    constructor(anchorNode, anchorOffset, focusNode, focusOffset) {\n        this.anchorNode = anchorNode;\n        this.anchorOffset = anchorOffset;\n        this.focusNode = focusNode;\n        this.focusOffset = focusOffset;\n    }\n    static from(range) {\n        if (range instanceof StoredDOMSel)\n            return range;\n        return new StoredDOMSel(range.anchorNode, range.anchorOffset, range.focusNode, range.focusOffset);\n    }\n    eq(sel) {\n        return sel.anchorNode == this.anchorNode && sel.anchorOffset == this.anchorOffset &&\n            sel.focusNode == this.focusNode && sel.focusOffset == this.focusOffset;\n    }\n}\nStoredDOMSel.null = new StoredDOMSel(null, 0, null, 0);\n// Tracks the relation between the DOM selection and the editor state\n// selection. Caches the current selection range for cheap access.\n//\n// Will read the DOM selection state on selectionchange events and\n// when explicitly synced. Not guaranteed to hold the _current_ DOM\n// selection unless you are on a code path where you know it was\n// synced. So for one-off event handlers, it's safer to use\n// `domSel.readRange()` (fetches the range from the DOM), whereas in\n// things like the DOM flush logic, `domSel.range` is safe and cheap\n// to use.\nclass DOMSelState {\n    constructor(view) {\n        this.view = view;\n        // The last read selection range. Updated by `read`, `sync`,\n        // `ignore`, and `clear`. Only means anything when `active` is true.\n        this.range = StoredDOMSel.null;\n        // Indicates whether the editor has focus and selection\n        this.active = false;\n        // True when we are active and the current range has been synced\n        // with the state selection\n        this.synced = false;\n        this.suppress = false;\n        this.currentDocument = null;\n        this.onSelectionChange = this.onSelectionChange.bind(this);\n    }\n    ensureListener() {\n        let doc = this.view.dom.ownerDocument;\n        if (doc != this.currentDocument) {\n            if (this.currentDocument)\n                this.currentDocument.removeEventListener(\"selectionchange\", this.onSelectionChange);\n            this.currentDocument = doc;\n            doc.addEventListener(\"selectionchange\", this.onSelectionChange);\n        }\n    }\n    destroy() {\n        if (this.currentDocument) {\n            this.currentDocument.removeEventListener(\"selectionchange\", this.onSelectionChange);\n            this.currentDocument = null;\n        }\n        this.active = false;\n        this.range = StoredDOMSel.null;\n    }\n    suppressChanges() {\n        this.suppress = true;\n        setTimeout(() => this.suppress = false, 50);\n    }\n    onSelectionChange() {\n        if (this.suppress && this.view.hasFocus())\n            return this.sync();\n        if (this.read())\n            this.view.domObserver.flush(false);\n    }\n    // Reads the active range from the DOM, if any.\n    readRange() {\n        let { view } = this;\n        let sel = view.dom.isConnected !== false && view.domSelection();\n        if (!sel)\n            return StoredDOMSel.null;\n        if (safari && view.root.nodeType === 11 && deepActiveElement(view.dom.ownerDocument) == view.dom)\n            return StoredDOMSel.from(safariShadowSelectionRange(view, sel) || sel);\n        return StoredDOMSel.from(sel);\n    }\n    read() {\n        this.ensureListener();\n        let sel = hasFocusAndSelection(this.view);\n        if (!sel) {\n            this.active = false;\n            this.range = StoredDOMSel.null;\n            return;\n        }\n        this.active = true;\n        if (this.range.eq(sel))\n            return false;\n        this.range = sel;\n        this.synced = false;\n        return true;\n    }\n    // Sync the DOM selection to the state selection\n    sync(force = false) {\n        let { view } = this;\n        if (!view.docView)\n            return;\n        this.ensureListener();\n        view.domObserver.stopped(() => {\n            syncNodeSelection(view, view.state.selection);\n            let sel = view.state.selection;\n            if (view.input.mouseSelecting || editorOwnsSelection(view)) {\n                let { desc, start } = innerViewDesc(view.docView, sel.from, sel.to, 0);\n                if (view.cursorWrapper) {\n                    selectCursorWrapper(view);\n                }\n                else if (desc instanceof CustomNodeViewDesc && desc.spec.setSelection) {\n                    desc.spec.setSelection(sel.anchor - start, sel.head - start, view.root);\n                }\n                else {\n                    selectionToDOM(view, force, desc, start);\n                }\n                this.synced = this.active = true;\n            }\n            if (sel.visible == view.dom.classList.contains(\"ProseMirror-hideselection\")) {\n                if (sel.visible) {\n                    view.dom.classList.remove(\"ProseMirror-hideselection\");\n                }\n                else {\n                    view.dom.classList.add(\"ProseMirror-hideselection\");\n                    removeClassOnSelectionChange(view);\n                }\n            }\n            this.range = this.readRange();\n        });\n    }\n    ignore(sel = this.readRange()) {\n        this.range = StoredDOMSel.from(sel);\n        this.synced = true;\n    }\n    // Called when the editor is blurred\n    deactivate() {\n        this.range = StoredDOMSel.null;\n        this.active = this.synced = false;\n    }\n}\n// Used to work around the fact that is is rather hard to get the\n// selection in a shadow root in Safari.\nfunction safariShadowSelectionRange(view, selection) {\n    if (selection.getComposedRanges) {\n        let range = selection.getComposedRanges({ shadowRoots: [view.root] })[0];\n        if (range)\n            return rangeToSelectionRange(view, range);\n    }\n    let found;\n    function read(event) {\n        event.preventDefault();\n        event.stopImmediatePropagation();\n        found = event.getTargetRanges()[0];\n    }\n    // Because Safari (at least in 2018-2022) doesn't provide regular\n    // access to the selection inside a shadowRoot, we have to perform a\n    // ridiculous hack to get at it\u2014using `execCommand` to trigger a\n    // `beforeInput` event so that we can read the target range from the\n    // event.\n    view.dom.addEventListener(\"beforeinput\", read, true);\n    document.execCommand(\"indent\");\n    view.dom.removeEventListener(\"beforeinput\", read, true);\n    return found ? rangeToSelectionRange(view, found) : null;\n}\nfunction rangeToSelectionRange(view, range) {\n    let anchorNode = range.startContainer, anchorOffset = range.startOffset;\n    let focusNode = range.endContainer, focusOffset = range.endOffset;\n    let currentAnchor = view.domAtPos(view.state.selection.anchor);\n    // Since such a range doesn't distinguish between anchor and head,\n    // use a heuristic that flips it around if its end matches the\n    // current anchor.\n    if (isEquivalentPosition(currentAnchor.node, currentAnchor.offset, focusNode, focusOffset))\n        [anchorNode, anchorOffset, focusNode, focusOffset] = [focusNode, focusOffset, anchorNode, anchorOffset];\n    return new StoredDOMSel(anchorNode, anchorOffset, focusNode, focusOffset);\n}\nfunction selectionFromDOM(view, domSel, origin = null) {\n    let doc = view.state.doc;\n    if (!domSel.focusNode)\n        return null;\n    let nearestDesc = view.docView.nearestDesc(domSel.focusNode), inWidget = nearestDesc && nearestDesc.size == 0;\n    let head = view.docView.posFromDOM(domSel.focusNode, domSel.focusOffset, 1);\n    if (head < 0)\n        return null;\n    let $head = doc.resolve(head), anchor, selection;\n    if (selectionCollapsed(domSel)) {\n        anchor = head;\n        while (nearestDesc && !nearestDesc.node)\n            nearestDesc = nearestDesc.parent;\n        if (nearestDesc && nearestDesc.node.isAtom && NodeSelection.isSelectable(nearestDesc.node) &&\n            nearestDesc.parent &&\n            !(nearestDesc.node.isInline && isOnEdge(domSel.focusNode, domSel.focusOffset, nearestDesc.dom))) {\n            let pos = nearestDesc.posBefore;\n            selection = new NodeSelection(head == pos ? $head : doc.resolve(pos));\n        }\n        else if (gecko && origin == \"key\" && head > view.state.selection.to &&\n            isElt(domSel.focusNode) && domSel.focusOffset == domSel.focusNode.childNodes.length &&\n            nearestDesc && nearestDesc.posAtStart > view.state.selection.to) {\n            // Firefox will jump across scrollable wrapper nodes on keyboard\n            // cursor motion (#1594). This tries to detect this situation\n            // and work around it.\n            for (let scan = domSel.focusNode;; scan = scan.parentNode) {\n                if (getComputedStyle(scan).overflow != \"visible\") {\n                    selection = Selection.findFrom(doc.resolve(nearestDesc.posAtStart), 1);\n                    break;\n                }\n                if (scan == nearestDesc.dom || scan.nextSibling || !scan.parentNode || !isElt(scan.parentNode))\n                    break;\n            }\n        }\n    }\n    else {\n        if (domSel instanceof view.dom.ownerDocument.defaultView.Selection && domSel.rangeCount > 1) {\n            let min = head, max = head;\n            for (let i = 0; i < domSel.rangeCount; i++) {\n                let range = domSel.getRangeAt(i);\n                min = Math.min(min, view.docView.posFromDOM(range.startContainer, range.startOffset, 1));\n                max = Math.max(max, view.docView.posFromDOM(range.endContainer, range.endOffset, -1));\n            }\n            if (min < 0)\n                return null;\n            [anchor, head] = max == view.state.selection.anchor ? [max, min] : [min, max];\n            $head = doc.resolve(head);\n        }\n        else {\n            anchor = view.docView.posFromDOM(domSel.anchorNode, domSel.anchorOffset, 1);\n        }\n        if (anchor < 0)\n            return null;\n    }\n    let $anchor = doc.resolve(anchor);\n    if (!selection) {\n        let bias = origin == \"pointer\" || (view.state.selection.head < $head.pos && !inWidget) ? 1 : -1;\n        selection = selectionBetween(view, $anchor, $head, bias);\n    }\n    return selection;\n}\nfunction editorOwnsSelection(view) {\n    return view.editable ? view.hasFocus() :\n        hasSelection(view, view.domSel.readRange()) && (!document.activeElement || document.activeElement.contains(view.dom));\n}\nfunction selectionToDOM(view, force, desc, start) {\n    let sel = view.state.selection;\n    let { anchor, head } = sel, resetEditableFrom, resetEditableTo;\n    if (brokenSelectBetweenUneditable && !(sel instanceof TextSelection)) {\n        if (!sel.$from.parent.inlineContent)\n            resetEditableFrom = temporarilyEditableNear(view, sel.from);\n        if (!sel.empty && !sel.$from.parent.inlineContent)\n            resetEditableTo = temporarilyEditableNear(view, sel.to);\n    }\n    let anchorDOM = desc.domFromPos(anchor - start, anchor > start ? -1 : 1);\n    let headDOM = head == anchor ? anchorDOM : desc.domFromPos(head - start, head > start ? -1 : 1);\n    setSelection(anchor, head, anchorDOM, headDOM, view, force);\n    if (brokenSelectBetweenUneditable) {\n        if (resetEditableFrom)\n            resetEditable(resetEditableFrom);\n        if (resetEditableTo)\n            resetEditable(resetEditableTo);\n    }\n}\n// See if the selection falls within a custom node view that overrides it\nfunction innerViewDesc(desc, from, to, start = 0) {\n    for (let i = 0, off = start; i < desc.children.length; i++) {\n        let child = desc.children[i], end = off + child.size;\n        if (from > off && to < end)\n            return innerViewDesc(child, from, to, off + child.border);\n        off = end;\n    }\n    return { desc, start };\n}\nfunction setSelection(anchor, head, anchorDOM, headDOM, view, force) {\n    let brKludge = false;\n    // On Firefox, using Selection.collapse to put the cursor after a\n    // BR node for some reason doesn't always work (#1073). On Safari,\n    // the cursor sometimes inexplicable visually lags behind its\n    // reported position in such situations (#1092).\n    if ((gecko || safari) && anchor == head) {\n        let { node, offset } = anchorDOM;\n        if (isText(node)) {\n            brKludge = !!(offset && node.nodeValue[offset - 1] == \"\\n\");\n            // Issue #1128\n            if (brKludge && offset == node.nodeValue.length) {\n                for (let scan = node, after; scan; scan = scan.parentNode) {\n                    if (after = scan.nextSibling) {\n                        if (after.nodeName == \"BR\")\n                            anchorDOM = headDOM = { node: after.parentNode, offset: domIndex(after) + 1 };\n                        break;\n                    }\n                    let desc = scan.pmViewDesc;\n                    if (desc && desc.node && desc.node.isBlock)\n                        break;\n                }\n            }\n        }\n        else {\n            let prev = node.childNodes[offset - 1];\n            brKludge = prev && (prev.nodeName == \"BR\" || prev.contentEditable == \"false\");\n        }\n    }\n    let selRange = view.domSel.readRange();\n    // Firefox can act strangely when the selection is in front of an\n    // uneditable node. See #1163 and https://bugzilla.mozilla.org/show_bug.cgi?id=1709536\n    if (gecko && selRange.focusNode && selRange.focusNode != headDOM.node && isElt(selRange.focusNode)) {\n        let after = selRange.focusNode.childNodes[selRange.focusOffset];\n        if (after && after.contentEditable == \"false\")\n            force = true;\n    }\n    if (!(force || brKludge && safari) &&\n        isEquivalentPosition(anchorDOM.node, anchorDOM.offset, selRange.anchorNode, selRange.anchorOffset) &&\n        isEquivalentPosition(headDOM.node, headDOM.offset, selRange.focusNode, selRange.focusOffset))\n        return;\n    let domSel = view.domSelection(), mouse = view.input.mouseSelecting;\n    if (mouse && mouse.affinity && anchor == head && mouse.pos == anchor) {\n        let { affinity } = mouse;\n        // Kludge to set DOM selection affinity on line boundaries: put the\n        // selection to the side of the target position, and then move it\n        // back with Selection.modify and see if it lands in the right spot.\n        let { node, offset } = headDOM, targetNode, targetOffset = 0;\n        if (isText(node) && (affinity > 0 ? offset < nodeSize(node) : offset > 0)) {\n            targetNode = node;\n            targetOffset = offset + affinity;\n        }\n        else {\n            targetNode = (affinity > 0 ? textNodeAfter : textNodeBefore)(node, offset);\n            if (targetNode)\n                targetOffset = affinity > 0 ? 1 : targetNode.nodeValue.length - 1;\n        }\n        if (targetNode) {\n            domSel.collapse(targetNode, targetOffset);\n            domSel.modify(\"move\", affinity > 0 ? \"backward\" : \"forward\", \"lineboundary\");\n            let { focusNode, focusOffset } = domSel;\n            if (safari && view.root.nodeType == 11) {\n                let ranges = domSel.getComposedRanges({ shadowRoots: [view.root] });\n                if (ranges.length) {\n                    focusNode = ranges[0].startContainer;\n                    focusOffset = ranges[0].startOffset;\n                }\n            }\n            if (isEquivalentPosition(node, offset, focusNode, focusOffset))\n                return;\n        }\n    }\n    writeSelection(domSel, {\n        focusNode: headDOM.node, focusOffset: headDOM.offset,\n        anchorNode: anchorDOM.node, anchorOffset: anchorDOM.offset\n    });\n}\n// Kludge to work around Webkit not allowing a selection to start/end\n// between non-editable block nodes. We briefly make something\n// editable, set the selection, then set it uneditable again.\nconst brokenSelectBetweenUneditable = safari || chrome && chrome_version < 63;\nfunction temporarilyEditableNear(view, pos) {\n    let { node, offset } = view.docView.domFromPos(pos, 0);\n    let after = offset < node.childNodes.length ? node.childNodes[offset] : null;\n    let before = offset ? node.childNodes[offset - 1] : null;\n    if (safari && after && after.contentEditable == \"false\")\n        return setEditable(after);\n    if ((!after || after.contentEditable == \"false\") &&\n        (!before || before.contentEditable == \"false\")) {\n        if (after)\n            return setEditable(after);\n        else if (before)\n            return setEditable(before);\n    }\n}\nfunction setEditable(element) {\n    element.contentEditable = \"true\";\n    if (safari && element.draggable) {\n        element.draggable = false;\n        element.wasDraggable = true;\n    }\n    return element;\n}\nfunction resetEditable(element) {\n    element.contentEditable = \"false\";\n    if (element.wasDraggable) {\n        element.draggable = true;\n        element.wasDraggable = null;\n    }\n}\nfunction removeClassOnSelectionChange(view) {\n    let doc = view.dom.ownerDocument;\n    doc.removeEventListener(\"selectionchange\", view.input.hideSelectionGuard);\n    let domSel = view.domSel.readRange();\n    let node = domSel.anchorNode, offset = domSel.anchorOffset;\n    doc.addEventListener(\"selectionchange\", view.input.hideSelectionGuard = () => {\n        if (domSel.anchorNode != node || domSel.anchorOffset != offset) {\n            doc.removeEventListener(\"selectionchange\", view.input.hideSelectionGuard);\n            setTimeout(() => {\n                if (!editorOwnsSelection(view) || view.state.selection.visible)\n                    view.dom.classList.remove(\"ProseMirror-hideselection\");\n            }, 20);\n        }\n    });\n}\nfunction selectCursorWrapper(view) {\n    let domSel = view.domSelection();\n    if (!domSel)\n        return;\n    let node = view.cursorWrapper.dom, img = node.nodeName == \"IMG\";\n    if (img)\n        domSel.collapse(node.parentNode, domIndex(node) + 1);\n    else\n        domSel.collapse(node, 0);\n}\nfunction syncNodeSelection(view, sel) {\n    if (sel instanceof NodeSelection) {\n        let desc = view.docView.descAt(sel.from);\n        if (desc != view.lastSelectedViewDesc) {\n            clearNodeSelection(view);\n            if (desc)\n                desc.selectNode();\n            view.lastSelectedViewDesc = desc;\n        }\n    }\n    else {\n        clearNodeSelection(view);\n    }\n}\n// Clear all DOM statefulness of the last node selection.\nfunction clearNodeSelection(view) {\n    if (view.lastSelectedViewDesc) {\n        if (view.lastSelectedViewDesc.parent)\n            view.lastSelectedViewDesc.deselectNode();\n        view.lastSelectedViewDesc = undefined;\n    }\n}\nfunction selectionBetween(view, $anchor, $head, bias) {\n    let sel = view.someProp(\"createSelectionBetween\", f => f(view, $anchor, $head))\n        || TextSelection.between($anchor, $head, bias);\n    view.someProp(\"adjustSelectionFromDOM\", f => { sel = f(view, sel); });\n    return sel;\n}\nfunction hasFocusAndSelection(view) {\n    if (view.editable && !view.hasFocus())\n        return null;\n    let sel = view.domSel.readRange();\n    return sel && hasSelection(view, sel) ? sel : null;\n}\nfunction hasSelection(view, sel) {\n    if (!sel.anchorNode)\n        return false;\n    try {\n        // Firefox will raise 'permission denied' errors when accessing\n        // properties of `sel.anchorNode` when it's in a generated CSS\n        // element.\n        return contains(view.dom, sel.anchorNode) && (view.editable || contains(view.dom, sel.focusNode));\n    }\n    catch (_) {\n        return false;\n    }\n}\n\n// A collection of DOM events that occur within the editor, and callback functions\n// to invoke when the event fires.\nconst handlers = {};\nconst editHandlers = {};\nconst passiveHandlers = { touchstart: true, touchmove: true };\nclass InputState {\n    constructor() {\n        this.shiftKey = false;\n        this.mouseDown = null;\n        this.lastKeyCode = null;\n        this.lastKeyCodeTime = 0;\n        this.lastKeyDispatched = false;\n        this.lastClick = { time: 0, x: 0, y: 0, type: \"\", button: 0 };\n        this.lastSelectionOrigin = null;\n        this.lastSelectionTime = 0;\n        this.lastIOSEnter = 0;\n        this.lastIOSEnterFallbackTimeout = -1;\n        this.lastFocus = 0;\n        this.lastTouch = 0;\n        this.lastChromeDelete = 0;\n        this.composing = false;\n        this.compositionNode = null;\n        this.composingTimeout = -1;\n        this.compositionNodes = [];\n        this.compositionEndedAt = -2e8;\n        this.compositionID = 1;\n        // Set during a selection change originated by mouse handling\n        this.mouseSelecting = null;\n        this.badSafariComposition = false;\n        // Set to a composition ID when there are pending changes at compositionend\n        this.compositionPendingChanges = 0;\n        this.domChangeCount = 0;\n        this.eventHandlers = Object.create(null);\n        this.hideSelectionGuard = null;\n    }\n}\nfunction initInput(view) {\n    for (let event in handlers) {\n        let handler = handlers[event];\n        view.dom.addEventListener(event, view.input.eventHandlers[event] = (event) => {\n            if (!eventBelongsToView(view, event))\n                return;\n            if (view.input.composing && (event.type == \"keydown\" || event.type == \"beforeinput\") &&\n                event.isComposing === false)\n                leaveComposition(view, true);\n            if (!runCustomHandler(view, event) && (view.editable || !(event.type in editHandlers)))\n                handler(view, event);\n        }, passiveHandlers[event] ? { passive: true } : undefined);\n    }\n    // On Safari, for reasons beyond my understanding, adding an input\n    // event handler makes an issue where the composition vanishes when\n    // you press enter go away.\n    if (safari)\n        view.dom.addEventListener(\"input\", () => null);\n    ensureListeners(view);\n}\nfunction setSelectionOrigin(view, origin) {\n    view.input.lastSelectionOrigin = origin;\n    view.input.lastSelectionTime = Date.now();\n}\nfunction destroyInput(view) {\n    if (view.input.mouseDown)\n        view.input.mouseDown.done();\n    view.domObserver.stop();\n    for (let type in view.input.eventHandlers)\n        view.dom.removeEventListener(type, view.input.eventHandlers[type]);\n    clearTimeout(view.input.composingTimeout);\n    clearTimeout(view.input.lastIOSEnterFallbackTimeout);\n}\nfunction ensureListeners(view) {\n    view.someProp(\"handleDOMEvents\", currentHandlers => {\n        for (let type in currentHandlers)\n            if (!view.input.eventHandlers[type])\n                view.dom.addEventListener(type, view.input.eventHandlers[type] = event => runCustomHandler(view, event));\n    });\n}\nfunction runCustomHandler(view, event) {\n    return view.someProp(\"handleDOMEvents\", handlers => {\n        let handler = handlers[event.type];\n        return handler ? handler(view, event) || event.defaultPrevented : false;\n    });\n}\nfunction eventBelongsToView(view, event) {\n    if (!event.bubbles)\n        return true;\n    if (event.defaultPrevented)\n        return false;\n    for (let node = event.target; node != view.dom; node = node.parentNode)\n        if (!node || node.nodeType == 11 ||\n            (node.pmViewDesc && node.pmViewDesc.stopEvent(event)))\n            return false;\n    return true;\n}\nfunction dispatchEvent(view, event) {\n    if (!runCustomHandler(view, event) && handlers[event.type] &&\n        (view.editable || !(event.type in editHandlers)))\n        handlers[event.type](view, event);\n}\nfunction dispatchKey(view, event) {\n    let { input } = view;\n    if (input.lastKeyDispatched || view.composing)\n        return false;\n    input.lastKeyDispatched = true;\n    if (typeof event == \"string\")\n        event = keyEvent(event == \"Backspace\" ? 8 : 13, event);\n    return view.someProp(\"handleKeyDown\", f => f(view, event));\n}\neditHandlers.keydown = (view, _event) => {\n    let event = _event;\n    view.input.shiftKey = event.keyCode == 16 || event.shiftKey;\n    view.input.lastKeyCode = event.keyCode;\n    view.input.lastKeyCodeTime = Date.now();\n    view.input.lastKeyDispatched = false;\n    // Suppress enter key events on Chrome Android, because those tend\n    // to be part of a confused sequence of composition events fired,\n    // and handling them eagerly tends to corrupt the input.\n    if (android && chrome && event.keyCode == 13)\n        return;\n    // On iOS, if we preventDefault enter key presses, the virtual\n    // keyboard gets confused. So the hack here is to set a flag that\n    // makes the DOM change code recognize that what just happens should\n    // be replaced by whatever the Enter key handlers do.\n    if (ios && event.keyCode == 13 && !event.ctrlKey && !event.altKey && !event.metaKey) {\n        let now = Date.now();\n        view.input.lastIOSEnter = now;\n        view.input.lastIOSEnterFallbackTimeout = setTimeout(() => {\n            if (view.input.lastIOSEnter == now) {\n                dispatchKey(view, \"Enter\");\n                view.input.lastIOSEnter = 0;\n            }\n        }, 200);\n        return;\n    }\n    if (event.keyCode != 229)\n        view.domObserver.forceFlush(true);\n    if (dispatchKey(view, event) || captureKeyDown(view, event))\n        event.preventDefault();\n    else\n        setSelectionOrigin(view, \"key\");\n};\neditHandlers.keyup = (view, event) => {\n    if (event.keyCode == 16)\n        view.input.shiftKey = false;\n};\neditHandlers.keypress = (view, _event) => {\n    let event = _event;\n    if (inOrNearComposition(view) || !event.charCode ||\n        event.ctrlKey && !event.altKey || mac && event.metaKey)\n        return;\n    if (view.someProp(\"handleKeyPress\", f => f(view, event))) {\n        event.preventDefault();\n        return;\n    }\n    let sel = view.state.selection;\n    if (!(sel instanceof TextSelection) || !sel.$from.sameParent(sel.$to)) {\n        let text = String.fromCharCode(event.charCode);\n        let deflt = () => view.state.tr.insertText(text).scrollIntoView();\n        if (!/[\\r\\n]/.test(text) && !view.someProp(\"handleTextInput\", f => f(view, sel.$from.pos, sel.$to.pos, text, deflt)))\n            view.dispatch(deflt());\n        event.preventDefault();\n    }\n};\nfunction eventCoords(event) { return { left: event.clientX, top: event.clientY }; }\nfunction isNear(event, click) {\n    let dx = click.x - event.clientX, dy = click.y - event.clientY;\n    return dx * dx + dy * dy < 100;\n}\nfunction runHandlerOnContext(view, propName, pos, inside, event) {\n    if (inside == -1)\n        return false;\n    let $pos = view.state.doc.resolve(inside);\n    for (let i = $pos.depth + 1; i > 0; i--) {\n        if (view.someProp(propName, f => i > $pos.depth ? f(view, pos, $pos.nodeAfter, $pos.before(i), event, true)\n            : f(view, pos, $pos.node(i), $pos.before(i), event, false)))\n            return true;\n    }\n    return false;\n}\nfunction updateSelection(view, selection, origin) {\n    if (!view.focused)\n        view.focus();\n    if (view.state.selection.eq(selection))\n        return;\n    let tr = view.state.tr.setSelection(selection);\n    tr.setMeta(\"pointer\", true);\n    view.dispatch(tr);\n}\nfunction selectClickedLeaf(view, inside) {\n    if (inside == -1)\n        return false;\n    let $pos = view.state.doc.resolve(inside), node = $pos.nodeAfter;\n    if (node && node.isAtom && NodeSelection.isSelectable(node)) {\n        updateSelection(view, new NodeSelection($pos));\n        return true;\n    }\n    return false;\n}\nfunction selectClickedNode(view, inside) {\n    if (inside == -1)\n        return false;\n    let sel = view.state.selection, selectedNode, selectAt;\n    if (sel instanceof NodeSelection)\n        selectedNode = sel.node;\n    let $pos = view.state.doc.resolve(inside);\n    for (let i = $pos.depth + 1; i > 0; i--) {\n        let node = i > $pos.depth ? $pos.nodeAfter : $pos.node(i);\n        if (NodeSelection.isSelectable(node)) {\n            if (selectedNode && sel.$from.depth > 0 &&\n                i >= sel.$from.depth && $pos.before(sel.$from.depth + 1) == sel.$from.pos)\n                selectAt = $pos.before(sel.$from.depth);\n            else\n                selectAt = $pos.before(i);\n            break;\n        }\n    }\n    if (selectAt != null) {\n        updateSelection(view, NodeSelection.create(view.state.doc, selectAt));\n        return true;\n    }\n    else {\n        return false;\n    }\n}\nfunction handleSingleClick(view, pos, inside, event, selectNode) {\n    return runHandlerOnContext(view, \"handleClickOn\", pos, inside, event) ||\n        view.someProp(\"handleClick\", f => f(view, pos, event)) ||\n        (selectNode ? selectClickedNode(view, inside) : selectClickedLeaf(view, inside));\n}\nfunction handleDoubleClick(view, pos, inside, event) {\n    return runHandlerOnContext(view, \"handleDoubleClickOn\", pos, inside, event) ||\n        view.someProp(\"handleDoubleClick\", f => f(view, pos, event));\n}\nfunction handleTripleClick(view, pos, inside, event) {\n    return runHandlerOnContext(view, \"handleTripleClickOn\", pos, inside, event) ||\n        view.someProp(\"handleTripleClick\", f => f(view, pos, event));\n}\nfunction selectionForTripleClick(doc, inside, selectNodes) {\n    if (inside == -1)\n        return doc.inlineContent ? TextSelection.create(doc, 0, doc.content.size) : null;\n    let $pos = doc.resolve(inside);\n    for (let i = $pos.depth + 1; i > 0; i--) {\n        let node = i > $pos.depth ? $pos.nodeAfter : $pos.node(i);\n        let nodePos = $pos.before(i);\n        if (node.inlineContent)\n            return TextSelection.create(doc, nodePos + 1, nodePos + 1 + node.content.size);\n        else if (selectNodes && NodeSelection.isSelectable(node))\n            return NodeSelection.create(doc, nodePos);\n    }\n    return null;\n}\nlet wordRE = /[\\w_\\u00a1-\\uffff]+/g;\ntry {\n    wordRE = new RegExp(\"[\\\\p{L}\\\\p{N}_]+\", \"gu\");\n}\ncatch (_a) { }\nfunction getWordAt(doc, pos) {\n    let $pos = doc.resolve(pos), parent = $pos.node();\n    let context = \"\", from = pos, to = pos;\n    for (let i = $pos.indexAfter(), sawNonWS = false; i > 0; i--) {\n        let prev = parent.child(i - 1);\n        if (!prev.text)\n            break;\n        let end = from == pos ? pos - $pos.posAtIndex(i - 1) : prev.text.length, start = end;\n        for (; start > 0; start--) {\n            if (/\\S/.test(prev.text[start - 1]))\n                sawNonWS = true;\n            else if (sawNonWS)\n                break;\n        }\n        context = prev.text.slice(start, end) + context;\n        from -= end - start;\n        if (start || from < pos - 50)\n            break;\n    }\n    for (let i = $pos.index(), sawNonWS = false; i < parent.childCount; i++) {\n        let next = parent.child(i);\n        if (!next.text)\n            break;\n        let start = to == pos ? pos - $pos.posAtIndex(i) : 0, end = start;\n        for (; end < next.text.length; end++) {\n            if (/\\S/.test(next.text[end]))\n                sawNonWS = true;\n            else if (sawNonWS)\n                break;\n        }\n        context += next.text.slice(start, end);\n        to += end - start;\n        if (end < next.text.length || to > pos + 50)\n            break;\n    }\n    let lastBefore = from, firstAfter = to;\n    if (Intl.Segmenter) {\n        for (let segment of new Intl.Segmenter(undefined, { granularity: \"word\" }).segment(context)) {\n            if (segment.isWordLike) {\n                let start = segment.index + from, end = start + segment.segment.length;\n                if (end < pos)\n                    lastBefore = end;\n                else if (start > pos) {\n                    firstAfter = start;\n                    break;\n                }\n                else\n                    return TextSelection.create(doc, start, end);\n            }\n        }\n    }\n    else {\n        wordRE.lastIndex = 0;\n        for (let m; m = wordRE.exec(context);) {\n            let start = m.index + from, end = start + m[0].length;\n            if (end < pos)\n                lastBefore = end;\n            else if (start > pos) {\n                firstAfter = start;\n                break;\n            }\n            else\n                return TextSelection.create(doc, start, end);\n        }\n    }\n    let before = context.slice(lastBefore - from, pos - from), after = context.slice(pos - from, firstAfter - from);\n    let nonSpaceBefore = /\\S*$/.exec(before)[0].length, nonSpaceAfter = /^\\S*/.exec(after)[0].length;\n    if (nonSpaceBefore || nonSpaceAfter)\n        return TextSelection.create(doc, pos - nonSpaceBefore, pos + nonSpaceAfter);\n    let spaceBefore = /\\s*$/.exec(before)[0].length, spaceAfter = /^\\s*/.exec(after)[0].length;\n    return TextSelection.create(doc, pos - spaceBefore, pos + spaceAfter);\n}\nconst selectNodeModifier = mac ? \"metaKey\" : \"ctrlKey\";\nhandlers.mousedown = (view, _event) => {\n    let event = _event, now = Date.now();\n    view.input.shiftKey = event.shiftKey;\n    if (view.input.lastTouch > now - 500)\n        return false; // Ignore touch interaction\n    endComposition(view);\n    let type = \"singleClick\";\n    if (now - view.input.lastClick.time < 500 && isNear(event, view.input.lastClick) && !event[selectNodeModifier] &&\n        view.input.lastClick.button == event.button) {\n        if (view.input.lastClick.type == \"singleClick\")\n            type = \"doubleClick\";\n        else if (view.input.lastClick.type == \"doubleClick\")\n            type = \"tripleClick\";\n    }\n    view.input.lastClick = { time: now, x: event.clientX, y: event.clientY, type, button: event.button };\n    if (view.input.mouseDown)\n        view.input.mouseDown.done();\n    let pos = view.posAtCoords(eventCoords(event));\n    if (!pos)\n        return;\n    if (event.button == 0) {\n        if (!view.hasFocus()) {\n            focusPreventScroll(view.dom);\n            let active = view.root.activeElement;\n            if (active && !active.contains(view.dom))\n                active.blur();\n        }\n        let mouseDown = view.input.mouseDown = new MouseDown(view, pos, event, type);\n        if (!mouseDown.mightDrag)\n            event.preventDefault();\n    }\n    else {\n        setSelectionOrigin(view, \"pointer\");\n    }\n};\nclass MouseDown {\n    constructor(view, startPos, event, type // single/double/tripleClick\n    ) {\n        var _a;\n        this.view = view;\n        this.startPos = startPos;\n        this.event = event;\n        this.type = type;\n        this.didMove = false;\n        this.lastPos = -1;\n        // Anchor for the selection. With shift held, this will be the\n        // original start selection. Otherwise, it'll be the selection\n        // created for the initial position.\n        this.anchorRange = null;\n        this.startDoc = view.state.doc;\n        this.selectNode = !!event[selectNodeModifier];\n        this.extend = event.shiftKey;\n        this.anchorDoc = this.startDoc;\n        let startBase = docBase(view);\n        if (this.extend) {\n            let sel = view.state.selection;\n            this.anchorRange = sel instanceof NodeSelection ? { from: sel.from, to: sel.to } : { from: sel.anchor, to: sel.anchor };\n            let rect = sel instanceof NodeSelection ? view.nodeDOM(sel.from).getBoundingClientRect()\n                : view.coordsAtPos(sel.anchor);\n            this.anchorOffset = { x: (rect.left + rect.right) / 2 - startBase.x,\n                y: (rect.top + rect.bottom) / 2 - startBase.y };\n        }\n        else {\n            this.anchorOffset = { x: event.clientX - startBase.x, y: event.clientY - startBase.y };\n        }\n        if (type == \"singleClick\") {\n            let { selection } = view.state;\n            let targetNode, targetPos, targetSelected = false;\n            if (selection instanceof NodeSelection && selection.from <= startPos.pos && selection.to >= startPos.pos) {\n                targetPos = selection.from;\n                targetNode = selection.node;\n                targetSelected = true;\n            }\n            else if (startPos.inside > -1) {\n                targetNode = view.state.doc.nodeAt(startPos.inside);\n                targetPos = startPos.inside;\n            }\n            else {\n                let $pos = view.state.doc.resolve(startPos.pos);\n                targetNode = $pos.parent;\n                targetPos = $pos.depth ? $pos.before() : -1;\n            }\n            if (targetSelected || targetPos > -1 && targetNode.type.spec.draggable && targetNode.type.spec.selectable !== false) {\n                let elt = (_a = view.docView.descAt(targetPos)) === null || _a === void 0 ? void 0 : _a.nodeDOM;\n                this.mightDrag = {\n                    node: targetNode,\n                    elt,\n                    pos: targetPos,\n                    addAttr: false\n                };\n                if (elt && !elt.draggable) {\n                    this.mightDrag.addAttr = true;\n                    view.domObserver.stopped(() => elt.draggable = true);\n                }\n            }\n            else {\n                this.mightDrag = isInSelection(view, event);\n            }\n        }\n        else {\n            this.mightDrag = false;\n        }\n        view.root.addEventListener(\"mouseup\", this.up = this.up.bind(this));\n        view.root.addEventListener(\"mousemove\", this.move = this.move.bind(this));\n        if (!this.mightDrag)\n            this.select(this.startPos, true);\n    }\n    done() {\n        this.view.root.removeEventListener(\"mouseup\", this.up);\n        this.view.root.removeEventListener(\"mousemove\", this.move);\n        if (this.view.input.mouseDown == this)\n            this.view.input.mouseDown = null;\n        if (typeof this.mightDrag == \"object\" && this.mightDrag.addAttr) {\n            this.view.domObserver.stopped(() => this.mightDrag.elt.removeAttribute(\"draggable\"));\n        }\n    }\n    maybeRunHandler(pos, event) {\n        let handler = this.type == \"singleClick\" ? handleSingleClick\n            : this.type == \"doubleClick\" ? handleDoubleClick : handleTripleClick;\n        return handler(this.view, pos.pos, pos.inside, event, this.selectNode);\n    }\n    up(event) {\n        this.done();\n        if (!this.view.dom.contains(event.target))\n            return;\n        let pos = this.startPos;\n        if (this.view.state.doc != this.startDoc)\n            pos = this.view.posAtCoords(eventCoords(event));\n        if (!pos)\n            return;\n        if (!this.didMove) {\n            this.maybeRunHandler(pos, event) || this.select(pos, true);\n        }\n        event.preventDefault();\n    }\n    move(event) {\n        if (event.buttons == 0) {\n            this.done();\n            return;\n        }\n        if (!this.didMove &&\n            (Math.abs(this.event.x - event.clientX) > 8 || Math.abs(this.event.y - event.clientY) > 8)) {\n            this.didMove = true;\n            this.mightDrag = false;\n        }\n        if (!this.mightDrag) {\n            let pos = this.view.posAtCoords(eventCoords(event));\n            if (pos)\n                this.select(pos, false);\n        }\n        event.preventDefault();\n    }\n    select(pos, first) {\n        if (pos.pos == this.lastPos)\n            return;\n        this.lastPos = pos.pos;\n        let { view } = this, { doc } = view.state;\n        let selection = this.type == \"singleClick\" ? clickedRange(view, doc, pos)\n            : this.type == \"doubleClick\" ? getWordAt(doc, pos.pos)\n                : selectionForTripleClick(doc, pos.inside, first);\n        if (!selection)\n            return;\n        if (first && !this.extend) {\n            this.anchorRange = selection;\n        }\n        else if (!first || this.extend) {\n            if (!doc.eq(this.anchorDoc))\n                this.restoreAnchor();\n            if (this.anchorRange && this.anchorRange.from < selection.from)\n                selection = selectionBetween(view, doc.resolve(this.anchorRange.from), doc.resolve(selection.to));\n            else if (this.anchorRange && this.anchorRange.to > selection.to)\n                selection = selectionBetween(view, doc.resolve(this.anchorRange.to), doc.resolve(selection.from));\n        }\n        if (!selection.eq(view.state.selection)) {\n            view.input.mouseSelecting = pos;\n            view.dispatch(view.state.tr.setSelection(selection).setMeta(\"pointer\", true).scrollIntoView());\n            view.input.mouseSelecting = null;\n        }\n    }\n    restoreAnchor() {\n        let base = docBase(this.view);\n        let pos = this.view.posAtCoords({ left: this.anchorOffset.x + base.x, top: this.anchorOffset.y + base.y });\n        if (!pos) {\n            this.anchorRange = null;\n        }\n        else {\n            let { doc } = this.view.state;\n            this.anchorRange = this.type == \"singleClick\" ? clickedRange(this.view, doc, pos)\n                : this.type == \"doubleClick\" ? getWordAt(doc, pos.pos)\n                    : selectionForTripleClick(doc, pos.inside, false);\n            this.anchorDoc = this.view.state.doc;\n        }\n    }\n}\nfunction docBase(view) {\n    let rect = view.dom.getBoundingClientRect();\n    return { x: rect.left - view.dom.scrollLeft, y: rect.top - view.dom.scrollTop };\n}\nfunction clickedRange(view, doc, pos) {\n    if (pos.inside > -1) {\n        let target = doc.nodeAt(pos.inside);\n        if (target.isAtom && NodeSelection.isSelectable(target))\n            return NodeSelection.create(doc, pos.inside);\n    }\n    let $pos = doc.resolve(pos.pos);\n    return selectionBetween(view, $pos, $pos);\n}\nfunction isInSelection(view, event) {\n    let { selection } = view.state;\n    if (selection.empty)\n        return false;\n    let sel = view.domSelection();\n    if (!sel || sel.rangeCount == 0)\n        return true;\n    let rects = sel.getRangeAt(0).getClientRects();\n    for (let i = 0; i < rects.length; i++) {\n        let rect = rects[i];\n        if (rect.left <= event.clientX && rect.right >= event.clientX &&\n            rect.top <= event.clientY && rect.bottom >= event.clientY)\n            return true;\n    }\n    return false;\n}\nhandlers.touchstart = view => {\n    view.input.lastTouch = Date.now();\n    endComposition(view);\n    setSelectionOrigin(view, \"pointer\");\n};\nhandlers.touchmove = view => {\n    view.input.lastTouch = Date.now();\n    setSelectionOrigin(view, \"pointer\");\n};\nhandlers.contextmenu = view => endComposition(view);\nfunction inOrNearComposition(view, event) {\n    if (view.composing)\n        return true;\n    // See https://www.stum.de/2016/06/24/handling-ime-events-in-javascript/.\n    // On Japanese input method editors (IMEs), the Enter key is used to confirm character\n    // selection. On Safari, when Enter is pressed, compositionend and keydown events are\n    // emitted. The keydown event triggers newline insertion, which we don't want.\n    // This method returns true if the keydown event should be ignored.\n    // We only ignore it once, as pressing Enter a second time *should* insert a newline.\n    // Furthermore, the keydown event timestamp must be close to the compositionEndedAt timestamp.\n    // This guards against the case where compositionend is triggered without the keyboard\n    // (e.g. character confirmation may be done with the mouse), and keydown is triggered\n    // afterwards- we wouldn't want to ignore the keydown event in this case.\n    if (safari && Math.abs(Date.now() - view.input.compositionEndedAt) < 500) {\n        view.input.compositionEndedAt = -2e8;\n        return true;\n    }\n    return false;\n}\n// Drop active composition after 5 seconds of inactivity on Android\nconst timeoutComposition = android ? 5000 : -1;\neditHandlers.compositionstart = editHandlers.compositionupdate = view => {\n    if (!view.composing) {\n        view.domObserver.flush();\n        let { state } = view, $pos = state.selection.$to;\n        if (state.selection instanceof TextSelection && state.selection.empty &&\n            (state.storedMarks ||\n                (!$pos.textOffset && $pos.parentOffset && $pos.nodeBefore.marks.some(m => m.type.spec.inclusive === false)) ||\n                chrome && windows && selectionBeforeUneditable(view))) { // Issue #1500\n            // Need to wrap the cursor in mark nodes different from the ones in the DOM context\n            view.markCursor = view.state.storedMarks || $pos.marks();\n            endComposition(view, true);\n            view.markCursor = null;\n        }\n        else {\n            endComposition(view, !state.selection.empty);\n            // In firefox, if the cursor is after but outside a marked node,\n            // the inserted text won't inherit the marks. So this moves it\n            // inside if necessary.\n            if (gecko && view.domSel.active && state.selection.empty &&\n                $pos.parentOffset && !$pos.textOffset && $pos.nodeBefore.marks.length) {\n                for (let { focusNode: node, focusOffset: offset } = view.domSel.range; node && isElt(node) && offset != 0;) {\n                    let before = offset < 0 ? node.lastChild : node.childNodes[offset - 1];\n                    if (!before)\n                        break;\n                    if (isText(before)) {\n                        let sel = view.domSelection();\n                        if (sel)\n                            sel.collapse(before, before.nodeValue.length);\n                        break;\n                    }\n                    else {\n                        node = before;\n                        offset = -1;\n                    }\n                }\n            }\n        }\n        view.input.composing = true;\n    }\n    scheduleComposeEnd(view, timeoutComposition);\n};\nfunction selectionBeforeUneditable(view) {\n    let { focusNode, focusOffset } = view.domSel.range;\n    if (!focusNode || !isElt(focusNode) || focusOffset >= focusNode.childNodes.length)\n        return false;\n    let next = focusNode.childNodes[focusOffset];\n    return isElt(next) && next.contentEditable == \"false\";\n}\neditHandlers.compositionend = (view, event) => {\n    if (view.composing)\n        leaveComposition(view);\n};\nfunction leaveComposition(view, sync = false) {\n    view.input.composing = false;\n    view.input.compositionEndedAt = Date.now();\n    view.input.compositionPendingChanges = view.domObserver.pendingRecords().length ? view.input.compositionID : 0;\n    view.input.compositionNode = null;\n    if (view.input.badSafariComposition)\n        view.domObserver.forceFlush();\n    else if (view.input.compositionPendingChanges)\n        Promise.resolve().then(() => view.domObserver.flush());\n    view.input.compositionID++;\n    if (sync)\n        endComposition(view);\n    else\n        scheduleComposeEnd(view, 20);\n}\nfunction scheduleComposeEnd(view, delay) {\n    clearTimeout(view.input.composingTimeout);\n    if (delay > -1)\n        view.input.composingTimeout = setTimeout(() => endComposition(view), delay);\n}\nfunction clearComposition(view) {\n    if (view.composing) {\n        view.input.composing = false;\n        view.input.compositionEndedAt = Date.now();\n    }\n    for (let node; node = view.input.compositionNodes.pop();)\n        node.markParentDamage();\n}\nfunction findCompositionNode(view) {\n    let sel = view.domSel.range;\n    if (!view.domSel.active || !sel.focusNode)\n        return null;\n    let textBefore = textNodeBefore(sel.focusNode, sel.focusOffset);\n    let textAfter = textNodeAfter(sel.focusNode, sel.focusOffset);\n    if (textBefore && textAfter && textBefore != textAfter) {\n        let descAfter = textAfter.pmViewDesc, lastChanged = view.domObserver.lastChangedTextNode;\n        if (textBefore == lastChanged || textAfter == lastChanged)\n            return lastChanged;\n        if (!descAfter || !descAfter.isText(textAfter.nodeValue)) {\n            return textAfter;\n        }\n        else if (view.input.compositionNode == textAfter) {\n            let descBefore = textBefore.pmViewDesc;\n            if (!(!descBefore || !descBefore.isText(textBefore.nodeValue)))\n                return textAfter;\n        }\n    }\n    return textBefore || textAfter;\n}\n/**\n@internal\n*/\nfunction endComposition(view, restarting = false) {\n    if (android && view.domObserver.flushingSoon >= 0)\n        return;\n    view.domObserver.forceFlush();\n    clearComposition(view);\n    if (restarting || view.docView && view.docView.damage) {\n        let sel = selectionFromDOM(view, view.domSel.readRange()), cur = view.state.selection;\n        if (sel && !sel.eq(cur))\n            view.dispatch(view.state.tr.setSelection(sel));\n        else if ((view.markCursor || restarting) && !cur.$from.node(cur.$from.sharedDepth(cur.to)).inlineContent)\n            view.dispatch(view.state.tr.deleteSelection());\n        else\n            view.updateState(view.state);\n    }\n}\nfunction captureCopy(view, dom) {\n    // The extra wrapper is somehow necessary on IE/Edge to prevent the\n    // content from being mangled when it is put onto the clipboard\n    if (!view.dom.parentNode)\n        return;\n    let wrap = view.dom.parentNode.appendChild(document.createElement(\"div\"));\n    wrap.appendChild(dom);\n    wrap.style.cssText = \"position: fixed; left: -10000px; top: 10px\";\n    let sel = getSelection(), range = document.createRange();\n    range.selectNodeContents(dom);\n    // Done because IE will fire a selectionchange moving the selection\n    // to its start when removeAllRanges is called and the editor still\n    // has focus (which will mess up the editor's selection state).\n    view.dom.blur();\n    sel.removeAllRanges();\n    sel.addRange(range);\n    setTimeout(() => {\n        if (wrap.parentNode)\n            wrap.parentNode.removeChild(wrap);\n        view.focus();\n    }, 50);\n}\n// This is very crude, but unfortunately old iOS Safari versions\n// _pretend_ that they have a clipboard API\u2014all the objects and\n// methods are there, they just don't work, and they are hard to test.\nconst brokenClipboardAPI = ios && webkit_version < 604;\nhandlers.copy = editHandlers.cut = (view, _event) => {\n    let event = _event;\n    let sel = view.state.selection, cut = event.type == \"cut\";\n    if (sel.empty)\n        return;\n    // IE and Edge's clipboard interface is completely broken\n    let data = brokenClipboardAPI ? null : event.clipboardData;\n    let slice = sel.content(), { dom, text } = serializeForClipboard(view, slice);\n    if (data) {\n        event.preventDefault();\n        data.clearData();\n        data.setData(\"text/html\", dom.innerHTML);\n        data.setData(\"text/plain\", text);\n    }\n    else {\n        captureCopy(view, dom);\n    }\n    if (cut)\n        view.dispatch(view.state.tr.deleteSelection().scrollIntoView().setMeta(\"uiEvent\", \"cut\"));\n};\nfunction sliceSingleNode(slice) {\n    return slice.openStart == 0 && slice.openEnd == 0 && slice.content.childCount == 1 ? slice.content.firstChild : null;\n}\nfunction capturePaste(view, event) {\n    if (!view.dom.parentNode)\n        return;\n    let plainText = view.input.shiftKey || view.state.selection.$from.parent.type.spec.code;\n    let target = view.dom.parentNode.appendChild(document.createElement(plainText ? \"textarea\" : \"div\"));\n    if (!plainText)\n        target.contentEditable = \"true\";\n    target.style.cssText = \"position: fixed; left: -10000px; top: 10px\";\n    target.focus();\n    let plain = view.input.shiftKey && view.input.lastKeyCode != 45;\n    setTimeout(() => {\n        view.focus();\n        if (target.parentNode)\n            target.parentNode.removeChild(target);\n        if (plainText)\n            doPaste(view, target.value, null, plain, event);\n        else\n            doPaste(view, target.textContent, target.innerHTML, plain, event);\n    }, 50);\n}\nfunction doPaste(view, text, html, preferPlain, event) {\n    let slice = parseFromClipboard(view, text, html, preferPlain, view.state.selection.$from);\n    if (view.someProp(\"handlePaste\", f => f(view, event, slice || Slice.empty)))\n        return true;\n    if (!slice)\n        return false;\n    let singleNode = sliceSingleNode(slice);\n    let tr = singleNode\n        ? view.state.tr.replaceSelectionWith(singleNode, preferPlain)\n        : view.state.tr.replaceSelection(slice);\n    view.dispatch(tr.scrollIntoView().setMeta(\"paste\", true).setMeta(\"uiEvent\", \"paste\"));\n    return true;\n}\nfunction getText(clipboardData) {\n    let text = clipboardData.getData(\"text/plain\") || clipboardData.getData(\"Text\");\n    if (text)\n        return text;\n    let uris = clipboardData.getData(\"text/uri-list\");\n    return uris ? uris.replace(/\\r?\\n/g, \" \") : \"\";\n}\neditHandlers.paste = (view, _event) => {\n    let event = _event;\n    // Handling paste from JavaScript during composition is very poorly\n    // handled by browsers, so as a dodgy but preferable kludge, we just\n    // let the browser do its native thing there, except on Android,\n    // where the editor is almost always composing.\n    if (view.composing && !android)\n        return;\n    let data = brokenClipboardAPI ? null : event.clipboardData;\n    let plain = view.input.shiftKey && view.input.lastKeyCode != 45;\n    if (data && doPaste(view, getText(data), data.getData(\"text/html\"), plain, event))\n        event.preventDefault();\n    else\n        capturePaste(view, event);\n};\nclass Dragging {\n    constructor(slice, move, node) {\n        this.slice = slice;\n        this.move = move;\n        this.node = node;\n    }\n}\nconst dragCopyModifier = mac ? \"altKey\" : \"ctrlKey\";\nfunction dragMoves(view, event) {\n    let copy;\n    view.someProp(\"dragCopies\", test => { copy = copy || test(event); });\n    return copy != null ? !copy : !event[dragCopyModifier];\n}\nhandlers.dragstart = (view, _event) => {\n    let event = _event;\n    let mouseDown = view.input.mouseDown;\n    if (mouseDown)\n        mouseDown.done();\n    if (!event.dataTransfer)\n        return;\n    let sel = view.state.selection;\n    let pos = sel.empty ? null : view.posAtCoords(eventCoords(event));\n    let node;\n    if (pos && pos.pos >= sel.from && pos.pos <= (sel instanceof NodeSelection ? sel.to - 1 : sel.to)) ;\n    else if (mouseDown && typeof mouseDown.mightDrag == \"object\") {\n        node = NodeSelection.create(view.state.doc, mouseDown.mightDrag.pos);\n    }\n    else if (event.target && isElt(event.target)) {\n        let desc = view.docView.nearestDesc(event.target, true);\n        if (desc && desc.node.type.spec.draggable && desc != view.docView)\n            node = NodeSelection.create(view.state.doc, desc.posBefore);\n    }\n    let draggedSlice = (node || view.state.selection).content();\n    let { dom, text, slice } = serializeForClipboard(view, draggedSlice);\n    // Pre-120 Chrome versions clear files when calling `clearData` (#1472)\n    if (!event.dataTransfer.files.length || !chrome || chrome_version > 120)\n        event.dataTransfer.clearData();\n    event.dataTransfer.setData(brokenClipboardAPI ? \"Text\" : \"text/html\", dom.innerHTML);\n    // See https://code.haverbeke.berlin/prosemirror/prosemirror/issues/1156\n    event.dataTransfer.effectAllowed = \"copyMove\";\n    if (!brokenClipboardAPI)\n        event.dataTransfer.setData(\"text/plain\", text);\n    view.dragging = new Dragging(slice, dragMoves(view, event), node);\n};\nhandlers.dragend = view => {\n    let dragging = view.dragging;\n    window.setTimeout(() => {\n        if (view.dragging == dragging)\n            view.dragging = null;\n    }, 50);\n};\neditHandlers.dragover = editHandlers.dragenter = (_, e) => e.preventDefault();\neditHandlers.drop = (view, event) => {\n    try {\n        handleDrop(view, event, view.dragging);\n    }\n    finally {\n        view.dragging = null;\n    }\n};\nfunction handleDrop(view, event, dragging) {\n    if (!event.dataTransfer)\n        return;\n    let eventPos = view.posAtCoords(eventCoords(event));\n    if (!eventPos)\n        return;\n    let $mouse = view.state.doc.resolve(eventPos.pos);\n    let slice = dragging && dragging.slice;\n    if (slice) {\n        view.someProp(\"transformPasted\", f => { slice = f(slice, view, false); });\n    }\n    else {\n        slice = parseFromClipboard(view, getText(event.dataTransfer), brokenClipboardAPI ? null : event.dataTransfer.getData(\"text/html\"), false, $mouse);\n    }\n    let move = !!(dragging && dragMoves(view, event));\n    if (view.someProp(\"handleDrop\", f => f(view, event, slice || Slice.empty, move))) {\n        event.preventDefault();\n        return;\n    }\n    if (!slice)\n        return;\n    event.preventDefault();\n    let insertPos = slice ? dropPoint(view.state.doc, $mouse.pos, slice) : $mouse.pos;\n    if (insertPos == null)\n        insertPos = $mouse.pos;\n    let tr = view.state.tr;\n    if (move) {\n        let { node } = dragging;\n        if (node)\n            node.replace(tr);\n        else\n            tr.deleteSelection();\n    }\n    let pos = tr.mapping.map(insertPos);\n    let isNode = slice.openStart == 0 && slice.openEnd == 0 && slice.content.childCount == 1;\n    let beforeInsert = tr.doc;\n    if (isNode)\n        tr.replaceRangeWith(pos, pos, slice.content.firstChild);\n    else\n        tr.replaceRange(pos, pos, slice);\n    if (tr.doc.eq(beforeInsert))\n        return;\n    let $pos = tr.doc.resolve(pos);\n    if (isNode && NodeSelection.isSelectable(slice.content.firstChild) &&\n        $pos.nodeAfter && $pos.nodeAfter.sameMarkup(slice.content.firstChild)) {\n        tr.setSelection(new NodeSelection($pos));\n    }\n    else {\n        let end = tr.mapping.map(insertPos);\n        tr.mapping.maps[tr.mapping.maps.length - 1].forEach((_from, _to, _newFrom, newTo) => end = newTo);\n        tr.setSelection(selectionBetween(view, $pos, tr.doc.resolve(end)));\n    }\n    view.focus();\n    view.dispatch(tr.setMeta(\"uiEvent\", \"drop\"));\n}\nhandlers.focus = view => {\n    view.input.lastFocus = Date.now();\n    if (!view.focused) {\n        view.domObserver.stopped(() => view.dom.classList.add(\"ProseMirror-focused\"));\n        view.focused = true;\n        view.domSel.read();\n        if (!view.domSel.synced) {\n            let startSel = view.domSel.range;\n            setTimeout(() => {\n                let curSel = view.domSel.readRange();\n                if (curSel && startSel.eq(curSel))\n                    view.domSel.sync();\n            }, 20);\n        }\n    }\n};\nhandlers.blur = (view, _event) => {\n    let event = _event;\n    if (view.focused) {\n        view.domObserver.stopped(() => view.dom.classList.remove(\"ProseMirror-focused\"));\n        if (event.relatedTarget && view.dom.contains(event.relatedTarget))\n            view.domSel.deactivate();\n        view.focused = false;\n    }\n};\nhandlers.beforeinput = (view, _event) => {\n    let event = _event;\n    // We should probably do more with beforeinput events, but support\n    // is so spotty that I'm still waiting to see where they are going.\n    // Very specific hack to deal with backspace sometimes failing on\n    // Chrome and Firefox Android when after an uneditable node.\n    if (android && event.inputType == \"deleteContentBackward\") {\n        view.domObserver.flushSoon();\n        let { domChangeCount } = view.input;\n        setTimeout(() => {\n            if (view.input.domChangeCount != domChangeCount || view.domObserver.pendingRecords().length)\n                return; // Event already had some effect\n            // This bug tends to close the virtual keyboard, so we refocus\n            view.dom.blur();\n            view.focus();\n            if (dispatchKey(view, \"Backspace\"))\n                return;\n            let { $cursor } = view.state.selection;\n            // Crude approximation of backspace behavior when no command handled it\n            if ($cursor && $cursor.pos > 0)\n                view.dispatch(view.state.tr.delete($cursor.pos - 1, $cursor.pos).scrollIntoView());\n        }, 50);\n    }\n};\n// Make sure all handlers get registered\nfor (let prop in editHandlers)\n    handlers[prop] = editHandlers[prop];\n\nfunction compareObjs(a, b) {\n    if (a == b)\n        return true;\n    for (let p in a)\n        if (a[p] !== b[p])\n            return false;\n    for (let p in b)\n        if (!(p in a))\n            return false;\n    return true;\n}\nclass FragmentCursor {\n    constructor(frag) {\n        this.frag = frag;\n        this.index = 0;\n        this.off = 0;\n    }\n    nodeAt(off) {\n        while (this.off <= off && this.index < this.frag.childCount) {\n            let next = this.frag.child(this.index);\n            if (this.off == off)\n                return next;\n            this.off += next.nodeSize;\n            this.index++;\n        }\n        return null;\n    }\n}\nclass WidgetType {\n    constructor(toDOM, spec) {\n        this.toDOM = toDOM;\n        this.spec = spec || noSpec;\n        this.side = this.spec.side || 0;\n    }\n    map(mapping, span, offset, oldOffset) {\n        let { pos, deleted } = mapping.mapResult(span.from + oldOffset, this.side < 0 ? -1 : 1);\n        return deleted ? null : new Decoration(pos - offset, pos - offset, this);\n    }\n    valid() { return true; }\n    eq(other) {\n        return this == other ||\n            (other instanceof WidgetType &&\n                (this.spec.key && this.spec.key == other.spec.key ||\n                    this.toDOM == other.toDOM && compareObjs(this.spec, other.spec)));\n    }\n    destroy(node) {\n        if (this.spec.destroy)\n            this.spec.destroy(node);\n    }\n}\nclass InlineType {\n    constructor(attrs, spec) {\n        this.attrs = attrs;\n        this.spec = spec || noSpec;\n    }\n    map(mapping, span, offset, oldOffset) {\n        let from = mapping.map(span.from + oldOffset, this.spec.inclusiveStart ? -1 : 1) - offset;\n        let to = mapping.map(span.to + oldOffset, this.spec.inclusiveEnd ? 1 : -1) - offset;\n        return from >= to ? null : new Decoration(from, to, this);\n    }\n    valid(_, span) { return span.from < span.to; }\n    eq(other) {\n        return this == other ||\n            (other instanceof InlineType && compareObjs(this.attrs, other.attrs) &&\n                compareObjs(this.spec, other.spec));\n    }\n    static is(span) { return span.type instanceof InlineType; }\n    destroy() { }\n}\nclass NodeType {\n    constructor(attrs, spec) {\n        this.attrs = attrs;\n        this.spec = spec || noSpec;\n    }\n    map(mapping, span, offset, oldOffset) {\n        let from = mapping.mapResult(span.from + oldOffset, 1);\n        if (from.deleted)\n            return null;\n        let to = mapping.mapResult(span.to + oldOffset, -1);\n        if (to.deleted || to.pos <= from.pos)\n            return null;\n        return new Decoration(from.pos - offset, to.pos - offset, this);\n    }\n    valid(node, span, cursor) {\n        let found = cursor.nodeAt(span.from);\n        return !!found && !found.isText && span.from + found.nodeSize == span.to;\n    }\n    eq(other) {\n        return this == other ||\n            (other instanceof NodeType && compareObjs(this.attrs, other.attrs) &&\n                compareObjs(this.spec, other.spec));\n    }\n    destroy() { }\n}\n/**\nDecoration objects can be provided to the view through the\n[`decorations` prop](https://prosemirror.net/docs/ref/#view.EditorProps.decorations). They come in\nseveral variants\u2014see the static members of this class for details.\n*/\nclass Decoration {\n    /**\n    @internal\n    */\n    constructor(\n    /**\n    The start position of the decoration.\n    */\n    from, \n    /**\n    The end position. Will be the same as `from` for [widget\n    decorations](https://prosemirror.net/docs/ref/#view.Decoration^widget).\n    */\n    to, \n    /**\n    @internal\n    */\n    type) {\n        this.from = from;\n        this.to = to;\n        this.type = type;\n    }\n    /**\n    @internal\n    */\n    copy(from, to) {\n        return new Decoration(from, to, this.type);\n    }\n    /**\n    @internal\n    */\n    eq(other, offset = 0) {\n        return this.type.eq(other.type) && this.from + offset == other.from && this.to + offset == other.to;\n    }\n    /**\n    @internal\n    */\n    map(mapping, offset, oldOffset) {\n        return this.type.map(mapping, this, offset, oldOffset);\n    }\n    /**\n    Creates a widget decoration, which is a DOM node that's shown in\n    the document at the given position. It is recommended that you\n    delay rendering the widget by passing a function that will be\n    called when the widget is actually drawn in a view, but you can\n    also directly pass a DOM node. `getPos` can be used to find the\n    widget's current document position.\n    */\n    static widget(pos, toDOM, spec) {\n        return new Decoration(pos, pos, new WidgetType(toDOM, spec));\n    }\n    /**\n    Creates an inline decoration, which adds the given attributes to\n    each inline node between `from` and `to`.\n    */\n    static inline(from, to, attrs, spec) {\n        return new Decoration(from, to, new InlineType(attrs, spec));\n    }\n    /**\n    Creates a node decoration. `from` and `to` should point precisely\n    before and after a node in the document. That node, and only that\n    node, will receive the given attributes.\n    */\n    static node(from, to, attrs, spec) {\n        return new Decoration(from, to, new NodeType(attrs, spec));\n    }\n    /**\n    The spec provided when creating this decoration. Can be useful\n    if you've stored extra information in that object.\n    */\n    get spec() { return this.type.spec; }\n    /**\n    @internal\n    */\n    get inline() { return this.type instanceof InlineType; }\n    /**\n    @internal\n    */\n    get widget() { return this.type instanceof WidgetType; }\n}\nconst none = [], noSpec = {};\n/**\nA collection of [decorations](https://prosemirror.net/docs/ref/#view.Decoration), organized in such\na way that the drawing algorithm can efficiently use and compare\nthem. This is a persistent data structure\u2014it is not modified,\nupdates create a new value.\n*/\nclass DecorationSet {\n    /**\n    @internal\n    */\n    constructor(local, children) {\n        this.local = local.length ? local : none;\n        this.children = children.length ? children : none;\n    }\n    /**\n    Create a set of decorations, using the structure of the given\n    document. This will consume (modify) the `decorations` array, so\n    you must make a copy if you want need to preserve that.\n    */\n    static create(doc, decorations) {\n        return decorations.length ? buildTree(decorations, doc, 0, noSpec) : empty;\n    }\n    /**\n    Find all decorations in this set which touch the given range\n    (including decorations that start or end directly at the\n    boundaries) and match the given predicate on their spec. When\n    `start` and `end` are omitted, all decorations in the set are\n    considered. When `predicate` isn't given, all decorations are\n    assumed to match.\n    */\n    find(start, end, predicate) {\n        let result = [];\n        this.findInner(start == null ? 0 : start, end == null ? 1e9 : end, result, 0, predicate);\n        return result;\n    }\n    findInner(start, end, result, offset, predicate) {\n        for (let i = 0; i < this.local.length; i++) {\n            let span = this.local[i];\n            // Spans are sorted by start position.\n            if (span.from > end)\n                break;\n            if (span.to >= start && (!predicate || predicate(span.spec)))\n                result.push(span.copy(span.from + offset, span.to + offset));\n        }\n        for (let i = 0; i < this.children.length; i += 3) {\n            // Children are sorted by start position.\n            if (this.children[i] >= end)\n                break;\n            if (this.children[i + 1] > start) {\n                let childOff = this.children[i] + 1;\n                this.children[i + 2].findInner(start - childOff, end - childOff, result, offset + childOff, predicate);\n            }\n        }\n    }\n    /**\n    Map the set of decorations in response to a change in the\n    document.\n    */\n    map(mapping, doc, options) {\n        if (this == empty || mapping.maps.length == 0)\n            return this;\n        return this.mapInner(mapping, doc, 0, 0, options || noSpec);\n    }\n    /**\n    @internal\n    */\n    mapInner(mapping, node, offset, oldOffset, options) {\n        let newLocal;\n        if (this.local.length) {\n            let cur = new FragmentCursor(node.content);\n            for (let i = 0; i < this.local.length; i++) {\n                let mapped = this.local[i].map(mapping, offset, oldOffset);\n                if (mapped && mapped.type.valid(node, mapped, cur))\n                    (newLocal || (newLocal = [])).push(mapped);\n                else if (options.onRemove)\n                    options.onRemove(this.local[i].spec);\n            }\n        }\n        if (this.children.length)\n            return mapChildren(this.children, newLocal || [], mapping, node, offset, oldOffset, options);\n        else\n            return newLocal ? new DecorationSet(newLocal.sort(byPos), none) : empty;\n    }\n    /**\n    Add the given array of decorations to the ones in the set,\n    producing a new set. Consumes the `decorations` array. Needs\n    access to the current document to create the appropriate tree\n    structure.\n    */\n    add(doc, decorations) {\n        if (!decorations.length)\n            return this;\n        if (this == empty)\n            return DecorationSet.create(doc, decorations);\n        return this.addInner(doc, decorations, 0);\n    }\n    addInner(doc, decorations, offset) {\n        let children, childIndex = 0;\n        doc.forEach((childNode, childOffset) => {\n            let baseOffset = childOffset + offset, found;\n            if (!(found = takeSpansForNode(decorations, childNode, baseOffset)))\n                return;\n            if (!children)\n                children = this.children.slice();\n            while (childIndex < children.length && children[childIndex] < childOffset)\n                childIndex += 3;\n            if (children[childIndex] == childOffset)\n                children[childIndex + 2] = children[childIndex + 2].addInner(childNode, found, baseOffset + 1);\n            else\n                children.splice(childIndex, 0, childOffset, childOffset + childNode.nodeSize, buildTree(found, childNode, baseOffset + 1, noSpec));\n            childIndex += 3;\n        });\n        let local = moveSpans(childIndex ? withoutNulls(decorations) : decorations, -offset).sort(byPos);\n        if (local.length) {\n            let cur = new FragmentCursor(doc.content);\n            for (let i = 0; i < local.length; i++)\n                if (!local[i].type.valid(doc, local[i], cur))\n                    local.splice(i--, 1);\n        }\n        return new DecorationSet(local.length ? this.local.concat(local).sort(byPos) : this.local, children || this.children);\n    }\n    /**\n    Create a new set that contains the decorations in this set, minus\n    the ones in the given array.\n    */\n    remove(decorations) {\n        if (decorations.length == 0 || this == empty)\n            return this;\n        return this.removeInner(decorations, 0);\n    }\n    removeInner(decorations, offset) {\n        let children = this.children, local = this.local;\n        for (let i = 0; i < children.length; i += 3) {\n            let found;\n            let from = children[i] + offset, to = children[i + 1] + offset;\n            for (let j = 0, span; j < decorations.length; j++)\n                if (span = decorations[j]) {\n                    if (span.from > from && span.to < to) {\n                        decorations[j] = null;\n                        (found || (found = [])).push(span);\n                    }\n                }\n            if (!found)\n                continue;\n            if (children == this.children)\n                children = this.children.slice();\n            let removed = children[i + 2].removeInner(found, from + 1);\n            if (removed != empty) {\n                children[i + 2] = removed;\n            }\n            else {\n                children.splice(i, 3);\n                i -= 3;\n            }\n        }\n        if (local.length)\n            for (let i = 0, span; i < decorations.length; i++)\n                if (span = decorations[i]) {\n                    for (let j = 0; j < local.length; j++)\n                        if (local[j].eq(span, offset)) {\n                            if (local == this.local)\n                                local = this.local.slice();\n                            local.splice(j--, 1);\n                        }\n                }\n        if (children == this.children && local == this.local)\n            return this;\n        return local.length || children.length ? new DecorationSet(local, children) : empty;\n    }\n    forChild(offset, node) {\n        if (this == empty)\n            return this;\n        if (node.isLeaf)\n            return DecorationSet.empty;\n        let child, local;\n        // Children are sorted triples of start, end, and decoration set.\n        let low = 0, high = this.children.length / 3;\n        while (low < high) {\n            let mid = (low + high) >>> 1, index = mid * 3, start = this.children[index];\n            if (start < offset) {\n                low = mid + 1;\n            }\n            else if (start > offset) {\n                high = mid;\n            }\n            else {\n                child = this.children[index + 2];\n                break;\n            }\n        }\n        let start = offset + 1, end = start + node.content.size;\n        for (let i = 0; i < this.local.length; i++) {\n            let dec = this.local[i];\n            if (dec.from < end && dec.to > start && (dec.type instanceof InlineType)) {\n                let from = Math.max(start, dec.from) - start, to = Math.min(end, dec.to) - start;\n                if (from < to)\n                    (local || (local = [])).push(dec.copy(from, to));\n            }\n        }\n        if (local) {\n            let localSet = new DecorationSet(local.sort(byPos), none);\n            return child ? new DecorationGroup([localSet, child]) : localSet;\n        }\n        return child || empty;\n    }\n    /**\n    @internal\n    */\n    eq(other) {\n        if (this == other)\n            return true;\n        if (!(other instanceof DecorationSet) ||\n            this.local.length != other.local.length ||\n            this.children.length != other.children.length)\n            return false;\n        for (let i = 0; i < this.local.length; i++)\n            if (!this.local[i].eq(other.local[i]))\n                return false;\n        for (let i = 0; i < this.children.length; i += 3)\n            if (this.children[i] != other.children[i] ||\n                this.children[i + 1] != other.children[i + 1] ||\n                !this.children[i + 2].eq(other.children[i + 2]))\n                return false;\n        return true;\n    }\n    /**\n    @internal\n    */\n    locals(node) {\n        return removeOverlap(this.localsInner(node));\n    }\n    /**\n    @internal\n    */\n    localsInner(node) {\n        if (this == empty)\n            return none;\n        if (node.inlineContent || !this.local.some(InlineType.is))\n            return this.local;\n        let result = [];\n        for (let i = 0; i < this.local.length; i++) {\n            if (!(this.local[i].type instanceof InlineType))\n                result.push(this.local[i]);\n        }\n        return result;\n    }\n    forEachSet(f) { f(this); }\n}\n/**\nThe empty set of decorations.\n*/\nDecorationSet.empty = new DecorationSet([], []);\n/**\n@internal\n*/\nDecorationSet.removeOverlap = removeOverlap;\nconst empty = DecorationSet.empty;\n// An abstraction that allows the code dealing with decorations to\n// treat multiple DecorationSet objects as if it were a single object\n// with (a subset of) the same interface.\nclass DecorationGroup {\n    constructor(members) {\n        this.members = members;\n    }\n    map(mapping, doc) {\n        const mappedDecos = this.members.map(member => member.map(mapping, doc, noSpec));\n        return DecorationGroup.from(mappedDecos);\n    }\n    forChild(offset, child) {\n        if (child.isLeaf)\n            return DecorationSet.empty;\n        let found = [];\n        for (let i = 0; i < this.members.length; i++) {\n            let result = this.members[i].forChild(offset, child);\n            if (result == empty)\n                continue;\n            if (result instanceof DecorationGroup)\n                found = found.concat(result.members);\n            else\n                found.push(result);\n        }\n        return DecorationGroup.from(found);\n    }\n    eq(other) {\n        if (!(other instanceof DecorationGroup) ||\n            other.members.length != this.members.length)\n            return false;\n        for (let i = 0; i < this.members.length; i++)\n            if (!this.members[i].eq(other.members[i]))\n                return false;\n        return true;\n    }\n    locals(node) {\n        let result, sorted = true;\n        for (let i = 0; i < this.members.length; i++) {\n            let locals = this.members[i].localsInner(node);\n            if (!locals.length)\n                continue;\n            if (!result) {\n                result = locals;\n            }\n            else {\n                if (sorted) {\n                    result = result.slice();\n                    sorted = false;\n                }\n                for (let j = 0; j < locals.length; j++)\n                    result.push(locals[j]);\n            }\n        }\n        return result ? removeOverlap(sorted ? result : result.sort(byPos)) : none;\n    }\n    // Create a group for the given array of decoration sets, or return\n    // a single set when possible.\n    static from(members) {\n        switch (members.length) {\n            case 0: return empty;\n            case 1: return members[0];\n            default: return new DecorationGroup(members.every(m => m instanceof DecorationSet) ? members :\n                members.reduce((r, m) => r.concat(m instanceof DecorationSet ? m : m.members), []));\n        }\n    }\n    forEachSet(f) {\n        for (let i = 0; i < this.members.length; i++)\n            this.members[i].forEachSet(f);\n    }\n}\nfunction mapChildren(oldChildren, newLocal, mapping, node, offset, oldOffset, options) {\n    let children = oldChildren.slice();\n    // Mark the children that are directly touched by changes, and\n    // move those that are after the changes.\n    for (let i = 0, baseOffset = oldOffset; i < mapping.maps.length; i++) {\n        let moved = 0;\n        mapping.maps[i].forEach((oldStart, oldEnd, newStart, newEnd) => {\n            let dSize = (newEnd - newStart) - (oldEnd - oldStart);\n            for (let i = 0; i < children.length; i += 3) {\n                let end = children[i + 1];\n                if (end < 0 || oldStart > end + baseOffset - moved)\n                    continue;\n                let start = children[i] + baseOffset - moved;\n                if (oldEnd >= start) {\n                    children[i + 1] = oldStart <= start ? -2 : -1;\n                }\n                else if (oldStart >= baseOffset && dSize) {\n                    children[i] += dSize;\n                    children[i + 1] += dSize;\n                }\n            }\n            moved += dSize;\n        });\n        baseOffset = mapping.maps[i].map(baseOffset, -1);\n    }\n    // Find the child nodes that still correspond to a single node,\n    // recursively call mapInner on them and update their positions.\n    let mustRebuild = false;\n    for (let i = 0; i < children.length; i += 3)\n        if (children[i + 1] < 0) { // Touched nodes\n            if (children[i + 1] == -2) {\n                mustRebuild = true;\n                children[i + 1] = -1;\n                continue;\n            }\n            let from = mapping.map(oldChildren[i] + oldOffset), fromLocal = from - offset;\n            if (fromLocal < 0 || fromLocal >= node.content.size) {\n                mustRebuild = true;\n                continue;\n            }\n            // Must read oldChildren because children was tagged with -1\n            let to = mapping.map(oldChildren[i + 1] + oldOffset, -1), toLocal = to - offset;\n            let { index, offset: childOffset } = node.content.findIndex(fromLocal);\n            let childNode = node.maybeChild(index);\n            if (childNode && childOffset == fromLocal && childOffset + childNode.nodeSize == toLocal) {\n                let mapped = children[i + 2]\n                    .mapInner(mapping, childNode, from + 1, oldChildren[i] + oldOffset + 1, options);\n                if (mapped != empty) {\n                    children[i] = fromLocal;\n                    children[i + 1] = toLocal;\n                    children[i + 2] = mapped;\n                }\n                else {\n                    children[i + 1] = -2;\n                    mustRebuild = true;\n                }\n            }\n            else {\n                mustRebuild = true;\n            }\n        }\n    // Remaining children must be collected and rebuilt into the appropriate structure\n    if (mustRebuild) {\n        let decorations = mapAndGatherRemainingDecorations(children, oldChildren, newLocal, mapping, offset, oldOffset, options);\n        let built = buildTree(decorations, node, 0, options);\n        newLocal = built.local;\n        for (let i = 0; i < children.length; i += 3)\n            if (children[i + 1] < 0) {\n                children.splice(i, 3);\n                i -= 3;\n            }\n        for (let i = 0, j = 0; i < built.children.length; i += 3) {\n            let from = built.children[i];\n            while (j < children.length && children[j] < from)\n                j += 3;\n            children.splice(j, 0, built.children[i], built.children[i + 1], built.children[i + 2]);\n        }\n    }\n    return new DecorationSet(newLocal.sort(byPos), children);\n}\nfunction moveSpans(spans, offset) {\n    if (!offset || !spans.length)\n        return spans;\n    let result = [];\n    for (let i = 0; i < spans.length; i++) {\n        let span = spans[i];\n        result.push(new Decoration(span.from + offset, span.to + offset, span.type));\n    }\n    return result;\n}\nfunction mapAndGatherRemainingDecorations(children, oldChildren, decorations, mapping, offset, oldOffset, options) {\n    // Gather all decorations from the remaining marked children\n    function gather(set, oldOffset) {\n        for (let i = 0; i < set.local.length; i++) {\n            let mapped = set.local[i].map(mapping, offset, oldOffset);\n            if (mapped)\n                decorations.push(mapped);\n            else if (options.onRemove)\n                options.onRemove(set.local[i].spec);\n        }\n        for (let i = 0; i < set.children.length; i += 3)\n            gather(set.children[i + 2], set.children[i] + oldOffset + 1);\n    }\n    for (let i = 0; i < children.length; i += 3)\n        if (children[i + 1] == -1)\n            gather(children[i + 2], oldChildren[i] + oldOffset + 1);\n    return decorations;\n}\nfunction takeSpansForNode(spans, node, offset) {\n    if (node.isLeaf)\n        return null;\n    let end = offset + node.nodeSize, found = null;\n    for (let i = 0, span; i < spans.length; i++) {\n        if ((span = spans[i]) && span.from > offset && span.to < end) {\n            (found || (found = [])).push(span);\n            spans[i] = null;\n        }\n    }\n    return found;\n}\nfunction withoutNulls(array) {\n    let result = [];\n    for (let i = 0; i < array.length; i++)\n        if (array[i] != null)\n            result.push(array[i]);\n    return result;\n}\n// Build up a tree that corresponds to a set of decorations. `offset`\n// is a base offset that should be subtracted from the `from` and `to`\n// positions in the spans (so that we don't have to allocate new spans\n// for recursive calls).\nfunction buildTree(spans, node, offset, options) {\n    let children = [], hasNulls = false;\n    node.forEach((childNode, localStart) => {\n        let found = takeSpansForNode(spans, childNode, localStart + offset);\n        if (found) {\n            hasNulls = true;\n            let subtree = buildTree(found, childNode, offset + localStart + 1, options);\n            if (subtree != empty)\n                children.push(localStart, localStart + childNode.nodeSize, subtree);\n        }\n    });\n    let locals = moveSpans(hasNulls ? withoutNulls(spans) : spans, -offset).sort(byPos);\n    if (locals.length) {\n        let cur = new FragmentCursor(node.content);\n        for (let i = 0; i < locals.length; i++)\n            if (!locals[i].type.valid(node, locals[i], cur)) {\n                if (options.onRemove)\n                    options.onRemove(locals[i].spec);\n                locals.splice(i--, 1);\n            }\n    }\n    return locals.length || children.length ? new DecorationSet(locals, children) : empty;\n}\n// Used to sort decorations so that ones with a low start position\n// come first, and within a set with the same start position, those\n// with an smaller end position come first.\nfunction byPos(a, b) {\n    return a.from - b.from || a.to - b.to;\n}\n// Scan a sorted array of decorations for partially overlapping spans,\n// and split those so that only fully overlapping spans are left (to\n// make subsequent rendering easier). Will return the input array if\n// no partially overlapping spans are found (the common case).\nfunction removeOverlap(spans) {\n    let working = spans;\n    for (let i = 0; i < working.length - 1; i++) {\n        let span = working[i];\n        if (span.from != span.to)\n            for (let j = i + 1; j < working.length; j++) {\n                let next = working[j];\n                if (next.from == span.from) {\n                    if (next.to != span.to) {\n                        if (working == spans)\n                            working = spans.slice();\n                        // Followed by a partially overlapping larger span. Split that\n                        // span.\n                        working[j] = next.copy(next.from, span.to);\n                        insertAhead(working, j + 1, next.copy(span.to, next.to));\n                    }\n                    continue;\n                }\n                else {\n                    if (next.from < span.to) {\n                        if (working == spans)\n                            working = spans.slice();\n                        // The end of this one overlaps with a subsequent span. Split\n                        // this one.\n                        working[i] = span.copy(span.from, next.from);\n                        insertAhead(working, j, span.copy(next.from, span.to));\n                    }\n                    break;\n                }\n            }\n    }\n    return working;\n}\nfunction insertAhead(array, i, deco) {\n    while (i < array.length && byPos(deco, array[i]) > 0)\n        i++;\n    array.splice(i, 0, deco);\n}\n// Get the decorations associated with the current props of a view.\nfunction viewDecorations(view) {\n    let found = [];\n    view.someProp(\"decorations\", f => {\n        let result = f(view.state);\n        if (result && result != empty)\n            found.push(result);\n    });\n    if (view.cursorWrapper)\n        found.push(DecorationSet.create(view.state.doc, [view.cursorWrapper.deco]));\n    return DecorationGroup.from(found);\n}\n\n// Note that all referencing and parsing is done with the\n// start-of-operation selection and document, since that's the one\n// that the DOM represents. If any changes came in in the meantime,\n// the modification is mapped over those before it is applied, in\n// readDOMChange.\nfunction parseBetween(view, from_, to_, addedNodes) {\n    let { node: parent, fromOffset, toOffset, from, to } = view.docView.parseRange(from_, to_);\n    let domSel = view.domSel.range;\n    let find;\n    let anchor = domSel.anchorNode;\n    if (anchor && contains(view.dom, anchor)) {\n        find = [{ node: anchor, offset: domSel.anchorOffset }];\n        if (!selectionCollapsed(domSel))\n            find.push({ node: domSel.focusNode, offset: domSel.focusOffset });\n    }\n    // Work around issue in Chrome where backspacing sometimes replaces\n    // the deleted content with a random BR node (issues #799, #831)\n    if (chrome && view.input.lastKeyCode === 8) {\n        for (let off = toOffset; off > fromOffset; off--) {\n            let node = parent.childNodes[off - 1], desc = node.pmViewDesc;\n            if (node.nodeName == \"BR\" && !desc) {\n                toOffset = off;\n                break;\n            }\n            if (!desc || desc.size)\n                break;\n        }\n    }\n    let startDoc = view.state.doc;\n    let parser = view.someProp(\"domParser\") || DOMParser.fromSchema(view.state.schema);\n    let $from = startDoc.resolve(from);\n    let sel = null, doc = parser.parse(parent, {\n        topNode: $from.parent,\n        topMatch: $from.parent.contentMatchAt($from.index()),\n        topOpen: true,\n        from: fromOffset,\n        to: toOffset,\n        preserveWhitespace: $from.parent.type.whitespace == \"pre\" ? \"full\" : true,\n        findPositions: find,\n        ruleFromNode: ruleFromNode(addedNodes),\n        context: $from\n    });\n    if (find && find[0].pos != null) {\n        let anchor = find[0].pos, head = find[1] && find[1].pos;\n        if (head == null)\n            head = anchor;\n        sel = { anchor: anchor + from, head: head + from };\n    }\n    return { doc, sel, from, to };\n}\nconst ruleFromNode = (added) => (dom) => {\n    let desc = dom.pmViewDesc;\n    if (desc) {\n        return desc.parseRule(added);\n    }\n    else if (dom.nodeName == \"BR\" && dom.parentNode) {\n        // Safari replaces the list item or table cell with a BR\n        // directly in the list node (?!) if you delete the last\n        // character in a list item or table cell (#708, #862)\n        if (safari && /^(ul|ol)$/i.test(dom.parentNode.nodeName)) {\n            let skip = document.createElement(\"div\");\n            skip.appendChild(document.createElement(\"li\"));\n            return { skip };\n        }\n        else if (dom.parentNode.lastChild == dom || safari && /^(tr|table)$/i.test(dom.parentNode.nodeName)) {\n            return { ignore: true };\n        }\n    }\n    else if (dom.nodeName == \"IMG\" && dom.getAttribute(\"mark-placeholder\")) {\n        return { ignore: true };\n    }\n    return null;\n};\nconst isInline = /^(a|abbr|acronym|b|bd[io]|big|br|button|cite|code|data(list)?|del|dfn|em|i|img|ins|kbd|label|map|mark|meter|output|q|ruby|s|samp|small|span|strong|su[bp]|time|u|tt|var)$/i;\nfunction readDOMChange(view, from, to, selChange, typeOver, addedNodes) {\n    let compositionID = view.input.compositionPendingChanges || (view.composing ? view.input.compositionID : 0);\n    view.input.compositionPendingChanges = 0;\n    if (from < 0) {\n        let origin = view.input.lastSelectionTime > Date.now() - 50 ? view.input.lastSelectionOrigin : null;\n        let newSel = selectionFromDOM(view, view.domSel.range, origin);\n        if (newSel && !view.state.selection.eq(newSel) && view.domSel.active) {\n            if (chrome && android &&\n                view.input.lastKeyCode === 13 && Date.now() - 100 < view.input.lastKeyCodeTime &&\n                dispatchKey(view, \"Enter\"))\n                return;\n            let tr = view.state.tr.setSelection(newSel);\n            if (origin == \"pointer\")\n                tr.setMeta(\"pointer\", true);\n            else if (origin == \"key\")\n                tr.scrollIntoView();\n            if (compositionID)\n                tr.setMeta(\"composition\", compositionID);\n            view.dispatch(tr);\n        }\n        return;\n    }\n    let $before = view.state.doc.resolve(from);\n    let shared = $before.sharedDepth(to);\n    from = $before.before(shared + 1);\n    to = view.state.doc.resolve(to).after(shared + 1);\n    let sel = view.state.selection;\n    let parse = parseBetween(view, from, to, addedNodes);\n    let doc = view.state.doc, compare = doc.slice(parse.from, parse.to);\n    let preferredPos, preferredSide;\n    // Prefer anchoring to end when Backspace is pressed\n    if (view.input.lastKeyCode === 8 && Date.now() - 100 < view.input.lastKeyCodeTime) {\n        preferredPos = view.state.selection.to;\n        preferredSide = \"end\";\n    }\n    else {\n        preferredPos = view.state.selection.from;\n        preferredSide = \"start\";\n    }\n    view.input.lastKeyCode = null;\n    let change = findDiff(compare.content, parse.doc.content, parse.from, preferredPos, preferredSide);\n    if (change)\n        view.input.domChangeCount++;\n    if ((ios && view.input.lastIOSEnter > Date.now() - 225 || android) &&\n        addedNodes.some(n => isElt(n) && !isInline.test(n.nodeName)) &&\n        (!change || change.endA >= change.endB) &&\n        dispatchKey(view, \"Enter\")) {\n        view.input.lastIOSEnter = 0;\n        return;\n    }\n    if (!change) {\n        if (typeOver && sel instanceof TextSelection && !sel.empty && sel.$head.sameParent(sel.$anchor) &&\n            !view.composing && !(parse.sel && parse.sel.anchor != parse.sel.head)) {\n            change = { start: sel.from, endA: sel.to, endB: sel.to };\n        }\n        else {\n            if (parse.sel) {\n                let sel = resolveSelection(view, view.state.doc, parse.sel);\n                if (sel && !sel.eq(view.state.selection)) {\n                    let tr = view.state.tr.setSelection(sel);\n                    if (compositionID)\n                        tr.setMeta(\"composition\", compositionID);\n                    view.dispatch(tr);\n                }\n            }\n            return;\n        }\n    }\n    // Handle the case where overwriting a selection by typing matches\n    // the start or end of the selected content, creating a change\n    // that's smaller than what was actually overwritten.\n    if (view.state.selection.from < view.state.selection.to &&\n        change.start == change.endB &&\n        view.state.selection instanceof TextSelection) {\n        if (change.start > view.state.selection.from && change.start <= view.state.selection.from + 2 &&\n            view.state.selection.from >= parse.from) {\n            change.start = view.state.selection.from;\n        }\n        else if (change.endA < view.state.selection.to && change.endA >= view.state.selection.to - 2 &&\n            view.state.selection.to <= parse.to) {\n            change.endB += (view.state.selection.to - change.endA);\n            change.endA = view.state.selection.to;\n        }\n    }\n    let $from = parse.doc.resolveNoCache(change.start - parse.from);\n    let $to = parse.doc.resolveNoCache(change.endB - parse.from);\n    let $fromA = doc.resolve(change.start);\n    let inlineChange = $from.sameParent($to) && $from.parent.inlineContent && $fromA.end() >= change.endA;\n    // If this looks like the effect of pressing Enter (or was recorded\n    // as being an iOS enter press), just dispatch an Enter key instead.\n    if (((ios && view.input.lastIOSEnter > Date.now() - 225 &&\n        (!inlineChange || addedNodes.some(n => n.nodeName == \"DIV\" || n.nodeName == \"P\"))) ||\n        (!inlineChange && looksLikeEnter(parse.doc, $from.pos, $to.pos))) &&\n        dispatchKey(view, \"Enter\")) {\n        view.input.lastIOSEnter = 0;\n        return;\n    }\n    // Same for backspace\n    if (view.state.selection.anchor > change.start &&\n        (inlineChange ? change.endA > change.start && change.endB == change.start\n            : looksLikeBlockJoin(doc, change.start, change.endA, $from, $to)) &&\n        dispatchKey(view, \"Backspace\")) {\n        if (android && chrome)\n            view.domSel.suppressChanges();\n        return;\n    }\n    // Chrome will occasionally, during composition, delete the\n    // entire composition and then immediately insert it again. This is\n    // used to detect that situation.\n    if (chrome && change.endB == change.start)\n        view.input.lastChromeDelete = Date.now();\n    // This tries to detect Android virtual keyboard\n    // enter-and-pick-suggestion action. That sometimes (see issue\n    // #1059) first fires a DOM mutation, before moving the selection to\n    // the newly created block. And then, because ProseMirror cleans up\n    // the DOM selection, it gives up moving the selection entirely,\n    // leaving the cursor in the wrong place. When that happens, we drop\n    // the new paragraph from the initial change, and fire a simulated\n    // enter key afterwards.\n    if (android && !inlineChange && $from.start() != $to.start() && $to.parentOffset == 0 && $from.depth == $to.depth &&\n        parse.sel && parse.sel.anchor == parse.sel.head && parse.sel.head == change.endA) {\n        change.endB -= 2;\n        $to = parse.doc.resolveNoCache(change.endB - parse.from);\n        setTimeout(() => dispatchKey(view, \"Enter\"), 20);\n    }\n    let chFrom = change.start, chTo = change.endA;\n    let mkTr = (base) => {\n        let tr = base || view.state.tr.replace(chFrom, chTo, parse.doc.slice(change.start - parse.from, change.endB - parse.from));\n        if (parse.sel) {\n            let sel = resolveSelection(view, tr.doc, parse.sel);\n            // Chrome will sometimes, during composition, report the\n            // selection in the wrong place. If it looks like that is\n            // happening, don't update the selection.\n            if (sel && !(chrome && view.composing && sel.empty &&\n                (change.start != change.endB || view.input.lastChromeDelete < Date.now() - 100) &&\n                (sel.head == chFrom || sel.head == tr.mapping.map(chTo) - 1)))\n                tr.setSelection(sel);\n        }\n        if (compositionID)\n            tr.setMeta(\"composition\", compositionID);\n        return tr.scrollIntoView();\n    };\n    let markChange;\n    if (inlineChange) {\n        if ($from.pos == $to.pos) { // Deletion\n            let tr = mkTr(view.state.tr.delete(chFrom, chTo));\n            let marks = doc.resolve(change.start).marksAcross(doc.resolve(change.endA));\n            if (marks)\n                tr.ensureMarks(marks);\n            view.dispatch(tr);\n        }\n        else if ( // Adding or removing a mark\n        change.endA == change.endB &&\n            (markChange = isMarkChange($from.parent.content.cut($from.parentOffset, $to.parentOffset), $fromA.parent.content.cut($fromA.parentOffset, change.endA - $fromA.start())))) {\n            let tr = mkTr(view.state.tr);\n            if (markChange.type == \"add\")\n                tr.addMark(chFrom, chTo, markChange.mark);\n            else\n                tr.removeMark(chFrom, chTo, markChange.mark);\n            view.dispatch(tr);\n        }\n        else if ($from.parent.child($from.index()).isText && $from.index() == $to.index() - ($to.textOffset ? 0 : 1)) {\n            // Both positions in the same text node -- simply insert text\n            let text = $from.parent.textBetween($from.parentOffset, $to.parentOffset);\n            let deflt = () => mkTr(view.state.tr.insertText(text, chFrom, chTo));\n            if (!view.someProp(\"handleTextInput\", f => f(view, chFrom, chTo, text, deflt)))\n                view.dispatch(deflt());\n        }\n        else {\n            view.dispatch(mkTr());\n        }\n    }\n    else {\n        view.dispatch(mkTr());\n    }\n}\nfunction resolveSelection(view, doc, parsedSel) {\n    if (Math.max(parsedSel.anchor, parsedSel.head) > doc.content.size)\n        return null;\n    return selectionBetween(view, doc.resolve(parsedSel.anchor), doc.resolve(parsedSel.head));\n}\n// Given two same-length, non-empty fragments of inline content,\n// determine whether the first could be created from the second by\n// removing or adding a single mark type.\nfunction isMarkChange(cur, prev) {\n    let curMarks = cur.firstChild.marks, prevMarks = prev.firstChild.marks;\n    let added = curMarks, removed = prevMarks, type, mark, update;\n    for (let i = 0; i < prevMarks.length; i++)\n        added = prevMarks[i].removeFromSet(added);\n    for (let i = 0; i < curMarks.length; i++)\n        removed = curMarks[i].removeFromSet(removed);\n    if (added.length == 1 && removed.length == 0) {\n        mark = added[0];\n        type = \"add\";\n        update = (node) => node.mark(mark.addToSet(node.marks));\n    }\n    else if (added.length == 0 && removed.length == 1) {\n        mark = removed[0];\n        type = \"remove\";\n        update = (node) => node.mark(mark.removeFromSet(node.marks));\n    }\n    else {\n        return null;\n    }\n    let updated = [];\n    for (let i = 0; i < prev.childCount; i++)\n        updated.push(update(prev.child(i)));\n    if (Fragment.from(updated).eq(cur))\n        return { mark, type };\n}\nfunction looksLikeBlockJoin(old, start, end, $newStart, $newEnd) {\n    if ( // The content must have shrunk\n    end - start <= $newEnd.pos - $newStart.pos ||\n        // newEnd must point directly at or after the end of the block that newStart points into\n        skipClosingAndOpening($newStart, true, false) < $newEnd.pos)\n        return false;\n    let $start = old.resolve(start);\n    // Handle the case where, rather than joining blocks, the change just removed an entire block\n    if (!$newStart.parent.inlineContent) {\n        let after = $start.nodeAfter;\n        return after != null && end == start + after.nodeSize;\n    }\n    // Start must be at the end of a block\n    if ($start.parentOffset < $start.parent.content.size || !$start.parent.isTextblock)\n        return false;\n    let $next = old.resolve(skipClosingAndOpening($start, true, true));\n    // The next textblock must start before end and end near it\n    if (!$next.parent.isTextblock || $next.pos > end ||\n        skipClosingAndOpening($next, true, false) < end)\n        return false;\n    // The fragments after the join point must match\n    return $newStart.parent.content.cut($newStart.parentOffset).eq($next.parent.content);\n}\nfunction looksLikeEnter(content, from, to) {\n    let newTextlines = 0, newLeaves = 0;\n    content.nodesBetween(from, to, (node, pos) => {\n        if (node.isTextblock && pos >= from && pos < to)\n            newTextlines++;\n        else if (node.isText ? /\\S/.test(node.text.slice(Math.max(0, from - pos), Math.min(node.nodeSize, to - pos))) : node.isLeaf)\n            newLeaves++;\n    });\n    return newLeaves == 0 && newTextlines == 1;\n}\nfunction skipClosingAndOpening($pos, fromEnd, mayOpen) {\n    let depth = $pos.depth, end = fromEnd ? $pos.end() : $pos.pos;\n    while (depth > 0 && (fromEnd || $pos.indexAfter(depth) == $pos.node(depth).childCount)) {\n        depth--;\n        end++;\n        fromEnd = false;\n    }\n    if (mayOpen) {\n        let next = $pos.node(depth).maybeChild($pos.indexAfter(depth));\n        while (next && !next.isLeaf) {\n            next = next.firstChild;\n            end++;\n        }\n    }\n    return end;\n}\nfunction findDiff(a, b, pos, preferredPos, preferredSide) {\n    let start = a.findDiffStart(b, pos), lenA = pos + a.size, lenB = pos + b.size;\n    if (start == null)\n        return null;\n    let { a: endA, b: endB } = a.findDiffEnd(b, lenA, lenB);\n    if (preferredSide == \"end\") {\n        let adjust = Math.max(0, start - Math.min(endA, endB));\n        preferredPos -= endA + adjust - start;\n    }\n    if (endA < start && lenA < lenB) {\n        let move = preferredPos <= start && preferredPos >= endA ? start - preferredPos : 0;\n        start -= move;\n        endB = start + (endB - endA);\n        endA = start;\n    }\n    else if (endB < start) {\n        let move = preferredPos <= start && preferredPos >= endB ? start - preferredPos : 0;\n        start -= move;\n        endA = start + (endA - endB);\n        endB = start;\n    }\n    return { start, endA, endB };\n}\n\nconst observeOptions = {\n    childList: true,\n    characterData: true,\n    characterDataOldValue: true,\n    attributes: true,\n    attributeOldValue: true,\n    subtree: true\n};\nclass DOMObserver {\n    constructor(view) {\n        this.view = view;\n        this.queue = [];\n        this.flushingSoon = -1;\n        this.suppressingSelectionUpdates = false;\n        this.lastChangedTextNode = null;\n        this.started = false;\n        this.observer = new window.MutationObserver(mutations => {\n            for (let i = 0; i < mutations.length; i++)\n                this.queue.push(mutations[i]);\n            if (safari && view.composing && mutations.some(m => m.type == \"childList\" && m.target.nodeName == \"TR\")) {\n                // Safari does weird stuff when finishing a composition in a\n                // table cell, which tends to involve inserting inappropriate\n                // nodes in the table row.\n                view.input.badSafariComposition = true;\n                this.flushSoon();\n            }\n            else {\n                this.flush();\n            }\n        });\n    }\n    flushSoon() {\n        if (this.flushingSoon < 0)\n            this.flushingSoon = window.setTimeout(() => { this.flushingSoon = -1; this.flush(); }, 20);\n    }\n    forceFlush(always = false) {\n        if (this.flushingSoon > -1) {\n            window.clearTimeout(this.flushingSoon);\n            this.flushingSoon = -1;\n            this.flush(true);\n        }\n        else if (always) {\n            this.flush(true);\n        }\n    }\n    start() {\n        this.observer.takeRecords();\n        this.observer.observe(this.view.dom, observeOptions);\n        this.started = true;\n    }\n    stop() {\n        let take = this.observer.takeRecords();\n        if (take.length) {\n            for (let i = 0; i < take.length; i++)\n                this.queue.push(take[i]);\n            window.setTimeout(() => this.flush(), 20);\n        }\n        this.observer.disconnect();\n        this.started = false;\n    }\n    stopped(f) {\n        if (!this.started)\n            return f();\n        this.stop();\n        try {\n            return f();\n        }\n        finally {\n            this.start();\n        }\n    }\n    ignoreSelectionChange(sel) {\n        if (!sel.focusNode)\n            return true;\n        let ancestors = new Set, container;\n        for (let scan = sel.focusNode; scan; scan = parentNode(scan))\n            ancestors.add(scan);\n        for (let scan = sel.anchorNode; scan; scan = parentNode(scan))\n            if (ancestors.has(scan)) {\n                container = scan;\n                break;\n            }\n        let desc = container && this.view.docView.nearestDesc(container);\n        if (desc && desc.ignoreMutation({\n            type: \"selection\",\n            target: isText(container) ? container.parentNode : container\n        })) {\n            this.view.domSel.ignore(sel);\n            return true;\n        }\n    }\n    pendingRecords() {\n        for (let mut of this.observer.takeRecords())\n            this.queue.push(mut);\n        return this.queue;\n    }\n    flush(readSel = true) {\n        let { view } = this;\n        if (!view.docView || this.flushingSoon > -1)\n            return;\n        let mutations = this.pendingRecords();\n        if (mutations.length)\n            this.queue = [];\n        if (readSel)\n            view.domSel.read();\n        let selChange = !view.domSel.suppress && !view.domSel.synced && !!hasFocusAndSelection(view) &&\n            !this.ignoreSelectionChange(view.domSel.range);\n        let from = -1, to = -1, typeOver = false, added = [];\n        if (view.editable) {\n            for (let i = 0; i < mutations.length; i++) {\n                let result = this.registerMutation(mutations[i], added);\n                if (result) {\n                    from = from < 0 ? result.from : Math.min(result.from, from);\n                    to = to < 0 ? result.to : Math.max(result.to, to);\n                    if (result.typeOver)\n                        typeOver = true;\n                }\n            }\n        }\n        if (added.some(n => n.nodeName == \"BR\") &&\n            (view.input.lastKeyCode == 8 || view.input.lastKeyCode == 46 ||\n                chrome && (view.composing || view.input.compositionEndedAt > Date.now() - 50) &&\n                    mutations.some(m => m.type == \"childList\" && m.removedNodes.length))) {\n            // Browsers sometimes insert a bogus break node if you\n            // backspace out the last bit of text before an inline-flex node (#1552)\n            for (let node of added)\n                if (node.nodeName == \"BR\" && node.parentNode) {\n                    let after = node.nextSibling;\n                    while (after && isElt(after)) {\n                        if (after.contentEditable == \"false\") {\n                            node.parentNode.removeChild(node);\n                            break;\n                        }\n                        after = after.firstChild;\n                    }\n                }\n        }\n        else if (gecko && added.length) {\n            let brs = added.filter(n => n.nodeName == \"BR\");\n            if (brs.length == 2) {\n                let [a, b] = brs;\n                if (a.parentNode && a.parentNode.parentNode == b.parentNode)\n                    b.remove();\n                else\n                    a.remove();\n            }\n            else {\n                let { focusNode } = view.domSel.range;\n                for (let br of brs) {\n                    let parent = br.parentNode;\n                    if (parent && parent.nodeName == \"LI\" && (!focusNode || blockParent(view, focusNode) != parent))\n                        br.remove();\n                }\n            }\n        }\n        let newSel = null;\n        // If it looks like the browser has reset the selection to the\n        // start of the document after focus, restore the selection from\n        // the state\n        if (from < 0 && selChange && view.domSel.active && view.input.lastFocus > Date.now() - 200 &&\n            view.input.lastTouch < Date.now() - 300 &&\n            selectionCollapsed(view.domSel.range) && (newSel = selectionFromDOM(view, view.domSel.range)) &&\n            newSel.eq(Selection.near(view.state.doc.resolve(0), 1))) {\n            view.input.lastFocus = 0;\n            view.domSel.sync();\n            view.scrollToSelection();\n        }\n        else if (from > -1 || selChange) {\n            if (from > -1)\n                checkCSS(view);\n            if (view.input.badSafariComposition) {\n                view.input.badSafariComposition = false;\n                fixUpBadSafariComposition(view, added);\n            }\n            readDOMChange(this.view, from, to, selChange, typeOver, added);\n            if (view.docView && view.docView.damage)\n                view.updateState(view.state);\n            else if (selChange)\n                view.domSel.sync();\n        }\n    }\n    registerMutation(mut, added) {\n        var _a;\n        // Ignore mutations inside nodes that were already noted as inserted\n        if (added.indexOf(mut.target) > -1)\n            return null;\n        let desc;\n        for (let scan = mut.target; scan; scan = scan.parentNode) {\n            if (desc = this.view.docView.getDesc(scan))\n                break;\n        }\n        if (mut.type == \"attributes\" &&\n            (desc == this.view.docView || mut.attributeName == \"contenteditable\" ||\n                // Firefox sometimes fires spurious events for null/empty styles\n                (mut.attributeName == \"style\" && !mut.oldValue && !mut.target.getAttribute(\"style\"))))\n            return null;\n        if (!desc || desc.ignoreMutation(mut))\n            return null;\n        if (mut.type == \"childList\") {\n            for (let i = 0; i < mut.addedNodes.length; i++) {\n                let node = mut.addedNodes[i];\n                added.push(node);\n                if (isText(node))\n                    this.lastChangedTextNode = node;\n            }\n            if (desc.contentDOM && desc.contentDOM != desc.dom && !desc.contentDOM.contains(mut.target)) {\n                desc.markDamage(4 /* Damage.Structure */);\n                return { from: desc.posBefore, to: desc.posAfter };\n            }\n            let prev = mut.previousSibling, next = mut.nextSibling;\n            let fromOffset = prev && prev.parentNode == mut.target\n                ? domIndex(prev) + 1 : 0;\n            let from = desc.localPosFromDOM(mut.target, fromOffset, -1);\n            let toOffset = next && next.parentNode == mut.target\n                ? domIndex(next) : mut.target.childNodes.length;\n            let to = desc.localPosFromDOM(mut.target, toOffset, 1);\n            desc.markDamage(((_a = desc.contentDOM) === null || _a === void 0 ? void 0 : _a.contains(mut.target)) ? 2 /* Damage.ChildList */ : 4 /* Damage.Structure */);\n            return { from, to };\n        }\n        else if (mut.type == \"attributes\") {\n            desc.markDamage(4 /* Damage.Structure */);\n            return { from: desc.posAtStart - desc.border, to: desc.posAtEnd + desc.border };\n        }\n        else { // \"characterData\"\n            this.lastChangedTextNode = mut.target;\n            desc.markDamage(desc instanceof TextViewDesc && mut.target == desc.nodeDOM ? 8 /* Damage.Text */ : 4 /* Damage.Structure */);\n            return {\n                from: desc.posAtStart,\n                to: desc.posAtEnd,\n                // An event was generated for a text change that didn't change\n                // any text. Mark the dom change to fall back to assuming the\n                // selection was typed over with an identical value if it can't\n                // find another change.\n                typeOver: mut.target.nodeValue == mut.oldValue\n            };\n        }\n    }\n}\nlet cssChecked = new WeakMap();\nlet cssCheckWarned = false;\nfunction checkCSS(view) {\n    if (cssChecked.has(view))\n        return;\n    cssChecked.set(view, null);\n    if (['normal', 'nowrap', 'pre-line'].indexOf(getComputedStyle(view.dom).whiteSpace) !== -1) {\n        view.requiresGeckoHackNode = gecko;\n        if (cssCheckWarned)\n            return;\n        console[\"warn\"](\"ProseMirror expects the CSS white-space property to be set, preferably to 'pre-wrap'. It is recommended to load style/prosemirror.css from the prosemirror-view package.\");\n        cssCheckWarned = true;\n    }\n}\nfunction blockParent(view, node) {\n    for (let p = node.parentNode; p && p != view.dom; p = p.parentNode) {\n        let desc = view.docView.nearestDesc(p, true);\n        if (desc && desc.node.isBlock)\n            return p;\n    }\n    return null;\n}\n// Kludge for a Safari bug where, on ending a composition in an\n// otherwise empty table cell, it randomly moves the composed text\n// into the table row around that cell, greatly confusing everything\n// (#188).\nfunction fixUpBadSafariComposition(view, addedNodes) {\n    var _a;\n    let { focusNode, focusOffset } = view.domSel.range;\n    for (let node of addedNodes) {\n        if (((_a = node.parentNode) === null || _a === void 0 ? void 0 : _a.nodeName) == \"TR\") {\n            let nextCell = node.nextSibling;\n            while (nextCell && (nextCell.nodeName != \"TD\" && nextCell.nodeName != \"TH\"))\n                nextCell = nextCell.nextSibling;\n            if (nextCell) {\n                let parent = nextCell;\n                for (;;) {\n                    let first = parent.firstChild;\n                    if (!first || !isElt(first) || first.contentEditable == \"false\" || /^(BR|IMG)$/.test(first.nodeName))\n                        break;\n                    parent = first;\n                }\n                parent.insertBefore(node, parent.firstChild);\n                if (focusNode == node)\n                    view.domSelection().collapse(node, focusOffset);\n            }\n            else {\n                node.parentNode.removeChild(node);\n            }\n        }\n    }\n}\n\n/**\n@internal\n*/\nconst __parseFromClipboard = parseFromClipboard;\n/**\n@internal\n*/\nconst __endComposition = endComposition;\n/**\nAn editor view manages the DOM structure that represents an\neditable document. Its state and behavior are determined by its\n[props](https://prosemirror.net/docs/ref/#view.DirectEditorProps).\n*/\nclass EditorView {\n    /**\n    Create a view. `place` may be a DOM node that the editor should\n    be appended to, a function that will place it into the document,\n    or an object whose `mount` property holds the node to use as the\n    document container. If it is `null`, the editor will not be\n    added to the document.\n    */\n    constructor(place, props) {\n        this._root = null;\n        /**\n        @internal\n        */\n        this.focused = false;\n        /**\n        Kludge used to work around a Chrome bug @internal\n        */\n        this.trackWrites = null;\n        this.mounted = false;\n        /**\n        @internal\n        */\n        this.markCursor = null;\n        /**\n        @internal\n        */\n        this.cursorWrapper = null;\n        /**\n        @internal\n        */\n        this.lastSelectedViewDesc = undefined;\n        /**\n        @internal\n        */\n        this.input = new InputState;\n        this.prevDirectPlugins = [];\n        this.pluginViews = [];\n        /**\n        Holds `true` when a hack node is needed in Firefox to prevent the\n        [space is eaten issue](https://code.haverbeke.berlin/prosemirror/prosemirror/issues/651)\n        @internal\n        */\n        this.requiresGeckoHackNode = false;\n        /**\n        When editor content is being dragged, this object contains\n        information about the dragged slice and whether it is being\n        copied or moved. At any other time, it is null.\n        */\n        this.dragging = null;\n        this._props = props;\n        this.state = props.state;\n        this.directPlugins = props.plugins || [];\n        this.directPlugins.forEach(checkStateComponent);\n        this.dispatch = this.dispatch.bind(this);\n        this.dom = (place && place.mount) || document.createElement(\"div\");\n        if (place) {\n            if (place.appendChild)\n                place.appendChild(this.dom);\n            else if (typeof place == \"function\")\n                place(this.dom);\n            else if (place.mount)\n                this.mounted = true;\n        }\n        this.editable = getEditable(this);\n        updateCursorWrapper(this);\n        this.nodeViews = buildNodeViews(this);\n        this.docView = docViewDesc(this.state.doc, computeDocDeco(this), viewDecorations(this), this.dom, this);\n        this.domObserver = new DOMObserver(this);\n        this.domSel = new DOMSelState(this);\n        this.domObserver.start();\n        this.domSel.read();\n        initInput(this);\n        this.updatePluginViews();\n    }\n    /**\n    Holds `true` when a\n    [composition](https://w3c.github.io/uievents/#events-compositionevents)\n    is active.\n    */\n    get composing() { return this.input.composing; }\n    /**\n    The view's current [props](https://prosemirror.net/docs/ref/#view.EditorProps).\n    */\n    get props() {\n        if (this._props.state != this.state) {\n            let prev = this._props;\n            this._props = {};\n            for (let name in prev)\n                this._props[name] = prev[name];\n            this._props.state = this.state;\n        }\n        return this._props;\n    }\n    /**\n    Update the view's props. Will immediately cause an update to\n    the DOM.\n    */\n    update(props) {\n        if (props.handleDOMEvents != this._props.handleDOMEvents)\n            ensureListeners(this);\n        let prevProps = this._props;\n        this._props = props;\n        if (props.plugins) {\n            props.plugins.forEach(checkStateComponent);\n            this.directPlugins = props.plugins;\n        }\n        this.updateStateInner(props.state, prevProps);\n    }\n    /**\n    Update the view by updating existing props object with the object\n    given as argument. Equivalent to `view.update(Object.assign({},\n    view.props, props))`.\n    */\n    setProps(props) {\n        let updated = {};\n        for (let name in this._props)\n            updated[name] = this._props[name];\n        updated.state = this.state;\n        for (let name in props)\n            updated[name] = props[name];\n        this.update(updated);\n    }\n    /**\n    Update the editor's `state` prop, without touching any of the\n    other props.\n    */\n    updateState(state) {\n        this.updateStateInner(state, this._props);\n    }\n    updateStateInner(state, prevProps) {\n        var _a;\n        let prev = this.state, redraw = false, updateSel = false;\n        // When stored marks are added, stop composition, so that they can\n        // be displayed.\n        if (state.storedMarks && this.composing) {\n            clearComposition(this);\n            updateSel = true;\n        }\n        this.state = state;\n        let pluginsChanged = prev.plugins != state.plugins || this._props.plugins != prevProps.plugins;\n        if (pluginsChanged || this._props.plugins != prevProps.plugins || this._props.nodeViews != prevProps.nodeViews) {\n            let nodeViews = buildNodeViews(this);\n            if (changedNodeViews(nodeViews, this.nodeViews)) {\n                this.nodeViews = nodeViews;\n                redraw = true;\n            }\n        }\n        if (pluginsChanged || prevProps.handleDOMEvents != this._props.handleDOMEvents) {\n            ensureListeners(this);\n        }\n        this.editable = getEditable(this);\n        updateCursorWrapper(this);\n        let innerDeco = viewDecorations(this), outerDeco = computeDocDeco(this);\n        let scroll = prev.plugins != state.plugins && !prev.doc.eq(state.doc) ? \"reset\"\n            : state.scrollToSelection > prev.scrollToSelection ? \"to selection\" : \"preserve\";\n        let updateDoc = redraw || !this.docView.matchesNode(state.doc, outerDeco, innerDeco);\n        if (updateDoc || !state.selection.eq(prev.selection))\n            updateSel = true;\n        let oldScrollPos = scroll == \"preserve\" && updateSel && this.dom.style.overflowAnchor == null && storeScrollPos(this);\n        if (updateSel)\n            this.domObserver.stopped(() => {\n                // Work around an issue in Chrome where changing the DOM around\n                // an active selection puts it into a broken state where the\n                // thing the user sees differs from the selection reported by\n                // the Selection object (#710, #973, #1011, #1013, #1035).\n                let forceSelUpdate = updateDoc && chrome && !this.composing &&\n                    !prev.selection.empty && !state.selection.empty && selectionContextChanged(prev.selection, state.selection);\n                if (updateDoc) {\n                    // If the node that the selection points into is written to,\n                    // Chrome sometimes starts misreporting the selection, so this\n                    // tracks that and forces a selection reset when our update\n                    // did write to the node.\n                    let chromeKludge = chrome ? (this.trackWrites = this.domSel.range.focusNode) : null;\n                    if (this.composing)\n                        this.input.compositionNode = findCompositionNode(this);\n                    if (redraw || !this.docView.update(state.doc, outerDeco, innerDeco, this, -1)) {\n                        let prevOuter = this.docView.outerDeco;\n                        this.docView.destroy();\n                        this.docView = docViewDesc(state.doc, outerDeco, innerDeco, this.dom, this, prevOuter);\n                    }\n                    if (chromeKludge && (!this.trackWrites || !this.dom.contains(this.trackWrites)))\n                        forceSelUpdate = true;\n                }\n                this.domSel.sync(forceSelUpdate);\n            });\n        this.updatePluginViews(prev);\n        if (((_a = this.dragging) === null || _a === void 0 ? void 0 : _a.node) && !prev.doc.eq(state.doc))\n            this.updateDraggedNode(this.dragging, prev);\n        if (scroll == \"reset\") {\n            this.dom.scrollTop = 0;\n        }\n        else if (scroll == \"to selection\") {\n            this.scrollToSelection();\n        }\n        else if (oldScrollPos) {\n            resetScrollPos(oldScrollPos);\n        }\n    }\n    /**\n    @internal\n    */\n    scrollToSelection() {\n        let startDOM = this.domSel.range.focusNode;\n        if (!startDOM || !this.domSel.active) ;\n        else if (this.someProp(\"handleScrollToSelection\", f => f(this))) ;\n        else if (this.state.selection instanceof NodeSelection) {\n            let target = this.docView.domAfterPos(this.state.selection.from);\n            if (isElt(target))\n                scrollRectIntoView(this, target.getBoundingClientRect(), startDOM);\n        }\n        else {\n            scrollRectIntoView(this, this.coordsAtPos(this.state.selection.head, 1), startDOM);\n        }\n    }\n    destroyPluginViews() {\n        let view;\n        while (view = this.pluginViews.pop())\n            if (view.destroy)\n                view.destroy();\n    }\n    updatePluginViews(prevState) {\n        if (!prevState || prevState.plugins != this.state.plugins || this.directPlugins != this.prevDirectPlugins) {\n            this.prevDirectPlugins = this.directPlugins;\n            this.destroyPluginViews();\n            for (let i = 0; i < this.directPlugins.length; i++) {\n                let plugin = this.directPlugins[i];\n                if (plugin.spec.view)\n                    this.pluginViews.push(plugin.spec.view(this));\n            }\n            for (let i = 0; i < this.state.plugins.length; i++) {\n                let plugin = this.state.plugins[i];\n                if (plugin.spec.view)\n                    this.pluginViews.push(plugin.spec.view(this));\n            }\n        }\n        else {\n            for (let i = 0; i < this.pluginViews.length; i++) {\n                let pluginView = this.pluginViews[i];\n                if (pluginView.update)\n                    pluginView.update(this, prevState);\n            }\n        }\n    }\n    updateDraggedNode(dragging, prev) {\n        let sel = dragging.node, found = -1;\n        if (sel.from < this.state.doc.content.size && this.state.doc.nodeAt(sel.from) == sel.node) {\n            found = sel.from;\n        }\n        else {\n            let movedPos = sel.from + (this.state.doc.content.size - prev.doc.content.size);\n            let moved = movedPos > 0 && movedPos < this.state.doc.content.size && this.state.doc.nodeAt(movedPos);\n            if (moved == sel.node)\n                found = movedPos;\n        }\n        this.dragging = new Dragging(dragging.slice, dragging.move, found < 0 ? undefined : NodeSelection.create(this.state.doc, found));\n    }\n    someProp(propName, f) {\n        let prop = this._props && this._props[propName], value;\n        if (prop != null && (value = f ? f(prop) : prop))\n            return value;\n        for (let i = 0; i < this.directPlugins.length; i++) {\n            let prop = this.directPlugins[i].props[propName];\n            if (prop != null && (value = f ? f(prop) : prop))\n                return value;\n        }\n        let plugins = this.state.plugins;\n        if (plugins)\n            for (let i = 0; i < plugins.length; i++) {\n                let prop = plugins[i].props[propName];\n                if (prop != null && (value = f ? f(prop) : prop))\n                    return value;\n            }\n    }\n    /**\n    Query whether the view has focus.\n    */\n    hasFocus() {\n        return this.root.activeElement == this.dom;\n    }\n    /**\n    Focus the editor.\n    */\n    focus() {\n        if (this.editable)\n            focusPreventScroll(this.dom);\n        this.domSel.sync();\n    }\n    /**\n    Get the document root in which the editor exists. This will\n    usually be the top-level `document`, but might be a [shadow\n    DOM](https://developer.mozilla.org/en-US/docs/Web/Web_Components/Shadow_DOM)\n    root if the editor is inside one.\n    */\n    get root() {\n        let connected = this.dom.isConnected !== false;\n        if (!connected)\n            this._root = null;\n        let cached = this._root;\n        if (cached == null && connected)\n            for (let search = this.dom.parentNode; search; search = search.parentNode) {\n                if (search.nodeType == 9 || (search.nodeType == 11 && search.host)) {\n                    if (!search.getSelection)\n                        Object.getPrototypeOf(search).getSelection = () => search.ownerDocument.getSelection();\n                    return this._root = search;\n                }\n            }\n        return cached || document;\n    }\n    /**\n    When an existing editor view is moved to a new document or\n    shadow tree, call this to make it recompute its root.\n    */\n    updateRoot() {\n        this._root = null;\n    }\n    /**\n    Given a pair of viewport coordinates, return the document\n    position that corresponds to them. May return null if the given\n    coordinates aren't inside of the editor. When an object is\n    returned, its `pos` property is the position nearest to the\n    coordinates, and its `inside` property holds the position of the\n    inner node that the position falls inside of, or -1 if it is at\n    the top level, not in any node.\n    */\n    posAtCoords(coords) {\n        return posAtCoords(this, coords);\n    }\n    /**\n    Returns the viewport rectangle at a given document position.\n    `left` and `right` will be the same number, as this returns a\n    flat cursor-ish rectangle. If the position is between two things\n    that aren't directly adjacent, `side` determines which element\n    is used. When < 0, the element before the position is used,\n    otherwise the element after.\n    */\n    coordsAtPos(pos, side = 1) {\n        return coordsAtPos(this, pos, side);\n    }\n    /**\n    Find the DOM position that corresponds to the given document\n    position. When `side` is negative, find the position as close as\n    possible to the content before the position. When positive,\n    prefer positions close to the content after the position. When\n    zero, prefer as shallow a position as possible.\n    \n    Note that you should **not** mutate the editor's internal DOM,\n    only inspect it (and even that is usually not necessary).\n    */\n    domAtPos(pos, side = 0) {\n        return this.docView.domFromPos(pos, side);\n    }\n    /**\n    Find the DOM node that represents the document node after the\n    given position. May return `null` when the position doesn't point\n    in front of a node or if the node is inside an opaque node view.\n    \n    This is intended to be able to call things like\n    `getBoundingClientRect` on that DOM node. Do **not** mutate the\n    editor DOM directly, or add styling this way, since that will be\n    immediately overriden by the editor as it redraws the node.\n    */\n    nodeDOM(pos) {\n        let desc = this.docView.descAt(pos);\n        return desc ? desc.nodeDOM : null;\n    }\n    /**\n    Find the document position that corresponds to a given DOM\n    position. (Whenever possible, it is preferable to inspect the\n    document structure directly, rather than poking around in the\n    DOM, but sometimes\u2014for example when interpreting an event\n    target\u2014you don't have a choice.)\n    \n    The `bias` parameter can be used to influence which side of a DOM\n    node to use when the position is inside a leaf node.\n    */\n    posAtDOM(node, offset, bias = -1) {\n        let pos = this.docView.posFromDOM(node, offset, bias);\n        if (pos == null)\n            throw new RangeError(\"DOM position not inside the editor\");\n        return pos;\n    }\n    /**\n    Find out whether the selection is at the end of a textblock when\n    moving in a given direction. When, for example, given `\"left\"`,\n    it will return true if moving left from the current cursor\n    position would leave that position's parent textblock. Will apply\n    to the view's current state by default, but it is possible to\n    pass a different state.\n    */\n    endOfTextblock(dir, state) {\n        return endOfTextblock(this, state || this.state, dir);\n    }\n    /**\n    Run the editor's paste logic with the given HTML string. The\n    `event`, if given, will be passed to the\n    [`handlePaste`](https://prosemirror.net/docs/ref/#view.EditorProps.handlePaste) hook.\n    */\n    pasteHTML(html, event) {\n        return doPaste(this, \"\", html, false, event || new ClipboardEvent(\"paste\"));\n    }\n    /**\n    Run the editor's paste logic with the given plain-text input.\n    */\n    pasteText(text, event) {\n        return doPaste(this, text, null, true, event || new ClipboardEvent(\"paste\"));\n    }\n    /**\n    Serialize the given slice as it would be if it was copied from\n    this editor. Returns a DOM element that contains a\n    representation of the slice as its children, a textual\n    representation, and the transformed slice (which can be\n    different from the given input due to hooks like\n    [`transformCopied`](https://prosemirror.net/docs/ref/#view.EditorProps.transformCopied)).\n    */\n    serializeForClipboard(slice) {\n        return serializeForClipboard(this, slice);\n    }\n    /**\n    Removes the editor from the DOM and destroys all [node\n    views](https://prosemirror.net/docs/ref/#view.NodeView).\n    */\n    destroy() {\n        if (!this.docView)\n            return;\n        destroyInput(this); // disconnects this.domObserver\n        this.domSel.destroy();\n        this.destroyPluginViews();\n        if (this.mounted) {\n            this.docView.update(this.state.doc, [], viewDecorations(this), this, -1);\n            this.dom.textContent = \"\";\n        }\n        else if (this.dom.parentNode) {\n            this.dom.parentNode.removeChild(this.dom);\n        }\n        this.docView.destroy();\n        this.docView = null;\n        clearReusedRange();\n    }\n    /**\n    This is true when the view has been\n    [destroyed](https://prosemirror.net/docs/ref/#view.EditorView.destroy) (and thus should not be\n    used anymore).\n    */\n    get isDestroyed() {\n        return this.docView == null;\n    }\n    /**\n    Used for testing.\n    */\n    dispatchEvent(event) {\n        return dispatchEvent(this, event);\n    }\n    /**\n    @internal\n    */\n    domSelection() {\n        return this.root.getSelection();\n    }\n}\nEditorView.prototype.dispatch = function (tr) {\n    let dispatchTransaction = this._props.dispatchTransaction;\n    if (dispatchTransaction)\n        dispatchTransaction.call(this, tr);\n    else\n        this.updateState(this.state.apply(tr));\n};\nfunction computeDocDeco(view) {\n    let attrs = Object.create(null);\n    attrs.class = \"ProseMirror\";\n    attrs.contenteditable = String(view.editable);\n    view.someProp(\"attributes\", value => {\n        if (typeof value == \"function\")\n            value = value(view.state);\n        if (value)\n            for (let attr in value) {\n                if (attr == \"class\")\n                    attrs.class += \" \" + value[attr];\n                else if (attr == \"style\")\n                    attrs.style = (attrs.style ? attrs.style + \";\" : \"\") + value[attr];\n                else if (!attrs[attr] && attr != \"contenteditable\" && attr != \"nodeName\")\n                    attrs[attr] = String(value[attr]);\n            }\n    });\n    if (!attrs.translate)\n        attrs.translate = \"no\";\n    return [Decoration.node(0, view.state.doc.content.size, attrs)];\n}\nfunction updateCursorWrapper(view) {\n    if (view.markCursor) {\n        let dom = document.createElement(\"img\");\n        dom.className = \"ProseMirror-separator\";\n        dom.setAttribute(\"mark-placeholder\", \"true\");\n        dom.setAttribute(\"alt\", \"\");\n        view.cursorWrapper = { dom, deco: Decoration.widget(view.state.selection.from, dom, { raw: true, marks: view.markCursor }) };\n    }\n    else {\n        view.cursorWrapper = null;\n    }\n}\nfunction getEditable(view) {\n    return !view.someProp(\"editable\", value => value(view.state) === false);\n}\nfunction selectionContextChanged(sel1, sel2) {\n    let depth = Math.min(sel1.$anchor.sharedDepth(sel1.head), sel2.$anchor.sharedDepth(sel2.head));\n    return sel1.$anchor.start(depth) != sel2.$anchor.start(depth);\n}\nfunction buildNodeViews(view) {\n    let result = Object.create(null);\n    function add(obj) {\n        for (let prop in obj)\n            if (!Object.prototype.hasOwnProperty.call(result, prop))\n                result[prop] = obj[prop];\n    }\n    view.someProp(\"nodeViews\", add);\n    view.someProp(\"markViews\", add);\n    return result;\n}\nfunction changedNodeViews(a, b) {\n    let nA = 0, nB = 0;\n    for (let prop in a) {\n        if (a[prop] != b[prop])\n            return true;\n        nA++;\n    }\n    for (let _ in b)\n        nB++;\n    return nA != nB;\n}\nfunction checkStateComponent(plugin) {\n    if (plugin.spec.state || plugin.spec.filterTransaction || plugin.spec.appendTransaction)\n        throw new RangeError(\"Plugins passed directly to the view must not have a state component\");\n}\n\nexport { Decoration, DecorationSet, EditorView, __endComposition, __parseFromClipboard };\n", "export var base = {\n  8: \"Backspace\",\n  9: \"Tab\",\n  10: \"Enter\",\n  12: \"NumLock\",\n  13: \"Enter\",\n  16: \"Shift\",\n  17: \"Control\",\n  18: \"Alt\",\n  20: \"CapsLock\",\n  27: \"Escape\",\n  32: \" \",\n  33: \"PageUp\",\n  34: \"PageDown\",\n  35: \"End\",\n  36: \"Home\",\n  37: \"ArrowLeft\",\n  38: \"ArrowUp\",\n  39: \"ArrowRight\",\n  40: \"ArrowDown\",\n  44: \"PrintScreen\",\n  45: \"Insert\",\n  46: \"Delete\",\n  59: \";\",\n  61: \"=\",\n  91: \"Meta\",\n  92: \"Meta\",\n  106: \"*\",\n  107: \"+\",\n  108: \",\",\n  109: \"-\",\n  110: \".\",\n  111: \"/\",\n  144: \"NumLock\",\n  145: \"ScrollLock\",\n  160: \"Shift\",\n  161: \"Shift\",\n  162: \"Control\",\n  163: \"Control\",\n  164: \"Alt\",\n  165: \"Alt\",\n  173: \"-\",\n  186: \";\",\n  187: \"=\",\n  188: \",\",\n  189: \"-\",\n  190: \".\",\n  191: \"/\",\n  192: \"`\",\n  219: \"[\",\n  220: \"\\\\\",\n  221: \"]\",\n  222: \"'\"\n}\n\nexport var shift = {\n  48: \")\",\n  49: \"!\",\n  50: \"@\",\n  51: \"#\",\n  52: \"$\",\n  53: \"%\",\n  54: \"^\",\n  55: \"&\",\n  56: \"*\",\n  57: \"(\",\n  59: \":\",\n  61: \"+\",\n  173: \"_\",\n  186: \":\",\n  187: \"+\",\n  188: \"<\",\n  189: \"_\",\n  190: \">\",\n  191: \"?\",\n  192: \"~\",\n  219: \"{\",\n  220: \"|\",\n  221: \"}\",\n  222: \"\\\"\"\n}\n\nvar mac = typeof navigator != \"undefined\" && /Mac/.test(navigator.platform)\nvar ie = typeof navigator != \"undefined\" && /MSIE \\d|Trident\\/(?:[7-9]|\\d{2,})\\..*rv:(\\d+)/.exec(navigator.userAgent)\n\n// Fill in the digit keys\nfor (var i = 0; i < 10; i++) base[48 + i] = base[96 + i] = String(i)\n\n// The function keys\nfor (var i = 1; i <= 24; i++) base[i + 111] = \"F\" + i\n\n// And the alphabetic keys\nfor (var i = 65; i <= 90; i++) {\n  base[i] = String.fromCharCode(i + 32)\n  shift[i] = String.fromCharCode(i)\n}\n\n// For each code that doesn't have a shift-equivalent, copy the base name\nfor (var code in base) if (!shift.hasOwnProperty(code)) shift[code] = base[code]\n\nexport function keyName(event) {\n  // On macOS, keys held with Shift and Cmd don't reflect the effect of Shift in `.key`.\n  // On IE, shift effect is never included in `.key`.\n  var ignoreKey = mac && event.metaKey && event.shiftKey && !event.ctrlKey && !event.altKey ||\n      ie && event.shiftKey && event.key && event.key.length == 1 ||\n      event.key == \"Unidentified\"\n  var name = (!ignoreKey && event.key) ||\n    (event.shiftKey ? shift : base)[event.keyCode] ||\n    event.key || \"Unidentified\"\n  // Edge sometimes produces wrong names (Issue #3)\n  if (name == \"Esc\") name = \"Escape\"\n  if (name == \"Del\") name = \"Delete\"\n  // https://developer.microsoft.com/en-us/microsoft-edge/platform/issues/8860571/\n  if (name == \"Left\") name = \"ArrowLeft\"\n  if (name == \"Up\") name = \"ArrowUp\"\n  if (name == \"Right\") name = \"ArrowRight\"\n  if (name == \"Down\") name = \"ArrowDown\"\n  return name\n}\n", "import { keyName, base } from 'w3c-keyname';\nimport { Plugin } from 'prosemirror-state';\n\nconst mac = typeof navigator != \"undefined\" && /Mac|iP(hone|[oa]d)/.test(navigator.platform);\nconst windows = typeof navigator != \"undefined\" && /Win/.test(navigator.platform);\nfunction normalizeKeyName(name) {\n    let parts = name.split(/-(?!$)/), result = parts[parts.length - 1];\n    if (result == \"Space\")\n        result = \" \";\n    let alt, ctrl, shift, meta;\n    for (let i = 0; i < parts.length - 1; i++) {\n        let mod = parts[i];\n        if (/^(cmd|meta|m)$/i.test(mod))\n            meta = true;\n        else if (/^a(lt)?$/i.test(mod))\n            alt = true;\n        else if (/^(c|ctrl|control)$/i.test(mod))\n            ctrl = true;\n        else if (/^s(hift)?$/i.test(mod))\n            shift = true;\n        else if (/^mod$/i.test(mod)) {\n            if (mac)\n                meta = true;\n            else\n                ctrl = true;\n        }\n        else\n            throw new Error(\"Unrecognized modifier name: \" + mod);\n    }\n    if (alt)\n        result = \"Alt-\" + result;\n    if (ctrl)\n        result = \"Ctrl-\" + result;\n    if (meta)\n        result = \"Meta-\" + result;\n    if (shift)\n        result = \"Shift-\" + result;\n    return result;\n}\nfunction normalize(map) {\n    let copy = Object.create(null);\n    for (let prop in map)\n        copy[normalizeKeyName(prop)] = map[prop];\n    return copy;\n}\nfunction modifiers(name, event, shift = true) {\n    if (event.altKey)\n        name = \"Alt-\" + name;\n    if (event.ctrlKey)\n        name = \"Ctrl-\" + name;\n    if (event.metaKey)\n        name = \"Meta-\" + name;\n    if (shift && event.shiftKey)\n        name = \"Shift-\" + name;\n    return name;\n}\n/**\nCreate a keymap plugin for the given set of bindings.\n\nBindings should map key names to [command](https://prosemirror.net/docs/ref/#commands)-style\nfunctions, which will be called with `(EditorState, dispatch,\nEditorView)` arguments, and should return true when they've handled\nthe key. Note that the view argument isn't part of the command\nprotocol, but can be used as an escape hatch if a binding needs to\ndirectly interact with the UI.\n\nKey names may be strings like `\"Shift-Ctrl-Enter\"`\u2014a key\nidentifier prefixed with zero or more modifiers. Key identifiers\nare based on the strings that can appear in\n[`KeyEvent.key`](https:developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/key).\nUse lowercase letters to refer to letter keys (or uppercase letters\nif you want shift to be held). You may use `\"Space\"` as an alias\nfor the `\" \"` name.\n\nModifiers can be given in any order. `Shift-` (or `s-`), `Alt-` (or\n`a-`), `Ctrl-` (or `c-` or `Control-`) and `Cmd-` (or `m-` or\n`Meta-`) are recognized. For characters that are created by holding\nshift, the `Shift-` prefix is implied, and should not be added\nexplicitly.\n\nYou can use `Mod-` as a shorthand for `Cmd-` on Mac and `Ctrl-` on\nother platforms.\n\nYou can add multiple keymap plugins to an editor. The order in\nwhich they appear determines their precedence (the ones early in\nthe array get to dispatch first).\n*/\nfunction keymap(bindings) {\n    return new Plugin({ props: { handleKeyDown: keydownHandler(bindings) } });\n}\n/**\nGiven a set of bindings (using the same format as\n[`keymap`](https://prosemirror.net/docs/ref/#keymap.keymap)), return a [keydown\nhandler](https://prosemirror.net/docs/ref/#view.EditorProps.handleKeyDown) that handles them.\n*/\nfunction keydownHandler(bindings) {\n    let map = normalize(bindings);\n    return function (view, event) {\n        let name = keyName(event), baseName, direct = map[modifiers(name, event)];\n        if (direct && direct(view.state, view.dispatch, view))\n            return true;\n        // A character key\n        if (name.length == 1 && name != \" \") {\n            if (event.shiftKey) {\n                // In case the name was already modified by shift, try looking\n                // it up without its shift modifier\n                let noShift = map[modifiers(name, event, false)];\n                if (noShift && noShift(view.state, view.dispatch, view))\n                    return true;\n            }\n            if ((event.altKey || event.metaKey || event.ctrlKey) &&\n                // Ctrl-Alt may be used for AltGr on Windows\n                !(windows && event.ctrlKey && event.altKey) &&\n                (baseName = base[event.keyCode]) && baseName != name) {\n                // Try falling back to the keyCode when there's a modifier\n                // active or the character produced isn't ASCII, and our table\n                // produces a different name from the the keyCode. See #668,\n                // #1060, #1529.\n                let fromCode = map[modifiers(baseName, event)];\n                if (fromCode && fromCode(view.state, view.dispatch, view))\n                    return true;\n            }\n        }\n        return false;\n    };\n}\n\nexport { keydownHandler, keymap };\n", "var GOOD_LEAF_SIZE = 200;\n\n// :: class<T> A rope sequence is a persistent sequence data structure\n// that supports appending, prepending, and slicing without doing a\n// full copy. It is represented as a mostly-balanced tree.\nvar RopeSequence = function RopeSequence () {};\n\nRopeSequence.prototype.append = function append (other) {\n  if (!other.length) { return this }\n  other = RopeSequence.from(other);\n\n  return (!this.length && other) ||\n    (other.length < GOOD_LEAF_SIZE && this.leafAppend(other)) ||\n    (this.length < GOOD_LEAF_SIZE && other.leafPrepend(this)) ||\n    this.appendInner(other)\n};\n\n// :: (union<[T], RopeSequence<T>>) \u2192 RopeSequence<T>\n// Prepend an array or other rope to this one, returning a new rope.\nRopeSequence.prototype.prepend = function prepend (other) {\n  if (!other.length) { return this }\n  return RopeSequence.from(other).append(this)\n};\n\nRopeSequence.prototype.appendInner = function appendInner (other) {\n  return new Append(this, other)\n};\n\n// :: (?number, ?number) \u2192 RopeSequence<T>\n// Create a rope repesenting a sub-sequence of this rope.\nRopeSequence.prototype.slice = function slice (from, to) {\n    if ( from === void 0 ) from = 0;\n    if ( to === void 0 ) to = this.length;\n\n  if (from >= to) { return RopeSequence.empty }\n  return this.sliceInner(Math.max(0, from), Math.min(this.length, to))\n};\n\n// :: (number) \u2192 T\n// Retrieve the element at the given position from this rope.\nRopeSequence.prototype.get = function get (i) {\n  if (i < 0 || i >= this.length) { return undefined }\n  return this.getInner(i)\n};\n\n// :: ((element: T, index: number) \u2192 ?bool, ?number, ?number)\n// Call the given function for each element between the given\n// indices. This tends to be more efficient than looping over the\n// indices and calling `get`, because it doesn't have to descend the\n// tree for every element.\nRopeSequence.prototype.forEach = function forEach (f, from, to) {\n    if ( from === void 0 ) from = 0;\n    if ( to === void 0 ) to = this.length;\n\n  if (from <= to)\n    { this.forEachInner(f, from, to, 0); }\n  else\n    { this.forEachInvertedInner(f, from, to, 0); }\n};\n\n// :: ((element: T, index: number) \u2192 U, ?number, ?number) \u2192 [U]\n// Map the given functions over the elements of the rope, producing\n// a flat array.\nRopeSequence.prototype.map = function map (f, from, to) {\n    if ( from === void 0 ) from = 0;\n    if ( to === void 0 ) to = this.length;\n\n  var result = [];\n  this.forEach(function (elt, i) { return result.push(f(elt, i)); }, from, to);\n  return result\n};\n\n// :: (?union<[T], RopeSequence<T>>) \u2192 RopeSequence<T>\n// Create a rope representing the given array, or return the rope\n// itself if a rope was given.\nRopeSequence.from = function from (values) {\n  if (values instanceof RopeSequence) { return values }\n  return values && values.length ? new Leaf(values) : RopeSequence.empty\n};\n\nvar Leaf = /*@__PURE__*/(function (RopeSequence) {\n  function Leaf(values) {\n    RopeSequence.call(this);\n    this.values = values;\n  }\n\n  if ( RopeSequence ) Leaf.__proto__ = RopeSequence;\n  Leaf.prototype = Object.create( RopeSequence && RopeSequence.prototype );\n  Leaf.prototype.constructor = Leaf;\n\n  var prototypeAccessors = { length: { configurable: true },depth: { configurable: true } };\n\n  Leaf.prototype.flatten = function flatten () {\n    return this.values\n  };\n\n  Leaf.prototype.sliceInner = function sliceInner (from, to) {\n    if (from == 0 && to == this.length) { return this }\n    return new Leaf(this.values.slice(from, to))\n  };\n\n  Leaf.prototype.getInner = function getInner (i) {\n    return this.values[i]\n  };\n\n  Leaf.prototype.forEachInner = function forEachInner (f, from, to, start) {\n    for (var i = from; i < to; i++)\n      { if (f(this.values[i], start + i) === false) { return false } }\n  };\n\n  Leaf.prototype.forEachInvertedInner = function forEachInvertedInner (f, from, to, start) {\n    for (var i = from - 1; i >= to; i--)\n      { if (f(this.values[i], start + i) === false) { return false } }\n  };\n\n  Leaf.prototype.leafAppend = function leafAppend (other) {\n    if (this.length + other.length <= GOOD_LEAF_SIZE)\n      { return new Leaf(this.values.concat(other.flatten())) }\n  };\n\n  Leaf.prototype.leafPrepend = function leafPrepend (other) {\n    if (this.length + other.length <= GOOD_LEAF_SIZE)\n      { return new Leaf(other.flatten().concat(this.values)) }\n  };\n\n  prototypeAccessors.length.get = function () { return this.values.length };\n\n  prototypeAccessors.depth.get = function () { return 0 };\n\n  Object.defineProperties( Leaf.prototype, prototypeAccessors );\n\n  return Leaf;\n}(RopeSequence));\n\n// :: RopeSequence\n// The empty rope sequence.\nRopeSequence.empty = new Leaf([]);\n\nvar Append = /*@__PURE__*/(function (RopeSequence) {\n  function Append(left, right) {\n    RopeSequence.call(this);\n    this.left = left;\n    this.right = right;\n    this.length = left.length + right.length;\n    this.depth = Math.max(left.depth, right.depth) + 1;\n  }\n\n  if ( RopeSequence ) Append.__proto__ = RopeSequence;\n  Append.prototype = Object.create( RopeSequence && RopeSequence.prototype );\n  Append.prototype.constructor = Append;\n\n  Append.prototype.flatten = function flatten () {\n    return this.left.flatten().concat(this.right.flatten())\n  };\n\n  Append.prototype.getInner = function getInner (i) {\n    return i < this.left.length ? this.left.get(i) : this.right.get(i - this.left.length)\n  };\n\n  Append.prototype.forEachInner = function forEachInner (f, from, to, start) {\n    var leftLen = this.left.length;\n    if (from < leftLen &&\n        this.left.forEachInner(f, from, Math.min(to, leftLen), start) === false)\n      { return false }\n    if (to > leftLen &&\n        this.right.forEachInner(f, Math.max(from - leftLen, 0), Math.min(this.length, to) - leftLen, start + leftLen) === false)\n      { return false }\n  };\n\n  Append.prototype.forEachInvertedInner = function forEachInvertedInner (f, from, to, start) {\n    var leftLen = this.left.length;\n    if (from > leftLen &&\n        this.right.forEachInvertedInner(f, from - leftLen, Math.max(to, leftLen) - leftLen, start + leftLen) === false)\n      { return false }\n    if (to < leftLen &&\n        this.left.forEachInvertedInner(f, Math.min(from, leftLen), to, start) === false)\n      { return false }\n  };\n\n  Append.prototype.sliceInner = function sliceInner (from, to) {\n    if (from == 0 && to == this.length) { return this }\n    var leftLen = this.left.length;\n    if (to <= leftLen) { return this.left.slice(from, to) }\n    if (from >= leftLen) { return this.right.slice(from - leftLen, to - leftLen) }\n    return this.left.slice(from, leftLen).append(this.right.slice(0, to - leftLen))\n  };\n\n  Append.prototype.leafAppend = function leafAppend (other) {\n    var inner = this.right.leafAppend(other);\n    if (inner) { return new Append(this.left, inner) }\n  };\n\n  Append.prototype.leafPrepend = function leafPrepend (other) {\n    var inner = this.left.leafPrepend(other);\n    if (inner) { return new Append(inner, this.right) }\n  };\n\n  Append.prototype.appendInner = function appendInner (other) {\n    if (this.left.depth >= Math.max(this.right.depth, other.depth) + 1)\n      { return new Append(this.left, new Append(this.right, other)) }\n    return new Append(this, other)\n  };\n\n  return Append;\n}(RopeSequence));\n\nexport default RopeSequence;\n", "import RopeSequence from 'rope-sequence';\nimport { Mapping, AddMarkStep, RemoveMarkStep } from 'prosemirror-transform';\nimport { PluginKey, Plugin, Selection } from 'prosemirror-state';\n\n// ProseMirror's history isn't simply a way to roll back to a previous\n// state, because ProseMirror supports applying changes without adding\n// them to the history (for example during collaboration).\n//\n// To this end, each 'Branch' (one for the undo history and one for\n// the redo history) keeps an array of 'Items', which can optionally\n// hold a step (an actual undoable change), and always hold a position\n// map (which is needed to move changes below them to apply to the\n// current document).\n//\n// An item that has both a step and a selection bookmark is the start\n// of an 'event' \u2014 a group of changes that will be undone or redone at\n// once. (It stores only the bookmark, since that way we don't have to\n// provide a document until the selection is actually applied, which\n// is useful when compressing.)\n// Used to schedule history compression\nconst max_empty_items = 500;\nclass Branch {\n    constructor(items, eventCount) {\n        this.items = items;\n        this.eventCount = eventCount;\n    }\n    // Pop the latest event off the branch's history and apply it\n    // to a document transform.\n    popEvent(state, preserveItems) {\n        if (this.eventCount == 0)\n            return null;\n        let end = this.items.length;\n        for (;; end--) {\n            let next = this.items.get(end - 1);\n            if (next.selection) {\n                --end;\n                break;\n            }\n        }\n        let remap, mapFrom;\n        if (preserveItems) {\n            remap = this.remapping(end, this.items.length);\n            mapFrom = remap.maps.length;\n        }\n        let transform = state.tr;\n        let selection, remaining;\n        let addAfter = [], addBefore = [];\n        this.items.forEach((item, i) => {\n            if (!item.step) {\n                if (!remap) {\n                    remap = this.remapping(end, i + 1);\n                    mapFrom = remap.maps.length;\n                }\n                mapFrom--;\n                addBefore.push(item);\n                return;\n            }\n            if (remap) {\n                addBefore.push(new Item(item.map));\n                let step = item.step.map(remap.slice(mapFrom)), map;\n                if (step && transform.maybeStep(step).doc) {\n                    map = transform.mapping.maps[transform.mapping.maps.length - 1];\n                    addAfter.push(new Item(map, undefined, undefined, addAfter.length + addBefore.length));\n                }\n                mapFrom--;\n                if (map)\n                    remap.appendMap(map, mapFrom);\n            }\n            else {\n                transform.maybeStep(item.step);\n            }\n            if (item.selection) {\n                selection = remap ? item.selection.map(remap.slice(mapFrom)) : item.selection;\n                remaining = new Branch(this.items.slice(0, end).append(addBefore.reverse().concat(addAfter)), this.eventCount - 1);\n                return false;\n            }\n        }, this.items.length, 0);\n        return { remaining: remaining, transform, selection: selection };\n    }\n    // Create a new branch with the given transform added.\n    addTransform(transform, selection, histOptions, preserveItems) {\n        let newItems = [], eventCount = this.eventCount;\n        let oldItems = this.items, lastItem = !preserveItems && oldItems.length ? oldItems.get(oldItems.length - 1) : null;\n        for (let i = 0; i < transform.steps.length; i++) {\n            let step = transform.steps[i].invert(transform.docs[i]);\n            let item = new Item(transform.mapping.maps[i], step, selection), merged;\n            if (merged = lastItem && lastItem.merge(item)) {\n                item = merged;\n                if (i)\n                    newItems.pop();\n                else\n                    oldItems = oldItems.slice(0, oldItems.length - 1);\n            }\n            newItems.push(item);\n            if (selection) {\n                eventCount++;\n                selection = undefined;\n            }\n            if (!preserveItems)\n                lastItem = item;\n        }\n        let overflow = eventCount - histOptions.depth;\n        if (overflow > DEPTH_OVERFLOW) {\n            oldItems = cutOffEvents(oldItems, overflow);\n            eventCount -= overflow;\n        }\n        return new Branch(oldItems.append(newItems), eventCount);\n    }\n    remapping(from, to) {\n        let maps = new Mapping;\n        this.items.forEach((item, i) => {\n            let mirrorPos = item.mirrorOffset != null && i - item.mirrorOffset >= from\n                ? maps.maps.length - item.mirrorOffset : undefined;\n            maps.appendMap(item.map, mirrorPos);\n        }, from, to);\n        return maps;\n    }\n    addMaps(array) {\n        if (this.eventCount == 0)\n            return this;\n        return new Branch(this.items.append(array.map(map => new Item(map))), this.eventCount);\n    }\n    // When the collab module receives remote changes, the history has\n    // to know about those, so that it can adjust the steps that were\n    // rebased on top of the remote changes, and include the position\n    // maps for the remote changes in its array of items.\n    rebased(rebasedTransform, rebasedCount) {\n        if (!this.eventCount)\n            return this;\n        rebasedCount = Math.min(this.items.length, rebasedCount);\n        let rebasedItems = [], start = this.items.length - rebasedCount;\n        let mapping = rebasedTransform.mapping;\n        let newUntil = rebasedTransform.steps.length;\n        let eventCount = this.eventCount;\n        this.items.forEach(item => { if (item.selection)\n            eventCount--; }, start);\n        let iRebased = rebasedCount;\n        this.items.forEach(item => {\n            let pos = mapping.getMirror(--iRebased);\n            if (pos == null)\n                return;\n            newUntil = Math.min(newUntil, pos);\n            let map = mapping.maps[pos];\n            if (item.step) {\n                let step = rebasedTransform.steps[pos].invert(rebasedTransform.docs[pos]);\n                let selection = item.selection && item.selection.map(mapping.slice(iRebased + 1, pos));\n                if (selection)\n                    eventCount++;\n                rebasedItems.push(new Item(map, step, selection));\n            }\n            else {\n                rebasedItems.push(new Item(map));\n            }\n        }, start);\n        let newMaps = [];\n        for (let i = rebasedCount; i < newUntil; i++)\n            newMaps.push(new Item(mapping.maps[i]));\n        let items = this.items.slice(0, start).append(newMaps).append(rebasedItems);\n        let branch = new Branch(items, eventCount);\n        if (branch.emptyItemCount() > max_empty_items)\n            branch = branch.compress(this.items.length - rebasedItems.length);\n        return branch;\n    }\n    emptyItemCount() {\n        let count = 0;\n        this.items.forEach(item => { if (!item.step)\n            count++; });\n        return count;\n    }\n    // Compressing a branch means rewriting it to push the air (map-only\n    // items) out. During collaboration, these naturally accumulate\n    // because each remote change adds one. The `upto` argument is used\n    // to ensure that only the items below a given level are compressed,\n    // because `rebased` relies on a clean, untouched set of items in\n    // order to associate old items with rebased steps.\n    compress(upto = this.items.length) {\n        let remap = this.remapping(0, upto), mapFrom = remap.maps.length;\n        let items = [], events = 0;\n        this.items.forEach((item, i) => {\n            if (i >= upto) {\n                items.push(item);\n                if (item.selection)\n                    events++;\n            }\n            else if (item.step) {\n                let step = item.step.map(remap.slice(mapFrom)), map = step && step.getMap();\n                mapFrom--;\n                if (map)\n                    remap.appendMap(map, mapFrom);\n                if (step) {\n                    let selection = item.selection && item.selection.map(remap.slice(mapFrom));\n                    if (selection)\n                        events++;\n                    let newItem = new Item(map.invert(), step, selection), merged, last = items.length - 1;\n                    if (merged = items.length && items[last].merge(newItem))\n                        items[last] = merged;\n                    else\n                        items.push(newItem);\n                }\n            }\n            else if (item.map) {\n                mapFrom--;\n            }\n        }, this.items.length, 0);\n        return new Branch(RopeSequence.from(items.reverse()), events);\n    }\n}\nBranch.empty = new Branch(RopeSequence.empty, 0);\nfunction cutOffEvents(items, n) {\n    let cutPoint;\n    items.forEach((item, i) => {\n        if (item.selection && (n-- == 0)) {\n            cutPoint = i;\n            return false;\n        }\n    });\n    return items.slice(cutPoint);\n}\nclass Item {\n    constructor(\n    // The (forward) step map for this item.\n    map, \n    // The inverted step\n    step, \n    // If this is non-null, this item is the start of a group, and\n    // this selection is the starting selection for the group (the one\n    // that was active before the first step was applied)\n    selection, \n    // If this item is the inverse of a previous mapping on the stack,\n    // this points at the inverse's offset\n    mirrorOffset) {\n        this.map = map;\n        this.step = step;\n        this.selection = selection;\n        this.mirrorOffset = mirrorOffset;\n    }\n    merge(other) {\n        if (this.step && other.step && !other.selection) {\n            let step = other.step.merge(this.step);\n            if (step)\n                return new Item(step.getMap().invert(), step, this.selection);\n        }\n    }\n}\n// The value of the state field that tracks undo/redo history for that\n// state. Will be stored in the plugin state when the history plugin\n// is active.\nclass HistoryState {\n    constructor(done, undone, prevRanges, prevTime, prevComposition) {\n        this.done = done;\n        this.undone = undone;\n        this.prevRanges = prevRanges;\n        this.prevTime = prevTime;\n        this.prevComposition = prevComposition;\n    }\n}\nconst DEPTH_OVERFLOW = 20;\n// Record a transformation in undo history.\nfunction applyTransaction(history, state, tr, options) {\n    let historyTr = tr.getMeta(historyKey), rebased;\n    if (historyTr)\n        return historyTr.historyState;\n    if (tr.getMeta(closeHistoryKey))\n        history = new HistoryState(history.done, history.undone, null, 0, -1);\n    let appended = tr.getMeta(\"appendedTransaction\");\n    if (tr.steps.length == 0) {\n        return history;\n    }\n    else if (appended && appended.getMeta(historyKey)) {\n        if (appended.getMeta(historyKey).redo)\n            return new HistoryState(history.done.addTransform(tr, undefined, options, mustPreserveItems(state)), history.undone, rangesFor(tr.mapping.maps), history.prevTime, history.prevComposition);\n        else\n            return new HistoryState(history.done, history.undone.addTransform(tr, undefined, options, mustPreserveItems(state)), null, history.prevTime, history.prevComposition);\n    }\n    else if (tr.getMeta(\"addToHistory\") !== false && !(appended && appended.getMeta(\"addToHistory\") === false)) {\n        // Group transforms that occur in quick succession into one event.\n        let composition = tr.getMeta(\"composition\");\n        let newGroup = history.prevTime == 0 ||\n            (!appended && history.prevComposition != composition &&\n                (history.prevTime < (tr.time || 0) - options.newGroupDelay || !isAdjacentTo(tr, history.prevRanges)));\n        let prevRanges = appended ? mapRanges(history.prevRanges, tr.mapping) : rangesFor(tr.mapping.maps);\n        return new HistoryState(history.done.addTransform(tr, newGroup ? state.selection.getBookmark() : undefined, options, mustPreserveItems(state)), Branch.empty, prevRanges, tr.time, composition == null ? history.prevComposition : composition);\n    }\n    else if (rebased = tr.getMeta(\"rebased\")) {\n        // Used by the collab module to tell the history that some of its\n        // content has been rebased.\n        return new HistoryState(history.done.rebased(tr, rebased), history.undone.rebased(tr, rebased), mapRanges(history.prevRanges, tr.mapping), history.prevTime, history.prevComposition);\n    }\n    else {\n        return new HistoryState(history.done.addMaps(tr.mapping.maps), history.undone.addMaps(tr.mapping.maps), mapRanges(history.prevRanges, tr.mapping), history.prevTime, history.prevComposition);\n    }\n}\nfunction isAdjacentTo(transform, prevRanges) {\n    if (!prevRanges)\n        return false;\n    if (!transform.docChanged)\n        return true;\n    let adjacent = false;\n    transform.mapping.maps[0].forEach((start, end) => {\n        for (let i = 0; i < prevRanges.length; i += 2)\n            if (start <= prevRanges[i + 1] && end >= prevRanges[i])\n                adjacent = true;\n    });\n    return adjacent;\n}\nfunction rangesFor(maps) {\n    let result = [];\n    for (let i = maps.length - 1; i >= 0 && result.length == 0; i--)\n        maps[i].forEach((_from, _to, from, to) => result.push(from, to));\n    return result;\n}\nfunction mapRanges(ranges, mapping) {\n    if (!ranges)\n        return null;\n    let result = [];\n    for (let i = 0; i < ranges.length; i += 2) {\n        let from = mapping.map(ranges[i], 1), to = mapping.map(ranges[i + 1], -1);\n        if (from <= to)\n            result.push(from, to);\n    }\n    return result;\n}\n// Get a selection (valid in state.doc) at the end of the first change\n// that we can determine a position for. Fall back to state.selection.\nfunction selectionFromChanges(state, tr) {\n    for (let i = 0; i < tr.steps.length; i++) {\n        let map = tr.mapping.maps[i], pos = -1;\n        map.forEach((_start, end) => pos = end);\n        if (pos < 0) {\n            let step = tr.steps[i];\n            if (step instanceof AddMarkStep || step instanceof RemoveMarkStep)\n                pos = step.to;\n        }\n        if (pos > -1)\n            return Selection.near(state.doc.resolve(pos));\n    }\n    return state.selection;\n}\n// Apply the latest event from one branch to the document and shift the event\n// onto the other branch.\nfunction histTransaction(history, state, redo) {\n    let preserveItems = mustPreserveItems(state);\n    let histOptions = historyKey.get(state).spec.config;\n    let pop = (redo ? history.undone : history.done).popEvent(state, preserveItems);\n    if (!pop)\n        return null;\n    let selection = pop.selection.resolve(pop.transform.doc);\n    let added = (redo ? history.done : history.undone).addTransform(pop.transform, selectionFromChanges(state, pop.transform).getBookmark(), histOptions, preserveItems);\n    let newHist = new HistoryState(redo ? added : pop.remaining, redo ? pop.remaining : added, null, 0, -1);\n    return pop.transform.setSelection(selection).setMeta(historyKey, { redo, historyState: newHist });\n}\nlet cachedPreserveItems = false, cachedPreserveItemsPlugins = null;\n// Check whether any plugin in the given state has a\n// `historyPreserveItems` property in its spec, in which case we must\n// preserve steps exactly as they came in, so that they can be\n// rebased.\nfunction mustPreserveItems(state) {\n    let plugins = state.plugins;\n    if (cachedPreserveItemsPlugins != plugins) {\n        cachedPreserveItems = false;\n        cachedPreserveItemsPlugins = plugins;\n        for (let i = 0; i < plugins.length; i++)\n            if (plugins[i].spec.historyPreserveItems) {\n                cachedPreserveItems = true;\n                break;\n            }\n    }\n    return cachedPreserveItems;\n}\n/**\nSet a flag on the given transaction that will prevent further steps\nfrom being appended to an existing history event (so that they\nrequire a separate undo command to undo).\n*/\nfunction closeHistory(tr) {\n    return tr.setMeta(closeHistoryKey, true);\n}\nconst historyKey = new PluginKey(\"history\");\nconst closeHistoryKey = new PluginKey(\"closeHistory\");\n/**\nReturns a plugin that enables the undo history for an editor. The\nplugin will track undo and redo stacks, which can be used with the\n[`undo`](https://prosemirror.net/docs/ref/#history.undo) and [`redo`](https://prosemirror.net/docs/ref/#history.redo) commands.\n\nYou can set an `\"addToHistory\"` [metadata\nproperty](https://prosemirror.net/docs/ref/#state.Transaction.setMeta) of `false` on a transaction\nto prevent it from being rolled back by undo.\n*/\nfunction history(config = {}) {\n    config = { depth: config.depth || 100,\n        newGroupDelay: config.newGroupDelay || 500 };\n    return new Plugin({\n        key: historyKey,\n        state: {\n            init() {\n                return new HistoryState(Branch.empty, Branch.empty, null, 0, -1);\n            },\n            apply(tr, hist, state) {\n                return applyTransaction(hist, state, tr, config);\n            }\n        },\n        config,\n        props: {\n            handleDOMEvents: {\n                beforeinput(view, e) {\n                    let inputType = e.inputType;\n                    let command = inputType == \"historyUndo\" ? undo : inputType == \"historyRedo\" ? redo : null;\n                    if (!command || !view.editable)\n                        return false;\n                    e.preventDefault();\n                    return command(view.state, view.dispatch);\n                }\n            }\n        }\n    });\n}\nfunction buildCommand(redo, scroll) {\n    return (state, dispatch) => {\n        let hist = historyKey.getState(state);\n        if (!hist || (redo ? hist.undone : hist.done).eventCount == 0)\n            return false;\n        if (dispatch) {\n            let tr = histTransaction(hist, state, redo);\n            if (tr)\n                dispatch(scroll ? tr.scrollIntoView() : tr);\n        }\n        return true;\n    };\n}\n/**\nA command function that undoes the last change, if any.\n*/\nconst undo = buildCommand(false, true);\n/**\nA command function that redoes the last undone change, if any.\n*/\nconst redo = buildCommand(true, true);\n/**\nA command function that undoes the last change. Don't scroll the\nselection into view.\n*/\nconst undoNoScroll = buildCommand(false, false);\n/**\nA command function that redoes the last undone change. Don't\nscroll the selection into view.\n*/\nconst redoNoScroll = buildCommand(true, false);\n/**\nThe amount of undoable events available in a given state.\n*/\nfunction undoDepth(state) {\n    let hist = historyKey.getState(state);\n    return hist ? hist.done.eventCount : 0;\n}\n/**\nThe amount of redoable events available in a given editor state.\n*/\nfunction redoDepth(state) {\n    let hist = historyKey.getState(state);\n    return hist ? hist.undone.eventCount : 0;\n}\n/**\nReturns true if the given transaction was generated by the history\nplugin.\n*/\nfunction isHistoryTransaction(tr) {\n    return tr.getMeta(historyKey) != null;\n}\n\nexport { closeHistory, history, isHistoryTransaction, redo, redoDepth, redoNoScroll, undo, undoDepth, undoNoScroll };\n", "import type { EditorState, Transaction } from '@tiptap/pm/state'\n\n/**\n * Takes a Transaction & Editor State and turns it into a chainable state object\n * @param config The transaction and state to create the chainable state from\n * @returns A chainable Editor state object\n */\nexport function createChainableState(config: {\n  transaction: Transaction\n  state: EditorState\n}): EditorState {\n  const { state, transaction } = config\n  let { selection } = transaction\n  let { doc } = transaction\n  let { storedMarks } = transaction\n\n  return {\n    ...state,\n    apply: state.apply.bind(state),\n    applyTransaction: state.applyTransaction.bind(state),\n    plugins: state.plugins,\n    schema: state.schema,\n    reconfigure: state.reconfigure.bind(state),\n    toJSON: state.toJSON.bind(state),\n    get storedMarks() {\n      return storedMarks\n    },\n    get selection() {\n      return selection\n    },\n    get doc() {\n      return doc\n    },\n    get tr() {\n      selection = transaction.selection\n      doc = transaction.doc\n      storedMarks = transaction.storedMarks\n\n      return transaction\n    },\n  }\n}\n", "import type { EditorState, Transaction } from '@tiptap/pm/state'\n\nimport type { Editor } from './Editor.js'\nimport { createChainableState } from './helpers/createChainableState.js'\nimport type {\n  AnyCommands,\n  CanCommands,\n  ChainedCommands,\n  CommandProps,\n  SingleCommands,\n} from './types.js'\n\nexport class CommandManager {\n  editor: Editor\n\n  rawCommands: AnyCommands\n\n  customState?: EditorState\n\n  constructor(props: { editor: Editor; state?: EditorState }) {\n    this.editor = props.editor\n    this.rawCommands = this.editor.extensionManager.commands\n    this.customState = props.state\n  }\n\n  get hasCustomState(): boolean {\n    return !!this.customState\n  }\n\n  get state(): EditorState {\n    return this.customState || this.editor.state\n  }\n\n  get commands(): SingleCommands {\n    const { rawCommands, editor, state } = this\n    const { view } = editor\n    const { tr } = state\n    const props = this.buildProps(tr)\n\n    return Object.fromEntries(\n      Object.entries(rawCommands).map(([name, command]) => {\n        const method = (...args: any[]) => {\n          const callback = command(...args)(props)\n\n          if (!tr.getMeta('preventDispatch') && !this.hasCustomState) {\n            view.dispatch(tr)\n          }\n\n          return callback\n        }\n\n        return [name, method]\n      }),\n    ) as unknown as SingleCommands\n  }\n\n  get chain(): () => ChainedCommands {\n    return () => this.createChain()\n  }\n\n  get can(): () => CanCommands {\n    return () => this.createCan()\n  }\n\n  public createChain(startTr?: Transaction, shouldDispatch = true): ChainedCommands {\n    const { rawCommands, editor, state } = this\n    const { view } = editor\n    const callbacks: boolean[] = []\n    const hasStartTransaction = !!startTr\n    const tr = startTr || state.tr\n\n    const run = () => {\n      if (\n        !hasStartTransaction &&\n        shouldDispatch &&\n        !tr.getMeta('preventDispatch') &&\n        !this.hasCustomState\n      ) {\n        view.dispatch(tr)\n      }\n\n      return callbacks.every(callback => callback === true)\n    }\n\n    const chain = {\n      ...Object.fromEntries(\n        Object.entries(rawCommands).map(([name, command]) => {\n          const chainedCommand = (...args: never[]) => {\n            const props = this.buildProps(tr, shouldDispatch)\n            const callback = command(...args)(props)\n\n            callbacks.push(callback)\n\n            return chain\n          }\n\n          return [name, chainedCommand]\n        }),\n      ),\n      run,\n    } as unknown as ChainedCommands\n\n    return chain\n  }\n\n  /**\n   * Creates a chain that safely returns `false` when run.\n   * @returns A non-dispatching command chain.\n   * @example\n   * const chain = CommandManager.createFakeChain()\n   * chain.focus().run() // false\n   */\n  public static createFakeChain(): ChainedCommands {\n    const chain = new Proxy(\n      {},\n      {\n        get: (_target, property) => {\n          if (property === 'then') {\n            return undefined\n          }\n\n          if (property === 'run') {\n            return () => false\n          }\n\n          return () => chain\n        },\n      },\n    ) as ChainedCommands\n\n    return chain\n  }\n\n  public createCan(startTr?: Transaction): CanCommands {\n    const { rawCommands, state } = this\n    const dispatch = false\n    const tr = startTr || state.tr\n    const props = this.buildProps(tr, dispatch)\n    const formattedCommands = Object.fromEntries(\n      Object.entries(rawCommands).map(([name, command]) => {\n        return [name, (...args: never[]) => command(...args)({ ...props, dispatch: undefined })]\n      }),\n    ) as unknown as SingleCommands\n\n    return {\n      ...formattedCommands,\n      chain: () => this.createChain(tr, dispatch),\n    } as CanCommands\n  }\n\n  /**\n   * Creates capability checks that safely return `false`.\n   * @returns A non-dispatching capability checker.\n   * @example\n   * const can = CommandManager.createFallbackCan()\n   * can.focus() // false\n   */\n  public static createFallbackCan(): CanCommands {\n    const chain = CommandManager.createFakeChain()\n    const can = new Proxy(\n      {\n        chain: () => chain,\n      },\n      {\n        get: (target, property) => {\n          if (property === 'then') {\n            return undefined\n          }\n\n          if (property === 'chain') {\n            return target.chain\n          }\n\n          return () => false\n        },\n      },\n    ) as CanCommands\n\n    return can\n  }\n\n  public buildProps(tr: Transaction, shouldDispatch = true): CommandProps {\n    const { rawCommands, editor, state } = this\n    const { view } = editor\n\n    const props: CommandProps = {\n      tr,\n      editor,\n      view,\n      state: createChainableState({\n        state,\n        transaction: tr,\n      }),\n      dispatch: shouldDispatch ? () => undefined : undefined,\n      chain: () => this.createChain(tr, shouldDispatch),\n      can: () => this.createCan(tr),\n      get commands() {\n        return Object.fromEntries(\n          Object.entries(rawCommands).map(([name, command]) => {\n            return [name, (...args: never[]) => command(...args)(props)]\n          }),\n        ) as unknown as SingleCommands\n      },\n    }\n\n    return props\n  }\n}\n", "import type { RawCommands } from '../types.js'\n\ndeclare module '@tiptap/core' {\n  interface Commands<ReturnType> {\n    blur: {\n      /**\n       * Removes focus from the editor.\n       * @example editor.commands.blur()\n       */\n      blur: () => ReturnType\n    }\n  }\n}\n\nexport const blur: RawCommands['blur'] =\n  () =>\n  ({ editor, view }) => {\n    requestAnimationFrame(() => {\n      if (!editor.isDestroyed) {\n        ;(view.dom as HTMLElement).blur()\n\n        // Browsers should remove the caret on blur but safari does not.\n        // See: https://github.com/ueberdosis/tiptap/issues/2405\n        window?.getSelection()?.removeAllRanges()\n      }\n    })\n\n    return true\n  }\n", "import type { RawCommands } from '../types.js'\n\ndeclare module '@tiptap/core' {\n  interface Commands<ReturnType> {\n    clearContent: {\n      /**\n       * Clear the whole document.\n       * @example editor.commands.clearContent()\n       */\n      clearContent: (\n        /**\n         * Whether to emit an update event.\n         * @default true\n         */\n        emitUpdate?: boolean,\n      ) => ReturnType\n    }\n  }\n}\n\nexport const clearContent: RawCommands['clearContent'] =\n  (emitUpdate = true) =>\n  ({ commands }) => {\n    return commands.setContent('', { emitUpdate })\n  }\n", "import { liftTarget } from '@tiptap/pm/transform'\n\nimport type { RawCommands } from '../types.js'\n\ndeclare module '@tiptap/core' {\n  interface Commands<ReturnType> {\n    clearNodes: {\n      /**\n       * Normalize nodes to a simple paragraph.\n       * @example editor.commands.clearNodes()\n       */\n      clearNodes: () => ReturnType\n    }\n  }\n}\n\nexport const clearNodes: RawCommands['clearNodes'] =\n  () =>\n  ({ tr, dispatch }) => {\n    const { selection } = tr\n    const { ranges } = selection\n\n    if (!dispatch) {\n      return true\n    }\n\n    // map the position through the transaction\n    // earlier commands may have already changed the document\n    const startMapsLength = tr.mapping.maps.length\n\n    ranges.forEach(({ $from, $to }) => {\n      const from = $from.pos\n      const to = $to.pos\n\n      // a lift can only run once the nesting above it is gone, so the number of\n      // sweeps is bounded by how deep the range is\n      const depthMapping = tr.mapping.slice(startMapsLength)\n      let maxSweeps = 1\n\n      tr.doc.nodesBetween(depthMapping.map(from), depthMapping.map(to), (_node, pos) => {\n        maxSweeps = Math.max(maxSweeps, tr.doc.resolve(pos).depth + 1)\n      })\n\n      // keep sweeping until no more lifts become valid\n      // earlier lifts can make nested items liftable\n      for (let sweep = 0; sweep < maxSweeps; sweep += 1) {\n        const docBefore = tr.doc\n        const sweepMapsLength = tr.mapping.maps.length\n        const rangeMapping = tr.mapping.slice(startMapsLength)\n\n        // rebuild the mapping after each sweep changes the document\n        // positions still refer to `docBefore`\n        let cachedMapsLength = sweepMapsLength\n        let sweepMapping = tr.mapping.slice(sweepMapsLength)\n\n        const mappedFrom = rangeMapping.map(from)\n        const mappedTo = rangeMapping.map(to)\n\n        docBefore.nodesBetween(mappedFrom, mappedTo, (node, pos) => {\n          if (node.type.isText) {\n            return\n          }\n\n          if (tr.mapping.maps.length !== cachedMapsLength) {\n            cachedMapsLength = tr.mapping.maps.length\n            sweepMapping = tr.mapping.slice(sweepMapsLength)\n          }\n\n          const $mappedFrom = tr.doc.resolve(sweepMapping.map(pos))\n          const $mappedTo = tr.doc.resolve(sweepMapping.map(pos + node.nodeSize))\n          const nodeRange = $mappedFrom.blockRange($mappedTo)\n\n          if (!nodeRange) {\n            return\n          }\n\n          const targetLiftDepth = liftTarget(nodeRange)\n\n          if (node.type.isTextblock) {\n            const { defaultType } = $mappedFrom.parent.contentMatchAt($mappedFrom.index())\n            const target = tr.doc.nodeAt(nodeRange.start)\n\n            // skip nodes that already have the default markup\n            // invalid nodes may throw after an earlier lift\n            if (\n              defaultType &&\n              target &&\n              !target.hasMarkup(defaultType) &&\n              defaultType.validContent(target.content)\n            ) {\n              tr.setNodeMarkup(nodeRange.start, defaultType)\n            }\n          }\n\n          if (targetLiftDepth || targetLiftDepth === 0) {\n            tr.lift(nodeRange, targetLiftDepth)\n          }\n        })\n\n        if (tr.doc.eq(docBefore)) {\n          break\n        }\n      }\n    })\n\n    return true\n  }\n", "import type { Command, RawCommands } from '../types.js'\n\ndeclare module '@tiptap/core' {\n  interface Commands<ReturnType> {\n    command: {\n      /**\n       * Define a command inline.\n       * @param fn The command function.\n       * @example\n       * editor.commands.command(({ tr, state }) => {\n       *   ...\n       *   return true\n       * })\n       */\n      command: (fn: (props: Parameters<Command>[0]) => boolean) => ReturnType\n    }\n  }\n}\n\nexport const command: RawCommands['command'] = fn => props => {\n  return fn(props)\n}\n", "import { createParagraphNear as originalCreateParagraphNear } from '@tiptap/pm/commands'\n\nimport type { RawCommands } from '../types.js'\n\ndeclare module '@tiptap/core' {\n  interface Commands<ReturnType> {\n    createParagraphNear: {\n      /**\n       * Create a paragraph nearby.\n       * @example editor.commands.createParagraphNear()\n       */\n      createParagraphNear: () => ReturnType\n    }\n  }\n}\n\nexport const createParagraphNear: RawCommands['createParagraphNear'] =\n  () =>\n  ({ state, dispatch }) => {\n    return originalCreateParagraphNear(state, dispatch)\n  }\n", "import { TextSelection } from '@tiptap/pm/state'\n\nimport type { RawCommands } from '../types.js'\n\ndeclare module '@tiptap/core' {\n  interface Commands<ReturnType> {\n    cut: {\n      /**\n       * Cuts content from a range and inserts it at a given position.\n       * @param range The range to cut.\n       * @param range.from The start position of the range.\n       * @param range.to The end position of the range.\n       * @param targetPos The position to insert the content at.\n       * @example editor.commands.cut({ from: 1, to: 3 }, 5)\n       */\n      cut: ({ from, to }: { from: number; to: number }, targetPos: number) => ReturnType\n    }\n  }\n}\n\nexport const cut: RawCommands['cut'] =\n  (originRange, targetPos) =>\n  ({ editor, tr }) => {\n    const { state } = editor\n\n    const contentSlice = state.doc.slice(originRange.from, originRange.to)\n\n    tr.deleteRange(originRange.from, originRange.to)\n    const newPos = tr.mapping.map(targetPos)\n\n    tr.insert(newPos, contentSlice.content)\n\n    tr.setSelection(new TextSelection(tr.doc.resolve(Math.max(newPos - 1, 0))))\n\n    return true\n  }\n", "import type { RawCommands } from '../types.js'\n\ndeclare module '@tiptap/core' {\n  interface Commands<ReturnType> {\n    deleteCurrentNode: {\n      /**\n       * Delete the node that currently has the selection anchor.\n       * @example editor.commands.deleteCurrentNode()\n       */\n      deleteCurrentNode: () => ReturnType\n    }\n  }\n}\n\nexport const deleteCurrentNode: RawCommands['deleteCurrentNode'] =\n  () =>\n  ({ tr, dispatch }) => {\n    const { selection } = tr\n    const currentNode = selection.$anchor.node()\n\n    // if there is content inside the current node, break out of this command\n    if (currentNode.content.size > 0) {\n      return false\n    }\n\n    const $pos = tr.selection.$anchor\n\n    for (let depth = $pos.depth; depth > 0; depth -= 1) {\n      const node = $pos.node(depth)\n\n      if (node.type === currentNode.type) {\n        if (dispatch) {\n          const from = $pos.before(depth)\n          const to = $pos.after(depth)\n\n          tr.delete(from, to).scrollIntoView()\n        }\n\n        return true\n      }\n    }\n\n    return false\n  }\n", "import type { NodeType, Schema } from '@tiptap/pm/model'\n\nexport function getNodeType(nameOrType: string | NodeType, schema: Schema): NodeType {\n  if (typeof nameOrType === 'string') {\n    if (!schema.nodes[nameOrType]) {\n      throw Error(\n        `There is no node type named '${nameOrType}'. Maybe you forgot to add the extension?`,\n      )\n    }\n\n    return schema.nodes[nameOrType]\n  }\n\n  return nameOrType\n}\n", "import type { NodeType } from '@tiptap/pm/model'\n\nimport { getNodeType } from '../helpers/getNodeType.js'\nimport type { RawCommands } from '../types.js'\n\ndeclare module '@tiptap/core' {\n  interface Commands<ReturnType> {\n    deleteNode: {\n      /**\n       * Delete a node with a given type or name.\n       * @param typeOrName The type or name of the node.\n       * @example editor.commands.deleteNode('paragraph')\n       */\n      deleteNode: (typeOrName: string | NodeType) => ReturnType\n    }\n  }\n}\n\nexport const deleteNode: RawCommands['deleteNode'] =\n  typeOrName =>\n  ({ tr, state, dispatch }) => {\n    const type = getNodeType(typeOrName, state.schema)\n    const $pos = tr.selection.$anchor\n\n    for (let depth = $pos.depth; depth > 0; depth -= 1) {\n      const node = $pos.node(depth)\n\n      if (node.type === type) {\n        if (dispatch) {\n          const from = $pos.before(depth)\n          const to = $pos.after(depth)\n\n          tr.delete(from, to).scrollIntoView()\n        }\n\n        return true\n      }\n    }\n\n    return false\n  }\n", "import type { Range, RawCommands } from '../types.js'\n\ndeclare module '@tiptap/core' {\n  interface Commands<ReturnType> {\n    deleteRange: {\n      /**\n       * Delete a given range.\n       * @param range The range to delete.\n       * @example editor.commands.deleteRange({ from: 1, to: 3 })\n       */\n      deleteRange: (range: Range) => ReturnType\n    }\n  }\n}\n\nexport const deleteRange: RawCommands['deleteRange'] =\n  range =>\n  ({ tr, dispatch }) => {\n    const { from, to } = range\n\n    if (dispatch) {\n      tr.delete(from, to)\n    }\n\n    return true\n  }\n", "import type { ResolvedPos, Schema } from '@tiptap/pm/model'\nimport { TextSelection } from '@tiptap/pm/state'\n\nimport type { RawCommands } from '../types.js'\n\n/**\n * Check if a node has text content based on its content specification.\n * Returns true if the node's content spec matches text* or text+ patterns.\n */\nconst hasTextContent = (nodeSpec: { content?: string }): boolean => {\n  if (!nodeSpec.content) {\n    return false\n  }\n  const textRegex = /^text(\\*|\\+)/\n  return textRegex.test(nodeSpec.content)\n}\n\n/**\n * Expand selection position for a specific side (left or right) to handle inline text nodes.\n * This function checks if the position is within an inline node with text content and\n * expands it to include the entire node boundaries for proper deletion.\n * @param $pos - The resolved position to expand\n * @param schema - The ProseMirror schema\n * @param side - Which side to expand ('left' or 'right')\n * @returns The expanded position for deletion\n */\nconst expandSelectionForSide = (\n  $pos: ResolvedPos,\n  schema: Schema,\n  side: 'left' | 'right',\n): number => {\n  if (!$pos.parent.isInline) {\n    return $pos.pos\n  }\n\n  if ((side === 'left' && $pos.pos > $pos.start()) || (side === 'right' && $pos.pos < $pos.end())) {\n    return $pos.pos\n  }\n\n  const parentContent = schema.nodes[$pos.parent.type.name].spec\n  if (!hasTextContent(parentContent)) {\n    return $pos.pos\n  }\n\n  return side === 'left' ? $pos.start() - 1 : $pos.end() + 1\n}\n\n/**\n * Expand selection range to properly handle deletion of inline text nodes.\n * Inline text nodes don't collapse correctly when text inside is deleted,\n * so we need to expand the selection to include the entire node.\n * See: https://code.haverbeke.berlin/prosemirror/prosemirror/issues/1365\n */\nconst expandSelectionForInlineText = (\n  $from: ResolvedPos,\n  $to: ResolvedPos,\n  schema: Schema,\n): { from: number; to: number } => {\n  const from = expandSelectionForSide($from, schema, 'left')\n  const to = expandSelectionForSide($to, schema, 'right')\n\n  return { from, to }\n}\n\ndeclare module '@tiptap/core' {\n  interface Commands<ReturnType> {\n    deleteSelection: {\n      /**\n       * Delete the selection, if there is one.\n       * @example editor.commands.deleteSelection()\n       */\n      deleteSelection: () => ReturnType\n    }\n  }\n}\n\nexport const deleteSelection: RawCommands['deleteSelection'] =\n  () =>\n  ({ state, dispatch }) => {\n    if (state.selection.empty) {\n      return false\n    }\n\n    if (dispatch) {\n      const tr = state.tr\n      const { ranges } = state.selection\n      // like ProseMirror's TextSelection.replace, keep the marks of the deleted text for the next input\n      const marks =\n        state.selection instanceof TextSelection\n          ? state.selection.$from.marksAcross(state.selection.$to)\n          : null\n      const mapFrom = tr.steps.length\n\n      ranges.forEach(range => {\n        const mapping = tr.mapping.slice(mapFrom)\n        const $from = tr.doc.resolve(mapping.map(range.$from.pos))\n        const $to = tr.doc.resolve(mapping.map(range.$to.pos))\n        const { from, to } = expandSelectionForInlineText($from, $to, state.schema)\n        tr.deleteRange(from, to)\n      })\n\n      // after deleting the selection we restore a text selection\n      // near the from position to avoid having confusing selections\n      // after the deletion (for example after deleting via Ctrl/Cmd+A)\n      if (!tr.selection.empty) {\n        tr.setSelection(TextSelection.near(tr.doc.resolve(tr.selection.from)))\n      }\n\n      if (marks) {\n        tr.ensureMarks(marks)\n      }\n\n      tr.scrollIntoView()\n      dispatch(tr)\n    }\n\n    return true\n  }\n", "import type { RawCommands } from '../types.js'\n\ndeclare module '@tiptap/core' {\n  interface Commands<ReturnType> {\n    enter: {\n      /**\n       * Trigger enter.\n       * @example editor.commands.enter()\n       */\n      enter: () => ReturnType\n    }\n  }\n}\n\nexport const enter: RawCommands['enter'] =\n  () =>\n  ({ commands }) => {\n    return commands.keyboardShortcut('Enter')\n  }\n", "import { exitCode as originalExitCode } from '@tiptap/pm/commands'\n\nimport type { RawCommands } from '../types.js'\n\ndeclare module '@tiptap/core' {\n  interface Commands<ReturnType> {\n    exitCode: {\n      /**\n       * Exit from a code block.\n       * @example editor.commands.exitCode()\n       */\n      exitCode: () => ReturnType\n    }\n  }\n}\n\nexport const exitCode: RawCommands['exitCode'] =\n  () =>\n  ({ state, dispatch }) => {\n    return originalExitCode(state, dispatch)\n  }\n", "export function isRegExp(value: any): value is RegExp {\n  return Object.prototype.toString.call(value) === '[object RegExp]'\n}\n", "import { isRegExp } from './isRegExp.js'\n\n/**\n * Check if object1 includes object2\n * @param object1 Object\n * @param object2 Object\n */\nexport function objectIncludes(\n  object1: Record<string, any>,\n  object2: Record<string, any>,\n  options: { strict: boolean } = { strict: true },\n): boolean {\n  const keys = Object.keys(object2)\n\n  if (!keys.length) {\n    return true\n  }\n\n  return keys.every(key => {\n    if (options.strict) {\n      return object2[key] === object1[key]\n    }\n\n    if (isRegExp(object2[key])) {\n      return object2[key].test(object1[key])\n    }\n\n    return object2[key] === object1[key]\n  })\n}\n", "import type { Mark as ProseMirrorMark, MarkType, ResolvedPos } from '@tiptap/pm/model'\n\nimport type { Range } from '../types.js'\nimport { objectIncludes } from '../utilities/objectIncludes.js'\n\nfunction findMarkInSet(\n  marks: ProseMirrorMark[],\n  type: MarkType,\n  attributes: Record<string, any> = {},\n): ProseMirrorMark | undefined {\n  return marks.find(item => {\n    return (\n      item.type === type &&\n      objectIncludes(\n        // Only check equality for the attributes that are provided\n        Object.fromEntries(Object.keys(attributes).map(k => [k, item.attrs[k]])),\n        attributes,\n      )\n    )\n  })\n}\n\nfunction isMarkInSet(\n  marks: ProseMirrorMark[],\n  type: MarkType,\n  attributes: Record<string, any> = {},\n): boolean {\n  return !!findMarkInSet(marks, type, attributes)\n}\n\n/**\n * Get the range of a mark at a resolved position.\n */\nexport function getMarkRange(\n  /**\n   * The position to get the mark range for.\n   */\n  $pos: ResolvedPos,\n  /**\n   * The mark type to get the range for.\n   */\n  type: MarkType,\n  /**\n   * The attributes to match against.\n   * If not provided, only the first mark at the position will be matched.\n   */\n  attributes?: Record<string, any>,\n): Range | void {\n  if (!$pos || !type) {\n    return\n  }\n  let start = $pos.parent.childAfter($pos.parentOffset)\n\n  // If the cursor is at the start of a text node that does not have the mark, look backward\n  if (!start.node || !start.node.marks.some(mark => mark.type === type)) {\n    start = $pos.parent.childBefore($pos.parentOffset)\n  }\n\n  // If there is no text node with the mark even backward, return undefined\n  if (!start.node || !start.node.marks.some(mark => mark.type === type)) {\n    return\n  }\n\n  // Default to only matching against the attributes of the first mark with the given type\n  if (!attributes) {\n    const firstMark = start.node.marks.find(mark => mark.type === type)\n    if (firstMark) {\n      attributes = firstMark.attrs\n    }\n  }\n\n  // We now know that the cursor is either at the start, middle or end of a text node with the specified mark\n  // so we can look it up on the targeted mark\n  const mark = findMarkInSet([...start.node.marks], type, attributes)\n\n  if (!mark) {\n    return\n  }\n\n  let startIndex = start.index\n  let startPos = $pos.start() + start.offset\n  let endIndex = startIndex + 1\n  let endPos = startPos + start.node.nodeSize\n\n  while (\n    startIndex > 0 &&\n    isMarkInSet([...$pos.parent.child(startIndex - 1).marks], type, attributes)\n  ) {\n    startIndex -= 1\n    startPos -= $pos.parent.child(startIndex).nodeSize\n  }\n\n  while (\n    endIndex < $pos.parent.childCount &&\n    isMarkInSet([...$pos.parent.child(endIndex).marks], type, attributes)\n  ) {\n    endPos += $pos.parent.child(endIndex).nodeSize\n    endIndex += 1\n  }\n\n  return {\n    from: startPos,\n    to: endPos,\n  }\n}\n", "import type { MarkType, Schema } from '@tiptap/pm/model'\n\nexport function getMarkType(nameOrType: string | MarkType, schema: Schema): MarkType {\n  if (typeof nameOrType === 'string') {\n    if (!schema.marks[nameOrType]) {\n      throw Error(\n        `There is no mark type named '${nameOrType}'. Maybe you forgot to add the extension?`,\n      )\n    }\n\n    return schema.marks[nameOrType]\n  }\n\n  return nameOrType\n}\n", "import type { MarkType } from '@tiptap/pm/model'\nimport { TextSelection } from '@tiptap/pm/state'\n\nimport { getMarkRange } from '../helpers/getMarkRange.js'\nimport { getMarkType } from '../helpers/getMarkType.js'\nimport type { RawCommands } from '../types.js'\n\ndeclare module '@tiptap/core' {\n  interface Commands<ReturnType> {\n    extendMarkRange: {\n      /**\n       * Extends the text selection to the current mark by type or name.\n       * @param typeOrName The type or name of the mark.\n       * @param attributes The attributes to match against.\n       * If not provided, only the first mark at the position will be matched.\n       * @example editor.commands.extendMarkRange('bold')\n       * @example editor.commands.extendMarkRange('mention', { userId: \"1\" })\n       */\n      extendMarkRange: (\n        /**\n         * The type or name of the mark.\n         */\n        typeOrName: string | MarkType,\n\n        /**\n         * The attributes of the mark.\n         */\n        attributes?: Record<string, any>,\n      ) => ReturnType\n    }\n  }\n}\n\nexport const extendMarkRange: RawCommands['extendMarkRange'] =\n  (typeOrName, attributes) =>\n  ({ tr, state, dispatch }) => {\n    const type = getMarkType(typeOrName, state.schema)\n    const { doc, selection } = tr\n    const { $from, from, to } = selection\n\n    if (dispatch) {\n      const range = getMarkRange($from, type, attributes)\n\n      if (range && range.from <= from && range.to >= to) {\n        const newSelection = TextSelection.create(doc, range.from, range.to)\n\n        tr.setSelection(newSelection)\n      }\n    }\n\n    return true\n  }\n", "import type { Command, CommandProps, RawCommands } from '../types.js'\n\ndeclare module '@tiptap/core' {\n  interface Commands<ReturnType> {\n    first: {\n      /**\n       * Runs one command after the other and stops at the first which returns true.\n       * @param commands The commands to run.\n       * @example editor.commands.first([command1, command2])\n       */\n      first: (commands: Command[] | ((props: CommandProps) => Command[])) => ReturnType\n    }\n  }\n}\n\nexport const first: RawCommands['first'] = commands => props => {\n  const items = typeof commands === 'function' ? commands(props) : commands\n\n  for (let i = 0; i < items.length; i += 1) {\n    if (items[i](props)) {\n      return true\n    }\n  }\n\n  return false\n}\n", "import { TextSelection } from '@tiptap/pm/state'\n\nexport function isTextSelection(value: unknown): value is TextSelection {\n  return value instanceof TextSelection\n}\n", "export function minMax(value = 0, min = 0, max = 0): number {\n  return Math.min(Math.max(value, min), max)\n}\n", "import type { Node as ProseMirrorNode } from '@tiptap/pm/model'\nimport { Selection, TextSelection } from '@tiptap/pm/state'\n\nimport type { FocusPosition } from '../types.js'\nimport { minMax } from '../utilities/minMax.js'\n\nexport function resolveFocusPosition(\n  doc: ProseMirrorNode,\n  position: FocusPosition = null,\n): Selection | null {\n  if (!position) {\n    return null\n  }\n\n  const selectionAtStart = Selection.atStart(doc)\n  const selectionAtEnd = Selection.atEnd(doc)\n\n  if (position === 'start' || position === true) {\n    return selectionAtStart\n  }\n\n  if (position === 'end') {\n    return selectionAtEnd\n  }\n\n  const minPos = selectionAtStart.from\n  const maxPos = selectionAtEnd.to\n\n  if (position === 'all') {\n    return TextSelection.create(\n      doc,\n      minMax(0, minPos, maxPos),\n      minMax(doc.content.size, minPos, maxPos),\n    )\n  }\n\n  return TextSelection.create(\n    doc,\n    minMax(position, minPos, maxPos),\n    minMax(position, minPos, maxPos),\n  )\n}\n", "export function isAndroid(): boolean {\n  return ['Android'].includes(navigator.platform) || /android/i.test(navigator.userAgent)\n}\n", "export function isiOS(): boolean {\n  return (\n    ['iPad Simulator', 'iPhone Simulator', 'iPod Simulator', 'iPad', 'iPhone', 'iPod'].includes(\n      navigator.platform,\n    ) ||\n    // iPad on iOS 13 detection\n    (navigator.userAgent.includes('Mac') && 'ontouchend' in document)\n  )\n}\n", "/**\n * Detects if the current browser is Safari (but not iOS Safari or Chrome).\n * @returns `true` if the browser is Safari, `false` otherwise.\n * @example\n * if (isSafari()) {\n *   // Safari-specific handling\n * }\n */\nexport function isSafari(): boolean {\n  return typeof navigator !== 'undefined'\n    ? /^((?!chrome|android).)*safari/i.test(navigator.userAgent)\n    : false\n}\n", "import { isTextSelection } from '../helpers/isTextSelection.js'\nimport { resolveFocusPosition } from '../helpers/resolveFocusPosition.js'\nimport type { FocusPosition, RawCommands } from '../types.js'\nimport { isAndroid } from '../utilities/isAndroid.js'\nimport { isiOS } from '../utilities/isiOS.js'\nimport { isSafari } from '../utilities/isSafari.js'\n\ndeclare module '@tiptap/core' {\n  interface Commands<ReturnType> {\n    focus: {\n      /**\n       * Focus the editor at the given position.\n       * @param position The position to focus at.\n       * @param options.scrollIntoView Scroll the focused position into view after focusing\n       * @example editor.commands.focus()\n       * @example editor.commands.focus(32, { scrollIntoView: false })\n       */\n      focus: (\n        /**\n         * The position to focus at.\n         */\n        position?: FocusPosition,\n\n        /**\n         * Optional options\n         * @default { scrollIntoView: true }\n         */\n        options?: {\n          scrollIntoView?: boolean\n        },\n      ) => ReturnType\n    }\n  }\n}\n\nexport const focus: RawCommands['focus'] =\n  (position = null, options = {}) =>\n  ({ editor, view, tr, dispatch }) => {\n    options = {\n      scrollIntoView: true,\n      ...options,\n    }\n\n    const delayedFocus = () => {\n      // focus within `requestAnimationFrame` breaks focus on iOS and Android\n      // so we have to call this\n      if (isiOS() || isAndroid()) {\n        ;(view.dom as HTMLElement).focus()\n      }\n\n      // Safari requires preventScroll to avoid the browser scrolling to the\n      // top of the editor when focus is called before the selection is set.\n      // We exclude iOS and Android since they are already handled above.\n      // see: https://github.com/ueberdosis/tiptap/issues/7318\n      if (isSafari() && !isiOS() && !isAndroid()) {\n        ;(view.dom as HTMLElement).focus({ preventScroll: true })\n      }\n\n      // For React we have to focus asynchronously. Otherwise wild things happen.\n      // see: https://github.com/ueberdosis/tiptap/issues/1520\n      requestAnimationFrame(() => {\n        if (!editor.isDestroyed) {\n          view.focus()\n\n          if (options?.scrollIntoView) {\n            editor.commands.scrollIntoView()\n          }\n        }\n      })\n    }\n\n    try {\n      if ((view.hasFocus() && position === null) || position === false) {\n        return true\n      }\n    } catch {\n      // if view.hasFocus fails (view not mounted yet)\n      // we will return false because there's nothing to focus\n      return false\n    }\n\n    // we don’t try to resolve a NodeSelection or CellSelection\n    if (dispatch && position === null && !isTextSelection(editor.state.selection)) {\n      delayedFocus()\n      return true\n    }\n\n    // pass through tr.doc instead of editor.state.doc\n    // since transactions could change the editors state before this command has been run\n    const selection = resolveFocusPosition(tr.doc, position) || editor.state.selection\n    const isSameSelection = editor.state.selection.eq(selection)\n\n    if (dispatch) {\n      if (!isSameSelection) {\n        tr.setSelection(selection)\n      }\n\n      // `tr.setSelection` resets the stored marks\n      // so we’ll restore them if the selection is the same as before\n      if (isSameSelection && tr.storedMarks) {\n        tr.setStoredMarks(tr.storedMarks)\n      }\n\n      delayedFocus()\n    }\n\n    return true\n  }\n", "import type { CommandProps, RawCommands } from '../types.js'\n\ndeclare module '@tiptap/core' {\n  interface Commands<ReturnType> {\n    forEach: {\n      /**\n       * Loop through an array of items.\n       */\n      forEach: <T>(\n        items: T[],\n        fn: (\n          item: T,\n          props: CommandProps & {\n            index: number\n          },\n        ) => boolean,\n      ) => ReturnType\n    }\n  }\n}\n\nexport const forEach: RawCommands['forEach'] = (items, fn) => props => {\n  return items.every((item, index) => fn(item, { ...props, index }))\n}\n", "import type { Fragment, Node as ProseMirrorNode, ParseOptions } from '@tiptap/pm/model'\n\nimport type { Content, RawCommands } from '../types.js'\n\nexport interface InsertContentOptions {\n  /**\n   * Options for parsing the content.\n   */\n  parseOptions?: ParseOptions\n\n  /**\n   * Whether to update the selection after inserting the content.\n   */\n  updateSelection?: boolean\n  applyInputRules?: boolean\n  applyPasteRules?: boolean\n}\n\ndeclare module '@tiptap/core' {\n  interface Commands<ReturnType> {\n    insertContent: {\n      /**\n       * Insert a node or string of HTML at the current position.\n       * @example editor.commands.insertContent('<h1>Example</h1>')\n       * @example editor.commands.insertContent('<h1>Example</h1>', { updateSelection: false })\n       */\n      insertContent: (\n        /**\n         * The ProseMirror content to insert.\n         */\n        value: Content | ProseMirrorNode | Fragment,\n\n        /**\n         * Optional options\n         */\n        options?: InsertContentOptions,\n      ) => ReturnType\n    }\n  }\n}\n\nexport const insertContent: RawCommands['insertContent'] =\n  (value, options) =>\n  ({ tr, commands }) => {\n    return commands.insertContentAt(\n      { from: tr.selection.from, to: tr.selection.to },\n      value,\n      options,\n    )\n  }\n", "const removeWhitespaces = (node: HTMLElement) => {\n  const children = node.childNodes\n\n  for (let i = children.length - 1; i >= 0; i -= 1) {\n    const child = children[i]\n\n    if (child.nodeType === 3 && child.nodeValue && /^(\\n\\s\\s|\\n)$/.test(child.nodeValue)) {\n      node.removeChild(child)\n    } else if (child.nodeType === 1) {\n      removeWhitespaces(child as HTMLElement)\n    }\n  }\n\n  return node\n}\n\nexport function elementFromString(value: string): HTMLElement {\n  if (typeof window === 'undefined') {\n    throw new Error(\n      '[tiptap error]: there is no window object available, so this function cannot be used',\n    )\n  }\n  // add a wrapper to preserve leading and trailing whitespace\n  const wrappedValue = `<body>${value}</body>`\n\n  const html = new window.DOMParser().parseFromString(wrappedValue, 'text/html').body\n\n  return removeWhitespaces(html)\n}\n", "import type { Fragment, Node as ProseMirrorNode } from '@tiptap/pm/model'\n\n/**\n * Checks whether a value is already a ProseMirror node or fragment. Looks for the\n * `nodesBetween` method, because `instanceof` fails when prosemirror-model is loaded twice.\n * @param value Any value that could be passed as content\n * @returns True for a node or a fragment, false for JSON, HTML and everything else\n * @example ```js\n * isProseMirrorContent(editor.state.doc)\n * ```\n */\nexport function isProseMirrorContent(value: unknown): value is ProseMirrorNode | Fragment {\n  return typeof (value as ProseMirrorNode | Fragment | undefined)?.nodesBetween === 'function'\n}\n", "import type { Node as ProseMirrorNode, ParseOptions } from '@tiptap/pm/model'\nimport { DOMParser, Fragment, Schema } from '@tiptap/pm/model'\n\nimport type { Content } from '../types.js'\nimport { elementFromString } from '../utilities/elementFromString.js'\nimport { isProseMirrorContent } from './isProseMirrorContent.js'\n\nexport type CreateNodeFromContentOptions = {\n  slice?: boolean\n  parseOptions?: ParseOptions\n  errorOnInvalidContent?: boolean\n}\n\n/**\n * Takes a JSON or HTML content and creates a Prosemirror node or fragment from it.\n * @param content The JSON or HTML content to create the node from\n * @param schema The Prosemirror schema to use for the node\n * @param options Options for the parser\n * @returns The created Prosemirror node or fragment\n */\nexport function createNodeFromContent(\n  content: Content | ProseMirrorNode | Fragment,\n  schema: Schema,\n  options?: CreateNodeFromContentOptions,\n): ProseMirrorNode | Fragment {\n  if (isProseMirrorContent(content)) {\n    return content\n  }\n\n  const isJSONContent = typeof content === 'object' && content !== null\n\n  options = {\n    slice: true,\n    parseOptions: {},\n    ...options,\n  }\n\n  const isTextContent = typeof content === 'string'\n\n  if (isJSONContent) {\n    try {\n      const isArrayContent = Array.isArray(content) && content.length > 0\n\n      // if the JSON Content is an array of nodes, create a fragment for each node\n      if (isArrayContent) {\n        return Fragment.fromArray(content.map(item => schema.nodeFromJSON(item)))\n      }\n\n      const node = schema.nodeFromJSON(content)\n\n      if (options.errorOnInvalidContent) {\n        node.check()\n      }\n\n      return node\n    } catch (error) {\n      if (options.errorOnInvalidContent) {\n        throw new Error('[tiptap error]: Invalid JSON content', { cause: error as Error })\n      }\n\n      console.warn('[tiptap warn]: Invalid content.', 'Passed value:', content, 'Error:', error)\n\n      return createNodeFromContent('', schema, options)\n    }\n  }\n\n  if (isTextContent) {\n    // Check for invalid content\n    if (options.errorOnInvalidContent) {\n      let hasInvalidContent = false\n      let invalidContent = ''\n\n      // A copy of the current schema with a catch-all node at the end\n      const contentCheckSchema = new Schema({\n        topNode: schema.spec.topNode,\n        marks: schema.spec.marks,\n        // Prosemirror's schemas are executed such that: the last to execute, matches last\n        // This means that we can add a catch-all node at the end of the schema to catch any content that we don't know how to handle\n        nodes: schema.spec.nodes.append({\n          __tiptap__private__unknown__catch__all__node: {\n            content: 'inline*',\n            group: 'block',\n            parseDOM: [\n              {\n                tag: '*',\n                getAttrs: e => {\n                  // If this is ever called, we know that the content has something that we don't know how to handle in the schema\n                  hasInvalidContent = true\n                  // Try to stringify the element for a more helpful error message\n                  invalidContent = typeof e === 'string' ? e : e.outerHTML\n                  return null\n                },\n              },\n            ],\n          },\n        }),\n      })\n\n      if (options.slice) {\n        DOMParser.fromSchema(contentCheckSchema).parseSlice(\n          elementFromString(content),\n          options.parseOptions,\n        )\n      } else {\n        DOMParser.fromSchema(contentCheckSchema).parse(\n          elementFromString(content),\n          options.parseOptions,\n        )\n      }\n\n      if (options.errorOnInvalidContent && hasInvalidContent) {\n        throw new Error('[tiptap error]: Invalid HTML content', {\n          cause: new Error(`Invalid element found: ${invalidContent}`),\n        })\n      }\n    }\n\n    const parser = DOMParser.fromSchema(schema)\n\n    if (options.slice) {\n      return parser.parseSlice(elementFromString(content), options.parseOptions).content\n    }\n\n    return parser.parse(elementFromString(content), options.parseOptions)\n  }\n\n  return createNodeFromContent('', schema, options)\n}\n", "import type { Fragment, Node as ProseMirrorNode } from '@tiptap/pm/model'\n\n/**\n * Checks whether a node or fragment is a fragment. Looks for a missing `type` field,\n * because `instanceof` fails when prosemirror-model is loaded twice.\n * @param nodeOrFragment A ProseMirror node or fragment\n * @returns True for a fragment, false for a node\n * @example ```js\n * isFragment(editor.state.doc.content)\n * ```\n */\nexport function isFragment(nodeOrFragment: ProseMirrorNode | Fragment): nodeOrFragment is Fragment {\n  return !('type' in nodeOrFragment)\n}\n", "import type { Transaction } from '@tiptap/pm/state'\nimport { Selection } from '@tiptap/pm/state'\nimport { ReplaceAroundStep, ReplaceStep } from '@tiptap/pm/transform'\n\n// source: https://github.com/ProseMirror/prosemirror-state/blob/master/src/selection.js#L466\nexport function selectionToInsertionEnd(tr: Transaction, startLen: number, bias: number) {\n  const last = tr.steps.length - 1\n\n  if (last < startLen) {\n    return\n  }\n\n  const step = tr.steps[last]\n\n  if (!(step instanceof ReplaceStep || step instanceof ReplaceAroundStep)) {\n    return\n  }\n\n  const map = tr.mapping.maps[last]\n  let end = 0\n\n  map.forEach((_from, _to, _newFrom, newTo) => {\n    if (end === 0) {\n      end = newTo\n    }\n  })\n\n  tr.setSelection(Selection.near(tr.doc.resolve(end), bias))\n}\n", "import type { Node as ProseMirrorNode, ParseOptions } from '@tiptap/pm/model'\nimport { Fragment } from '@tiptap/pm/model'\n\nimport { createNodeFromContent } from '../helpers/createNodeFromContent.js'\nimport { isFragment } from '../helpers/isFragment.js'\nimport { isProseMirrorContent } from '../helpers/isProseMirrorContent.js'\nimport { selectionToInsertionEnd } from '../helpers/selectionToInsertionEnd.js'\nimport type { Content, Range, RawCommands } from '../types.js'\n\nexport interface InsertContentAtOptions {\n  /**\n   * Options for parsing the content.\n   */\n  parseOptions?: ParseOptions\n\n  /**\n   * Whether to update the selection after inserting the content.\n   */\n  updateSelection?: boolean\n\n  /**\n   * Whether to apply input rules after inserting the content.\n   */\n  applyInputRules?: boolean\n\n  /**\n   * Whether to apply paste rules after inserting the content.\n   */\n  applyPasteRules?: boolean\n\n  /**\n   * Whether to throw an error if the content is invalid.\n   */\n  errorOnInvalidContent?: boolean\n}\n\ndeclare module '@tiptap/core' {\n  interface Commands<ReturnType> {\n    insertContentAt: {\n      /**\n       * Insert a node or string of HTML at a specific position.\n       * @example editor.commands.insertContentAt(0, '<h1>Example</h1>')\n       */\n      insertContentAt: (\n        /**\n         * The position to insert the content at.\n         */\n        position: number | Range,\n\n        /**\n         * The ProseMirror content to insert.\n         */\n        value: Content | ProseMirrorNode | Fragment,\n\n        /**\n         * Optional options\n         */\n        options?: InsertContentAtOptions,\n      ) => ReturnType\n    }\n  }\n}\n\nexport const insertContentAt: RawCommands['insertContentAt'] =\n  (position, value, options) =>\n  ({ tr, dispatch, editor }) => {\n    if (dispatch) {\n      options = {\n        parseOptions: editor.options.parseOptions,\n        updateSelection: true,\n        applyInputRules: false,\n        applyPasteRules: false,\n        ...options,\n      }\n\n      let content: Fragment | ProseMirrorNode\n\n      const emitContentError = (error: Error) => {\n        editor.emit('contentError', {\n          editor,\n          error,\n          disableCollaboration: () => {\n            if (\n              'collaboration' in editor.storage &&\n              typeof editor.storage.collaboration === 'object' &&\n              editor.storage.collaboration\n            ) {\n              ;(editor.storage.collaboration as any).isDisabled = true\n            }\n          },\n        })\n      }\n\n      const parseOptions: ParseOptions = {\n        preserveWhitespace: 'full',\n        ...options.parseOptions,\n      }\n\n      // If `emitContentError` is enabled, we want to check the content for errors\n      // but ignore them (do not remove the invalid content from the document)\n      if (\n        !options.errorOnInvalidContent &&\n        !editor.options.enableContentCheck &&\n        editor.options.emitContentError\n      ) {\n        try {\n          createNodeFromContent(value, editor.schema, {\n            parseOptions,\n            errorOnInvalidContent: true,\n          })\n        } catch (e) {\n          emitContentError(e as Error)\n        }\n      }\n\n      try {\n        content = createNodeFromContent(value, editor.schema, {\n          parseOptions,\n          errorOnInvalidContent: options.errorOnInvalidContent ?? editor.options.enableContentCheck,\n        })\n      } catch (e) {\n        emitContentError(e as Error)\n        return false\n      }\n\n      let { from, to } =\n        typeof position === 'number'\n          ? { from: position, to: position }\n          : { from: position.from, to: position.to }\n\n      let isOnlyTextContent = true\n      let isOnlyBlockContent = true\n      const nodes: readonly ProseMirrorNode[] = isFragment(content) ? content.content : [content]\n\n      nodes.forEach(node => {\n        // check if added node is valid\n        node.check()\n\n        isOnlyTextContent = isOnlyTextContent ? node.isText && node.marks.length === 0 : false\n\n        isOnlyBlockContent = isOnlyBlockContent ? node.isBlock : false\n      })\n\n      // check if we can replace the wrapping node by\n      // the newly inserted content\n      // example:\n      // replace an empty paragraph by an inserted image\n      // instead of inserting the image below the paragraph\n      if (from === to && isOnlyBlockContent) {\n        const { parent } = tr.doc.resolve(from)\n        const isEmptyTextBlock = parent.isTextblock && !parent.type.spec.code && !parent.childCount\n\n        if (isEmptyTextBlock) {\n          from -= 1\n          to += 1\n        }\n      }\n\n      let newContent\n\n      // if there is only plain text we have to use `insertText`\n      // because this will keep the current marks\n      if (isOnlyTextContent) {\n        // if value is string, we can use it directly\n        // otherwise if it is an array, we have to join it\n        if (Array.isArray(value)) {\n          newContent = value.map(item => item.text || '').join('')\n        } else if (isProseMirrorContent(value)) {\n          newContent = nodes.map(node => node.text ?? '').join('')\n        } else if (typeof value === 'object' && !!value && !!value.text) {\n          newContent = value.text\n        } else {\n          newContent = value as string\n        }\n\n        tr.insertText(newContent, from, to)\n      } else {\n        newContent = Fragment.from(nodes)\n\n        const $from = tr.doc.resolve(from)\n        const $fromNode = $from.node()\n        const fromSelectionAtStart = $from.parentOffset === 0\n        const isTextSelection = $fromNode.isText || $fromNode.isTextblock\n        const hasContent = $fromNode.content.size > 0\n\n        if (fromSelectionAtStart && isTextSelection && hasContent && isOnlyBlockContent) {\n          from = Math.max(0, from - 1)\n        }\n\n        tr.replaceWith(from, to, nodes)\n      }\n\n      // set cursor at end of inserted content\n      if (options.updateSelection) {\n        selectionToInsertionEnd(tr, tr.steps.length - 1, -1)\n      }\n\n      if (options.applyInputRules) {\n        tr.setMeta('applyInputRules', { from, text: newContent })\n      }\n\n      if (options.applyPasteRules) {\n        tr.setMeta('applyPasteRules', { from, text: newContent })\n      }\n    }\n\n    return true\n  }\n", "import type { ContentMatch, NodeType } from '@tiptap/pm/model'\n\n/**\n * Gets the default block type at a given match\n * @param match The content match to get the default block type from\n * @returns The default block type or null\n */\nexport function defaultBlockAt(match: ContentMatch): NodeType | null {\n  for (let i = 0; i < match.edgeCount; i += 1) {\n    const { type } = match.edge(i)\n\n    if (type.isTextblock && !type.hasRequiredAttrs()) {\n      return type\n    }\n  }\n\n  return null\n}\n", "import type { Node as ProseMirrorNode, Fragment, ResolvedPos } from '@tiptap/pm/model'\n\nimport { createNodeFromContent } from '../helpers/createNodeFromContent.js'\nimport { defaultBlockAt } from '../helpers/defaultBlockAt.js'\nimport { selectionToInsertionEnd } from '../helpers/selectionToInsertionEnd.js'\nimport type { Content, RawCommands } from '../types.js'\n\nexport interface InsertDefaultBlockOptions {\n  /**\n   * The position to insert the block at.\n   * Accepts a number or a resolved ProseMirror position.\n   * Defaults to the current caret position.\n   */\n  pos?: number | ResolvedPos\n\n  /**\n   * Attributes to apply to the inserted node.\n   * Only attributes that match the node's schema will be applied.\n   */\n  attrs?: Record<string, any>\n\n  /**\n   * Content to insert into the block.\n   * Accepts string (plain text or HTML), ProseMirror node, or Fragment.\n   */\n  content?: Content | ProseMirrorNode | Fragment\n\n  /**\n   * Whether to update the selection after inserting the content.\n   * @default true\n   */\n  updateSelection?: boolean\n}\n\ndeclare module '@tiptap/core' {\n  interface Commands<ReturnType> {\n    insertDefaultBlock: {\n      /**\n       * Insert a default content block at the given position.\n       * Returns false when the default block can't be inserted at that position.\n       * @example editor.commands.insertDefaultBlock()\n       * @example editor.commands.insertDefaultBlock({ pos: 5, content: 'Hello' })\n       */\n      insertDefaultBlock: (options?: InsertDefaultBlockOptions) => ReturnType\n    }\n  }\n}\n\nexport const insertDefaultBlock: RawCommands['insertDefaultBlock'] =\n  (options = {}) =>\n  ({ tr, dispatch, editor }) => {\n    const { pos, attrs, content, updateSelection = true } = options\n\n    let $pos: ResolvedPos\n\n    if (typeof pos === 'number') {\n      $pos = tr.doc.resolve(pos)\n    } else if (pos) {\n      $pos = pos\n    } else {\n      $pos = tr.selection.$from\n    }\n\n    const defaultType = defaultBlockAt($pos.parent.contentMatchAt($pos.index()))\n\n    if (!defaultType) {\n      return false\n    }\n\n    const validAttrKeys = Object.keys(defaultType.spec.attrs || {})\n    const filteredAttrs = attrs\n      ? Object.fromEntries(Object.entries(attrs).filter(([key]) => validAttrKeys.includes(key)))\n      : {}\n\n    let node: ProseMirrorNode | null | undefined\n\n    if (content) {\n      const parsed = createNodeFromContent(content, editor.schema)\n      node = defaultType.createAndFill(filteredAttrs, parsed)\n    } else {\n      node = defaultType.createAndFill(filteredAttrs)\n    }\n\n    if (!node) {\n      return false\n    }\n\n    if (dispatch) {\n      tr.insert($pos.pos, node)\n\n      if (updateSelection) {\n        selectionToInsertionEnd(tr, tr.steps.length - 1, -1)\n      }\n    }\n\n    return true\n  }\n", "import {\n  joinBackward as originalJoinBackward,\n  joinDown as originalJoinDown,\n  joinForward as originalJoinForward,\n  joinUp as originalJoinUp,\n} from '@tiptap/pm/commands'\n\nimport type { RawCommands } from '../types.js'\n\ndeclare module '@tiptap/core' {\n  interface Commands<ReturnType> {\n    joinUp: {\n      /**\n       * Join the selected block or, if there is a text selection, the closest ancestor block of the selection that can be joined, with the sibling above it.\n       * @example editor.commands.joinUp()\n       */\n      joinUp: () => ReturnType\n    }\n    joinDown: {\n      /**\n       * Join the selected block, or the closest ancestor of the selection that can be joined, with the sibling after it.\n       * @example editor.commands.joinDown()\n       */\n      joinDown: () => ReturnType\n    }\n    joinBackward: {\n      /**\n       * If the selection is empty and at the start of a textblock, try to reduce the distance between that block and the one before it—if there's a block directly before it that can be joined, join them.\n       * If not, try to move the selected block closer to the next one in the document structure by lifting it out of its\n       * parent or moving it into a parent of the previous block. Will use the view for accurate (bidi-aware) start-of-textblock detection if given.\n       * @example editor.commands.joinBackward()\n       */\n      joinBackward: () => ReturnType\n    }\n    joinForward: {\n      /**\n       * If the selection is empty and the cursor is at the end of a textblock, try to reduce or remove the boundary between that block and the one after it,\n       * either by joining them or by moving the other block closer to this one in the tree structure.\n       * Will use the view for accurate start-of-textblock detection if given.\n       * @example editor.commands.joinForward()\n       */\n      joinForward: () => ReturnType\n    }\n  }\n}\n\nexport const joinUp: RawCommands['joinUp'] =\n  () =>\n  ({ state, dispatch }) => {\n    return originalJoinUp(state, dispatch)\n  }\n\nexport const joinDown: RawCommands['joinDown'] =\n  () =>\n  ({ state, dispatch }) => {\n    return originalJoinDown(state, dispatch)\n  }\n\nexport const joinBackward: RawCommands['joinBackward'] =\n  () =>\n  ({ state, dispatch }) => {\n    return originalJoinBackward(state, dispatch)\n  }\n\nexport const joinForward: RawCommands['joinForward'] =\n  () =>\n  ({ state, dispatch }) => {\n    return originalJoinForward(state, dispatch)\n  }\n", "import type { Node as ProseMirrorNode } from '@tiptap/pm/model'\n\nexport const canJoinItemsAt = (doc: ProseMirrorNode, pos: number) => {\n  const $pos = doc.resolve(pos)\n  const before = $pos.nodeBefore\n  const after = $pos.nodeAfter\n\n  if (!before || !after) {\n    return false\n  }\n\n  return !before.type.spec.isolating && !after.type.spec.isolating\n}\n", "import { joinPoint } from '@tiptap/pm/transform'\n\nimport type { RawCommands } from '../types.js'\nimport { canJoinItemsAt } from './canJoinItemsAt.js'\n\ndeclare module '@tiptap/core' {\n  interface Commands<ReturnType> {\n    joinItemBackward: {\n      /**\n       * Join two items backward.\n       * @example editor.commands.joinItemBackward()\n       */\n      joinItemBackward: () => ReturnType\n    }\n  }\n}\n\nexport const joinItemBackward: RawCommands['joinItemBackward'] =\n  () =>\n  ({ state, dispatch, tr }) => {\n    try {\n      const point = joinPoint(state.doc, state.selection.$from.pos, -1)\n\n      if (point === null || point === undefined) {\n        return false\n      }\n\n      if (!canJoinItemsAt(state.doc, point)) {\n        return false\n      }\n\n      tr.join(point, 2)\n\n      if (dispatch) {\n        dispatch(tr)\n      }\n\n      return true\n    } catch {\n      return false\n    }\n  }\n", "import { joinPoint } from '@tiptap/pm/transform'\n\nimport type { RawCommands } from '../types.js'\nimport { canJoinItemsAt } from './canJoinItemsAt.js'\n\ndeclare module '@tiptap/core' {\n  interface Commands<ReturnType> {\n    joinItemForward: {\n      /**\n       * Join two items Forwards.\n       * @example editor.commands.joinItemForward()\n       */\n      joinItemForward: () => ReturnType\n    }\n  }\n}\n\nexport const joinItemForward: RawCommands['joinItemForward'] =\n  () =>\n  ({ state, dispatch, tr }) => {\n    try {\n      const point = joinPoint(state.doc, state.selection.$from.pos, +1)\n\n      if (point === null || point === undefined) {\n        return false\n      }\n\n      if (!canJoinItemsAt(state.doc, point)) {\n        return false\n      }\n\n      tr.join(point, 2)\n\n      if (dispatch) {\n        dispatch(tr)\n      }\n\n      return true\n    } catch {\n      return false\n    }\n  }\n", "import { joinTextblockBackward as originalCommand } from '@tiptap/pm/commands'\n\nimport type { RawCommands } from '../types.js'\n\ndeclare module '@tiptap/core' {\n  interface Commands<ReturnType> {\n    joinTextblockBackward: {\n      /**\n       * A more limited form of joinBackward that only tries to join the current textblock to the one before it, if the cursor is at the start of a textblock.\n       */\n      joinTextblockBackward: () => ReturnType\n    }\n  }\n}\n\nexport const joinTextblockBackward: RawCommands['joinTextblockBackward'] =\n  () =>\n  ({ state, dispatch }) => {\n    return originalCommand(state, dispatch)\n  }\n", "import { joinTextblockForward as originalCommand } from '@tiptap/pm/commands'\n\nimport type { RawCommands } from '../types.js'\n\ndeclare module '@tiptap/core' {\n  interface Commands<ReturnType> {\n    joinTextblockForward: {\n      /**\n       * A more limited form of joinForward that only tries to join the current textblock to the one after it, if the cursor is at the end of a textblock.\n       */\n      joinTextblockForward: () => ReturnType\n    }\n  }\n}\n\nexport const joinTextblockForward: RawCommands['joinTextblockForward'] =\n  () =>\n  ({ state, dispatch }) => {\n    return originalCommand(state, dispatch)\n  }\n", "export function isMacOS(): boolean {\n  return typeof navigator !== 'undefined' ? /Mac/.test(navigator.platform) : false\n}\n", "import type { RawCommands } from '../types.js'\nimport { isiOS } from '../utilities/isiOS.js'\nimport { isMacOS } from '../utilities/isMacOS.js'\n\nfunction normalizeKeyName(name: string) {\n  const parts = name.split(/-(?!$)/)\n  let result = parts[parts.length - 1]\n\n  if (result === 'Space') {\n    result = ' '\n  }\n\n  let alt\n  let ctrl\n  let shift\n  let meta\n\n  for (let i = 0; i < parts.length - 1; i += 1) {\n    const mod = parts[i]\n\n    if (/^(cmd|meta|m)$/i.test(mod)) {\n      meta = true\n    } else if (/^a(lt)?$/i.test(mod)) {\n      alt = true\n    } else if (/^(c|ctrl|control)$/i.test(mod)) {\n      ctrl = true\n    } else if (/^s(hift)?$/i.test(mod)) {\n      shift = true\n    } else if (/^mod$/i.test(mod)) {\n      if (isiOS() || isMacOS()) {\n        meta = true\n      } else {\n        ctrl = true\n      }\n    } else {\n      throw new Error(`Unrecognized modifier name: ${mod}`)\n    }\n  }\n\n  if (alt) {\n    result = `Alt-${result}`\n  }\n\n  if (ctrl) {\n    result = `Ctrl-${result}`\n  }\n\n  if (meta) {\n    result = `Meta-${result}`\n  }\n\n  if (shift) {\n    result = `Shift-${result}`\n  }\n\n  return result\n}\n\ndeclare module '@tiptap/core' {\n  interface Commands<ReturnType> {\n    keyboardShortcut: {\n      /**\n       * Trigger a keyboard shortcut.\n       * @param name The name of the keyboard shortcut.\n       * @example editor.commands.keyboardShortcut('Mod-b')\n       */\n      keyboardShortcut: (name: string) => ReturnType\n    }\n  }\n}\n\nexport const keyboardShortcut: RawCommands['keyboardShortcut'] =\n  name =>\n  ({ editor, view, tr, dispatch }) => {\n    const keys = normalizeKeyName(name).split(/-(?!$)/)\n    const key = keys.find(item => !['Alt', 'Ctrl', 'Meta', 'Shift'].includes(item))\n    const event = new KeyboardEvent('keydown', {\n      key: key === 'Space' ? ' ' : key,\n      altKey: keys.includes('Alt'),\n      ctrlKey: keys.includes('Ctrl'),\n      metaKey: keys.includes('Meta'),\n      shiftKey: keys.includes('Shift'),\n      bubbles: true,\n      cancelable: true,\n    })\n\n    const capturedTransaction = editor.captureTransaction(() => {\n      view.someProp('handleKeyDown', f => f(view, event))\n    })\n\n    capturedTransaction?.steps.forEach(step => {\n      const newStep = step.map(tr.mapping)\n\n      if (newStep && dispatch) {\n        tr.maybeStep(newStep)\n      }\n    })\n\n    return true\n  }\n", "import type { NodeType } from '@tiptap/pm/model'\nimport type { EditorState } from '@tiptap/pm/state'\n\nimport type { NodeRange } from '../types.js'\nimport { objectIncludes } from '../utilities/objectIncludes.js'\nimport { getNodeType } from './getNodeType.js'\n\nexport function isNodeActive(\n  state: EditorState,\n  typeOrName: NodeType | string | null,\n  attributes: Record<string, any> = {},\n): boolean {\n  const { from, to, empty } = state.selection\n  const type = typeOrName ? getNodeType(typeOrName, state.schema) : null\n\n  const nodeRanges: NodeRange[] = []\n\n  state.doc.nodesBetween(from, to, (node, pos) => {\n    if (node.isText) {\n      return\n    }\n\n    const relativeFrom = Math.max(from, pos)\n    const relativeTo = Math.min(to, pos + node.nodeSize)\n\n    nodeRanges.push({\n      node,\n      from: relativeFrom,\n      to: relativeTo,\n    })\n  })\n\n  const selectionRange = to - from\n  const matchedNodeRanges = nodeRanges\n    .filter(nodeRange => {\n      if (!type) {\n        return true\n      }\n\n      return type.name === nodeRange.node.type.name\n    })\n    .filter(nodeRange => objectIncludes(nodeRange.node.attrs, attributes, { strict: false }))\n\n  if (empty) {\n    return !!matchedNodeRanges.length\n  }\n\n  const range = matchedNodeRanges.reduce((sum, nodeRange) => sum + nodeRange.to - nodeRange.from, 0)\n\n  return range >= selectionRange\n}\n", "import { lift as originalLift } from '@tiptap/pm/commands'\nimport type { NodeType } from '@tiptap/pm/model'\n\nimport { getNodeType } from '../helpers/getNodeType.js'\nimport { isNodeActive } from '../helpers/isNodeActive.js'\nimport type { RawCommands } from '../types.js'\n\ndeclare module '@tiptap/core' {\n  interface Commands<ReturnType> {\n    lift: {\n      /**\n       * Removes an existing wrap if possible lifting the node out of it\n       * @param typeOrName The type or name of the node.\n       * @param attributes The attributes of the node.\n       * @example editor.commands.lift('paragraph')\n       * @example editor.commands.lift('heading', { level: 1 })\n       */\n      lift: (typeOrName: string | NodeType, attributes?: Record<string, any>) => ReturnType\n    }\n  }\n}\n\nexport const lift: RawCommands['lift'] =\n  (typeOrName, attributes = {}) =>\n  ({ state, dispatch }) => {\n    const type = getNodeType(typeOrName, state.schema)\n    const isActive = isNodeActive(state, type, attributes)\n\n    if (!isActive) {\n      return false\n    }\n\n    return originalLift(state, dispatch)\n  }\n", "import { liftEmptyBlock as originalLiftEmptyBlock } from '@tiptap/pm/commands'\n\nimport type { RawCommands } from '../types.js'\n\ndeclare module '@tiptap/core' {\n  interface Commands<ReturnType> {\n    liftEmptyBlock: {\n      /**\n       * If the cursor is in an empty textblock that can be lifted, lift the block.\n       * @example editor.commands.liftEmptyBlock()\n       */\n      liftEmptyBlock: () => ReturnType\n    }\n  }\n}\n\nexport const liftEmptyBlock: RawCommands['liftEmptyBlock'] =\n  () =>\n  ({ state, dispatch }) => {\n    return originalLiftEmptyBlock(state, dispatch)\n  }\n", "import type { NodeType } from '@tiptap/pm/model'\nimport { liftListItem as originalLiftListItem } from '@tiptap/pm/schema-list'\n\nimport { getNodeType } from '../helpers/getNodeType.js'\nimport type { RawCommands } from '../types.js'\n\ndeclare module '@tiptap/core' {\n  interface Commands<ReturnType> {\n    liftListItem: {\n      /**\n       * Create a command to lift the list item around the selection up into a wrapping list.\n       * @param typeOrName The type or name of the node.\n       * @example editor.commands.liftListItem('listItem')\n       */\n      liftListItem: (typeOrName: string | NodeType) => ReturnType\n    }\n  }\n}\n\nexport const liftListItem: RawCommands['liftListItem'] =\n  typeOrName =>\n  ({ state, dispatch }) => {\n    const type = getNodeType(typeOrName, state.schema)\n\n    return originalLiftListItem(type)(state, dispatch)\n  }\n", "import { newlineInCode as originalNewlineInCode } from '@tiptap/pm/commands'\n\nimport type { RawCommands } from '../types.js'\n\ndeclare module '@tiptap/core' {\n  interface Commands<ReturnType> {\n    newlineInCode: {\n      /**\n       * Add a newline character in code.\n       * @example editor.commands.newlineInCode()\n       */\n      newlineInCode: () => ReturnType\n    }\n  }\n}\n\nexport const newlineInCode: RawCommands['newlineInCode'] =\n  () =>\n  ({ state, dispatch }) => {\n    return originalNewlineInCode(state, dispatch)\n  }\n", "import type { Schema } from '@tiptap/pm/model'\n\n/**\n * Get the type of a schema item by its name.\n * @param name The name of the schema item\n * @param schema The Prosemiror schema to search in\n * @returns The type of the schema item (`node` or `mark`), or null if it doesn't exist\n */\nexport function getSchemaTypeNameByName(name: string, schema: Schema): 'node' | 'mark' | null {\n  if (schema.nodes[name]) {\n    return 'node'\n  }\n\n  if (schema.marks[name]) {\n    return 'mark'\n  }\n\n  return null\n}\n", "/**\n * Remove a property or an array of properties from an object\n * @param obj Object\n * @param key Key to remove\n */\nexport function deleteProps(\n  obj: Record<string, any>,\n  propOrProps: string | string[],\n): Record<string, any> {\n  const props = typeof propOrProps === 'string' ? [propOrProps] : propOrProps\n\n  return Object.keys(obj).reduce((newObj: Record<string, any>, prop) => {\n    if (!props.includes(prop)) {\n      newObj[prop] = obj[prop]\n    }\n\n    return newObj\n  }, {})\n}\n", "import type { MarkType, NodeType } from '@tiptap/pm/model'\n\nimport { getMarkType } from '../helpers/getMarkType.js'\nimport { getNodeType } from '../helpers/getNodeType.js'\nimport { getSchemaTypeNameByName } from '../helpers/getSchemaTypeNameByName.js'\nimport type { RawCommands } from '../types.js'\nimport { deleteProps } from '../utilities/deleteProps.js'\n\ndeclare module '@tiptap/core' {\n  interface Commands<ReturnType> {\n    resetAttributes: {\n      /**\n       * Resets some node attributes to the default value.\n       * @param typeOrName The type or name of the node.\n       * @param attributes The attributes of the node to reset.\n       * @example editor.commands.resetAttributes('heading', 'level')\n       */\n      resetAttributes: (\n        typeOrName: string | NodeType | MarkType,\n        attributes: string | string[],\n      ) => ReturnType\n    }\n  }\n}\n\nexport const resetAttributes: RawCommands['resetAttributes'] =\n  (typeOrName, attributes) =>\n  ({ tr, state, dispatch }) => {\n    let nodeType: NodeType | null = null\n    let markType: MarkType | null = null\n\n    const schemaType = getSchemaTypeNameByName(\n      typeof typeOrName === 'string' ? typeOrName : typeOrName.name,\n      state.schema,\n    )\n\n    if (!schemaType) {\n      return false\n    }\n\n    if (schemaType === 'node') {\n      nodeType = getNodeType(typeOrName as NodeType, state.schema)\n    }\n\n    if (schemaType === 'mark') {\n      markType = getMarkType(typeOrName as MarkType, state.schema)\n    }\n\n    let canReset = false\n\n    tr.selection.ranges.forEach(range => {\n      state.doc.nodesBetween(range.$from.pos, range.$to.pos, (node, pos) => {\n        if (nodeType && nodeType === node.type) {\n          canReset = true\n\n          if (dispatch) {\n            tr.setNodeMarkup(pos, undefined, deleteProps(node.attrs, attributes))\n          }\n        }\n\n        if (markType && node.marks.length) {\n          node.marks.forEach(mark => {\n            if (markType === mark.type) {\n              canReset = true\n\n              if (dispatch) {\n                tr.addMark(\n                  pos,\n                  pos + node.nodeSize,\n                  markType.create(deleteProps(mark.attrs, attributes)),\n                )\n              }\n            }\n          })\n        }\n      })\n    })\n\n    return canReset\n  }\n", "import type { RawCommands } from '../types.js'\n\ndeclare module '@tiptap/core' {\n  interface Commands<ReturnType> {\n    scrollIntoView: {\n      /**\n       * Scroll the selection into view.\n       * @example editor.commands.scrollIntoView()\n       */\n      scrollIntoView: () => ReturnType\n    }\n  }\n}\n\nexport const scrollIntoView: RawCommands['scrollIntoView'] =\n  () =>\n  ({ tr, dispatch }) => {\n    if (dispatch) {\n      tr.scrollIntoView()\n    }\n\n    return true\n  }\n", "import { AllSelection } from '@tiptap/pm/state'\n\nimport type { RawCommands } from '../types.js'\n\ndeclare module '@tiptap/core' {\n  interface Commands<ReturnType> {\n    selectAll: {\n      /**\n       * Select the whole document.\n       * @example editor.commands.selectAll()\n       */\n      selectAll: () => ReturnType\n    }\n  }\n}\n\nexport const selectAll: RawCommands['selectAll'] =\n  () =>\n  ({ tr, dispatch }) => {\n    if (dispatch) {\n      const selection = new AllSelection(tr.doc)\n\n      tr.setSelection(selection)\n    }\n\n    return true\n  }\n", "import { selectNodeBackward as originalSelectNodeBackward } from '@tiptap/pm/commands'\n\nimport type { RawCommands } from '../types.js'\n\ndeclare module '@tiptap/core' {\n  interface Commands<ReturnType> {\n    selectNodeBackward: {\n      /**\n       * Select a node backward.\n       * @example editor.commands.selectNodeBackward()\n       */\n      selectNodeBackward: () => ReturnType\n    }\n  }\n}\n\nexport const selectNodeBackward: RawCommands['selectNodeBackward'] =\n  () =>\n  ({ state, dispatch }) => {\n    return originalSelectNodeBackward(state, dispatch)\n  }\n", "import { selectNodeForward as originalSelectNodeForward } from '@tiptap/pm/commands'\n\nimport type { RawCommands } from '../types.js'\n\ndeclare module '@tiptap/core' {\n  interface Commands<ReturnType> {\n    selectNodeForward: {\n      /**\n       * Select a node forward.\n       * @example editor.commands.selectNodeForward()\n       */\n      selectNodeForward: () => ReturnType\n    }\n  }\n}\n\nexport const selectNodeForward: RawCommands['selectNodeForward'] =\n  () =>\n  ({ state, dispatch }) => {\n    return originalSelectNodeForward(state, dispatch)\n  }\n", "import { selectParentNode as originalSelectParentNode } from '@tiptap/pm/commands'\n\nimport type { RawCommands } from '../types.js'\n\ndeclare module '@tiptap/core' {\n  interface Commands<ReturnType> {\n    selectParentNode: {\n      /**\n       * Select the parent node.\n       * @example editor.commands.selectParentNode()\n       */\n      selectParentNode: () => ReturnType\n    }\n  }\n}\n\nexport const selectParentNode: RawCommands['selectParentNode'] =\n  () =>\n  ({ state, dispatch }) => {\n    return originalSelectParentNode(state, dispatch)\n  }\n", "// @ts-ignore\n// TODO: add types to @types/prosemirror-commands\nimport { selectTextblockEnd as originalSelectTextblockEnd } from '@tiptap/pm/commands'\n\nimport type { RawCommands } from '../types.js'\n\ndeclare module '@tiptap/core' {\n  interface Commands<ReturnType> {\n    selectTextblockEnd: {\n      /**\n       * Moves the cursor to the end of current text block.\n       * @example editor.commands.selectTextblockEnd()\n       */\n      selectTextblockEnd: () => ReturnType\n    }\n  }\n}\n\nexport const selectTextblockEnd: RawCommands['selectTextblockEnd'] =\n  () =>\n  ({ state, dispatch }) => {\n    return originalSelectTextblockEnd(state, dispatch)\n  }\n", "// @ts-ignore\n// TODO: add types to @types/prosemirror-commands\nimport { selectTextblockStart as originalSelectTextblockStart } from '@tiptap/pm/commands'\n\nimport type { RawCommands } from '../types.js'\n\ndeclare module '@tiptap/core' {\n  interface Commands<ReturnType> {\n    selectTextblockStart: {\n      /**\n       * Moves the cursor to the start of current text block.\n       * @example editor.commands.selectTextblockStart()\n       */\n      selectTextblockStart: () => ReturnType\n    }\n  }\n}\n\nexport const selectTextblockStart: RawCommands['selectTextblockStart'] =\n  () =>\n  ({ state, dispatch }) => {\n    return originalSelectTextblockStart(state, dispatch)\n  }\n", "import type { Fragment, Node as ProseMirrorNode, ParseOptions, Schema } from '@tiptap/pm/model'\n\nimport type { Content } from '../types.js'\nimport { createNodeFromContent } from './createNodeFromContent.js'\n\n/**\n * Create a new Prosemirror document node from content.\n * @param content The JSON or HTML content to create the document from\n * @param schema The Prosemirror schema to use for the document\n * @param parseOptions Options for the parser\n * @returns The created Prosemirror document node\n */\nexport function createDocument(\n  content: Content | ProseMirrorNode | Fragment,\n  schema: Schema,\n  parseOptions: ParseOptions = {},\n  options: { errorOnInvalidContent?: boolean } = {},\n): ProseMirrorNode {\n  return createNodeFromContent(content, schema, {\n    slice: false,\n    parseOptions,\n    errorOnInvalidContent: options.errorOnInvalidContent,\n  }) as ProseMirrorNode\n}\n", "import type { Fragment, Node as ProseMirrorNode, ParseOptions } from '@tiptap/pm/model'\n\nimport { createDocument } from '../helpers/createDocument.js'\nimport { isFragment } from '../helpers/isFragment.js'\nimport type { Content, RawCommands } from '../types.js'\n\nexport interface SetContentOptions {\n  /**\n   * Options for parsing the content.\n   * @default {}\n   */\n  parseOptions?: ParseOptions\n\n  /**\n   * Whether to throw an error if the content is invalid.\n   */\n  errorOnInvalidContent?: boolean\n\n  /**\n   * Whether to emit an update event.\n   * @default true\n   */\n  emitUpdate?: boolean\n}\n\ndeclare module '@tiptap/core' {\n  interface Commands<ReturnType> {\n    setContent: {\n      /**\n       * Replace the whole document with new content.\n       * @param content The new content.\n       * @param options Options for `setContent`.\n       * @example editor.commands.setContent('<p>Example text</p>')\n       */\n      setContent: (\n        /**\n         * The new content.\n         */\n        content: Content | Fragment | ProseMirrorNode,\n\n        /**\n         * Options for `setContent`.\n         */\n        options?: SetContentOptions,\n      ) => ReturnType\n    }\n  }\n}\n\nexport const setContent: RawCommands['setContent'] =\n  (content, { errorOnInvalidContent, emitUpdate = true, parseOptions = {} } = {}) =>\n  ({ editor, tr, dispatch, commands }) => {\n    const { doc } = tr\n\n    // This is to keep backward compatibility with the previous behavior\n    // TODO remove this in the next major version\n    if (parseOptions.preserveWhitespace !== 'full') {\n      const document = createDocument(content, editor.schema, parseOptions, {\n        errorOnInvalidContent: errorOnInvalidContent ?? editor.options.enableContentCheck,\n      })\n\n      if (dispatch) {\n        const nodes = isFragment(document) ? document.content : [document]\n\n        tr.replaceWith(0, doc.content.size, nodes).setMeta('preventUpdate', !emitUpdate)\n      }\n      return true\n    }\n\n    if (dispatch) {\n      tr.setMeta('preventUpdate', !emitUpdate)\n    }\n\n    return commands.insertContentAt({ from: 0, to: doc.content.size }, content, {\n      parseOptions,\n      errorOnInvalidContent: errorOnInvalidContent ?? editor.options.enableContentCheck,\n    })\n  }\n", "import type { Mark, MarkType } from '@tiptap/pm/model'\nimport type { EditorState } from '@tiptap/pm/state'\n\nimport { getMarkType } from './getMarkType.js'\n\nexport function getMarkAttributes(\n  state: EditorState,\n  typeOrName: string | MarkType,\n): Record<string, any> {\n  const type = getMarkType(typeOrName, state.schema)\n  const { from, to, empty } = state.selection\n  const marks: Mark[] = []\n\n  if (empty) {\n    if (state.storedMarks) {\n      marks.push(...state.storedMarks)\n    }\n\n    marks.push(...state.selection.$head.marks())\n  } else {\n    state.doc.nodesBetween(from, to, node => {\n      marks.push(...node.marks)\n    })\n  }\n\n  const mark = marks.find(markItem => markItem.type.name === type.name)\n\n  if (!mark) {\n    return {}\n  }\n\n  return { ...mark.attrs }\n}\n", "import type { Node as ProseMirrorNode } from '@tiptap/pm/model'\nimport type { Transaction } from '@tiptap/pm/state'\nimport { Transform } from '@tiptap/pm/transform'\n\n/**\n * Returns a new `Transform` based on all steps of the passed transactions.\n * @param oldDoc The Prosemirror node to start from\n * @param transactions The transactions to combine\n * @returns A new `Transform` with all steps of the passed transactions\n */\nexport function combineTransactionSteps(\n  oldDoc: ProseMirrorNode,\n  transactions: Transaction[],\n): Transform {\n  const transform = new Transform(oldDoc)\n\n  transactions.forEach(transaction => {\n    transaction.steps.forEach(step => {\n      transform.step(step)\n    })\n  })\n\n  return transform\n}\n", "import type { Node as ProseMirrorNode } from '@tiptap/pm/model'\n\nimport type { NodeWithPos, Predicate } from '../types.js'\n\n/**\n * Find children inside a Prosemirror node that match a predicate.\n * @param node The Prosemirror node to search in\n * @param predicate The predicate to match\n * @returns An array of nodes with their positions\n */\nexport function findChildren(node: ProseMirrorNode, predicate: Predicate): NodeWithPos[] {\n  const nodesWithPos: NodeWithPos[] = []\n\n  node.descendants((child, pos) => {\n    if (predicate(child)) {\n      nodesWithPos.push({\n        node: child,\n        pos,\n      })\n    }\n  })\n\n  return nodesWithPos\n}\n", "import type { Node as ProseMirrorNode } from '@tiptap/pm/model'\n\nimport type { NodeWithPos, Predicate, Range } from '../types.js'\n\n/**\n * Same as `findChildren` but searches only within a `range`.\n * @param node The Prosemirror node to search in\n * @param range The range to search in\n * @param predicate The predicate to match\n * @returns An array of nodes with their positions\n */\nexport function findChildrenInRange(\n  node: ProseMirrorNode,\n  range: Range,\n  predicate: Predicate,\n): NodeWithPos[] {\n  const nodesWithPos: NodeWithPos[] = []\n\n  // if (range.from === range.to) {\n  //   const nodeAt = node.nodeAt(range.from)\n\n  //   if (nodeAt) {\n  //     nodesWithPos.push({\n  //       node: nodeAt,\n  //       pos: range.from,\n  //     })\n  //   }\n  // }\n\n  node.nodesBetween(range.from, range.to, (child, pos) => {\n    if (predicate(child)) {\n      nodesWithPos.push({\n        node: child,\n        pos,\n      })\n    }\n  })\n\n  return nodesWithPos\n}\n", "import type { Node as ProseMirrorNode, ResolvedPos } from '@tiptap/pm/model'\n\nimport type { Predicate } from '../types.js'\n\n/**\n * Finds the closest parent node to a resolved position that matches a predicate.\n * @param $pos The resolved position to search from\n * @param predicate The predicate to match\n * @returns The closest parent node to the resolved position that matches the predicate\n * @example ```js\n * findParentNodeClosestToPos($from, node => node.type.name === 'paragraph')\n * ```\n */\nexport function findParentNodeClosestToPos(\n  $pos: ResolvedPos,\n  predicate: Predicate,\n):\n  | {\n      pos: number\n      start: number\n      depth: number\n      node: ProseMirrorNode\n    }\n  | undefined {\n  for (let i = $pos.depth; i > 0; i -= 1) {\n    const node = $pos.node(i)\n\n    if (predicate(node)) {\n      return {\n        pos: i > 0 ? $pos.before(i) : 0,\n        start: $pos.start(i),\n        depth: i,\n        node,\n      }\n    }\n  }\n}\n", "import type { Selection } from '@tiptap/pm/state'\n\nimport type { Predicate } from '../types.js'\nimport { findParentNodeClosestToPos } from './findParentNodeClosestToPos.js'\n\n/**\n * Finds the closest parent node to the current selection that matches a predicate.\n * @param predicate The predicate to match\n * @returns A command that finds the closest parent node to the current selection that matches the predicate\n * @example ```js\n * findParentNode(node => node.type.name === 'paragraph')\n * ```\n */\nexport function findParentNode(\n  predicate: Predicate,\n): (selection: Selection) => ReturnType<typeof findParentNodeClosestToPos> {\n  return (selection: Selection) => findParentNodeClosestToPos(selection.$from, predicate)\n}\n", "import type { ExtensionConfig } from '../Extension.js'\nimport type { MarkConfig } from '../Mark.js'\nimport type { NodeConfig } from '../Node.js'\nimport type { AnyExtension, MaybeThisParameterType, RemoveThis } from '../types.js'\n\n/**\n * Returns a field from an extension\n * @param extension The Tiptap extension\n * @param field The field, for example `renderHTML` or `priority`\n * @param context The context object that should be passed as `this` into the function\n * @returns The field value\n */\nexport function getExtensionField<T = any, E extends AnyExtension = any>(\n  extension: E,\n  field: keyof ExtensionConfig | keyof MarkConfig | keyof NodeConfig,\n  context?: Omit<MaybeThisParameterType<T>, 'parent'>,\n): RemoveThis<T> {\n  if (extension.config[field as keyof typeof extension.config] === undefined && extension.parent) {\n    return getExtensionField(extension.parent, field, context)\n  }\n\n  if (typeof extension.config[field as keyof typeof extension.config] === 'function') {\n    const value = (extension.config[field as keyof typeof extension.config] as any).bind({\n      ...context,\n      parent: extension.parent ? getExtensionField(extension.parent, field, context) : null,\n    })\n\n    return value\n  }\n\n  return extension.config[field as keyof typeof extension.config] as RemoveThis<T>\n}\n", "import type { AnyConfig, Extensions } from '../types.js'\nimport { getExtensionField } from './getExtensionField.js'\n\n/**\n * Create a flattened array of extensions by traversing the `addExtensions` field.\n * @param extensions An array of Tiptap extensions\n * @returns A flattened array of Tiptap extensions\n */\nexport function flattenExtensions(extensions: Extensions): Extensions {\n  return (\n    extensions\n      .map(extension => {\n        const context = {\n          name: extension.name,\n          options: extension.options,\n          storage: extension.storage,\n        }\n\n        const addExtensions = getExtensionField<AnyConfig['addExtensions']>(\n          extension,\n          'addExtensions',\n          context,\n        )\n\n        if (addExtensions) {\n          return [extension, ...flattenExtensions(addExtensions())]\n        }\n\n        return extension\n      })\n      // `Infinity` will break TypeScript so we set a number that is probably high enough\n      .flat(10)\n  )\n}\n", "import type { Fragment, Schema } from '@tiptap/pm/model'\nimport { DOMSerializer } from '@tiptap/pm/model'\n\nexport function getHTMLFromFragment(fragment: Fragment, schema: Schema): string {\n  const documentFragment = DOMSerializer.fromSchema(schema).serializeFragment(fragment)\n\n  const temporaryDocument = document.implementation.createHTMLDocument()\n  const container = temporaryDocument.createElement('div')\n\n  container.appendChild(documentFragment)\n\n  return container.innerHTML\n}\n", "import type { Schema } from '@tiptap/pm/model'\n\nimport type { ExtensionAttribute } from '../types.js'\n\n/**\n * Combines external attribute structure with local attribute behavior.\n * @param attributes The attributes from resolved local extensions\n * @param schema The schema that defines the allowed attributes\n * @returns Only attributes present in the schema\n */\nexport function getSchemaAttributes(\n  attributes: ExtensionAttribute[],\n  schema: Schema,\n): ExtensionAttribute[] {\n  const attributesByType = new Map<string, Map<string, ExtensionAttribute>>()\n\n  for (const attribute of attributes) {\n    const typeAttributes =\n      attributesByType.get(attribute.type) ?? new Map<string, ExtensionAttribute>()\n    typeAttributes.set(attribute.name, attribute)\n    attributesByType.set(attribute.type, typeAttributes)\n  }\n\n  return [...Object.values(schema.nodes), ...Object.values(schema.marks)].flatMap(type =>\n    Object.entries(type.spec.attrs ?? {}).map(([name, spec]) => {\n      const local = attributesByType.get(type.name)?.get(name)\n      const hasDefault = Object.hasOwn(spec, 'default')\n\n      return {\n        type: type.name,\n        name,\n        attribute: {\n          rendered: true,\n          renderHTML: null,\n          parseHTML: null,\n          keepOnSplit: true,\n          ...local?.attribute,\n          default: spec.default,\n          isRequired: !hasDefault,\n          validate: spec.validate,\n        },\n      }\n    }),\n  )\n}\n", "export const nodeSchemaFields = {\n  content: 'string',\n  marks: 'string',\n  group: 'string',\n  inline: 'boolean',\n  atom: 'boolean',\n  selectable: 'boolean',\n  draggable: 'boolean',\n  code: 'boolean',\n  whitespace: ['pre', 'normal'],\n  definingAsContext: 'boolean',\n  definingForContent: 'boolean',\n  defining: 'boolean',\n  isolating: 'boolean',\n  linebreakReplacement: 'boolean',\n} as const\n\nexport const markSchemaFields = {\n  inclusive: 'boolean',\n  excludes: 'string',\n  group: 'string',\n  spanning: 'boolean',\n  code: 'boolean',\n} as const\n", "import type { MarkSpec, NodeSpec, Schema, SchemaSpec } from '@tiptap/pm/model'\n\nimport type { getSchemaSpecByResolvedExtensions } from '../helpers/getSchemaSpecByResolvedExtensions.js'\nimport { markSchemaFields, nodeSchemaFields } from './schemaSpecFields.js'\n\ntype LocalSchemaSpec = ReturnType<typeof getSchemaSpecByResolvedExtensions>\ntype SchemaFields = Record<string, 'string' | 'boolean' | readonly string[]>\n\nfunction structuralFields(spec: NodeSpec | MarkSpec, fields: SchemaFields, path: string) {\n  return Object.fromEntries(\n    Object.entries(fields).flatMap(([name, expected]) => {\n      const value: unknown = spec[name]\n\n      if (value === undefined) {\n        return []\n      }\n\n      const valid =\n        typeof expected === 'string'\n          ? typeof value === expected\n          : typeof value === 'string' && expected.includes(value)\n\n      if (!valid) {\n        throw new RangeError(`Invalid schemaSpec field '${path}.${name}'`)\n      }\n\n      return [[name, value]]\n    }),\n  )\n}\n\nfunction mergeType(\n  name: string,\n  local: NodeSpec | MarkSpec,\n  external: NodeSpec | MarkSpec,\n  fields: SchemaFields,\n) {\n  const behavior = Object.fromEntries(\n    Object.entries(local).filter(([key]) => key !== 'attrs' && !Object.hasOwn(fields, key)),\n  )\n\n  return {\n    ...behavior,\n    ...structuralFields(external, fields, name),\n    attrs: external.attrs,\n  }\n}\n\nfunction checkTypes(local: Record<string, object>, external: Record<string, object>, kind: string) {\n  for (const name of Object.keys(external)) {\n    if (!Object.hasOwn(local, name)) {\n      throw new RangeError(`schemaSpec requires a local ${kind} extension named '${name}'`)\n    }\n  }\n\n  for (const name of Object.keys(local)) {\n    if (!Object.hasOwn(external, name)) {\n      throw new RangeError(`Local ${kind} extension '${name}' is not in schemaSpec`)\n    }\n  }\n}\n\n/**\n * Combines external structure with local DOM behavior and extension metadata.\n * @param local The specifications generated by resolved local extensions\n * @param external The schema compiled from the provided specification\n * @returns A specification in the external schema's node and mark order\n */\nexport function mergeSchemaSpec(local: LocalSchemaSpec, external: Schema): SchemaSpec {\n  checkTypes(local.nodes, external.nodes, 'node')\n  checkTypes(local.marks, external.marks, 'mark')\n  let nodes = external.spec.nodes\n  let marks = external.spec.marks\n\n  external.spec.nodes.forEach((name, spec) => {\n    nodes = nodes.update(name, mergeType(name, local.nodes[name], spec, nodeSchemaFields))\n  })\n  external.spec.marks.forEach((name, spec) => {\n    marks = marks.update(name, mergeType(name, local.marks[name], spec, markSchemaFields))\n  })\n\n  return { topNode: external.topNodeType.name, nodes, marks }\n}\n", "/**\n * Find duplicates in an array.\n */\nexport function findDuplicates<T>(items: T[]): T[] {\n  const filtered = items.filter((el, index) => items.indexOf(el) !== index)\n\n  return Array.from(new Set(filtered))\n}\n", "import type { Extension } from '../Extension.js'\nimport type { Mark } from '../Mark.js'\nimport type { Node } from '../Node.js'\nimport type { Extensions } from '../types.js'\n\nexport function splitExtensions(extensions: Extensions) {\n  const baseExtensions = extensions.filter(\n    extension => extension.type === 'extension',\n  ) as Extension[]\n  const nodeExtensions = extensions.filter(extension => extension.type === 'node') as Node[]\n  const markExtensions = extensions.filter(extension => extension.type === 'mark') as Mark[]\n\n  return {\n    baseExtensions,\n    nodeExtensions,\n    markExtensions,\n  }\n}\n", "import type { MarkConfig, NodeConfig } from '../index.js'\nimport type { AnyConfig, Attribute, Attributes, ExtensionAttribute, Extensions } from '../types.js'\nimport { getExtensionField } from './getExtensionField.js'\nimport { splitExtensions } from './splitExtensions.js'\n\n/**\n * Get a list of all extension attributes defined in `addAttribute` and `addGlobalAttribute`.\n * @param extensions List of extensions\n */\nexport function getAttributesFromExtensions(extensions: Extensions): ExtensionAttribute[] {\n  const extensionAttributes: ExtensionAttribute[] = []\n  const { nodeExtensions, markExtensions } = splitExtensions(extensions)\n  const nodeAndMarkExtensions = [...nodeExtensions, ...markExtensions]\n  const defaultAttribute: Required<Omit<Attribute, 'validate'>> & Pick<Attribute, 'validate'> = {\n    default: null,\n    validate: undefined,\n    rendered: true,\n    renderHTML: null,\n    parseHTML: null,\n    keepOnSplit: true,\n    isRequired: false,\n  }\n\n  // Precompute lists of extension types for global attribute resolution\n  const nodeExtensionTypes = nodeExtensions.filter(ext => ext.name !== 'text').map(ext => ext.name)\n  const markExtensionTypes = markExtensions.map(ext => ext.name)\n  const allExtensionTypes = [...nodeExtensionTypes, ...markExtensionTypes]\n\n  extensions.forEach(extension => {\n    const context = {\n      name: extension.name,\n      options: extension.options,\n      storage: extension.storage,\n      extensions: nodeAndMarkExtensions,\n    }\n\n    const addGlobalAttributes = getExtensionField<AnyConfig['addGlobalAttributes']>(\n      extension,\n      'addGlobalAttributes',\n      context,\n    )\n\n    if (!addGlobalAttributes) {\n      return\n    }\n\n    const globalAttributes = addGlobalAttributes()\n\n    globalAttributes.forEach(globalAttribute => {\n      // Resolve the types based on the string shorthand or explicit array\n      let resolvedTypes: string[]\n      if (Array.isArray(globalAttribute.types)) {\n        resolvedTypes = globalAttribute.types\n      } else if (globalAttribute.types === '*') {\n        resolvedTypes = allExtensionTypes\n      } else if (globalAttribute.types === 'nodes') {\n        resolvedTypes = nodeExtensionTypes\n      } else if (globalAttribute.types === 'marks') {\n        resolvedTypes = markExtensionTypes\n      } else {\n        resolvedTypes = []\n      }\n\n      resolvedTypes.forEach(type => {\n        Object.entries(globalAttribute.attributes).forEach(([name, attribute]) => {\n          extensionAttributes.push({\n            type,\n            name,\n            attribute: {\n              ...defaultAttribute,\n              ...attribute,\n            },\n          })\n        })\n      })\n    })\n  })\n\n  nodeAndMarkExtensions.forEach(extension => {\n    const context = {\n      name: extension.name,\n      options: extension.options,\n      storage: extension.storage,\n    }\n\n    const addAttributes = getExtensionField<\n      NodeConfig['addAttributes'] | MarkConfig['addAttributes']\n    >(extension, 'addAttributes', context)\n\n    if (!addAttributes) {\n      return\n    }\n\n    // TODO: remove `as Attributes`\n    const attributes = addAttributes() as Attributes\n\n    Object.entries(attributes).forEach(([name, attribute]) => {\n      const mergedAttr = {\n        ...defaultAttribute,\n        ...attribute,\n      }\n\n      if (typeof mergedAttr?.default === 'function') {\n        mergedAttr.default = mergedAttr.default()\n      }\n\n      if (mergedAttr?.isRequired && mergedAttr?.default === undefined) {\n        delete mergedAttr.default\n      }\n\n      extensionAttributes.push({\n        type: extension.name,\n        name,\n        attribute: mergedAttr,\n      })\n    })\n  })\n\n  return extensionAttributes\n}\n", "// oxlint-disable-next-lineno-unsafe-function-type\nexport function isFunction(value: any): value is Function {\n  return typeof value === 'function'\n}\n", "import type { MaybeReturnType } from '../types.js'\nimport { isFunction } from './isFunction.js'\n\n/**\n * Optionally calls `value` as a function.\n * Otherwise it is returned directly.\n * @param value Function or any value.\n * @param context Optional context to bind to function.\n * @param props Optional props to pass to function.\n */\nexport function callOrReturn<T>(\n  value: T,\n  context: any = undefined,\n  ...props: any[]\n): MaybeReturnType<T> {\n  if (isFunction(value)) {\n    if (context) {\n      return value.bind(context)(...props)\n    }\n\n    return value(...props)\n  }\n\n  return value as MaybeReturnType<T>\n}\n", "export function isEmptyObject(value = {}): boolean {\n  return Object.keys(value).length === 0 && value.constructor === Object\n}\n", "/** Splits a CSS style string into declarations, ignoring semicolons inside quotes/parentheses. */\nfunction splitStyleDeclarations(styles: string): string[] {\n  const result: string[] = []\n\n  let current = ''\n  let inSingleQuote = false\n  let inDoubleQuote = false\n  let parenDepth = 0\n\n  const length = styles.length\n  for (let i = 0; i < length; i += 1) {\n    const char = styles[i]\n    if (char === \"'\" && !inDoubleQuote) {\n      inSingleQuote = !inSingleQuote\n      current += char\n      continue\n    }\n    if (char === '\"' && !inSingleQuote) {\n      inDoubleQuote = !inDoubleQuote\n      current += char\n      continue\n    }\n    if (!inSingleQuote && !inDoubleQuote) {\n      if (char === '(') {\n        parenDepth += 1\n        current += char\n        continue\n      }\n      if (char === ')' && parenDepth > 0) {\n        parenDepth -= 1\n        current += char\n        continue\n      }\n      if (char === ';' && parenDepth === 0) {\n        result.push(current)\n        current = ''\n        continue\n      }\n    }\n    current += char\n  }\n  if (current) {\n    result.push(current)\n  }\n\n  return result\n}\n\n/** Yields property/value pairs from a style string. */\nfunction parseStyleEntries(styles: string | undefined): [property: string, value: string][] {\n  const pairs: [string, string][] = []\n\n  const declarations = splitStyleDeclarations(styles || '')\n  const numDeclarations = declarations.length\n\n  for (let i = 0; i < numDeclarations; i += 1) {\n    const declaration = declarations[i]\n\n    const firstColonIndex = declaration.indexOf(':')\n    if (firstColonIndex === -1) {\n      continue\n    }\n\n    const property = declaration.slice(0, firstColonIndex).trim()\n    const value = declaration.slice(firstColonIndex + 1).trim()\n    if (property && value) {\n      pairs.push([property, value])\n    }\n  }\n\n  return pairs\n}\n\nexport function mergeAttributes(...objects: Record<string, any>[]): Record<string, any> {\n  return objects\n    .filter(item => !!item)\n    .reduce((items, item) => {\n      const mergedAttributes = { ...items }\n\n      Object.entries(item).forEach(([key, value]) => {\n        // Define a data property so untrusted input cannot change the merged object's prototype.\n        if (key === '__proto__') {\n          Object.defineProperty(mergedAttributes, key, {\n            configurable: true,\n            enumerable: true,\n            value,\n            writable: true,\n          })\n\n          return\n        }\n\n        const exists = mergedAttributes[key]\n\n        if (!exists) {\n          mergedAttributes[key] = value\n\n          return\n        }\n\n        if (key === 'class') {\n          const valueClasses: string[] = value ? String(value).split(' ') : []\n          const existingClasses: string[] = mergedAttributes[key]\n            ? mergedAttributes[key].split(' ')\n            : []\n\n          const insertClasses = valueClasses.filter(\n            valueClass => !existingClasses.includes(valueClass),\n          )\n\n          mergedAttributes[key] = [...existingClasses, ...insertClasses].join(' ')\n        } else if (key === 'style') {\n          const styleMap = new Map([\n            ...parseStyleEntries(mergedAttributes[key]),\n            ...parseStyleEntries(value),\n          ])\n\n          mergedAttributes[key] = Array.from(styleMap.entries())\n            .map(([property, val]) => `${property}: ${val}`)\n            .join('; ')\n        } else {\n          mergedAttributes[key] = value\n        }\n      })\n\n      return mergedAttributes\n    }, {})\n}\n", "import type { Mark, Node } from '@tiptap/pm/model'\n\nimport type { ExtensionAttribute } from '../types.js'\nimport { mergeAttributes } from '../utilities/mergeAttributes.js'\n\nexport function getRenderedAttributes(\n  nodeOrMark: Node | Mark,\n  extensionAttributes: ExtensionAttribute[],\n): Record<string, any> {\n  return extensionAttributes\n    .filter(attribute => attribute.type === nodeOrMark.type.name)\n    .filter(item => item.attribute.rendered)\n    .map(item => {\n      if (!item.attribute.renderHTML) {\n        return {\n          [item.name]: nodeOrMark.attrs[item.name],\n        }\n      }\n\n      return item.attribute.renderHTML(nodeOrMark.attrs) || {}\n    })\n    .reduce((attributes, attribute) => mergeAttributes(attributes, attribute), {})\n}\n", "export function fromString(value: any): any {\n  if (typeof value !== 'string') {\n    return value\n  }\n\n  if (value.match(/^[+-]?(?:\\d*\\.)?\\d+$/)) {\n    return Number(value)\n  }\n\n  if (value === 'true') {\n    return true\n  }\n\n  if (value === 'false') {\n    return false\n  }\n\n  return value\n}\n", "import type { ParseRule } from '@tiptap/pm/model'\n\nimport type { ExtensionAttribute } from '../types.js'\nimport { fromString } from '../utilities/fromString.js'\n\n/**\n * This function merges extension attributes into parserule attributes (`attrs` or `getAttrs`).\n * Cancels when `getAttrs` returned `false`.\n * @param parseRule ProseMirror ParseRule\n * @param extensionAttributes List of attributes to inject\n */\nexport function injectExtensionAttributesToParseRule(\n  parseRule: ParseRule,\n  extensionAttributes: ExtensionAttribute[],\n): ParseRule {\n  if ('style' in parseRule) {\n    return parseRule\n  }\n\n  return {\n    ...parseRule,\n    getAttrs: (node: HTMLElement) => {\n      const oldAttributes = parseRule.getAttrs ? parseRule.getAttrs(node) : parseRule.attrs\n\n      if (oldAttributes === false) {\n        return false\n      }\n\n      const newAttributes = extensionAttributes.reduce((items, item) => {\n        const value = item.attribute.parseHTML\n          ? item.attribute.parseHTML(node)\n          : fromString(node.getAttribute(item.name))\n\n        if (value === null || value === undefined) {\n          return items\n        }\n\n        return {\n          ...items,\n          [item.name]: value,\n        }\n      }, {})\n\n      return { ...oldAttributes, ...newAttributes }\n    },\n  }\n}\n", "import type { MarkSpec, NodeSpec, TagParseRule } from '@tiptap/pm/model'\nimport type { SchemaSpec } from '@tiptap/pm/model'\n\nimport type { Editor, MarkConfig, NodeConfig } from '../index.js'\nimport type { AnyConfig, ExtensionAttribute, Extensions } from '../types.js'\nimport { callOrReturn } from '../utilities/callOrReturn.js'\nimport { isEmptyObject } from '../utilities/isEmptyObject.js'\nimport { getAttributesFromExtensions } from './getAttributesFromExtensions.js'\nimport { getExtensionField } from './getExtensionField.js'\nimport { getRenderedAttributes } from './getRenderedAttributes.js'\nimport { injectExtensionAttributesToParseRule } from './injectExtensionAttributesToParseRule.js'\nimport { splitExtensions } from './splitExtensions.js'\n\nfunction cleanUpSchemaItem<T>(data: T) {\n  return Object.fromEntries(\n    // @ts-ignore\n    Object.entries(data).filter(([key, value]) => {\n      if (key === 'attrs' && isEmptyObject(value as object | undefined)) {\n        return false\n      }\n\n      return value !== null && value !== undefined\n    }),\n  ) as T\n}\n\n/**\n * Builds an attribute spec tuple for ProseMirror schema from an extension attribute.\n * @param extensionAttribute The extension attribute to build the spec for\n * @returns A tuple of [attributeName, spec]\n */\nfunction buildAttributeSpec(\n  extensionAttribute: ReturnType<typeof getAttributesFromExtensions>[number],\n): [string, Record<string, any>] {\n  const spec: Record<string, any> = {}\n\n  // Only include 'default' if the attribute is not required and default is set on the attribute\n  if (\n    !extensionAttribute?.attribute?.isRequired &&\n    'default' in (extensionAttribute?.attribute || {})\n  ) {\n    spec.default = extensionAttribute.attribute.default\n  }\n\n  // Only include 'validate' if it's defined\n  if (extensionAttribute?.attribute?.validate !== undefined) {\n    spec.validate = extensionAttribute.attribute.validate\n  }\n\n  return [extensionAttribute.name, spec]\n}\n\n/**\n * Builds schema specifications without compiling content expressions.\n * @param extensions An array of Tiptap extensions\n * @param editor The editor instance\n * @param allAttributes The effective attributes used for schema and DOM behavior\n * @returns The node and mark specifications\n */\nexport function getSchemaSpecByResolvedExtensions(\n  extensions: Extensions,\n  editor?: Editor,\n  allAttributes: ExtensionAttribute[] = getAttributesFromExtensions(extensions),\n) {\n  const { nodeExtensions, markExtensions } = splitExtensions(extensions)\n  const topNode = nodeExtensions.find(extension => getExtensionField(extension, 'topNode'))?.name\n\n  const nodes: Record<string, NodeSpec> = Object.fromEntries(\n    nodeExtensions.map(extension => {\n      const extensionAttributes = allAttributes.filter(\n        attribute => attribute.type === extension.name,\n      )\n      const context = {\n        name: extension.name,\n        options: extension.options,\n        storage: extension.storage,\n        editor,\n      }\n\n      const extraNodeFields = extensions.reduce((fields, e) => {\n        const extendNodeSchema = getExtensionField<AnyConfig['extendNodeSchema']>(\n          e,\n          'extendNodeSchema',\n          context,\n        )\n\n        return {\n          ...fields,\n          ...(extendNodeSchema ? extendNodeSchema(extension) : {}),\n        }\n      }, {})\n\n      const schema: NodeSpec = cleanUpSchemaItem({\n        ...extraNodeFields,\n        content: callOrReturn(\n          getExtensionField<NodeConfig['content']>(extension, 'content', context),\n        ),\n        marks: callOrReturn(getExtensionField<NodeConfig['marks']>(extension, 'marks', context)),\n        group: callOrReturn(getExtensionField<NodeConfig['group']>(extension, 'group', context)),\n        inline: callOrReturn(getExtensionField<NodeConfig['inline']>(extension, 'inline', context)),\n        atom: callOrReturn(getExtensionField<NodeConfig['atom']>(extension, 'atom', context)),\n        selectable: callOrReturn(\n          getExtensionField<NodeConfig['selectable']>(extension, 'selectable', context),\n        ),\n        draggable: callOrReturn(\n          getExtensionField<NodeConfig['draggable']>(extension, 'draggable', context),\n        ),\n        code: callOrReturn(getExtensionField<NodeConfig['code']>(extension, 'code', context)),\n        whitespace: callOrReturn(\n          getExtensionField<NodeConfig['whitespace']>(extension, 'whitespace', context),\n        ),\n        linebreakReplacement: callOrReturn(\n          getExtensionField<NodeConfig['linebreakReplacement']>(\n            extension,\n            'linebreakReplacement',\n            context,\n          ),\n        ),\n        defining: callOrReturn(\n          getExtensionField<NodeConfig['defining']>(extension, 'defining', context),\n        ),\n        isolating: callOrReturn(\n          getExtensionField<NodeConfig['isolating']>(extension, 'isolating', context),\n        ),\n        attrs: Object.fromEntries(extensionAttributes.map(buildAttributeSpec)),\n      })\n\n      const parseHTML = callOrReturn(\n        getExtensionField<NodeConfig['parseHTML']>(extension, 'parseHTML', context),\n      )\n\n      if (parseHTML) {\n        schema.parseDOM = parseHTML.map(parseRule =>\n          injectExtensionAttributesToParseRule(parseRule, extensionAttributes),\n        ) as TagParseRule[]\n      }\n\n      const renderHTML = getExtensionField<NodeConfig['renderHTML']>(\n        extension,\n        'renderHTML',\n        context,\n      )\n\n      if (renderHTML) {\n        schema.toDOM = node =>\n          renderHTML({\n            node,\n            HTMLAttributes: getRenderedAttributes(node, extensionAttributes),\n          })\n      }\n\n      const renderText = getExtensionField<NodeConfig['renderText']>(\n        extension,\n        'renderText',\n        context,\n      )\n\n      if (renderText) {\n        schema.toText = renderText\n      }\n\n      return [extension.name, schema]\n    }),\n  )\n\n  const marks: Record<string, MarkSpec> = Object.fromEntries(\n    markExtensions.map(extension => {\n      const extensionAttributes = allAttributes.filter(\n        attribute => attribute.type === extension.name,\n      )\n      const context = {\n        name: extension.name,\n        options: extension.options,\n        storage: extension.storage,\n        editor,\n      }\n\n      const extraMarkFields = extensions.reduce((fields, e) => {\n        const extendMarkSchema = getExtensionField<AnyConfig['extendMarkSchema']>(\n          e,\n          'extendMarkSchema',\n          context,\n        )\n\n        return {\n          ...fields,\n          ...(extendMarkSchema ? extendMarkSchema(extension as any) : {}),\n        }\n      }, {})\n\n      const schema: MarkSpec = cleanUpSchemaItem({\n        ...extraMarkFields,\n        inclusive: callOrReturn(\n          getExtensionField<MarkConfig['inclusive']>(extension, 'inclusive', context),\n        ),\n        excludes: callOrReturn(\n          getExtensionField<MarkConfig['excludes']>(extension, 'excludes', context),\n        ),\n        group: callOrReturn(getExtensionField<MarkConfig['group']>(extension, 'group', context)),\n        spanning: callOrReturn(\n          getExtensionField<MarkConfig['spanning']>(extension, 'spanning', context),\n        ),\n        code: callOrReturn(getExtensionField<MarkConfig['code']>(extension, 'code', context)),\n        attrs: Object.fromEntries(extensionAttributes.map(buildAttributeSpec)),\n      })\n\n      const parseHTML = callOrReturn(\n        getExtensionField<MarkConfig['parseHTML']>(extension, 'parseHTML', context),\n      )\n\n      if (parseHTML) {\n        schema.parseDOM = parseHTML.map(parseRule =>\n          injectExtensionAttributesToParseRule(parseRule, extensionAttributes),\n        )\n      }\n\n      const renderHTML = getExtensionField<MarkConfig['renderHTML']>(\n        extension,\n        'renderHTML',\n        context,\n      )\n\n      if (renderHTML) {\n        schema.toDOM = mark =>\n          renderHTML({\n            mark,\n            HTMLAttributes: getRenderedAttributes(mark, extensionAttributes),\n          })\n      }\n\n      return [extension.name, schema]\n    }),\n  )\n\n  return {\n    topNode,\n    nodes,\n    marks,\n  } satisfies SchemaSpec\n}\n", "import { Schema } from '@tiptap/pm/model'\nimport type { SchemaSpec } from '@tiptap/pm/model'\n\nimport type { Editor } from '../Editor.js'\nimport type { Extensions } from '../types.js'\nimport { getSchemaAttributes } from '../schema/getSchemaAttributes.js'\nimport { mergeSchemaSpec } from '../schema/mergeSchemaSpec.js'\nimport { findDuplicates } from '../utilities/findDuplicates.js'\nimport { getAttributesFromExtensions } from './getAttributesFromExtensions.js'\nimport { getSchemaSpecByResolvedExtensions } from './getSchemaSpecByResolvedExtensions.js'\n\n/**\n * Creates a ProseMirror schema from resolved extensions.\n * @param extensions The flattened and sorted extensions\n * @param editor The editor instance\n * @param schemaSpec The external structure to use with local extension behavior\n * @returns A ProseMirror schema\n */\nexport function getSchemaByResolvedExtensions(\n  extensions: Extensions,\n  editor?: Editor,\n  schemaSpec?: SchemaSpec,\n): Schema {\n  if (schemaSpec === undefined) {\n    return new Schema(getSchemaSpecByResolvedExtensions(extensions, editor))\n  }\n\n  const duplicates = findDuplicates(\n    extensions.filter(extension => extension.type !== 'extension').map(extension => extension.name),\n  )\n\n  if (duplicates.length) {\n    throw new RangeError(`Duplicate local schema types: ${duplicates.join(', ')}`)\n  }\n\n  const external = new Schema(schemaSpec)\n  const attributes = getSchemaAttributes(getAttributesFromExtensions(extensions), external)\n  const local = getSchemaSpecByResolvedExtensions(extensions, editor, attributes)\n\n  return new Schema(mergeSchemaSpec(local, external))\n}\n", "import type { AnyConfig, Extensions } from '../types.js'\nimport { getExtensionField } from './getExtensionField.js'\n\n/**\n * Sort extensions by priority.\n * @param extensions An array of Tiptap extensions\n * @returns A sorted array of Tiptap extensions by priority\n */\nexport function sortExtensions(extensions: Extensions): Extensions {\n  const defaultPriority = 100\n\n  return extensions.sort((a, b) => {\n    const priorityA = getExtensionField<AnyConfig['priority']>(a, 'priority') || defaultPriority\n    const priorityB = getExtensionField<AnyConfig['priority']>(b, 'priority') || defaultPriority\n\n    if (priorityA > priorityB) {\n      return -1\n    }\n\n    if (priorityA < priorityB) {\n      return 1\n    }\n\n    return 0\n  })\n}\n", "import type { Extensions } from '../types.js'\nimport { findDuplicates } from '../utilities/findDuplicates.js'\nimport { flattenExtensions } from './flattenExtensions.js'\nimport { sortExtensions } from './sortExtensions.js'\n\n/**\n * Returns a flattened and sorted extension list while\n * also checking for duplicated extensions and warns the user.\n * @param extensions An array of Tiptap extensions\n * @returns An flattened and sorted array of Tiptap extensions\n */\nexport function resolveExtensions(extensions: Extensions): Extensions {\n  const resolvedExtensions = sortExtensions(flattenExtensions(extensions))\n  const duplicatedNames = findDuplicates(resolvedExtensions.map(extension => extension.name))\n\n  if (duplicatedNames.length) {\n    console.warn(\n      `[tiptap warn]: Duplicate extension names found: [${duplicatedNames\n        .map(item => `'${item}'`)\n        .join(', ')}]. This can lead to issues.`,\n    )\n  }\n\n  return resolvedExtensions\n}\n", "import type { Schema } from '@tiptap/pm/model'\n\nimport type { Editor } from '../Editor.js'\nimport type { Extensions } from '../types.js'\nimport { getSchemaByResolvedExtensions } from './getSchemaByResolvedExtensions.js'\nimport { resolveExtensions } from './resolveExtensions.js'\n\nexport function getSchema(extensions: Extensions, editor?: Editor): Schema {\n  const resolvedExtensions = resolveExtensions(extensions)\n\n  return getSchemaByResolvedExtensions(resolvedExtensions, editor)\n}\n", "import { Node } from '@tiptap/pm/model'\n\nimport type { Extensions, JSONContent } from '../types.js'\nimport { getHTMLFromFragment } from './getHTMLFromFragment.js'\nimport { getSchema } from './getSchema.js'\n\n/**\n * Generate HTML from a JSONContent\n * @param doc The JSONContent to generate HTML from\n * @param extensions The extensions to use for the schema\n * @returns The generated HTML\n */\nexport function generateHTML(doc: JSONContent, extensions: Extensions): string {\n  const schema = getSchema(extensions)\n  const contentNode = Node.fromJSON(schema, doc)\n\n  return getHTMLFromFragment(contentNode.content, schema)\n}\n", "import { DOMParser } from '@tiptap/pm/model'\n\nimport type { Extensions } from '../types.js'\nimport { elementFromString } from '../utilities/elementFromString.js'\nimport { getSchema } from './getSchema.js'\n\n/**\n * Generate JSONContent from HTML\n * @param html The HTML to generate JSONContent from\n * @param extensions The extensions to use for the schema\n * @returns The generated JSONContent\n */\nexport function generateJSON(html: string, extensions: Extensions): Record<string, any> {\n  const schema = getSchema(extensions)\n  const dom = elementFromString(html)\n\n  return DOMParser.fromSchema(schema).parse(dom).toJSON()\n}\n", "import type { Node as ProseMirrorNode } from '@tiptap/pm/model'\n\nimport type { Range, TextSerializer } from '../types.js'\n\n/**\n * Gets the text between two positions in a Prosemirror node\n * and serializes it using the given text serializers and block separator (see getText)\n * @param startNode The Prosemirror node to start from\n * @param range The range of the text to get\n * @param options Options for the text serializer & block separator\n * @returns The text between the two positions\n */\nexport function getTextBetween(\n  startNode: ProseMirrorNode,\n  range: Range,\n  options?: {\n    blockSeparator?: string\n    textSerializers?: Record<string, TextSerializer>\n  },\n): string {\n  const { from, to } = range\n  const { blockSeparator = '\\n\\n', textSerializers = {} } = options || {}\n  let text = ''\n\n  startNode.nodesBetween(from, to, (node, pos, parent, index) => {\n    if (node.isBlock && pos > from) {\n      text += blockSeparator\n    }\n\n    const textSerializer = textSerializers?.[node.type.name]\n\n    if (textSerializer) {\n      if (parent) {\n        text += textSerializer({\n          node,\n          pos,\n          parent,\n          index,\n          range,\n        })\n      }\n      // do not descend into child nodes when there exists a serializer\n      return false\n    }\n\n    if (node.isText) {\n      text += node?.text?.slice(Math.max(from, pos) - pos, to - pos) // oxlint-disable-line\n    }\n  })\n\n  return text\n}\n", "import type { Node as ProseMirrorNode } from '@tiptap/pm/model'\n\nimport type { TextSerializer } from '../types.js'\nimport { getTextBetween } from './getTextBetween.js'\n\n/**\n * Gets the text of a Prosemirror node\n * @param node The Prosemirror node\n * @param options Options for the text serializer & block separator\n * @returns The text of the node\n * @example ```js\n * const text = getText(node, { blockSeparator: '\\n' })\n * ```\n */\nexport function getText(\n  node: ProseMirrorNode,\n  options?: {\n    blockSeparator?: string\n    textSerializers?: Record<string, TextSerializer>\n  },\n) {\n  const range = {\n    from: 0,\n    to: node.content.size,\n  }\n\n  return getTextBetween(node, range, options)\n}\n", "import type { Schema } from '@tiptap/pm/model'\n\nimport type { TextSerializer } from '../types.js'\n\n/**\n * Find text serializers `toText` in a Prosemirror schema\n * @param schema The Prosemirror schema to search in\n * @returns A record of text serializers by node name\n */\nexport function getTextSerializersFromSchema(schema: Schema): Record<string, TextSerializer> {\n  return Object.fromEntries(\n    Object.entries(schema.nodes)\n      .filter(([, node]) => node.spec.toText)\n      .map(([name, node]) => [name, node.spec.toText]),\n  )\n}\n", "import { Node } from '@tiptap/pm/model'\n\nimport type { Extensions, JSONContent, TextSerializer } from '../types.js'\nimport { getSchema } from './getSchema.js'\nimport { getText } from './getText.js'\nimport { getTextSerializersFromSchema } from './getTextSerializersFromSchema.js'\n\n/**\n * Generate raw text from a JSONContent\n * @param doc The JSONContent to generate text from\n * @param extensions The extensions to use for the schema\n * @param options Options for the text generation f.e. blockSeparator or textSerializers\n * @returns The generated text\n */\nexport function generateText(\n  doc: JSONContent,\n  extensions: Extensions,\n  options?: {\n    blockSeparator?: string\n    textSerializers?: Record<string, TextSerializer>\n  },\n): string {\n  const { blockSeparator = '\\n\\n', textSerializers = {} } = options || {}\n  const schema = getSchema(extensions)\n  const contentNode = Node.fromJSON(schema, doc)\n\n  return getText(contentNode, {\n    blockSeparator,\n    textSerializers: {\n      ...getTextSerializersFromSchema(schema),\n      ...textSerializers,\n    },\n  })\n}\n", "import type { Node, NodeType } from '@tiptap/pm/model'\nimport type { EditorState } from '@tiptap/pm/state'\n\nimport { getNodeType } from './getNodeType.js'\n\nexport function getNodeAttributes(\n  state: EditorState,\n  typeOrName: string | NodeType,\n): Record<string, any> {\n  const type = getNodeType(typeOrName, state.schema)\n  const { from, to } = state.selection\n  const nodes: Node[] = []\n\n  state.doc.nodesBetween(from, to, node => {\n    nodes.push(node)\n  })\n\n  const node = nodes.reverse().find(nodeItem => nodeItem.type.name === type.name)\n\n  if (!node) {\n    return {}\n  }\n\n  return { ...node.attrs }\n}\n", "import type { MarkType, NodeType } from '@tiptap/pm/model'\nimport type { EditorState } from '@tiptap/pm/state'\n\nimport { getMarkAttributes } from './getMarkAttributes.js'\nimport { getNodeAttributes } from './getNodeAttributes.js'\nimport { getSchemaTypeNameByName } from './getSchemaTypeNameByName.js'\n\n/**\n * Get node or mark attributes by type or name on the current editor state\n * @param state The current editor state\n * @param typeOrName The node or mark type or name\n * @returns The attributes of the node or mark or an empty object\n */\nexport function getAttributes(\n  state: EditorState,\n  typeOrName: string | NodeType | MarkType,\n): Record<string, any> {\n  const schemaType = getSchemaTypeNameByName(\n    typeof typeOrName === 'string' ? typeOrName : typeOrName.name,\n    state.schema,\n  )\n\n  if (schemaType === 'node') {\n    return getNodeAttributes(state, typeOrName as NodeType)\n  }\n\n  if (schemaType === 'mark') {\n    return getMarkAttributes(state, typeOrName as MarkType)\n  }\n\n  return {}\n}\n", "/**\n * Removes duplicated values within an array.\n * Supports numbers, strings and objects.\n */\nexport function removeDuplicates<T>(array: T[], by = JSON.stringify): T[] {\n  const seen: Record<any, any> = {}\n\n  return array.filter(item => {\n    const key = by(item)\n\n    return Object.prototype.hasOwnProperty.call(seen, key) ? false : (seen[key] = true)\n  })\n}\n", "import type { Step, Transform } from '@tiptap/pm/transform'\n\nimport type { Range } from '../types.js'\nimport { removeDuplicates } from '../utilities/removeDuplicates.js'\n\nexport type ChangedRange = {\n  oldRange: Range\n  newRange: Range\n}\n\n/**\n * Removes duplicated ranges and ranges that are\n * fully captured by other ranges.\n */\nfunction simplifyChangedRanges(changes: ChangedRange[]): ChangedRange[] {\n  const uniqueChanges = removeDuplicates(changes)\n\n  return uniqueChanges.length === 1\n    ? uniqueChanges\n    : uniqueChanges.filter((change, index) => {\n        const rest = uniqueChanges.filter((_, i) => i !== index)\n\n        return !rest.some(otherChange => {\n          return (\n            change.oldRange.from >= otherChange.oldRange.from &&\n            change.oldRange.to <= otherChange.oldRange.to &&\n            change.newRange.from >= otherChange.newRange.from &&\n            change.newRange.to <= otherChange.newRange.to\n          )\n        })\n      })\n}\n\n/**\n * Returns a list of changed ranges\n * based on the first and last state of all steps.\n */\nexport function getChangedRanges(transform: Transform): ChangedRange[] {\n  const { mapping, steps } = transform\n  const changes: ChangedRange[] = []\n  const inverted = mapping.invert()\n\n  mapping.maps.forEach((stepMap, index) => {\n    const ranges: Range[] = []\n\n    // This accounts for step changes where no range was actually altered\n    // e.g. when setting a mark, node attribute, etc.\n    // @ts-ignore\n    if (!stepMap.ranges.length) {\n      const { from, to } = steps[index] as Step & {\n        from?: number\n        to?: number\n      }\n\n      if (from === undefined || to === undefined) {\n        return\n      }\n\n      ranges.push({ from, to })\n    } else {\n      stepMap.forEach((from, to) => {\n        ranges.push({ from, to })\n      })\n    }\n\n    const rest = mapping.slice(index)\n\n    ranges.forEach(({ from, to }) => {\n      const newStart = rest.map(from, -1)\n      const newEnd = rest.map(to)\n      const oldStart = inverted.map(newStart, -1)\n      const oldEnd = inverted.map(newEnd)\n\n      changes.push({\n        oldRange: {\n          from: oldStart,\n          to: oldEnd,\n        },\n        newRange: {\n          from: newStart,\n          to: newEnd,\n        },\n      })\n    })\n  })\n\n  return simplifyChangedRanges(changes)\n}\n", "import type { Node as ProseMirrorNode } from '@tiptap/pm/model'\n\nimport type { JSONContent } from '../types.js'\n\ninterface DebugJSONContent extends JSONContent {\n  from: number\n  to: number\n}\n\nexport function getDebugJSON(node: ProseMirrorNode, startOffset = 0): DebugJSONContent {\n  const isTopNode = node.type === node.type.schema.topNodeType\n  const increment = isTopNode ? 0 : 1\n  const from = startOffset\n  const to = from + node.nodeSize\n  const marks = node.marks.map(mark => {\n    const output: { type: string; attrs?: Record<string, any> } = {\n      type: mark.type.name,\n    }\n\n    if (Object.keys(mark.attrs).length) {\n      output.attrs = { ...mark.attrs }\n    }\n\n    return output\n  })\n  const attrs = { ...node.attrs }\n  const output: DebugJSONContent = {\n    type: node.type.name,\n    from,\n    to,\n  }\n\n  if (Object.keys(attrs).length) {\n    output.attrs = attrs\n  }\n\n  if (marks.length) {\n    output.marks = marks\n  }\n\n  if (node.content.childCount) {\n    output.content = []\n\n    node.forEach((child, offset) => {\n      output.content?.push(getDebugJSON(child, startOffset + offset + increment))\n    })\n  }\n\n  if (node.text) {\n    output.text = node.text\n  }\n\n  return output\n}\n", "import type { Node as ProseMirrorNode } from '@tiptap/pm/model'\n\nimport type { MarkRange } from '../types.js'\nimport { getMarkRange } from './getMarkRange.js'\n\nexport function getMarksBetween(from: number, to: number, doc: ProseMirrorNode): MarkRange[] {\n  const marks: MarkRange[] = []\n\n  // get all inclusive marks on empty selection\n  if (from === to) {\n    doc\n      .resolve(from)\n      .marks()\n      .forEach(mark => {\n        const $pos = doc.resolve(from)\n        const range = getMarkRange($pos, mark.type)\n\n        if (!range) {\n          return\n        }\n\n        marks.push({\n          mark,\n          ...range,\n        })\n      })\n  } else {\n    doc.nodesBetween(from, to, (node, pos) => {\n      if (!node || node?.nodeSize === undefined) {\n        return\n      }\n\n      marks.push(\n        ...node.marks.map(mark => ({\n          from: pos,\n          to: pos + node.nodeSize,\n          mark,\n        })),\n      )\n    })\n  }\n\n  return marks\n}\n", "import type { Node, NodeType } from '@tiptap/pm/model'\nimport type { EditorState } from '@tiptap/pm/state'\n\n/**\n * Finds the first node of a given type or name in the current selection.\n * @param state The editor state.\n * @param typeOrName The node type or name.\n * @param pos The position to start searching from.\n * @param maxDepth The maximum depth to search.\n * @returns The node and the depth as an array.\n */\nexport const getNodeAtPosition = (\n  state: EditorState,\n  typeOrName: string | NodeType,\n  pos: number,\n  maxDepth = 20,\n) => {\n  const $pos = state.doc.resolve(pos)\n\n  let currentDepth = maxDepth\n  let node: Node | null = null\n\n  while (currentDepth > 0 && node === null) {\n    const currentNode = $pos.node(currentDepth)\n\n    if (currentNode?.type.name === typeOrName) {\n      node = currentNode\n    } else {\n      currentDepth -= 1\n    }\n  }\n\n  return [node, currentDepth] as [Node | null, number]\n}\n", "import type { Node, ResolvedPos } from '@tiptap/pm/model'\n\n/**\n * Returns the block-level sibling immediately before the cursor's textblock\n * (or null when the cursor is at the first child of its block parent).\n *\n * The position does not have to sit inside a textblock: for any resolved\n * position, the result is the sibling immediately before `$pos.parent`. At a\n * GapCursor position this is the sibling before the whole container, not the\n * node before the gap.\n *\n * @param $pos The resolved position to look around\n * @returns The previous block-level sibling, or null\n * @example ```js\n * // Cursor in a top-level paragraph after a list:\n * // <ul><li>A</li></ul><p>|B</p>\n * getPreviousBlockSibling($from) // <ul>\n *\n * // Cursor in the second paragraph of a list item:\n * // <ul><li><p>A</p><p>|B</p></li></ul>\n * getPreviousBlockSibling($from) // <p>A</p>\n *\n * // Cursor in the first child of its block parent:\n * // <doc><p>|A</p></doc>\n * getPreviousBlockSibling($from) // null\n * ```\n */\nexport const getPreviousBlockSibling = ($pos: ResolvedPos): Node | null => {\n  const parentDepth = $pos.depth - 1\n  if (parentDepth < 0) return null\n\n  const index = $pos.index(parentDepth)\n  if (index === 0) return null\n\n  return $pos.node(parentDepth).child(index - 1)\n}\n", "import type { MarkType, NodeType, Schema } from '@tiptap/pm/model'\n\n/**\n * Tries to get a node or mark type by its name.\n * @param name The name of the node or mark type\n * @param schema The Prosemiror schema to search in\n * @returns The node or mark type, or null if it doesn't exist\n */\nexport function getSchemaTypeByName(name: string, schema: Schema): NodeType | MarkType | null {\n  return schema.nodes[name] || schema.marks[name] || null\n}\n", "import type { ExtensionAttribute } from '../types.js'\n\n/**\n * Return attributes of an extension that should be splitted by keepOnSplit flag\n * @param extensionAttributes Array of extension attributes\n * @param typeName The type of the extension\n * @param attributes The attributes of the extension\n * @returns The splitted attributes\n */\nexport function getSplittedAttributes(\n  extensionAttributes: ExtensionAttribute[],\n  typeName: string,\n  attributes: Record<string, any>,\n): Record<string, any> {\n  return Object.fromEntries(\n    Object.entries(attributes).filter(([name]) => {\n      const extensionAttribute = extensionAttributes.find(item => {\n        return item.type === typeName && item.name === name\n      })\n\n      if (!extensionAttribute) {\n        return false\n      }\n\n      return extensionAttribute.attribute.keepOnSplit\n    }),\n  )\n}\n", "import type { ResolvedPos } from '@tiptap/pm/model'\n\n/**\n * Returns the text content of a resolved prosemirror position\n * @param $from The resolved position to get the text content from\n * @param maxMatch The maximum number of characters to match\n * @returns The text content\n */\nexport const getTextContentFromNodes = ($from: ResolvedPos, maxMatch = 500) => {\n  let textBefore = ''\n\n  const sliceEndPos = $from.parentOffset\n\n  $from.parent.nodesBetween(\n    Math.max(0, sliceEndPos - maxMatch),\n    sliceEndPos,\n    (node, pos, parent, index) => {\n      const chunk =\n        node.type.spec.toText?.({\n          node,\n          pos,\n          parent,\n          index,\n        }) ||\n        node.textContent ||\n        '%leaf%'\n\n      textBefore +=\n        node.isAtom && !node.isText ? chunk : chunk.slice(0, Math.max(0, sliceEndPos - pos))\n    },\n  )\n\n  return textBefore\n}\n", "import type { MarkType } from '@tiptap/pm/model'\nimport type { EditorState } from '@tiptap/pm/state'\n\nimport type { MarkRange } from '../types.js'\nimport { objectIncludes } from '../utilities/objectIncludes.js'\nimport { getMarkType } from './getMarkType.js'\n\nexport function isMarkActive(\n  state: EditorState,\n  typeOrName: MarkType | string | null,\n  attributes: Record<string, any> = {},\n): boolean {\n  const { empty, ranges } = state.selection\n  const type = typeOrName ? getMarkType(typeOrName, state.schema) : null\n\n  if (empty) {\n    return !!(state.storedMarks || state.selection.$from.marks())\n      .filter(mark => {\n        if (!type) {\n          return true\n        }\n\n        return type.name === mark.type.name\n      })\n      .find(mark => objectIncludes(mark.attrs, attributes, { strict: false }))\n  }\n\n  let selectionRange = 0\n  const markRanges: MarkRange[] = []\n\n  ranges.forEach(({ $from, $to }) => {\n    const from = $from.pos\n    const to = $to.pos\n\n    state.doc.nodesBetween(from, to, (node, pos) => {\n      // ignore selected text inside nodes whose schema disallows this mark type\n      if (type && node.inlineContent && !node.type.allowsMarkType(type)) {\n        return false\n      }\n\n      if (!node.isText && !node.marks.length) {\n        return\n      }\n\n      const relativeFrom = Math.max(from, pos)\n      const relativeTo = Math.min(to, pos + node.nodeSize)\n      const range = relativeTo - relativeFrom\n\n      selectionRange += range\n\n      markRanges.push(\n        ...node.marks.map(mark => ({\n          mark,\n          from: relativeFrom,\n          to: relativeTo,\n        })),\n      )\n    })\n  })\n\n  if (selectionRange === 0) {\n    return false\n  }\n\n  // calculate range of matched mark\n  const matchedRange = markRanges\n    .filter(markRange => {\n      if (!type) {\n        return true\n      }\n\n      return type.name === markRange.mark.type.name\n    })\n    .filter(markRange => objectIncludes(markRange.mark.attrs, attributes, { strict: false }))\n    .reduce((sum, markRange) => sum + markRange.to - markRange.from, 0)\n\n  // calculate range of marks that excludes the searched mark\n  // for example `code` doesn’t allow any other marks\n  const excludedRange = markRanges\n    .filter(markRange => {\n      if (!type) {\n        return true\n      }\n\n      return markRange.mark.type !== type && markRange.mark.type.excludes(type)\n    })\n    .reduce((sum, markRange) => sum + markRange.to - markRange.from, 0)\n\n  // we only include the result of `excludedRange`\n  // if there is a match at all\n  const range = matchedRange > 0 ? matchedRange + excludedRange : matchedRange\n\n  return range >= selectionRange\n}\n", "import type { EditorState } from '@tiptap/pm/state'\n\nimport { getSchemaTypeNameByName } from './getSchemaTypeNameByName.js'\nimport { isMarkActive } from './isMarkActive.js'\nimport { isNodeActive } from './isNodeActive.js'\n\nexport function isActive(\n  state: EditorState,\n  name: string | null,\n  attributes: Record<string, any> = {},\n): boolean {\n  if (!name) {\n    return isNodeActive(state, null, attributes) || isMarkActive(state, null, attributes)\n  }\n\n  const schemaType = getSchemaTypeNameByName(name, state.schema)\n\n  if (schemaType === 'node') {\n    return isNodeActive(state, name, attributes)\n  }\n\n  if (schemaType === 'mark') {\n    return isMarkActive(state, name, attributes)\n  }\n\n  return false\n}\n", "import type { EditorState } from '@tiptap/pm/state'\n\nimport { findParentNode } from './findParentNode.js'\n\nexport const isAtEndOfNode = (state: EditorState, nodeType?: string) => {\n  const { $from, $to, $anchor } = state.selection\n\n  if (nodeType) {\n    const parentNode = findParentNode(node => node.type.name === nodeType)(state.selection)\n\n    if (!parentNode) {\n      return false\n    }\n\n    const $parentPos = state.doc.resolve(parentNode.pos + 1)\n\n    if ($anchor.pos + 1 === $parentPos.end()) {\n      return true\n    }\n\n    return false\n  }\n\n  if ($to.parentOffset < $to.parent.nodeSize - 2 || $from.pos !== $to.pos) {\n    return false\n  }\n\n  return true\n}\n", "import type { EditorState } from '@tiptap/pm/state'\n\nexport const isAtStartOfNode = (state: EditorState) => {\n  const { $from, $to } = state.selection\n\n  if ($from.parentOffset > 0 || $from.pos !== $to.pos) {\n    return false\n  }\n\n  return true\n}\n", "import type { AnyExtension, EnableRules } from '../types.js'\n\nexport function isExtensionRulesEnabled(extension: AnyExtension, enabled: EnableRules): boolean {\n  if (Array.isArray(enabled)) {\n    return enabled.some(enabledExtension => {\n      const name = typeof enabledExtension === 'string' ? enabledExtension : enabledExtension.name\n\n      return name === extension.name\n    })\n  }\n\n  return enabled\n}\n", "import { getExtensionField } from '../helpers/getExtensionField.js'\nimport type { NodeConfig } from '../index.js'\nimport type { Extensions } from '../types.js'\nimport { callOrReturn } from '../utilities/callOrReturn.js'\nimport { splitExtensions } from './splitExtensions.js'\n\nexport function isList(name: string, extensions: Extensions): boolean {\n  const { nodeExtensions } = splitExtensions(extensions)\n  const extension = nodeExtensions.find(item => item.name === name)\n\n  if (!extension) {\n    return false\n  }\n\n  const context = {\n    name: extension.name,\n    options: extension.options,\n    storage: extension.storage,\n  }\n  const group = callOrReturn(getExtensionField<NodeConfig['group']>(extension, 'group', context))\n\n  if (typeof group !== 'string') {\n    return false\n  }\n\n  return group.split(' ').includes('list')\n}\n", "import type { Node as ProseMirrorNode } from '@tiptap/pm/model'\n\n/**\n * Returns true if the given prosemirror node is empty.\n */\nexport function isNodeEmpty(\n  node: ProseMirrorNode,\n  {\n    checkChildren = true,\n    ignoreWhitespace = false,\n  }: {\n    /**\n     * When true (default), it will also check if all children are empty.\n     */\n    checkChildren?: boolean\n    /**\n     * When true, it will ignore whitespace when checking for emptiness.\n     */\n    ignoreWhitespace?: boolean\n  } = {},\n): boolean {\n  if (ignoreWhitespace) {\n    if (node.type.name === 'hardBreak') {\n      // Hard breaks are considered empty\n      return true\n    }\n    if (node.isText) {\n      return !/\\S/.test(node.text ?? '')\n    }\n  }\n\n  if (node.isText) {\n    return !node.text\n  }\n\n  if (node.isAtom || node.isLeaf) {\n    return false\n  }\n\n  if (node.content.childCount === 0) {\n    return true\n  }\n\n  if (checkChildren) {\n    let isContentEmpty = true\n\n    node.content.forEach(childNode => {\n      if (isContentEmpty === false) {\n        // Exit early for perf\n        return\n      }\n\n      if (!isNodeEmpty(childNode, { ignoreWhitespace, checkChildren })) {\n        isContentEmpty = false\n      }\n    })\n\n    return isContentEmpty\n  }\n\n  return false\n}\n", "import { NodeSelection } from '@tiptap/pm/state'\n\nexport function isNodeSelection(value: unknown): value is NodeSelection {\n  return value instanceof NodeSelection\n}\n", "import type { Selection } from '@tiptap/pm/state'\n\nimport { isTextSelection } from './isTextSelection.js'\n\n/**\n * Determines whether a node view should be considered selected for the given\n * editor selection.\n *\n * A node is considered selected when the current selection fully covers it\n * (e.g. a `NodeSelection`). When `selectedOnTextSelection` is enabled, the\n * node is additionally considered selected if a `TextSelection` is fully\n * contained within the node's range.\n *\n * @param selection The current editor selection.\n * @param pos The start position of the node in the document.\n * @param nodeSize The size of the node.\n * @param selectedOnTextSelection When `true`, also treat selections inside the node as selected.\n * @returns `true` if the node view should render as selected.\n */\nexport function isNodeViewSelected({\n  selection,\n  pos,\n  nodeSize,\n  selectedOnTextSelection = false,\n}: {\n  selection: Selection\n  pos: number\n  nodeSize: number\n  selectedOnTextSelection?: boolean\n}): boolean {\n  const { from, to } = selection\n\n  if (from <= pos && to >= pos + nodeSize) {\n    return true\n  }\n\n  if (selectedOnTextSelection && isTextSelection(selection) && from > pos && to < pos + nodeSize) {\n    return true\n  }\n\n  return false\n}\n", "import { type Step } from '@tiptap/pm/transform'\n\n/**\n * Checks if a value is a ProseMirror step\n * @param value The value to check\n * @returns - A boolean, if the boolean is true the value is a ProseMirror Step\n * @example ```js\n * isProseMirrorStep(transaction.steps[0])\n * ```\n */\nexport function isProseMirrorStep(value: unknown): value is Step {\n  if (value === null || typeof value !== 'object') {\n    return false\n  }\n\n  const step = value as Record<string, unknown>\n\n  if (\n    typeof step.apply !== 'function' ||\n    typeof step.getMap !== 'function' ||\n    typeof step.invert !== 'function' ||\n    typeof step.map !== 'function' ||\n    typeof step.merge !== 'function' ||\n    typeof step.toJSON !== 'function'\n  ) {\n    return false\n  }\n\n  return true\n}\n", "import { type AddMarkStep } from '@tiptap/pm/transform'\nimport { isProseMirrorStep } from './isProseMirrorStep.js'\n\n/**\n * Checks if a value is a ProseMirror add mark step\n * @param value The value to check\n * @returns - A boolean, if the boolean is true the value is a ProseMirror AddMarkStep\n * @example ```js\n * isProseMirrorAddMarkStep(transaction.steps[0])\n * ```\n */\nexport function isProseMirrorAddMarkStep(value: unknown): value is AddMarkStep {\n  if (value === null || typeof value !== 'object') {\n    return false\n  }\n\n  const step = value as Record<string, unknown>\n\n  if (!isProseMirrorStep(step)) {\n    return false\n  }\n\n  const json = step.toJSON()\n\n  // we use the steps jsonID to check if the step is an add mark step\n  if (json === null || typeof json !== 'object' || json.stepType !== 'addMark') {\n    return false\n  }\n\n  return true\n}\n", "import { type AddNodeMarkStep } from '@tiptap/pm/transform'\nimport { isProseMirrorStep } from './isProseMirrorStep.js'\n\n/**\n * Checks if a value is a ProseMirror add node mark step\n * @param value The value to check\n * @returns - A boolean, if the boolean is true the value is a ProseMirror AddNodeMarkStep\n * @example ```js\n * isProseMirrorAddNodeMarkStep(transaction.steps[0])\n * ```\n */\nexport function isProseMirrorAddNodeMarkStep(value: unknown): value is AddNodeMarkStep {\n  if (value === null || typeof value !== 'object') {\n    return false\n  }\n\n  const step = value as Record<string, unknown>\n\n  if (!isProseMirrorStep(step)) {\n    return false\n  }\n\n  const json = step.toJSON()\n\n  // we use the steps jsonID to check if the step is an add node mark step\n  if (json === null || typeof json !== 'object' || json.stepType !== 'addNodeMark') {\n    return false\n  }\n\n  return true\n}\n", "import { type AttrStep } from '@tiptap/pm/transform'\nimport { isProseMirrorStep } from './isProseMirrorStep.js'\n\n/**\n * Checks if a value is a ProseMirror attribute step\n * @param value The value to check\n * @returns - A boolean, if the boolean is true the value is a ProseMirror AttrStep\n * @example ```js\n * isProseMirrorAttrStep(transaction.steps[0])\n * ```\n */\nexport function isProseMirrorAttrStep(value: unknown): value is AttrStep {\n  if (value === null || typeof value !== 'object') {\n    return false\n  }\n\n  const step = value as Record<string, unknown>\n\n  if (!isProseMirrorStep(step)) {\n    return false\n  }\n\n  const json = step.toJSON()\n\n  // we use the steps jsonID to check if the step is an attribute step\n  if (json === null || typeof json !== 'object' || json.stepType !== 'attr') {\n    return false\n  }\n\n  return true\n}\n", "import type { CellSelection } from '@tiptap/pm/tables'\n\n/**\n * Check whether a selection provides the cell-iteration API.\n *\n * @param selection - Selection to inspect.\n * @returns Whether the selection is a table cell selection.\n * @example ```js\n * isProseMirrorCellSelection(editor.state.selection)\n * ```\n */\nexport function isProseMirrorCellSelection(selection: unknown): selection is CellSelection {\n  if (selection === null || typeof selection !== 'object') {\n    return false\n  }\n\n  return 'forEachCell' in selection && typeof selection.forEachCell === 'function'\n}\n", "import { type DocAttrStep } from '@tiptap/pm/transform'\nimport { isProseMirrorStep } from './isProseMirrorStep.js'\n\n/**\n * Checks if a value is a ProseMirror document attribute step\n * @param value The value to check\n * @returns - A boolean, if the boolean is true the value is a ProseMirror DocAttrStep\n * @example ```js\n * isProseMirrorDocAttrStep(transaction.steps[0])\n * ```\n */\nexport function isProseMirrorDocAttrStep(value: unknown): value is DocAttrStep {\n  if (value === null || typeof value !== 'object') {\n    return false\n  }\n\n  const step = value as Record<string, unknown>\n\n  if (!isProseMirrorStep(step)) {\n    return false\n  }\n\n  const json = step.toJSON()\n\n  // we use the steps jsonID to check if the step is a document attribute step\n  if (json === null || typeof json !== 'object' || json.stepType !== 'docAttr') {\n    return false\n  }\n\n  return true\n}\n", "import { type Fragment } from '@tiptap/pm/model'\n\n/**\n * Checks if a value is a ProseMirror fragment by inspecting it\n * @param value The value to check\n * @returns - A boolean, if true the value is a ProseMirror fragment\n * @example ```js\n * isProseMirrorFragment(editor.state.doc.content)\n * ```\n */\nexport function isProseMirrorFragment(value: unknown): value is Fragment {\n  if (value === null || typeof value !== 'object') {\n    return false\n  }\n\n  const fragment = value as Record<string, unknown>\n\n  if (\n    !Array.isArray(fragment.content) ||\n    typeof fragment.size !== 'number' ||\n    typeof fragment.nodesBetween !== 'function' ||\n    typeof fragment.descendants !== 'function' ||\n    typeof fragment.textBetween !== 'function' ||\n    typeof fragment.append !== 'function' ||\n    typeof fragment.cut !== 'function' ||\n    typeof fragment.eq !== 'function' ||\n    typeof fragment.child !== 'function' ||\n    typeof fragment.forEach !== 'function'\n  ) {\n    return false\n  }\n\n  return true\n}\n", "import type { NodeSelection } from '@tiptap/pm/state'\n\n/**\n * Check whether a selection exposes a selected node.\n *\n * @param selection - Selection to inspect.\n * @returns Whether the selection is a node selection.\n * @example ```js\n * isProseMirrorNodeSelection(editor.state.selection)\n * ```\n */\nexport function isProseMirrorNodeSelection(selection: unknown): selection is NodeSelection {\n  if (selection === null || typeof selection !== 'object') {\n    return false\n  }\n\n  return 'node' in selection && selection.node != null\n}\n", "import { type RemoveMarkStep } from '@tiptap/pm/transform'\nimport { isProseMirrorStep } from './isProseMirrorStep.js'\n\n/**\n * Checks if a value is a ProseMirror remove mark step\n * @param value The value to check\n * @returns - A boolean, if the boolean is true the value is a ProseMirror RemoveMarkStep\n * @example ```js\n * isProseMirrorRemoveMarkStep(transaction.steps[0])\n * ```\n */\nexport function isProseMirrorRemoveMarkStep(value: unknown): value is RemoveMarkStep {\n  if (value === null || typeof value !== 'object') {\n    return false\n  }\n\n  const step = value as Record<string, unknown>\n\n  if (!isProseMirrorStep(step)) {\n    return false\n  }\n\n  const json = step.toJSON()\n\n  // we use the steps jsonID to check if the step is a remove mark step\n  if (json === null || typeof json !== 'object' || json.stepType !== 'removeMark') {\n    return false\n  }\n\n  return true\n}\n", "import { type RemoveNodeMarkStep } from '@tiptap/pm/transform'\nimport { isProseMirrorStep } from './isProseMirrorStep.js'\n\n/**\n * Checks if a value is a ProseMirror remove node mark step\n * @param value The value to check\n * @returns - A boolean, if the boolean is true the value is a ProseMirror RemoveNodeMarkStep\n * @example ```js\n * isProseMirrorRemoveNodeMarkStep(transaction.steps[0])\n * ```\n */\nexport function isProseMirrorRemoveNodeMarkStep(value: unknown): value is RemoveNodeMarkStep {\n  if (value === null || typeof value !== 'object') {\n    return false\n  }\n\n  const step = value as Record<string, unknown>\n\n  if (!isProseMirrorStep(step)) {\n    return false\n  }\n\n  const json = step.toJSON()\n\n  // we use the steps jsonID to check if the step is a remove node mark step\n  if (json === null || typeof json !== 'object' || json.stepType !== 'removeNodeMark') {\n    return false\n  }\n\n  return true\n}\n", "import { type ReplaceAroundStep } from '@tiptap/pm/transform'\nimport { isProseMirrorStep } from './isProseMirrorStep.js'\n\n/**\n * Checks if a value is a ProseMirror replace around step\n * @param value The value to check\n * @returns - A boolean, if the boolean is true the value is a ProseMirror ReplaceAroundStep\n * @example ```js\n * isProseMirrorReplaceAroundStep(transaction.steps[0])\n * ```\n */\nexport function isProseMirrorReplaceAroundStep(value: unknown): value is ReplaceAroundStep {\n  if (value === null || typeof value !== 'object') {\n    return false\n  }\n\n  const step = value as Record<string, unknown>\n\n  if (!isProseMirrorStep(step)) {\n    return false\n  }\n\n  const json = step.toJSON()\n\n  // we use the steps jsonID to check if the step is a replace around step\n  if (json === null || typeof json !== 'object' || json.stepType !== 'replaceAround') {\n    return false\n  }\n\n  return true\n}\n", "import { type ReplaceStep } from '@tiptap/pm/transform'\nimport { isProseMirrorStep } from './isProseMirrorStep.js'\n\n/**\n * Checks if a value is a ProseMirror replace step result\n * @param value The value to check\n * @returns - A boolean, if the boolean is true the value is a ProseMirror ReplaceStep\n * @example ```js\n * isProseMirrorReplaceStep(transaction.steps[0])\n * ```\n */\nexport function isProseMirrorReplaceStep(value: unknown): value is ReplaceStep {\n  if (value === null || typeof value !== 'object') {\n    return false\n  }\n\n  const step = value as Record<string, unknown>\n\n  if (!isProseMirrorStep(step)) {\n    return false\n  }\n\n  const json = step.toJSON()\n\n  // we use the steps jsonID to check if the step is a replace step\n  if (json === null || typeof json !== 'object' || json.stepType !== 'replace') {\n    return false\n  }\n\n  return true\n}\n", "import { type Slice } from '@tiptap/pm/model'\nimport { isProseMirrorFragment } from './isProseMirrorFragment.js'\n\n/**\n * Checks if a value is a ProseMirror slice by inspecting it\n * @param value The value to check\n * @returns - A boolean, if true the value is a ProseMirror slice\n * @example ```js\n * isProseMirrorSlice(editor.state.doc.content.slice(0, 10))\n * ```\n */\nexport function isProseMirrorSlice(value: unknown): value is Slice {\n  if (value === null || typeof value !== 'object') {\n    return false\n  }\n\n  const slice = value as Record<string, unknown>\n\n  const openStartIsNumber = Number.isInteger(slice.openStart) && (slice.openStart as number) >= 0\n  const openEndIsNumber = Number.isInteger(slice.openEnd) && (slice.openEnd as number) >= 0\n  const sliceHasRequiredProperties =\n    typeof slice.size === 'number' &&\n    typeof slice.eq === 'function' &&\n    typeof slice.toJSON === 'function'\n\n  if (!openStartIsNumber || !openEndIsNumber || !sliceHasRequiredProperties) {\n    return false\n  }\n\n  const content = slice.content\n\n  if (content === null || typeof content !== 'object') {\n    return false\n  }\n\n  const fragment = content as Record<string, unknown>\n\n  if (!isProseMirrorFragment(fragment)) {\n    return false\n  }\n\n  return true\n}\n", "import { type StepResult } from '@tiptap/pm/transform'\n\n/**\n * Checks if a value is a ProseMirror step result\n * @param value The value to check\n * @returns - A boolean, if the boolean is true the value is a ProseMirror StepResult\n * @example ```js\n * isProseMirrorStepResult(step.apply(editor.state.doc))\n * ```\n */\nexport function isProseMirrorStepResult(value: unknown): value is StepResult {\n  if (value === null || typeof value !== 'object') {\n    return false\n  }\n\n  const result = value as Record<string, unknown>\n\n  const isValidDoc = result.doc !== null && typeof result.doc === 'object' && result.failed === null\n  const isValidFailed = typeof result.failed === 'string' && result.doc === null\n\n  if (!isValidDoc && !isValidFailed) {\n    return false\n  }\n\n  return true\n}\n", "import type { Transaction } from '@tiptap/pm/state'\nimport type { MapResult } from '@tiptap/pm/transform'\n\n/**\n * A class that represents a mappable position in the editor. It can be extended\n * by other extensions to add additional position mapping capabilities.\n */\nexport class MappablePosition {\n  /**\n   * The absolute position in the editor.\n   */\n  public position: number\n\n  constructor(position: number) {\n    this.position = position\n  }\n\n  /**\n   * Creates a MappablePosition from a JSON object.\n   */\n  static fromJSON(json: any): MappablePosition {\n    return new MappablePosition(json.position)\n  }\n\n  /**\n   * Converts the MappablePosition to a JSON object.\n   */\n  toJSON(): any {\n    return {\n      position: this.position,\n    }\n  }\n}\n\n/**\n * The result of the getUpdatedPosition function.\n */\nexport interface GetUpdatedPositionResult {\n  position: MappablePosition\n  mapResult: MapResult | null\n}\n\n/**\n * Calculates the new position after applying a transaction.\n *\n * @returns The new mappable position and the map result.\n */\nexport function getUpdatedPosition(\n  position: MappablePosition,\n  transaction: Transaction,\n): GetUpdatedPositionResult {\n  const mapResult = transaction.mapping.mapResult(position.position)\n  return {\n    position: new MappablePosition(mapResult.pos),\n    mapResult,\n  }\n}\n\n/**\n * Creates a MappablePosition from a position number. This is the default\n * implementation for Tiptap core. It can be overridden by other Tiptap\n * extensions.\n *\n * @param position The position (as a number) where the MappablePosition will be created.\n * @returns A new MappablePosition instance at the given position.\n */\nexport function createMappablePosition(position: number): MappablePosition {\n  return new MappablePosition(position)\n}\n", "import type { EditorView } from '@tiptap/pm/view'\n\nimport { minMax } from '../utilities/minMax.js'\n\nexport function posToDOMRect(view: EditorView, from: number, to: number): DOMRect {\n  const minPos = 0\n  const maxPos = view.state.doc.content.size\n  const resolvedFrom = minMax(from, minPos, maxPos)\n  const resolvedEnd = minMax(to, minPos, maxPos)\n  const start = view.coordsAtPos(resolvedFrom)\n  const end = view.coordsAtPos(resolvedEnd, -1)\n  const top = Math.min(start.top, end.top)\n  const bottom = Math.max(start.bottom, end.bottom)\n  const left = Math.min(start.left, end.left)\n  const right = Math.max(start.right, end.right)\n  const width = right - left\n  const height = bottom - top\n  const x = left\n  const y = top\n  const data = {\n    top,\n    bottom,\n    left,\n    right,\n    width,\n    height,\n    x,\n    y,\n  }\n\n  return {\n    ...data,\n    toJSON: () => data,\n  }\n}\n", "import type { Schema } from '@tiptap/pm/model'\n\nimport type { JSONContent } from '../types.js'\n\ntype RewriteUnknownContentOptions = {\n  /**\n   * If true, unknown nodes will be treated as paragraphs\n   * @default true\n   */\n  fallbackToParagraph?: boolean\n}\n\ntype RewrittenContent = {\n  /**\n   * The original JSON content that was rewritten\n   */\n  original: JSONContent\n  /**\n   * The name of the node or mark that was unsupported\n   */\n  unsupported: string\n}[]\n\n/**\n * The actual implementation of the rewriteUnknownContent function\n */\nfunction rewriteUnknownContentInner({\n  json,\n  validMarks,\n  validNodes,\n  options,\n  rewrittenContent = [],\n}: {\n  json: JSONContent\n  validMarks: Set<string>\n  validNodes: Set<string>\n  options?: RewriteUnknownContentOptions\n  rewrittenContent?: RewrittenContent\n}): {\n  /**\n   * The cleaned JSON content\n   */\n  json: JSONContent | null\n  /**\n   * The array of nodes and marks that were rewritten\n   */\n  rewrittenContent: RewrittenContent\n} {\n  if (json.marks && Array.isArray(json.marks)) {\n    json.marks = json.marks.filter(mark => {\n      if (mark === null || mark === undefined) {\n        // Drop malformed (nullish) mark entries instead of crashing\n        return false\n      }\n\n      const name = typeof mark === 'string' ? mark : mark.type\n\n      if (validMarks.has(name)) {\n        return true\n      }\n\n      rewrittenContent.push({\n        original: JSON.parse(JSON.stringify(mark)),\n        unsupported: name,\n      })\n      // Just ignore any unknown marks\n      return false\n    })\n  }\n\n  if (json.content && Array.isArray(json.content)) {\n    json.content = json.content\n      .map(value => {\n        if (value === null || value === undefined) {\n          // Drop malformed (nullish) content entries instead of crashing\n          return null\n        }\n\n        return rewriteUnknownContentInner({\n          json: value,\n          validMarks,\n          validNodes,\n          options,\n          rewrittenContent,\n        }).json\n      })\n      .filter(a => a !== null && a !== undefined)\n  }\n\n  if (json.type && !validNodes.has(json.type)) {\n    rewrittenContent.push({\n      original: JSON.parse(JSON.stringify(json)),\n      unsupported: json.type,\n    })\n\n    if (json.content && Array.isArray(json.content) && options?.fallbackToParagraph !== false) {\n      // Just treat it like a paragraph and hope for the best\n      json.type = 'paragraph'\n\n      return {\n        json,\n        rewrittenContent,\n      }\n    }\n\n    // or just omit it entirely\n    return {\n      json: null,\n      rewrittenContent,\n    }\n  }\n\n  return { json, rewrittenContent }\n}\n\n/**\n * Rewrite unknown nodes and marks within JSON content\n * Allowing for user within the editor\n */\nexport function rewriteUnknownContent(\n  /**\n   * The JSON content to clean of unknown nodes and marks\n   */\n  json: JSONContent,\n  /**\n   * The schema to use for validation\n   */\n  schema: Schema,\n  /**\n   * Options for the cleaning process\n   */\n  options?: RewriteUnknownContentOptions,\n): {\n  /**\n   * The cleaned JSON content\n   */\n  json: JSONContent | null\n  /**\n   * The array of nodes and marks that were rewritten\n   */\n  rewrittenContent: {\n    /**\n     * The original JSON content that was rewritten\n     */\n    original: JSONContent\n    /**\n     * The name of the node or mark that was unsupported\n     */\n    unsupported: string\n  }[]\n} {\n  return rewriteUnknownContentInner({\n    json,\n    validNodes: new Set(Object.keys(schema.nodes)),\n    validMarks: new Set(Object.keys(schema.marks)),\n    options,\n  })\n}\n", "import type { MarkType, ResolvedPos } from '@tiptap/pm/model'\nimport type { EditorState, Transaction } from '@tiptap/pm/state'\n\nimport { getMarkAttributes } from '../helpers/getMarkAttributes.js'\nimport { getMarkType } from '../helpers/getMarkType.js'\nimport { isTextSelection } from '../helpers/index.js'\nimport type { RawCommands } from '../types.js'\n\ndeclare module '@tiptap/core' {\n  interface Commands<ReturnType> {\n    setMark: {\n      /**\n       * Add a mark with new attributes.\n       * @param typeOrName The mark type or name.\n       * @example editor.commands.setMark('bold', { level: 1 })\n       */\n      setMark: (typeOrName: string | MarkType, attributes?: Record<string, any>) => ReturnType\n    }\n  }\n}\n\nfunction canSetMark(state: EditorState, tr: Transaction, newMarkType: MarkType) {\n  const { selection } = tr\n  let cursor: ResolvedPos | null = null\n\n  if (isTextSelection(selection)) {\n    cursor = selection.$cursor\n  }\n\n  if (cursor) {\n    const currentMarks = state.storedMarks ?? cursor.marks()\n    const parentAllowsMarkType = cursor.parent.type.allowsMarkType(newMarkType)\n\n    // There can be no current marks that exclude the new mark, and the parent must allow this mark type\n    return (\n      parentAllowsMarkType &&\n      (!!newMarkType.isInSet(currentMarks) ||\n        !currentMarks.some(mark => mark.type.excludes(newMarkType)))\n    )\n  }\n\n  const { ranges } = selection\n\n  return ranges.some(({ $from, $to }) => {\n    let someNodeSupportsMark =\n      $from.depth === 0\n        ? state.doc.inlineContent && state.doc.type.allowsMarkType(newMarkType)\n        : false\n\n    state.doc.nodesBetween($from.pos, $to.pos, (node, _pos, parent) => {\n      // If we already found a mark that we can enable, return false to bypass the remaining search\n      if (someNodeSupportsMark) {\n        return false\n      }\n\n      if (node.isInline) {\n        const parentAllowsMarkType = !parent || parent.type.allowsMarkType(newMarkType)\n        const currentMarksAllowMarkType =\n          !!newMarkType.isInSet(node.marks) ||\n          !node.marks.some(otherMark => otherMark.type.excludes(newMarkType))\n\n        someNodeSupportsMark = parentAllowsMarkType && currentMarksAllowMarkType\n      }\n      return !someNodeSupportsMark\n    })\n\n    return someNodeSupportsMark\n  })\n}\nexport const setMark: RawCommands['setMark'] =\n  (typeOrName, attributes = {}) =>\n  ({ tr, state, dispatch }) => {\n    const { selection } = tr\n    const { empty, ranges } = selection\n    const type = getMarkType(typeOrName, state.schema)\n\n    if (dispatch) {\n      if (empty) {\n        const oldAttributes = getMarkAttributes(state, type)\n\n        tr.addStoredMark(\n          type.create({\n            ...oldAttributes,\n            ...attributes,\n          }),\n        )\n      } else {\n        ranges.forEach(range => {\n          const from = range.$from.pos\n          const to = range.$to.pos\n\n          state.doc.nodesBetween(from, to, (node, pos) => {\n            const trimmedFrom = Math.max(pos, from)\n            const trimmedTo = Math.min(pos + node.nodeSize, to)\n            const someHasMark = node.marks.find(mark => mark.type === type)\n\n            // if there is already a mark of this type\n            // we know that we have to merge its attributes\n            // otherwise we add a fresh new mark\n            if (someHasMark) {\n              node.marks.forEach(mark => {\n                if (type === mark.type) {\n                  tr.addMark(\n                    trimmedFrom,\n                    trimmedTo,\n                    type.create({\n                      ...mark.attrs,\n                      ...attributes,\n                    }),\n                  )\n                }\n              })\n            } else {\n              tr.addMark(trimmedFrom, trimmedTo, type.create(attributes))\n            }\n          })\n        })\n      }\n    }\n\n    return canSetMark(state, tr, type)\n  }\n", "import type { Plugin, PluginKey } from '@tiptap/pm/state'\n\nimport type { RawCommands } from '../types.js'\n\ndeclare module '@tiptap/core' {\n  interface Commands<ReturnType> {\n    setMeta: {\n      /**\n       * Store a metadata property in the current transaction.\n       * @param key The key of the metadata property.\n       * @param value The value to store.\n       * @example editor.commands.setMeta('foo', 'bar')\n       */\n      setMeta: (key: string | Plugin | PluginKey, value: any) => ReturnType\n    }\n  }\n}\n\nexport const setMeta: RawCommands['setMeta'] =\n  (key, value) =>\n  ({ tr }) => {\n    tr.setMeta(key, value)\n\n    return true\n  }\n", "import { setBlockType } from '@tiptap/pm/commands'\nimport type { NodeType } from '@tiptap/pm/model'\n\nimport { getNodeType } from '../helpers/getNodeType.js'\nimport type { RawCommands } from '../types.js'\n\ndeclare module '@tiptap/core' {\n  interface Commands<ReturnType> {\n    setNode: {\n      /**\n       * Replace a given range with a node.\n       * @param typeOrName The type or name of the node\n       * @param attributes The attributes of the node\n       * @example editor.commands.setNode('paragraph')\n       */\n      setNode: (typeOrName: string | NodeType, attributes?: Record<string, any>) => ReturnType\n    }\n  }\n}\n\nexport const setNode: RawCommands['setNode'] =\n  (typeOrName, attributes = {}) =>\n  ({ state, dispatch, chain }) => {\n    const type = getNodeType(typeOrName, state.schema)\n\n    let attributesToCopy: Record<string, any> | undefined\n\n    if (state.selection.$anchor.sameParent(state.selection.$head)) {\n      // only copy attributes if the selection is pointing to a node of the same type\n      attributesToCopy = state.selection.$anchor.parent.attrs\n    }\n\n    // TODO: use a fallback like insertContent?\n    if (!type.isTextblock) {\n      console.warn('[tiptap warn]: Currently \"setNode()\" only supports text block nodes.')\n\n      return false\n    }\n\n    return (\n      chain()\n        // try to convert node to default node if needed\n        .command(({ commands }) => {\n          const canSetBlock = setBlockType(type, { ...attributesToCopy, ...attributes })(state)\n\n          if (canSetBlock) {\n            return true\n          }\n\n          return commands.clearNodes()\n        })\n        .command(({ state: updatedState }) => {\n          return setBlockType(type, { ...attributesToCopy, ...attributes })(updatedState, dispatch)\n        })\n        .run()\n    )\n  }\n", "import { NodeSelection } from '@tiptap/pm/state'\n\nimport type { RawCommands } from '../types.js'\nimport { minMax } from '../utilities/minMax.js'\n\ndeclare module '@tiptap/core' {\n  interface Commands<ReturnType> {\n    setNodeSelection: {\n      /**\n       * Creates a NodeSelection.\n       * @param position - Position of the node.\n       * @example editor.commands.setNodeSelection(10)\n       */\n      setNodeSelection: (position: number) => ReturnType\n    }\n  }\n}\n\nexport const setNodeSelection: RawCommands['setNodeSelection'] =\n  position =>\n  ({ tr, dispatch }) => {\n    if (dispatch) {\n      const { doc } = tr\n      const from = minMax(position, 0, doc.content.size)\n      const selection = NodeSelection.create(doc, from)\n\n      tr.setSelection(selection)\n    }\n\n    return true\n  }\n", "import type { Range, RawCommands } from '../types.js'\n\ndeclare module '@tiptap/core' {\n  interface Commands<ReturnType> {\n    setTextDirection: {\n      /**\n       * Set the text direction for nodes.\n       * If no position is provided, it will use the current selection.\n       * @param direction The text direction to set ('ltr', 'rtl', or 'auto')\n       * @param position Optional position or range to apply the direction to\n       * @example editor.commands.setTextDirection('rtl')\n       * @example editor.commands.setTextDirection('ltr', { from: 0, to: 10 })\n       */\n      setTextDirection: (direction: 'ltr' | 'rtl' | 'auto', position?: number | Range) => ReturnType\n    }\n  }\n}\n\nexport const setTextDirection: RawCommands['setTextDirection'] =\n  (direction, position) =>\n  ({ tr, state, dispatch }) => {\n    const { selection } = state\n    let from: number\n    let to: number\n\n    if (typeof position === 'number') {\n      from = position\n      to = position\n    } else if (position && 'from' in position && 'to' in position) {\n      from = position.from\n      to = position.to\n    } else {\n      from = selection.from\n      to = selection.to\n    }\n\n    if (dispatch) {\n      tr.doc.nodesBetween(from, to, (node, pos) => {\n        if (node.isText) {\n          return\n        }\n\n        tr.setNodeMarkup(pos, undefined, {\n          ...node.attrs,\n          dir: direction,\n        })\n      })\n    }\n\n    return true\n  }\n", "import { TextSelection } from '@tiptap/pm/state'\n\nimport type { Range, RawCommands } from '../types.js'\nimport { minMax } from '../utilities/minMax.js'\n\ndeclare module '@tiptap/core' {\n  interface Commands<ReturnType> {\n    setTextSelection: {\n      /**\n       * Creates a TextSelection.\n       * @param position The position of the selection.\n       * @example editor.commands.setTextSelection(10)\n       */\n      setTextSelection: (position: number | Range) => ReturnType\n    }\n  }\n}\n\nexport const setTextSelection: RawCommands['setTextSelection'] =\n  position =>\n  ({ tr, dispatch }) => {\n    if (dispatch) {\n      const { doc } = tr\n      const { from, to } =\n        typeof position === 'number' ? { from: position, to: position } : position\n      const minPos = TextSelection.atStart(doc).from\n      const maxPos = TextSelection.atEnd(doc).to\n      const resolvedFrom = minMax(from, minPos, maxPos)\n      const resolvedEnd = minMax(to, minPos, maxPos)\n      const selection = TextSelection.create(doc, resolvedFrom, resolvedEnd)\n\n      tr.setSelection(selection)\n    }\n\n    return true\n  }\n", "import type { NodeType } from '@tiptap/pm/model'\nimport { sinkListItem as originalSinkListItem } from '@tiptap/pm/schema-list'\n\nimport { getNodeType } from '../helpers/getNodeType.js'\nimport type { RawCommands } from '../types.js'\n\ndeclare module '@tiptap/core' {\n  interface Commands<ReturnType> {\n    sinkListItem: {\n      /**\n       * Sink the list item down into an inner list.\n       * @param typeOrName The type or name of the node.\n       * @example editor.commands.sinkListItem('listItem')\n       */\n      sinkListItem: (typeOrName: string | NodeType) => ReturnType\n    }\n  }\n}\n\nexport const sinkListItem: RawCommands['sinkListItem'] =\n  typeOrName =>\n  ({ state, dispatch }) => {\n    const type = getNodeType(typeOrName, state.schema)\n\n    return originalSinkListItem(type)(state, dispatch)\n  }\n", "import { EditorState, NodeSelection, TextSelection } from '@tiptap/pm/state'\nimport { canSplit } from '@tiptap/pm/transform'\n\nimport { defaultBlockAt } from '../helpers/defaultBlockAt.js'\nimport { getSplittedAttributes } from '../helpers/getSplittedAttributes.js'\nimport type { RawCommands } from '../types.js'\n\nfunction ensureMarks(state: EditorState, splittableMarks?: string[]) {\n  const marks =\n    state.storedMarks || (state.selection.$to.parentOffset && state.selection.$from.marks())\n\n  if (marks) {\n    const filteredMarks = marks.filter(mark => splittableMarks?.includes(mark.type.name))\n\n    state.tr.ensureMarks(filteredMarks)\n  }\n}\n\ndeclare module '@tiptap/core' {\n  interface Commands<ReturnType> {\n    splitBlock: {\n      /**\n       * Forks a new node from an existing node.\n       * @param options.keepMarks Keep marks from the previous node.\n       * @example editor.commands.splitBlock()\n       * @example editor.commands.splitBlock({ keepMarks: true })\n       */\n      splitBlock: (options?: { keepMarks?: boolean }) => ReturnType\n    }\n  }\n}\n\nexport const splitBlock: RawCommands['splitBlock'] =\n  ({ keepMarks = true } = {}) =>\n  ({ tr, state, dispatch, editor }) => {\n    const { selection, doc } = tr\n    const { $from, $to } = selection\n    const extensionAttributes = editor.extensionManager.attributes\n    const newAttributes = getSplittedAttributes(\n      extensionAttributes,\n      $from.node().type.name,\n      $from.node().attrs,\n    )\n\n    if (selection instanceof NodeSelection && selection.node.isBlock) {\n      if (!$from.parentOffset || !canSplit(doc, $from.pos)) {\n        return false\n      }\n\n      if (dispatch) {\n        if (keepMarks) {\n          ensureMarks(state, editor.extensionManager.splittableMarks)\n        }\n\n        tr.split($from.pos).scrollIntoView()\n      }\n\n      return true\n    }\n\n    if (!$from.parent.isBlock) {\n      return false\n    }\n\n    const atEnd = $to.parentOffset === $to.parent.content.size\n\n    const deflt =\n      $from.depth === 0\n        ? undefined\n        : defaultBlockAt($from.node(-1).contentMatchAt($from.indexAfter(-1)))\n\n    let types =\n      atEnd && deflt\n        ? [\n            {\n              type: deflt,\n              attrs: newAttributes,\n            },\n          ]\n        : undefined\n\n    // Deleting the selection can restructure the document, so the split has to\n    // be validated against the document as it will look after the deletion.\n    // Simulate the deletion on a scratch transaction instead of mutating `tr`:\n    // the shared transaction is dispatched even when a command returns `false`,\n    // so it must stay untouched until the split is known to be possible.\n    const willDeleteSelection = selection instanceof TextSelection && !selection.empty\n    const deletedTr = willDeleteSelection\n      ? EditorState.create({ doc: tr.doc, selection }).tr.deleteSelection()\n      : null\n    const splitDoc = deletedTr ? deletedTr.doc : tr.doc\n    const splitPos = deletedTr ? deletedTr.mapping.map($from.pos) : $from.pos\n\n    let can = canSplit(splitDoc, splitPos, 1, types)\n\n    if (!types && !can && canSplit(splitDoc, splitPos, 1, deflt ? [{ type: deflt }] : undefined)) {\n      can = true\n      types = deflt\n        ? [\n            {\n              type: deflt,\n              attrs: newAttributes,\n            },\n          ]\n        : undefined\n    }\n\n    if (dispatch) {\n      if (can) {\n        const mapFrom = tr.steps.length\n\n        if (selection instanceof TextSelection) {\n          tr.deleteSelection()\n        }\n\n        tr.split(tr.mapping.slice(mapFrom).map($from.pos), 1, types)\n\n        if (deflt && !atEnd && !$from.parentOffset && $from.parent.type !== deflt) {\n          const first = tr.mapping.slice(mapFrom).map($from.before())\n          const $first = tr.doc.resolve(first)\n\n          if ($from.node(-1).canReplaceWith($first.index(), $first.index() + 1, deflt)) {\n            tr.setNodeMarkup(tr.mapping.slice(mapFrom).map($from.before()), deflt)\n          }\n        }\n      }\n\n      if (keepMarks) {\n        ensureMarks(state, editor.extensionManager.splittableMarks)\n      }\n\n      tr.scrollIntoView()\n    }\n\n    return can\n  }\n", "import type { Node as ProseMirrorNode, NodeType } from '@tiptap/pm/model'\nimport { Fragment, Slice } from '@tiptap/pm/model'\nimport { TextSelection } from '@tiptap/pm/state'\nimport { canSplit } from '@tiptap/pm/transform'\n\nimport { getNodeType } from '../helpers/getNodeType.js'\nimport { getSplittedAttributes } from '../helpers/getSplittedAttributes.js'\nimport type { RawCommands } from '../types.js'\n\ndeclare module '@tiptap/core' {\n  interface Commands<ReturnType> {\n    splitListItem: {\n      /**\n       * Splits one list item into two list items.\n       * @param typeOrName The type or name of the node.\n       * @param overrideAttrs The attributes to ensure on the new node.\n       * @example editor.commands.splitListItem('listItem')\n       */\n      splitListItem: (\n        typeOrName: string | NodeType,\n        overrideAttrs?: Record<string, any>,\n      ) => ReturnType\n    }\n  }\n}\n\nexport const splitListItem: RawCommands['splitListItem'] =\n  (typeOrName, overrideAttrs = {}) =>\n  ({ tr, state, dispatch, editor }) => {\n    const type = getNodeType(typeOrName, state.schema)\n    const { $from, $to } = state.selection\n\n    // @ts-ignore\n    // oxlint-disable-next-line\n    const node: ProseMirrorNode = state.selection.node\n\n    if ((node && node.isBlock) || $from.depth < 2 || !$from.sameParent($to)) {\n      return false\n    }\n\n    const grandParent = $from.node(-1)\n\n    if (grandParent.type !== type) {\n      return false\n    }\n\n    const extensionAttributes = editor.extensionManager.attributes\n\n    if ($from.parent.content.size === 0 && $from.node(-1).childCount === $from.indexAfter(-1)) {\n      // In an empty block. If this is a nested list, the wrapping\n      // list item should be split. Otherwise, bail out and let next\n      // command handle lifting.\n      if (\n        $from.depth === 2 ||\n        $from.node(-3).type !== type ||\n        $from.index(-2) !== $from.node(-2).childCount - 1\n      ) {\n        return false\n      }\n\n      if (dispatch) {\n        let wrap = Fragment.empty\n        // oxlint-disable-next-line\n        const depthBefore = $from.index(-1) ? 1 : $from.index(-2) ? 2 : 3\n\n        // Build a fragment containing empty versions of the structure\n        // from the outer list item to the parent node of the cursor\n        for (let d = $from.depth - depthBefore; d >= $from.depth - 3; d -= 1) {\n          wrap = Fragment.from($from.node(d).copy(wrap))\n        }\n\n        const depthAfter =\n          // oxlint-disable-next-line no-nested-ternary\n          $from.indexAfter(-1) < $from.node(-2).childCount\n            ? 1\n            : $from.indexAfter(-2) < $from.node(-3).childCount\n              ? 2\n              : 3\n\n        // Add a second list item with an empty default start node\n        const newNextTypeAttributes = {\n          ...getSplittedAttributes(extensionAttributes, $from.node().type.name, $from.node().attrs),\n          ...overrideAttrs,\n        }\n        const nextType =\n          type.contentMatch.defaultType?.createAndFill(newNextTypeAttributes) || undefined\n\n        wrap = wrap.append(Fragment.from(type.createAndFill(null, nextType) || undefined))\n\n        const start = $from.before($from.depth - (depthBefore - 1))\n\n        tr.replace(start, $from.after(-depthAfter), new Slice(wrap, 4 - depthBefore, 0))\n\n        let sel = -1\n\n        tr.doc.nodesBetween(start, tr.doc.content.size, (n, pos) => {\n          if (sel > -1) {\n            return false\n          }\n\n          if (n.isTextblock && n.content.size === 0) {\n            sel = pos + 1\n          }\n        })\n\n        if (sel > -1) {\n          tr.setSelection(TextSelection.near(tr.doc.resolve(sel)))\n        }\n\n        tr.scrollIntoView()\n      }\n\n      return true\n    }\n\n    const nextType = $to.pos === $from.end() ? grandParent.contentMatchAt(0).defaultType : null\n\n    const newTypeAttributes = {\n      ...getSplittedAttributes(extensionAttributes, grandParent.type.name, grandParent.attrs),\n      ...overrideAttrs,\n    }\n    const newNextTypeAttributes = {\n      ...getSplittedAttributes(extensionAttributes, $from.node().type.name, $from.node().attrs),\n      ...overrideAttrs,\n    }\n\n    const splitsAtStartOfItem = $from.parentOffset === 0 && $from.index(-1) === 0\n    const itemStart = $from.before(-1)\n\n    tr.delete($from.pos, $to.pos)\n\n    const trailingTypeAttributes = splitsAtStartOfItem ? grandParent.attrs : newTypeAttributes\n\n    const types = nextType\n      ? [\n          { type, attrs: trailingTypeAttributes },\n          { type: nextType, attrs: newNextTypeAttributes },\n        ]\n      : [{ type, attrs: trailingTypeAttributes }]\n\n    if (!canSplit(tr.doc, $from.pos, 2)) {\n      return false\n    }\n\n    if (dispatch) {\n      const { selection, storedMarks } = state\n      const { splittableMarks } = editor.extensionManager\n      const marks = storedMarks || (selection.$to.parentOffset && selection.$from.marks())\n\n      tr.split($from.pos, 2, types).scrollIntoView()\n\n      if (splitsAtStartOfItem) {\n        tr.setNodeMarkup(itemStart, undefined, newTypeAttributes)\n      }\n\n      if (!marks || !dispatch) {\n        return true\n      }\n\n      const filteredMarks = marks.filter(mark => splittableMarks.includes(mark.type.name))\n\n      tr.ensureMarks(filteredMarks)\n    }\n\n    return true\n  }\n", "import type { Attrs, Fragment, Node as ProseMirrorNode, NodeType } from '@tiptap/pm/model'\n\n/** Creates a node when its content and required attributes are valid. */\nexport function createNode(\n  type: NodeType,\n  content: Fragment,\n  attrs?: Attrs | null,\n): ProseMirrorNode | null {\n  if (!type.validContent(content)) {\n    return null\n  }\n\n  try {\n    return type.create(attrs, content)\n  } catch {\n    return null\n  }\n}\n", "import { Fragment } from '@tiptap/pm/model'\nimport type { NodeType } from '@tiptap/pm/model'\n\nimport { createNode } from './createNode.js'\nimport type { ListItemConversionState } from './listConversionTypes.js'\n\n/** Converts and appends the content accumulated for the current list item. */\nexport function flushPendingContent(state: ListItemConversionState, itemType: NodeType): boolean {\n  if (state.pendingContent.length === 0) {\n    return true\n  }\n\n  const item = createNode(itemType, Fragment.from(state.pendingContent))\n\n  if (!item) {\n    return false\n  }\n\n  state.items.push(item)\n  state.pendingContent = []\n\n  return true\n}\n", "import { Fragment } from '@tiptap/pm/model'\nimport type { Node as ProseMirrorNode, NodeType } from '@tiptap/pm/model'\n\nimport { flushPendingContent } from './flushPendingContent.js'\nimport type { ListItemConversionState } from './listConversionTypes.js'\n\n/** Appends a content node to the current item or starts a new item when needed. */\nexport function appendContentNode(\n  node: ProseMirrorNode,\n  state: ListItemConversionState,\n  itemType: NodeType,\n): boolean {\n  if (itemType.validContent(Fragment.from([...state.pendingContent, node]))) {\n    state.pendingContent.push(node)\n    return true\n  }\n\n  if (!flushPendingContent(state, itemType) || !itemType.validContent(Fragment.from(node))) {\n    return false\n  }\n\n  state.pendingContent.push(node)\n\n  return true\n}\n", "import { Fragment } from '@tiptap/pm/model'\nimport type { Node as ProseMirrorNode } from '@tiptap/pm/model'\n\nimport { createNode } from './createNode.js'\nimport { flushPendingContent } from './flushPendingContent.js'\nimport type {\n  ConvertListItems,\n  ListConversionContext,\n  ListItemConversionState,\n} from './listConversionTypes.js'\n\n/** Preserves a nested list when supported or flattens its converted items. */\nexport function appendNestedList(\n  sourceList: ProseMirrorNode,\n  state: ListItemConversionState,\n  context: ListConversionContext,\n  convertListItems: ConvertListItems,\n): boolean {\n  const nestedItems = convertListItems(sourceList, context)\n\n  if (!nestedItems) {\n    return false\n  }\n\n  const nestedList = createNode(context.listType, Fragment.from(nestedItems), sourceList.attrs)\n\n  if (!nestedList) {\n    return false\n  }\n\n  if (context.itemType.validContent(Fragment.from([...state.pendingContent, nestedList]))) {\n    state.pendingContent.push(nestedList)\n    return true\n  }\n\n  if (!flushPendingContent(state, context.itemType)) {\n    return false\n  }\n\n  state.items.push(...nestedItems)\n\n  return true\n}\n", "import type { Node as ProseMirrorNode } from '@tiptap/pm/model'\n\nimport { appendContentNode } from './appendContentNode.js'\nimport { appendNestedList } from './appendNestedList.js'\nimport { flushPendingContent } from './flushPendingContent.js'\nimport type {\n  ConvertListItems,\n  ListConversionContext,\n  ListItemConversionState,\n} from './listConversionTypes.js'\n\n/** Converts one source list item into one or more target list items. */\nexport function convertListItem(\n  sourceItem: ProseMirrorNode,\n  context: ListConversionContext,\n  convertListItems: ConvertListItems,\n): ProseMirrorNode[] | null {\n  const state: ListItemConversionState = { items: [], pendingContent: [] }\n\n  for (let index = 0; index < sourceItem.childCount; index += 1) {\n    const child = sourceItem.child(index)\n    const appended = context.isListNode(child)\n      ? appendNestedList(child, state, context, convertListItems)\n      : appendContentNode(child, state, context.itemType)\n\n    if (!appended) {\n      return null\n    }\n  }\n\n  return flushPendingContent(state, context.itemType) ? state.items : null\n}\n", "import type { Node as ProseMirrorNode } from '@tiptap/pm/model'\n\nimport { convertListItem } from './convertListItem.js'\nimport type { ListConversionContext } from './listConversionTypes.js'\n\n/** Recursively converts all items in a source list to the target list schema. */\nexport function convertListItems(\n  sourceList: ProseMirrorNode,\n  context: ListConversionContext,\n): ProseMirrorNode[] | null {\n  const convertedItems: ProseMirrorNode[] = []\n\n  for (let index = 0; index < sourceList.childCount; index += 1) {\n    const items = convertListItem(sourceList.child(index), context, convertListItems)\n\n    if (!items) {\n      return null\n    }\n\n    convertedItems.push(...items)\n  }\n\n  return convertedItems\n}\n", "import type { Node as ProseMirrorNode } from '@tiptap/pm/model'\n\n/** Finds a descendant node's position relative to its root node. */\nexport function findNodePosition(root: ProseMirrorNode, target: ProseMirrorNode): number | null {\n  let targetPos: number | null = null\n\n  root.descendants((node, pos) => {\n    if (node !== target) {\n      return true\n    }\n\n    targetPos = pos\n\n    return false\n  })\n\n  return targetPos\n}\n", "import { Fragment } from '@tiptap/pm/model'\nimport type { Node as ProseMirrorNode, NodeType } from '@tiptap/pm/model'\nimport type { Transaction } from '@tiptap/pm/state'\nimport { TextSelection } from '@tiptap/pm/state'\nimport { canJoin } from '@tiptap/pm/transform'\n\nimport { findParentNode } from '../helpers/findParentNode.js'\nimport { getNodeType } from '../helpers/getNodeType.js'\nimport { isList } from '../helpers/isList.js'\nimport type { RawCommands } from '../types.js'\nimport { convertListItems } from './utils/convertListItems.js'\nimport { findNodePosition } from './utils/findNodePosition.js'\n\n/**\n * Normalise a list type attribute for comparison.\n * Treats null, undefined, and \"1\" as equivalent (the default numeric type).\n */\nfunction normalizeListType(type: string | null | undefined): string | null {\n  return !type || type === '1' ? null : type\n}\n\n/**\n * Check if two list type attributes are compatible for joining.\n * Lists can only join when they have the same type (both default, or both the same non-default type).\n */\nfunction areListTypesCompatible(\n  typeA: string | null | undefined,\n  typeB: string | null | undefined,\n): boolean {\n  return normalizeListType(typeA) === normalizeListType(typeB)\n}\n\nconst joinListBackwards = (tr: Transaction, listType: NodeType): boolean => {\n  const list = findParentNode(node => node.type === listType)(tr.selection)\n\n  if (!list) {\n    return true\n  }\n\n  const before = tr.doc.resolve(Math.max(0, list.pos - 1)).before(list.depth)\n\n  if (before === undefined) {\n    return true\n  }\n\n  const nodeBefore = tr.doc.nodeAt(before)\n  const canJoinBackwards = list.node.type === nodeBefore?.type && canJoin(tr.doc, list.pos)\n\n  if (!canJoinBackwards) {\n    return true\n  }\n\n  // Don't join if the type attributes are incompatible\n  // (e.g. a default-type list should not merge with a type=\"a\" list)\n  if (!areListTypesCompatible(list.node.attrs.type, nodeBefore?.attrs.type)) {\n    return true\n  }\n\n  tr.join(list.pos)\n\n  return true\n}\n\nconst joinListForwards = (tr: Transaction, listType: NodeType): boolean => {\n  const list = findParentNode(node => node.type === listType)(tr.selection)\n\n  if (!list) {\n    return true\n  }\n\n  const after = tr.doc.resolve(list.start).after(list.depth)\n\n  if (after === undefined) {\n    return true\n  }\n\n  const nodeAfter = tr.doc.nodeAt(after)\n  const canJoinForwards = list.node.type === nodeAfter?.type && canJoin(tr.doc, after)\n\n  if (!canJoinForwards) {\n    return true\n  }\n\n  // Don't join if the type attributes are incompatible\n  if (!areListTypesCompatible(list.node.attrs.type, nodeAfter?.attrs.type)) {\n    return true\n  }\n\n  tr.join(after)\n\n  return true\n}\n\ndeclare module '@tiptap/core' {\n  interface Commands<ReturnType> {\n    toggleList: {\n      /**\n       * Toggle between different list types.\n       * @param listTypeOrName The type or name of the list.\n       * @param itemTypeOrName The type or name of the list item.\n       * @param keepMarks Keep marks when toggling.\n       * @param attributes Attributes for the new list.\n       * @example editor.commands.toggleList('bulletList', 'listItem')\n       */\n      toggleList: (\n        listTypeOrName: string | NodeType,\n        itemTypeOrName: string | NodeType,\n        keepMarks?: boolean,\n        attributes?: Record<string, any>,\n      ) => ReturnType\n    }\n  }\n}\n\nfunction createInnerSelectionForWholeDocList(tr: Transaction) {\n  const doc = tr.doc\n  const list = doc.firstChild\n\n  if (!list) {\n    return null\n  }\n\n  // Move the root AllSelection into the list so liftListItem can operate\n  // while preserving a valid text selection.\n  const $start = doc.resolve(1)\n  const $end = doc.resolve(list.nodeSize - 1)\n\n  return TextSelection.between($start, $end)\n}\n\nexport const toggleList: RawCommands['toggleList'] =\n  (listTypeOrName, itemTypeOrName, keepMarks, attributes = {}) =>\n  ({ editor, tr, state, dispatch, chain, commands, can }) => {\n    const { extensions, splittableMarks } = editor.extensionManager\n    const listType = getNodeType(listTypeOrName, state.schema)\n    const itemType = getNodeType(itemTypeOrName, state.schema)\n    const { selection, storedMarks } = state\n    const { $from, $to } = selection\n    const range = $from.blockRange($to)\n\n    const marks = storedMarks || (selection.$to.parentOffset && selection.$from.marks())\n\n    if (!range) {\n      return false\n    }\n\n    const parentList = findParentNode(node => isList(node.type.name, extensions))(selection)\n\n    // Treat a sole top-level list selected with Ctrl/Cmd+A as the active list,\n    // since findParentNode cannot detect it from the document root.\n    const isAllSelection = selection.from === 0 && selection.to === state.doc.content.size\n    const topLevelNodes = state.doc.content.content\n    const soleTopLevelNode = topLevelNodes.length === 1 ? topLevelNodes[0] : null\n    const allSelectionList =\n      isAllSelection && soleTopLevelNode && isList(soleTopLevelNode.type.name, extensions)\n        ? {\n            node: soleTopLevelNode,\n            pos: 0,\n            depth: 0,\n          }\n        : null\n\n    const currentList = parentList ?? allSelectionList\n\n    const isInsideExistingList =\n      !!parentList && range.depth >= 1 && range.depth - parentList.depth <= 1\n\n    const hasWholeDocSelectedList = !!allSelectionList\n    if ((isInsideExistingList || hasWholeDocSelectedList) && currentList) {\n      // remove list\n      if (currentList.node.type === listType) {\n        if (isAllSelection && hasWholeDocSelectedList) {\n          return chain()\n            .command(({ tr: trx, dispatch: disp }) => {\n              // Move the root AllSelection into the list before lifting it.\n              const nextSelection = createInnerSelectionForWholeDocList(trx)\n\n              if (!nextSelection) {\n                return false\n              }\n\n              trx.setSelection(nextSelection)\n\n              if (disp) {\n                disp(trx)\n              }\n\n              return true\n            })\n            .liftListItem(itemType)\n            .run()\n        }\n\n        return commands.liftListItem(itemType)\n      }\n\n      // change list type: same item type (e.g., bulletList to orderedList)\n      if (\n        isList(currentList.node.type.name, extensions) &&\n        listType.validContent(currentList.node.content)\n      ) {\n        return chain()\n          .command(() => {\n            tr.setNodeMarkup(currentList.pos, listType)\n\n            return true\n          })\n          .command(() => joinListBackwards(tr, listType))\n          .command(() => joinListForwards(tr, listType))\n          .run()\n      }\n\n      // change list type: cross-item-type conversion\n      // Handles cases like bulletList(listItem) to taskList(taskItem)\n      // where the list item type differs between source and target lists.\n      if (isList(currentList.node.type.name, extensions)) {\n        const currentItemType = currentList.node.firstChild?.type\n\n        if (currentItemType && currentItemType !== itemType) {\n          const convertedItems = convertListItems(currentList.node, {\n            listType,\n            itemType,\n            isListNode: node => isList(node.type.name, extensions),\n          })\n\n          const convertedContent = convertedItems ? Fragment.from(convertedItems) : null\n\n          if (!convertedContent || !listType.validContent(convertedContent)) {\n            return false\n          }\n\n          return chain()\n            .command(() => {\n              const { $anchor, $head } = tr.selection\n              const anchorParent = $anchor.parent\n              const headParent = $head.parent\n              const anchorOffset = $anchor.parentOffset\n              const headOffset = $head.parentOffset\n              let newList: ProseMirrorNode\n\n              try {\n                newList = listType.create(attributes, convertedContent)\n              } catch {\n                return false\n              }\n\n              tr.replaceWith(currentList.pos, currentList.pos + currentList.node.nodeSize, newList)\n\n              if (anchorParent.inlineContent && headParent.inlineContent) {\n                const anchorParentPos = findNodePosition(newList, anchorParent)\n                const headParentPos = findNodePosition(newList, headParent)\n\n                if (anchorParentPos !== null && headParentPos !== null) {\n                  const anchor = currentList.pos + anchorParentPos + 2 + anchorOffset\n                  const head = currentList.pos + headParentPos + 2 + headOffset\n\n                  tr.setSelection(TextSelection.create(tr.doc, anchor, head))\n                }\n              }\n\n              return true\n            })\n            .command(() => joinListBackwards(tr, listType))\n            .command(() => joinListForwards(tr, listType))\n            .run()\n        }\n      }\n    }\n\n    if (!keepMarks || !marks || !dispatch) {\n      return (\n        chain()\n          // try to convert node to default node if needed\n          .command(() => {\n            const canWrapInList = can().wrapInList(listType, attributes)\n            if (canWrapInList) {\n              return true\n            }\n            return commands.clearNodes()\n          })\n          .wrapInList(listType, attributes)\n          .command(() => joinListBackwards(tr, listType))\n          .command(() => joinListForwards(tr, listType))\n          .run()\n      )\n    }\n\n    return (\n      chain()\n        // try to convert node to default node if needed\n        .command(() => {\n          const canWrapInList = can().wrapInList(listType, attributes)\n\n          const filteredMarks = marks.filter(mark => splittableMarks.includes(mark.type.name))\n\n          tr.ensureMarks(filteredMarks)\n\n          if (canWrapInList) {\n            return true\n          }\n          return commands.clearNodes()\n        })\n        .wrapInList(listType, attributes)\n        .command(() => joinListBackwards(tr, listType))\n        .command(() => joinListForwards(tr, listType))\n        .run()\n    )\n  }\n", "import type { MarkType } from '@tiptap/pm/model'\n\nimport { getMarkType } from '../helpers/getMarkType.js'\nimport { isMarkActive } from '../helpers/isMarkActive.js'\nimport type { RawCommands } from '../types.js'\n\ndeclare module '@tiptap/core' {\n  interface Commands<ReturnType> {\n    toggleMark: {\n      /**\n       * Toggle a mark on and off.\n       * @param typeOrName The mark type or name.\n       * @param attributes The attributes of the mark.\n       * @param options.extendEmptyMarkRange Removes the mark even across the current selection. Defaults to `false`.\n       * @example editor.commands.toggleMark('bold')\n       */\n      toggleMark: (\n        /**\n         * The mark type or name.\n         */\n        typeOrName: string | MarkType,\n\n        /**\n         * The attributes of the mark.\n         */\n        attributes?: Record<string, any>,\n\n        options?: {\n          /**\n           * Removes the mark even across the current selection. Defaults to `false`.\n           */\n          extendEmptyMarkRange?: boolean\n        },\n      ) => ReturnType\n    }\n  }\n}\n\nexport const toggleMark: RawCommands['toggleMark'] =\n  (typeOrName, attributes = {}, options = {}) =>\n  ({ state, commands }) => {\n    const { extendEmptyMarkRange = false } = options\n    const type = getMarkType(typeOrName, state.schema)\n    const isActive = isMarkActive(state, type, attributes)\n\n    if (isActive) {\n      return commands.unsetMark(type, { extendEmptyMarkRange })\n    }\n\n    return commands.setMark(type, attributes)\n  }\n", "import type { NodeType } from '@tiptap/pm/model'\n\nimport { getNodeType } from '../helpers/getNodeType.js'\nimport { isNodeActive } from '../helpers/isNodeActive.js'\nimport type { RawCommands } from '../types.js'\n\ndeclare module '@tiptap/core' {\n  interface Commands<ReturnType> {\n    toggleNode: {\n      /**\n       * Toggle a node with another node.\n       * @param typeOrName The type or name of the node.\n       * @param toggleTypeOrName The type or name of the node to toggle.\n       * @param attributes The attributes of the node.\n       * @example editor.commands.toggleNode('heading', 'paragraph')\n       */\n      toggleNode: (\n        typeOrName: string | NodeType,\n        toggleTypeOrName: string | NodeType,\n        attributes?: Record<string, any>,\n      ) => ReturnType\n    }\n  }\n}\n\nexport const toggleNode: RawCommands['toggleNode'] =\n  (typeOrName, toggleTypeOrName, attributes = {}) =>\n  ({ state, commands }) => {\n    const type = getNodeType(typeOrName, state.schema)\n    const toggleType = getNodeType(toggleTypeOrName, state.schema)\n    const isActive = isNodeActive(state, type, attributes)\n\n    let attributesToCopy: Record<string, any> | undefined\n\n    if (state.selection.$anchor.sameParent(state.selection.$head)) {\n      // only copy attributes if the selection is pointing to a node of the same type\n      attributesToCopy = state.selection.$anchor.parent.attrs\n    }\n\n    if (isActive) {\n      return commands.setNode(toggleType, attributesToCopy)\n    }\n\n    // If the node is not active, we want to set the new node type with the given attributes\n    // Copying over the attributes from the current node if the selection is pointing to a node of the same type\n    return commands.setNode(type, { ...attributesToCopy, ...attributes })\n  }\n", "import type { NodeType } from '@tiptap/pm/model'\n\nimport { getNodeType } from '../helpers/getNodeType.js'\nimport { isNodeActive } from '../helpers/isNodeActive.js'\nimport type { RawCommands } from '../types.js'\n\ndeclare module '@tiptap/core' {\n  interface Commands<ReturnType> {\n    toggleWrap: {\n      /**\n       * Wraps nodes in another node, or removes an existing wrap.\n       * @param typeOrName The type or name of the node.\n       * @param attributes The attributes of the node.\n       * @example editor.commands.toggleWrap('blockquote')\n       */\n      toggleWrap: (typeOrName: string | NodeType, attributes?: Record<string, any>) => ReturnType\n    }\n  }\n}\n\nexport const toggleWrap: RawCommands['toggleWrap'] =\n  (typeOrName, attributes = {}) =>\n  ({ state, commands }) => {\n    const type = getNodeType(typeOrName, state.schema)\n    const isActive = isNodeActive(state, type, attributes)\n\n    if (isActive) {\n      return commands.lift(type)\n    }\n\n    return commands.wrapIn(type, attributes)\n  }\n", "import type { RawCommands } from '../types.js'\n\ndeclare module '@tiptap/core' {\n  interface Commands<ReturnType> {\n    undoInputRule: {\n      /**\n       * Undo an input rule.\n       * @example editor.commands.undoInputRule()\n       */\n      undoInputRule: () => ReturnType\n    }\n  }\n}\n\nexport const undoInputRule: RawCommands['undoInputRule'] =\n  () =>\n  ({ state, dispatch }) => {\n    const plugins = state.plugins\n\n    for (let i = 0; i < plugins.length; i += 1) {\n      const plugin = plugins[i]\n      let undoable\n\n      // @ts-ignore\n      // oxlint-disable-next-line\n      if (plugin.spec.isInputRules && (undoable = plugin.getState(state))) {\n        if (dispatch) {\n          const tr = state.tr\n          const toUndo = undoable.transform\n\n          for (let j = toUndo.steps.length - 1; j >= 0; j -= 1) {\n            tr.step(toUndo.steps[j].invert(toUndo.docs[j]))\n          }\n\n          if (undoable.text) {\n            const marks = tr.doc.resolve(undoable.from).marks()\n\n            tr.replaceWith(undoable.from, undoable.to, state.schema.text(undoable.text, marks))\n          } else {\n            tr.delete(undoable.from, undoable.to)\n          }\n        }\n\n        return true\n      }\n    }\n\n    return false\n  }\n", "import type { RawCommands } from '../types.js'\n\ndeclare module '@tiptap/core' {\n  interface Commands<ReturnType> {\n    unsetAllMarks: {\n      /**\n       * Remove all clearable marks in the current selection.\n       * Marks with `clearable: false` are preserved\n       * @param options.ignoreClearable If true, removes all marks regardless of `clearable` setting. Defaults to `false`.\n       * @example editor.commands.unsetAllMarks()\n       * @example editor.commands.unsetAllMarks({ ignoreClearable: true })\n       */\n      unsetAllMarks: (options?: { ignoreClearable?: boolean }) => ReturnType\n    }\n  }\n}\n\nexport const unsetAllMarks: RawCommands['unsetAllMarks'] =\n  (options = {}) =>\n  ({ tr, dispatch, editor }) => {\n    const { ignoreClearable = false } = options\n    const { selection } = tr\n    const { empty, ranges } = selection\n\n    if (empty) {\n      return true\n    }\n\n    const { nonClearableMarks } = editor.extensionManager\n\n    if (dispatch) {\n      const clearableMarkTypes = Object.values(editor.schema.marks).filter(\n        markType => ignoreClearable || !nonClearableMarks.includes(markType.name),\n      )\n\n      ranges.forEach(range => {\n        for (const markType of clearableMarkTypes) {\n          tr.removeMark(range.$from.pos, range.$to.pos, markType)\n        }\n      })\n    }\n\n    return true\n  }\n", "import type { MarkType } from '@tiptap/pm/model'\n\nimport { getMarkRange } from '../helpers/getMarkRange.js'\nimport { getMarkType } from '../helpers/getMarkType.js'\nimport type { RawCommands } from '../types.js'\n\ndeclare module '@tiptap/core' {\n  interface Commands<ReturnType> {\n    unsetMark: {\n      /**\n       * Remove all marks in the current selection.\n       * @param typeOrName The mark type or name.\n       * @param options.extendEmptyMarkRange Removes the mark even across the current selection. Defaults to `false`.\n       * @example editor.commands.unsetMark('bold')\n       */\n      unsetMark: (\n        /**\n         * The mark type or name.\n         */\n        typeOrName: string | MarkType,\n\n        options?: {\n          /**\n           * Removes the mark even across the current selection. Defaults to `false`.\n           */\n          extendEmptyMarkRange?: boolean\n        },\n      ) => ReturnType\n    }\n  }\n}\n\nexport const unsetMark: RawCommands['unsetMark'] =\n  (typeOrName, options = {}) =>\n  ({ tr, state, dispatch }) => {\n    const { extendEmptyMarkRange = false } = options\n    const { selection } = tr\n    const type = getMarkType(typeOrName, state.schema)\n    const { $from, empty, ranges } = selection\n\n    if (!dispatch) {\n      return true\n    }\n\n    if (empty && extendEmptyMarkRange) {\n      let { from, to } = selection\n      const attrs = $from.marks().find(mark => mark.type === type)?.attrs\n      const range = getMarkRange($from, type, attrs)\n\n      if (range) {\n        from = range.from\n        to = range.to\n      }\n\n      tr.removeMark(from, to, type)\n    } else {\n      ranges.forEach(range => {\n        tr.removeMark(range.$from.pos, range.$to.pos, type)\n      })\n    }\n\n    tr.removeStoredMark(type)\n\n    return true\n  }\n", "import type { Range, RawCommands } from '../types.js'\n\ndeclare module '@tiptap/core' {\n  interface Commands<ReturnType> {\n    unsetTextDirection: {\n      /**\n       * Remove the text direction attribute from nodes.\n       * If no position is provided, it will use the current selection.\n       * @param position Optional position or range to remove the direction from\n       * @example editor.commands.unsetTextDirection()\n       * @example editor.commands.unsetTextDirection({ from: 0, to: 10 })\n       */\n      unsetTextDirection: (position?: number | Range) => ReturnType\n    }\n  }\n}\n\nexport const unsetTextDirection: RawCommands['unsetTextDirection'] =\n  position =>\n  ({ tr, state, dispatch }) => {\n    const { selection } = state\n    let from: number\n    let to: number\n\n    if (typeof position === 'number') {\n      from = position\n      to = position\n    } else if (position && 'from' in position && 'to' in position) {\n      from = position.from\n      to = position.to\n    } else {\n      from = selection.from\n      to = selection.to\n    }\n\n    if (dispatch) {\n      tr.doc.nodesBetween(from, to, (node, pos) => {\n        if (node.isText) {\n          return\n        }\n\n        const newAttrs = { ...node.attrs }\n\n        delete newAttrs.dir\n\n        tr.setNodeMarkup(pos, undefined, newAttrs)\n      })\n    }\n\n    return true\n  }\n", "import type { Mark, MarkType, Node, NodeType } from '@tiptap/pm/model'\nimport type { SelectionRange } from '@tiptap/pm/state'\n\nimport { getMarkType } from '../helpers/getMarkType.js'\nimport { getNodeType } from '../helpers/getNodeType.js'\nimport { getSchemaTypeNameByName } from '../helpers/getSchemaTypeNameByName.js'\nimport type { RawCommands } from '../types.js'\n\ndeclare module '@tiptap/core' {\n  interface Commands<ReturnType> {\n    updateAttributes: {\n      /**\n       * Update attributes of a node or mark.\n       * @param typeOrName The type or name of the node or mark.\n       * @param attributes The attributes of the node or mark.\n       * @example editor.commands.updateAttributes('mention', { userId: \"2\" })\n       */\n      updateAttributes: (\n        /**\n         * The type or name of the node or mark.\n         */\n        typeOrName: string | NodeType | MarkType,\n\n        /**\n         * The attributes of the node or mark.\n         */\n        attributes: Record<string, any>,\n      ) => ReturnType\n    }\n  }\n}\n\nexport const updateAttributes: RawCommands['updateAttributes'] =\n  (typeOrName, attributes = {}) =>\n  ({ tr, state, dispatch }) => {\n    let nodeType: NodeType | null = null\n    let markType: MarkType | null = null\n\n    const schemaType = getSchemaTypeNameByName(\n      typeof typeOrName === 'string' ? typeOrName : typeOrName.name,\n      state.schema,\n    )\n\n    if (!schemaType) {\n      return false\n    }\n\n    if (schemaType === 'node') {\n      nodeType = getNodeType(typeOrName as NodeType, state.schema)\n    }\n\n    if (schemaType === 'mark') {\n      markType = getMarkType(typeOrName as MarkType, state.schema)\n    }\n\n    let canUpdate = false\n\n    tr.selection.ranges.forEach((range: SelectionRange) => {\n      const from = range.$from.pos\n      const to = range.$to.pos\n\n      let lastPos: number | undefined\n      let lastNode: Node | undefined\n      let trimmedFrom: number\n      let trimmedTo: number\n\n      if (tr.selection.empty) {\n        state.doc.nodesBetween(from, to, (node: Node, pos: number) => {\n          if (nodeType && nodeType === node.type) {\n            canUpdate = true\n            trimmedFrom = Math.max(pos, from)\n            trimmedTo = Math.min(pos + node.nodeSize, to)\n            lastPos = pos\n            lastNode = node\n          }\n        })\n      } else {\n        state.doc.nodesBetween(from, to, (node: Node, pos: number) => {\n          if (pos < from && nodeType && nodeType === node.type) {\n            canUpdate = true\n            trimmedFrom = Math.max(pos, from)\n            trimmedTo = Math.min(pos + node.nodeSize, to)\n            lastPos = pos\n            lastNode = node\n          }\n\n          if (pos >= from && pos <= to) {\n            if (nodeType && nodeType === node.type) {\n              canUpdate = true\n\n              if (dispatch) {\n                tr.setNodeMarkup(pos, undefined, {\n                  ...node.attrs,\n                  ...attributes,\n                })\n              }\n            }\n\n            if (markType && node.marks.length) {\n              node.marks.forEach((mark: Mark) => {\n                if (markType === mark.type) {\n                  canUpdate = true\n\n                  if (dispatch) {\n                    const trimmedFrom2 = Math.max(pos, from)\n                    const trimmedTo2 = Math.min(pos + node.nodeSize, to)\n\n                    tr.addMark(\n                      trimmedFrom2,\n                      trimmedTo2,\n                      markType.create({\n                        ...mark.attrs,\n                        ...attributes,\n                      }),\n                    )\n                  }\n                }\n              })\n            }\n          }\n        })\n      }\n\n      if (lastNode) {\n        if (lastPos !== undefined && dispatch) {\n          tr.setNodeMarkup(lastPos, undefined, {\n            ...lastNode.attrs,\n            ...attributes,\n          })\n        }\n\n        if (markType && lastNode.marks.length) {\n          lastNode.marks.forEach((mark: Mark) => {\n            if (markType === mark.type && dispatch) {\n              tr.addMark(\n                trimmedFrom,\n                trimmedTo,\n                markType.create({\n                  ...mark.attrs,\n                  ...attributes,\n                }),\n              )\n            }\n          })\n        }\n      }\n    })\n\n    return canUpdate\n  }\n", "import { PluginKey } from '@tiptap/pm/state'\nimport { DecorationManagerState } from './types.js'\n\nexport const DECORATION_MANAGER_PLUGIN_KEY_NAME = '__tiptap_decorations__'\nexport const DECORATION_MANAGER_PLUGIN_KEY = new PluginKey<DecorationManagerState>(\n  DECORATION_MANAGER_PLUGIN_KEY_NAME,\n)\n", "import { DECORATION_MANAGER_PLUGIN_KEY } from '../decorations/constants.js'\nimport type { RawCommands } from '../types.js'\n\ndeclare module '@tiptap/core' {\n  interface Commands<ReturnType> {\n    updateDecorations: {\n      /**\n       * Force declarative decorations to recompute, bypassing each extension's\n       * `shouldUpdate` gate. Pass an extension name to recompute only that\n       * extension's decorations, or omit it to recompute all of them.\n       * @param extensionName The name of the extension to recompute (optional).\n       * @example editor.commands.updateDecorations()\n       * @example editor.commands.updateDecorations('myExtension')\n       */\n      updateDecorations: (extensionName?: string) => ReturnType\n    }\n  }\n}\n\nexport const updateDecorations: RawCommands['updateDecorations'] =\n  extensionName =>\n  ({ tr, dispatch }) => {\n    if (dispatch) {\n      tr.setMeta(DECORATION_MANAGER_PLUGIN_KEY, { type: 'force', name: extensionName })\n    }\n\n    return true\n  }\n", "import { wrapIn as originalWrapIn } from '@tiptap/pm/commands'\nimport type { NodeType } from '@tiptap/pm/model'\n\nimport { getNodeType } from '../helpers/getNodeType.js'\nimport type { RawCommands } from '../types.js'\n\ndeclare module '@tiptap/core' {\n  interface Commands<ReturnType> {\n    wrapIn: {\n      /**\n       * Wraps nodes in another node.\n       * @param typeOrName The type or name of the node.\n       * @param attributes The attributes of the node.\n       * @example editor.commands.wrapIn('blockquote')\n       */\n      wrapIn: (typeOrName: string | NodeType, attributes?: Record<string, any>) => ReturnType\n    }\n  }\n}\n\nexport const wrapIn: RawCommands['wrapIn'] =\n  (typeOrName, attributes = {}) =>\n  ({ state, dispatch }) => {\n    const type = getNodeType(typeOrName, state.schema)\n\n    return originalWrapIn(type, attributes)(state, dispatch)\n  }\n", "import type { NodeType } from '@tiptap/pm/model'\nimport { wrapInList as originalWrapInList } from '@tiptap/pm/schema-list'\n\nimport { getNodeType } from '../helpers/getNodeType.js'\nimport type { RawCommands } from '../types.js'\n\ndeclare module '@tiptap/core' {\n  interface Commands<ReturnType> {\n    wrapInList: {\n      /**\n       * Wrap a node in a list.\n       * @param typeOrName The type or name of the node.\n       * @param attributes The attributes of the node.\n       * @example editor.commands.wrapInList('bulletList')\n       */\n      wrapInList: (typeOrName: string | NodeType, attributes?: Record<string, any>) => ReturnType\n    }\n  }\n}\n\nexport const wrapInList: RawCommands['wrapInList'] =\n  (typeOrName, attributes = {}) =>\n  ({ state, dispatch }) => {\n    const type = getNodeType(typeOrName, state.schema)\n\n    return originalWrapInList(type, attributes)(state, dispatch)\n  }\n", "export * from './blur.js'\nexport * from './clearContent.js'\nexport * from './clearNodes.js'\nexport * from './command.js'\nexport * from './createParagraphNear.js'\nexport * from './cut.js'\nexport * from './deleteCurrentNode.js'\nexport * from './deleteNode.js'\nexport * from './deleteRange.js'\nexport * from './deleteSelection.js'\nexport * from './enter.js'\nexport * from './exitCode.js'\nexport * from './extendMarkRange.js'\nexport * from './first.js'\nexport * from './focus.js'\nexport * from './forEach.js'\nexport * from './insertContent.js'\nexport * from './insertContentAt.js'\nexport * from './insertDefaultBlock.js'\nexport * from './join.js'\nexport * from './joinItemBackward.js'\nexport * from './joinItemForward.js'\nexport * from './joinTextblockBackward.js'\nexport * from './joinTextblockForward.js'\nexport * from './keyboardShortcut.js'\nexport * from './lift.js'\nexport * from './liftEmptyBlock.js'\nexport * from './liftListItem.js'\nexport * from './newlineInCode.js'\nexport * from './resetAttributes.js'\nexport * from './scrollIntoView.js'\nexport * from './selectAll.js'\nexport * from './selectNodeBackward.js'\nexport * from './selectNodeForward.js'\nexport * from './selectParentNode.js'\nexport * from './selectTextblockEnd.js'\nexport * from './selectTextblockStart.js'\nexport * from './setContent.js'\nexport * from './setMark.js'\nexport * from './setMeta.js'\nexport * from './setNode.js'\nexport * from './setNodeSelection.js'\nexport * from './setTextDirection.js'\nexport * from './setTextSelection.js'\nexport * from './sinkListItem.js'\nexport * from './splitBlock.js'\nexport * from './splitListItem.js'\nexport * from './toggleList.js'\nexport * from './toggleMark.js'\nexport * from './toggleNode.js'\nexport * from './toggleWrap.js'\nexport * from './undoInputRule.js'\nexport * from './unsetAllMarks.js'\nexport * from './unsetMark.js'\nexport * from './unsetTextDirection.js'\nexport * from './updateAttributes.js'\nexport * from './updateDecorations.js'\nexport * from './wrapIn.js'\nexport * from './wrapInList.js'\n", "/**\n * Tracks which editors are running decoration create() callbacks inside state.apply,\n * using a private WeakMap to keep this off the public Editor surface.\n */\nconst depthByEditor = new WeakMap<object, number>()\n\n/**\n * Marks callback as decoration-apply work for editor, so editor.state can warn\n * about stale reads. Counts depth to handle nested applies.\n *\n * @param editor The editor the decorations belong to\n * @param callback The work to run inside the scope\n * @returns Whatever `callback` returns\n * @example\n * runInDecorationApplyScope(editor, () => spec.create({ editor, state, view }))\n */\nexport function runInDecorationApplyScope<T>(editor: object, callback: () => T): T {\n  depthByEditor.set(editor, (depthByEditor.get(editor) ?? 0) + 1)\n\n  try {\n    return callback()\n  } finally {\n    const remaining = (depthByEditor.get(editor) ?? 1) - 1\n\n    if (remaining > 0) {\n      depthByEditor.set(editor, remaining)\n    } else {\n      depthByEditor.delete(editor)\n    }\n  }\n}\n\n/**\n * Whether the editor is currently inside a decoration apply scope.\n *\n * @param editor The editor to check\n * @returns `true` while decoration create() callbacks run\n * @example\n * if (isInDecorationApplyScope(editor)) {\n *   // reads of editor.state are stale here\n * }\n */\nexport function isInDecorationApplyScope(editor: object): boolean {\n  return depthByEditor.has(editor)\n}\n", "type StringKeyOf<T> = Extract<keyof T, string>\ntype CallbackType<\n  T extends Record<string, any>,\n  EventName extends StringKeyOf<T>,\n> = T[EventName] extends any[] ? T[EventName] : [T[EventName]]\ntype CallbackFunction<T extends Record<string, any>, EventName extends StringKeyOf<T>> = (\n  ...props: CallbackType<T, EventName>\n) => any\n\nexport class EventEmitter<T extends Record<string, any>> {\n  private callbacks: { [key: string]: Array<(...args: any[]) => void> } = {}\n\n  public on<EventName extends StringKeyOf<T>>(\n    event: EventName,\n    fn: CallbackFunction<T, EventName>,\n  ): this {\n    if (!this.callbacks[event]) {\n      this.callbacks[event] = []\n    }\n\n    this.callbacks[event].push(fn)\n\n    return this\n  }\n\n  public emit<EventName extends StringKeyOf<T>>(\n    event: EventName,\n    ...args: CallbackType<T, EventName>\n  ): this {\n    const callbacks = this.callbacks[event]\n\n    if (callbacks) {\n      callbacks.forEach(callback => callback.apply(this, args))\n    }\n\n    return this\n  }\n\n  public off<EventName extends StringKeyOf<T>>(\n    event: EventName,\n    fn?: CallbackFunction<T, EventName>,\n  ): this {\n    const callbacks = this.callbacks[event]\n\n    if (callbacks) {\n      if (fn) {\n        this.callbacks[event] = callbacks.filter(callback => callback !== fn)\n      } else {\n        delete this.callbacks[event]\n      }\n    }\n\n    return this\n  }\n\n  public once<EventName extends StringKeyOf<T>>(\n    event: EventName,\n    fn: CallbackFunction<T, EventName>,\n  ): this {\n    const onceFn = (...args: CallbackType<T, EventName>) => {\n      this.off(event, onceFn)\n      fn.apply(this, args)\n    }\n\n    return this.on(event, onceFn)\n  }\n\n  public removeAllListeners(): void {\n    this.callbacks = {}\n  }\n}\n", "// Core has no node types and can run unbundled in the browser, where `process`\n// is missing. The `typeof` check keeps that case from throwing, and the inline\n// `process.env.NODE_ENV` lets bundlers fold this to `false` and strip dev-only\n// warnings from production builds.\ndeclare const process: { env: { NODE_ENV?: string } } | undefined\n\n/**\n * Whether the editor runs in a development build. Use it to guard warnings so\n * bundlers can drop them from production output.\n */\nexport const isDev: boolean =\n  typeof process !== 'undefined' && process.env.NODE_ENV !== 'production'\n", "import { Decoration as PMDecoration } from '@tiptap/pm/view'\n\nimport type { Decoration, WidgetDecoration } from '../Decoration.js'\n\nfunction isWidgetDecoration(decoration: Decoration): decoration is WidgetDecoration {\n  return decoration.kind === 'widget'\n}\n\n/**\n * Converts a list of decorations to ProseMirror decorations.\n * @param decorations The decorations to convert.\n * @param extensionName The name of the extension that created the decorations.\n * @returns The converted decorations and the widget keys.\n */\nexport function decorationsToPMDecorations(\n  decorations: Decoration[],\n  extensionName?: string,\n): {\n  decorations: PMDecoration[]\n  widgetKeys: Set<string>\n} {\n  const pmDecorations: PMDecoration[] = []\n  const widgetKeys = new Set<string>()\n\n  for (const decoration of decorations) {\n    if (decoration.kind === 'widget') {\n      if (isWidgetDecoration(decoration)) {\n        widgetKeys.add(decoration.key)\n      }\n    }\n\n    pmDecorations.push(decoration.toPMDecoration(extensionName))\n  }\n\n  return { decorations: pmDecorations, widgetKeys }\n}\n", "import type { Node } from '@tiptap/pm/model'\nimport { DecorationSet } from '@tiptap/pm/view'\n\nimport type { Decoration } from '../Decoration.js'\nimport { decorationsToPMDecorations } from './decorationsToPMDecorations.js'\n\n/**\n * Builds a DecorationSet from a list of decorations.\n * @param doc The document to build the decoration set for.\n * @param decorations The decorations to build the set from.\n * @param extensionName The name of the extension that created the decorations.\n * @returns The built decoration set and the widget keys.\n */\nexport function buildDecorationSet(\n  doc: Node,\n  decorations: Decoration[],\n  extensionName?: string,\n): { set: DecorationSet; widgetKeys: Set<string> } {\n  const { decorations: pmDecorations, widgetKeys } = decorationsToPMDecorations(\n    decorations,\n    extensionName,\n  )\n\n  return { set: DecorationSet.create(doc, pmDecorations), widgetKeys }\n}\n", "export interface RangeOwnsPositionOptions {\n  position: number\n  from: number\n  to: number\n  /** `doc.content.size` of the document the range was computed against. */\n  docSize: number\n}\n\n/**\n * Whether the block range `[from, to)` owns a decoration at `position`.\n *\n * `to` is the next block's start, so that block owns it. The last block is the\n * exception: nothing follows it, so it owns the end of the document.\n *\n * @param options The position, the range, and the document size.\n * @returns True when the range owns the position.\n * @example\n * // <p>foo</p><p>bar</p>, blocks [0, 5] and [5, 10]\n * rangeOwnsPosition({ position: 5, from: 0, to: 5, docSize: 10 }) // false, block 2 owns it\n * rangeOwnsPosition({ position: 5, from: 5, to: 10, docSize: 10 }) // true\n * rangeOwnsPosition({ position: 10, from: 5, to: 10, docSize: 10 }) // true, end of document\n */\nexport function rangeOwnsPosition({\n  position,\n  from,\n  to,\n  docSize,\n}: RangeOwnsPositionOptions): boolean {\n  if (position < from) {\n    return false\n  }\n\n  if (position < to) {\n    return true\n  }\n\n  return position === to && to === docSize\n}\n", "import type { Decoration } from '../Decoration.js'\nimport { rangeOwnsPosition } from './rangeOwnsPosition.js'\n\nexport interface FilterOutOfRangeDecorationsOptions {\n  decorations: Decoration[]\n  from: number\n  to: number\n  /** `doc.content.size` of the document the range was computed against. */\n  docSize: number\n  /** The extension that created the decorations, used in the warning. */\n  extensionName: string\n  /** Extensions already warned about, so a buggy one warns once per editor. */\n  warnedExtensions: Set<string>\n}\n\n/**\n * Filter decorations the block range `[from, to)` does not own.\n * Must match the stale sweep in `DecorationManager.rebuildRanges`.\n *\n * @param options The decorations, the range, and the warning bookkeeping.\n * @returns The filtered decorations.\n */\nexport function filterOutOfRangeDecorations({\n  decorations,\n  from,\n  to,\n  docSize,\n  extensionName,\n  warnedExtensions,\n}: FilterOutOfRangeDecorationsOptions): Decoration[] {\n  return decorations.filter(decoration => {\n    if (rangeOwnsPosition({ position: decoration.anchor, from, to, docSize })) {\n      return true\n    }\n\n    // The next block owns `to` and rebuilds it there, so this is a normal\n    // overlap from scanning the boundary, not an authoring mistake.\n    if (decoration.anchor === to) {\n      return false\n    }\n\n    if (!warnedExtensions.has(extensionName)) {\n      warnedExtensions.add(extensionName)\n      console.warn(\n        `[tiptap warn]: Extension \"${extensionName}\" returned a decoration outside the ` +\n          `requested range [${from}, ${to}). It was ignored.`,\n      )\n    }\n\n    return false\n  })\n}\n", "import type { Decoration } from '@tiptap/pm/view'\n\n/**\n * Extracts the widget key from a decoration spec.\n * @param decoration The decoration to extract the key from.\n * @returns The widget key, or undefined if the decoration has no key.\n */\nexport function widgetKeyOf(decoration: Decoration): string | undefined {\n  const key = (decoration.spec as { key?: unknown } | undefined)?.key\n  return typeof key === 'string' ? key : undefined\n}\n", "import type { DecorationSet } from '@tiptap/pm/view'\n\nimport { widgetKeyOf } from './widgetKeyOf.js'\n\nexport interface DuplicateWidgetKey {\n  key: string\n  extensions: Set<string>\n}\n\n/**\n * Finds widget keys which are still duplicated in the final decoration set.\n * @param decorationSet The merged decoration set to inspect.\n * @returns The duplicate keys and their producing extensions.\n */\nexport function findDuplicateWidgetKeys(decorationSet: DecorationSet): DuplicateWidgetKey[] {\n  const extensionsByKey = new Map<string, Set<string>>()\n  const counts = new Map<string, number>()\n\n  for (const decoration of decorationSet.find()) {\n    const key = widgetKeyOf(decoration)\n\n    if (!key) {\n      continue\n    }\n\n    const extension = (decoration.spec as { extensionName?: string }).extensionName ?? 'unknown'\n    const extensions = extensionsByKey.get(key) ?? new Set<string>()\n\n    extensions.add(extension)\n    extensionsByKey.set(key, extensions)\n    counts.set(key, (counts.get(key) ?? 0) + 1)\n  }\n\n  return Array.from(extensionsByKey, ([key, extensions]) => ({ key, extensions })).filter(\n    ({ key }) => (counts.get(key) ?? 0) > 1,\n  )\n}\n", "import type { Step } from '@tiptap/pm/transform'\n\n/** `jsonID` is set on each step's prototype by `Step.jsonID`; not in the type defs. */\ntype StepWithId = Step & { jsonID?: string }\n\n/**\n * Whether a step only sets a node attribute.\n *\n * Matched by `jsonID` rather than `instanceof`, which fails when two copies of\n * prosemirror-transform are loaded.\n *\n * @param step The step to check.\n * @returns `true` for an `AttrStep`, which carries the target node's position.\n * @example\n * if (isAttrStep(step)) {\n *   rebuildBlockAt(step.pos)\n * }\n */\nexport function isAttrStep(step: Step): step is Step & { pos: number } {\n  return (step as StepWithId).jsonID === 'attr'\n}\n", "import type { Step } from '@tiptap/pm/transform'\n\nimport { isAttrStep } from './isAttrStep.js'\n\n/**\n * Check if a step has a resolvable changed range.\n * @param step The step to check.\n * @returns True if the step has a resolvable changed range, false otherwise.\n */\nexport function hasResolvableChangedRange(step: Step): boolean {\n  let hasMappedRange = false\n\n  step.getMap().forEach(() => {\n    hasMappedRange = true\n  })\n\n  if (hasMappedRange || isAttrStep(step)) {\n    return true\n  }\n\n  const positionalStep = step as Step & { from?: unknown; to?: unknown }\n\n  return typeof positionalStep.from === 'number' && typeof positionalStep.to === 'number'\n}\n", "import type { Node } from '@tiptap/pm/model'\nimport type { Transaction } from '@tiptap/pm/state'\n\nimport { getChangedRanges } from '../../helpers/getChangedRanges.js'\nimport type { Range } from '../../types.js'\nimport { hasResolvableChangedRange } from './hasResolvableChangedRange.js'\nimport { isAttrStep } from './isAttrStep.js'\n\nexport type RebuildRangeResolution = { type: 'ranges'; ranges: Range[] } | { type: 'full' }\n\n/**\n * Expands a changed range to the top-level blocks it touches. Blocks are\n * ordered, so the walk stops as soon as it passes the range.\n */\nfunction blockRangeFor(doc: Node, changed: Range): Range | null {\n  let from: number | null = null\n  let to = 0\n  let nodeStart = 0\n\n  for (let index = 0; index < doc.childCount; index += 1) {\n    if (nodeStart > changed.to) {\n      break\n    }\n\n    const nodeEnd = nodeStart + doc.child(index).nodeSize\n\n    // A block ending exactly at `changed.from` still owns decorations that\n    // span the boundary, so it counts as overlapping.\n    if (nodeEnd >= changed.from) {\n      if (from === null) {\n        from = nodeStart\n      }\n\n      to = nodeEnd\n    }\n\n    nodeStart = nodeEnd\n  }\n\n  return from === null ? null : { from, to }\n}\n\n/**\n * Returns the top-level block ranges to recompute after a transaction,\n * or `{ type: 'full' }` when the whole document must be rebuilt.\n * @param tr The transaction to inspect.\n * @param doc The new document after the transaction.\n * @returns The block ranges to recompute, or a full-recompute signal.\n */\nexport function getRebuildRanges(tr: Transaction, doc: Node): RebuildRangeResolution {\n  // If any step cannot be resolved, fall back to full recompute.\n  if (tr.steps.some(step => !hasResolvableChangedRange(step))) {\n    return { type: 'full' }\n  }\n\n  const newRanges: Range[] = getChangedRanges(tr).map(({ newRange }) => newRange)\n\n  // An AttrStep maps no position, so getChangedRanges misses it.\n  tr.steps.forEach((step, index) => {\n    if (!isAttrStep(step)) {\n      return\n    }\n\n    const mapping = tr.mapping.slice(index)\n\n    newRanges.push({ from: mapping.map(step.pos, -1), to: mapping.map(step.pos + 1) })\n  })\n\n  const ranges: Range[] = []\n\n  for (const newRange of newRanges) {\n    const blockRange = blockRangeFor(doc, newRange)\n\n    if (blockRange) {\n      ranges.push(blockRange)\n    }\n  }\n\n  ranges.sort((a, b) => a.from - b.from)\n\n  const merged: Range[] = []\n\n  // for each range, merge it with the previous range if it overlaps\n  for (const range of ranges) {\n    const last = merged[merged.length - 1]\n\n    // if the current range overlaps with the previous range, merge it\n    if (last && range.from <= last.to) {\n      last.to = Math.max(last.to, range.to)\n    } else {\n      merged.push({ ...range })\n    }\n  }\n\n  return { type: 'ranges', ranges: merged }\n}\n", "import type { Mapping } from '@tiptap/pm/transform'\nimport type { Node } from '@tiptap/pm/model'\nimport { DecorationSet } from '@tiptap/pm/view'\n\ntype RemovedDecorationSpec = { key?: unknown } | undefined\n\n/**\n * Maps a decoration set through a mapping and prunes the keys of any widget\n * dropped because its position was deleted.\n * @param set The decoration set to map.\n * @param mapping The mapping to use.\n * @param doc The document to map the set through.\n * @param widgetKeys The set of widget keys to prune.\n * @returns The mapped decoration set.\n */\nexport function mapDecorationSet(\n  set: DecorationSet,\n  mapping: Mapping,\n  doc: Node,\n  widgetKeys: Set<string>,\n): DecorationSet {\n  return set.map(mapping, doc, {\n    onRemove: (removedSpec: RemovedDecorationSpec) => {\n      const key = removedSpec?.key\n\n      if (typeof key === 'string') {\n        widgetKeys.delete(key)\n      }\n    },\n  })\n}\n", "import { DecorationSet } from '@tiptap/pm/view'\nimport type { Transaction } from '@tiptap/pm/state'\n\nimport type { DecorationManagerState } from '../types.js'\nimport { mapDecorationSet } from './mapDecorationSet.js'\n\n/**\n * Moves an extension's existing decorations to their new positions after a\n * transaction, and prunes widget keys for any widget whose position was deleted.\n * @param name The name of the decoration extension.\n * @param previous The previous decoration manager state.\n * @param tr The transaction to map through.\n * @returns The updated decoration set and widget keys.\n */\nexport function mapDecorations(\n  name: string,\n  previous: DecorationManagerState,\n  tr: Transaction,\n): { set: DecorationSet; widgetKeys: Set<string> } {\n  const previousSet = previous.decorationSetsByExtension[name] ?? DecorationSet.empty\n  const widgetKeys = new Set<string>(previous.widgetKeysByExtension[name] ?? [])\n\n  const set = mapDecorationSet(previousSet, tr.mapping, tr.doc, widgetKeys)\n\n  return { set, widgetKeys }\n}\n", "import type { Node } from '@tiptap/pm/model'\nimport { DecorationSet } from '@tiptap/pm/view'\n\n/**\n * Merges multiple decoration sets into a single decoration set.\n * @param doc The document to merge the decoration sets for.\n * @param decorationSetsByExtension The decoration sets to merge.\n * @returns The merged decoration set.\n */\nexport function mergeDecorationSets(\n  doc: Node,\n  decorationSetsByExtension: Record<string, DecorationSet>,\n): DecorationSet {\n  const allDecorations = Object.values(decorationSetsByExtension).flatMap(set => set.find())\n  return DecorationSet.create(doc, allDecorations)\n}\n", "/**\n * Unions all widget keys from multiple extensions into a single set.\n * @param widgetKeysByExtension The widget keys to union.\n * @returns The unioned widget keys.\n */\nexport function unionWidgetKeys(widgetKeysByExtension: Record<string, Set<string>>): Set<string> {\n  const merged = new Set<string>()\n  for (const keys of Object.values(widgetKeysByExtension)) {\n    for (const key of keys) {\n      merged.add(key)\n    }\n  }\n\n  return merged\n}\n", "import type { DecorationSpec } from '../types.js'\n\n/**\n * Validates a decoration spec to ensure it follows the correct pattern for its update strategy.\n * @param name The name of the extension.\n * @param spec The decoration spec to validate\n */\nexport function validateDecorationSpec(name: string, spec: DecorationSpec): void {\n  const strategy = (spec as DecorationSpec & { update?: unknown }).update ?? 'document'\n\n  switch (strategy) {\n    case 'document':\n      if (spec.createInRange) {\n        throw new Error(\n          `[tiptap error]: Extension \"${name}\" provides createInRange() but does not use the ` +\n            '\"changedRanges\" decoration update strategy.',\n        )\n      }\n      return\n    case 'changedRanges':\n      if (!spec.createInRange) {\n        throw new Error(\n          `[tiptap error]: Extension \"${name}\" uses the \"changedRanges\" decoration update ` +\n            'strategy but does not provide createInRange().',\n        )\n      }\n      return\n    case 'manual':\n      if (spec.createInRange) {\n        throw new Error(\n          `[tiptap error]: Extension \"${name}\" uses the \"manual\" decoration update strategy, ` +\n            'which is not compatible with createInRange(). createInRange() requires the ' +\n            '\"changedRanges\" strategy.',\n        )\n      }\n      if (spec.shouldUpdate) {\n        throw new Error(\n          `[tiptap error]: Extension \"${name}\" cannot combine the \"manual\" decoration update ` +\n            'strategy with shouldUpdate().',\n        )\n      }\n      return\n    default:\n      throw new Error(\n        `[tiptap error]: Extension \"${name}\" uses an unknown decoration update strategy. ` +\n          'Expected \"document\", \"changedRanges\", or \"manual\".',\n      )\n  }\n}\n", "import type { DecorationShouldUpdateProps, DecorationSpec } from '../types.js'\n\n/**\n * Decides whether a decoration spec should be recomputed for a transaction.\n * @param spec The decoration spec to check.\n * @param props Properties containing editor, transaction, and state.\n * @param forced Whether recomputation was forced.\n * @returns `true` if the decoration should be recomputed.\n */\nexport function shouldRecomputeDecoration(\n  spec: DecorationSpec,\n  props: DecorationShouldUpdateProps,\n  forced: boolean,\n): boolean {\n  if (forced) {\n    return true\n  }\n\n  if (spec.update === 'manual') {\n    return false\n  }\n\n  return spec.shouldUpdate ? spec.shouldUpdate(props) : props.tr.docChanged\n}\n", "import type { Node } from '@tiptap/pm/model'\nimport type { EditorState, Transaction } from '@tiptap/pm/state'\nimport { Plugin } from '@tiptap/pm/state'\nimport type { EditorView } from '@tiptap/pm/view'\nimport { DecorationSet } from '@tiptap/pm/view'\n\nimport type { Editor } from '../Editor.js'\nimport type { Range } from '../types.js'\nimport { isDev } from '../utilities/isDev.js'\nimport { DECORATION_MANAGER_PLUGIN_KEY } from './constants.js'\nimport type { Decoration } from './Decoration.js'\nimport { runInDecorationApplyScope } from './decorationApplyScope.js'\nimport { buildDecorationSet } from './helpers/buildDecorationSet.js'\nimport { decorationsToPMDecorations } from './helpers/decorationsToPMDecorations.js'\nimport { filterOutOfRangeDecorations } from './helpers/filterOutOfRangeDecorations.js'\nimport { findDuplicateWidgetKeys } from './helpers/findDuplicateWidgetKeys.js'\nimport { getRebuildRanges } from './helpers/getRebuildRanges.js'\nimport { mapDecorations } from './helpers/mapDecorations.js'\nimport { mapDecorationSet } from './helpers/mapDecorationSet.js'\nimport { mergeDecorationSets } from './helpers/mergeDecorationSets.js'\nimport { rangeOwnsPosition } from './helpers/rangeOwnsPosition.js'\nimport { unionWidgetKeys } from './helpers/unionWidgetKeys.js'\nimport { validateDecorationSpec } from './helpers/validateDecorationSpec.js'\nimport { shouldRecomputeDecoration } from './helpers/shouldRecomputeDecoration.js'\nimport { widgetKeyOf } from './helpers/widgetKeyOf.js'\nimport type {\n  DecorationCreateProps,\n  DecorationManagerEntry,\n  DecorationManagerState,\n  DecorationMeta,\n  DecorationRangeProps,\n  DecorationSpec,\n  ResolvedDecorationEntry,\n} from './types.js'\nexport type { DecorationManagerEntry } from './types.js'\n\nconst EMPTY_KEYS: ReadonlySet<string> = new Set()\n\nexport function liveWidgetKeys(editor: Editor): ReadonlySet<string> {\n  return editor.extensionManager?.decorationManager?.liveWidgetKeys() ?? EMPTY_KEYS\n}\n\nexport class DecorationManager {\n  editor: Editor\n  entries: ResolvedDecorationEntry[]\n  plugin: Plugin<DecorationManagerState> | null\n  private warnedWidgetKeys = new Set<string>()\n  private warnedOutOfRangeExtensions = new Set<string>()\n  private readonly handleBeforeTransaction = ({ nextState }: { nextState: EditorState }) => {\n    const state = DECORATION_MANAGER_PLUGIN_KEY.getState(nextState)\n\n    if (state) {\n      this.warnDuplicateWidgetKeys(state)\n    }\n  }\n\n  constructor(options: { editor: Editor; entries: DecorationManagerEntry[] }) {\n    this.editor = options.editor\n    this.entries = this.resolveEntries(options.entries)\n    this.entries.forEach(({ name, spec }) => validateDecorationSpec(name, spec))\n    this.plugin = this.entries.length > 0 ? this.createPlugin() : null\n\n    this.editor.on('beforeTransaction', this.handleBeforeTransaction)\n  }\n\n  destroy(): void {\n    this.editor.off('beforeTransaction', this.handleBeforeTransaction)\n  }\n\n  /**\n   * Returns the set of live widget keys from all decoration extensions.\n   * @returns A readonly set of widget keys\n   */\n  liveWidgetKeys(): ReadonlySet<string> {\n    return DECORATION_MANAGER_PLUGIN_KEY.getState(this.editor.state)?.widgetKeys ?? EMPTY_KEYS\n  }\n\n  /**\n   * The mounted editor view, or `null` when destroyed. Decoration callbacks\n   * must never receive the placeholder view `editor.view` falls back to.\n   * @returns The mounted editor view, or `null`\n   */\n  private get mountedView(): EditorView | null {\n    return this.editor.isDestroyed ? null : this.editor.view\n  }\n\n  /**\n   * Resolves decoration entries by calling the addDecorations function for each extension entry.\n   * @param entries The decoration manager entries to resolve\n   * @returns An array of resolved decoration entries\n   */\n  private resolveEntries(entries: DecorationManagerEntry[]): ResolvedDecorationEntry[] {\n    const resolved: ResolvedDecorationEntry[] = []\n\n    for (const { name, addDecorations } of entries) {\n      const spec = addDecorations()\n\n      if (spec) {\n        resolved.push({ name, spec })\n      }\n    }\n\n    return resolved\n  }\n\n  /**\n   * Creates the ProseMirror plugin for managing decorations.\n   * @returns A ProseMirror plugin with state management\n   */\n  private createPlugin(): Plugin<DecorationManagerState> {\n    const { editor, entries } = this\n\n    return new Plugin<DecorationManagerState>({\n      key: DECORATION_MANAGER_PLUGIN_KEY,\n      state: {\n        init: (_config, state) => {\n          const decorationSetsByExtension: Record<string, DecorationSet> = {}\n          const widgetKeysByExtension: Record<string, Set<string>> = {}\n\n          for (const { name, spec } of entries) {\n            const { set, widgetKeys } = this.buildFullSet(name, spec, state)\n\n            decorationSetsByExtension[name] = set\n            widgetKeysByExtension[name] = widgetKeys\n          }\n\n          const managerState = {\n            decorationSetsByExtension,\n            widgetKeysByExtension,\n            mergedDecorationSet: this.buildMergedSet(state.doc, decorationSetsByExtension),\n            widgetKeys: unionWidgetKeys(widgetKeysByExtension),\n          }\n\n          this.warnDuplicateWidgetKeys(managerState)\n\n          return managerState\n        },\n        apply: (tr, previous, oldState, newState) => {\n          const meta = tr.getMeta(DECORATION_MANAGER_PLUGIN_KEY) as DecorationMeta | undefined\n          const forceAll = meta?.type === 'force' && !meta.name\n          const forceName = meta?.type === 'force' ? meta.name : undefined\n\n          const decorationSetsByExtension: Record<string, DecorationSet> = {}\n          const widgetKeysByExtension: Record<string, Set<string>> = {}\n          const recomputedNames = new Set<string>()\n\n          runInDecorationApplyScope(editor, () => {\n            for (const { name, spec } of entries) {\n              const forced = forceAll || forceName === name\n              const shouldRecompute = shouldRecomputeDecoration(\n                spec,\n                { editor, tr, oldState, newState },\n                forced,\n              )\n\n              if (!shouldRecompute) {\n                const result = mapDecorations(name, previous, tr)\n                decorationSetsByExtension[name] = result.set\n                widgetKeysByExtension[name] = result.widgetKeys\n              } else if (spec.update === 'changedRanges' && tr.docChanged && !forced) {\n                const result = this.applyChangedRangesRecompute(name, spec, previous, tr, newState)\n\n                decorationSetsByExtension[name] = result.set\n                widgetKeysByExtension[name] = result.widgetKeys\n                recomputedNames.add(name)\n              } else {\n                const { set, widgetKeys } = this.buildFullSet(name, spec, newState)\n\n                decorationSetsByExtension[name] = set\n                widgetKeysByExtension[name] = widgetKeys\n                recomputedNames.add(name)\n              }\n            }\n          })\n\n          if (recomputedNames.size === 0 && !tr.docChanged) {\n            return previous\n          }\n\n          const mergedDecorationSet = this.mergeAfterApply({\n            entries,\n            previous,\n            tr,\n            decorationSetsByExtension,\n            recomputedNames,\n          })\n\n          return {\n            decorationSetsByExtension,\n            widgetKeysByExtension,\n            mergedDecorationSet,\n            widgetKeys: unionWidgetKeys(widgetKeysByExtension),\n          }\n        },\n      },\n      props: {\n        decorations(state) {\n          return (\n            DECORATION_MANAGER_PLUGIN_KEY.getState(state)?.mergedDecorationSet ??\n            DecorationSet.empty\n          )\n        },\n      },\n    })\n  }\n\n  /**\n   * Applies changed ranges recomputation to a decoration set, dropping stale decorations and rebuilding only the touched blocks.\n   * @param name The name of the decoration extension\n   * @param spec The decoration spec\n   * @param previous The previous decoration manager state\n   * @param tr The transaction to apply\n   * @param newState The new editor state\n   * @returns The updated decoration set and widget keys\n   */\n  private applyChangedRangesRecompute(\n    name: string,\n    spec: DecorationSpec,\n    previous: DecorationManagerState,\n    tr: Transaction,\n    newState: EditorState,\n  ): { set: DecorationSet; widgetKeys: Set<string> } {\n    const resolution = getRebuildRanges(tr, newState.doc)\n\n    if (resolution.type === 'full') {\n      return this.buildFullSet(name, spec, newState)\n    }\n\n    return this.rebuildRanges(name, spec, previous, tr, newState, resolution.ranges)\n  }\n\n  /**\n   * Rebuilds decorations for the changed block ranges: maps the previous set\n   * forward, then for each range removes stale decorations, calls\n   * `createInRange`, and adds the new ones while syncing widget keys.\n   * @param name The extension name.\n   * @param spec The decoration spec.\n   * @param previous The previous decoration manager state.\n   * @param tr The transaction to apply.\n   * @param newState The new editor state.\n   * @param ranges The block ranges to rebuild.\n   * @returns The updated decoration set and widget keys.\n   */\n  private rebuildRanges(\n    name: string,\n    spec: DecorationSpec,\n    previous: DecorationManagerState,\n    tr: Transaction,\n    newState: EditorState,\n    ranges: Range[],\n  ): { set: DecorationSet; widgetKeys: Set<string> } {\n    const previousSet = previous.decorationSetsByExtension[name] ?? DecorationSet.empty\n    const widgetKeys = new Set<string>(previous.widgetKeysByExtension[name] ?? [])\n    let set = mapDecorationSet(previousSet, tr.mapping, tr.doc, widgetKeys)\n\n    const docSize = newState.doc.content.size\n\n    for (const { from, to } of ranges) {\n      const stale = set\n        .find(from, to)\n        .filter(decoration => rangeOwnsPosition({ position: decoration.from, from, to, docSize }))\n\n      for (const decoration of stale) {\n        const key = widgetKeyOf(decoration)\n\n        if (key) {\n          widgetKeys.delete(key)\n        }\n      }\n\n      set = set.remove(stale)\n\n      const rangeDecorations = filterOutOfRangeDecorations({\n        decorations: this.runCreate(name, 'createInRange', () =>\n          spec.createInRange!({\n            editor: this.editor,\n            state: newState,\n            view: this.mountedView,\n            from,\n            to,\n          } satisfies DecorationRangeProps),\n        ),\n        from,\n        to,\n        docSize,\n        extensionName: name,\n        warnedExtensions: this.warnedOutOfRangeExtensions,\n      })\n      const { decorations: pmDecorations, widgetKeys: addedKeys } = decorationsToPMDecorations(\n        rangeDecorations,\n        name,\n      )\n\n      set = set.add(newState.doc, pmDecorations)\n\n      for (const key of addedKeys) {\n        widgetKeys.add(key)\n      }\n    }\n\n    return { set, widgetKeys }\n  }\n\n  /**\n   * Builds a full decoration set for the entire document.\n   * @param name The name of the decoration extension\n   * @param spec The decoration spec\n   * @param state The editor state\n   * @returns The decoration set and widget keys\n   */\n  private buildFullSet(\n    name: string,\n    spec: DecorationSpec,\n    state: EditorState,\n  ): { set: DecorationSet; widgetKeys: Set<string> } {\n    const decorations = this.runCreate(name, 'create', () =>\n      spec.create({\n        editor: this.editor,\n        state,\n        view: this.mountedView,\n      } satisfies DecorationCreateProps),\n    )\n\n    return buildDecorationSet(state.doc, decorations, name)\n  }\n\n  /**\n   * Runs a decoration callback and swallows anything it throws. These run inside\n   * `state.apply`, where an uncaught error would abort the whole transaction.\n   * @param name The extension name.\n   * @param method The callback name, used in the error message.\n   * @param create The callback to run.\n   * @returns The decorations, or an empty array if the callback threw.\n   */\n  private runCreate(\n    name: string,\n    method: 'create' | 'createInRange',\n    create: () => Decoration[],\n  ): Decoration[] {\n    try {\n      return create()\n    } catch (error) {\n      console.error(\n        `[tiptap error]: Extension \"${name}\" threw in \\`addDecorations().${method}()\\`. ` +\n          'Its decorations were dropped for this update.',\n        error,\n      )\n\n      return []\n    }\n  }\n\n  private warnDuplicateWidgetKeys(state: DecorationManagerState): void {\n    if (!isDev) {\n      return\n    }\n\n    // No widget keys means no duplicates, so the scan over the merged set is\n    // pointless. Most documents carry only node and inline decorations.\n    if (state.widgetKeys.size === 0) {\n      this.warnedWidgetKeys.clear()\n\n      return\n    }\n\n    const duplicateKeys = findDuplicateWidgetKeys(state.mergedDecorationSet)\n    const nextWarningKeys = new Set(duplicateKeys.map(({ key }) => key))\n\n    for (const { key, extensions } of duplicateKeys) {\n      if (this.warnedWidgetKeys.has(key)) {\n        continue\n      }\n\n      const names = Array.from(extensions)\n        .map(name => `\"${name}\"`)\n        .join(', ')\n\n      console.warn(\n        `[tiptap warn]: Duplicate widget decoration key \"${key}\" in extension${\n          extensions.size === 1 ? '' : 's'\n        } ${names}. Widget decoration keys must be globally unique, otherwise ProseMirror ` +\n          'misplaces the widget DOM. Use a stable, unique key (e.g. `comment-${id}`).',\n      )\n    }\n\n    this.warnedWidgetKeys = nextWarningKeys\n  }\n\n  /**\n   * Builds the merged DecorationSet during init. Skips the merge for a\n   * single extension since its per-extension set is already correct.\n   * @param doc The document to build the merged set for.\n   * @param decorationSetsByExtension The per-extension decoration sets.\n   * @returns The merged decoration set.\n   */\n  private buildMergedSet(\n    doc: Node,\n    decorationSetsByExtension: Record<string, DecorationSet>,\n  ): DecorationSet {\n    const names = Object.keys(decorationSetsByExtension)\n\n    if (names.length === 1) {\n      return decorationSetsByExtension[names[0]]\n    }\n\n    return mergeDecorationSets(doc, decorationSetsByExtension)\n  }\n\n  /**\n   * Computes the merged DecorationSet after apply. Single extension skips the\n   * merge; nothing recomputed maps the previous merged set forward; otherwise\n   * the merge is rebuilt from the per-extension sets.\n   */\n  private mergeAfterApply({\n    entries,\n    previous,\n    tr,\n    decorationSetsByExtension,\n    recomputedNames,\n  }: {\n    entries: ResolvedDecorationEntry[]\n    previous: DecorationManagerState\n    tr: Transaction\n    decorationSetsByExtension: Record<string, DecorationSet>\n    recomputedNames: Set<string>\n  }): DecorationSet {\n    if (entries.length === 1) {\n      return decorationSetsByExtension[entries[0].name]\n    }\n\n    if (recomputedNames.size === 0) {\n      return previous.mergedDecorationSet.map(tr.mapping, tr.doc)\n    }\n\n    // Patching the previous merged set is far slower than rebuilding it:\n    // `DecorationSet.remove` scans every decoration once per block, so it goes\n    // quadratic on large documents. Every set here already matches `tr.doc`.\n    return mergeDecorationSets(tr.doc, decorationSetsByExtension)\n  }\n}\n", "/**\n * Compare two attribute objects for equality.\n * Handles null/undefined and asserts key presence in both objects so that\n * `{ foo: undefined }` and `{ bar: undefined }` are not treated as equal.\n */\nexport function attrsEqual(\n  a: Record<string, any> | null | undefined,\n  b: Record<string, any> | null | undefined,\n): boolean {\n  if (a === b) {\n    return true\n  }\n  if (!a || !b) {\n    return false\n  }\n\n  const keysA = Object.keys(a)\n  const keysB = Object.keys(b)\n\n  if (keysA.length !== keysB.length) {\n    return false\n  }\n\n  return keysA.every(\n    key => Object.prototype.hasOwnProperty.call(b, key) && Object.is(a[key], b[key]),\n  )\n}\n", "import type { NodeType } from '@tiptap/pm/model'\nimport { type EditorState, NodeSelection } from '@tiptap/pm/state'\n\nexport function canInsertNode(state: EditorState, nodeType: NodeType): boolean {\n  const { selection } = state\n  const { $from } = selection\n\n  // Special handling for NodeSelection\n  if (selection instanceof NodeSelection) {\n    const index = $from.index()\n    const parent = $from.parent\n\n    // Can we replace the selected node with the horizontal rule?\n    return parent.canReplaceWith(index, index + 1, nodeType)\n  }\n\n  // Default: check if we can insert at the current position\n  let depth = $from.depth\n\n  while (depth >= 0) {\n    const index = $from.index(depth)\n    const parent = $from.node(depth)\n    const match = parent.contentMatchAt(index)\n    if (match.matchType(nodeType)) {\n      return true\n    }\n    depth -= 1\n  }\n  return false\n}\n", "export function createStyleTag(style: string, nonce?: string, suffix?: string): HTMLStyleElement {\n  const tiptapStyleTag = <HTMLStyleElement>(\n    document.querySelector(`style[data-tiptap-style${suffix ? `-${suffix}` : ''}]`)\n  )\n\n  if (tiptapStyleTag !== null) {\n    return tiptapStyleTag\n  }\n\n  const styleNode = document.createElement('style')\n\n  if (nonce) {\n    styleNode.setAttribute('nonce', nonce)\n  }\n\n  styleNode.setAttribute(`data-tiptap-style${suffix ? `-${suffix}` : ''}`, '')\n  styleNode.innerHTML = style\n  document.getElementsByTagName('head')[0].appendChild(styleNode)\n\n  return styleNode\n}\n", "// source: https://stackoverflow.com/a/6969486\nexport function escapeForRegEx(string: string): string {\n  return string.replace(/[-/\\\\^$*+?.()|[\\]{}]/g, '\\\\$&')\n}\n", "/**\n * Read a CSS property value directly from an element's raw inline `style`\n * attribute, bypassing the CSSOM (e.g. `element.style.fontFamily`) which\n * canonicalizes values and can change formatting. The original format is\n * preserved (quotes, hex vs rgb, etc.).\n *\n * When a property is declared more than once, the last declaration wins —\n * this matches CSS cascade order and is useful when nested spans are merged\n * and the child's value should take priority.\n *\n * Property name comparison is case-insensitive.\n *\n * @param element - The element whose `style` attribute should be read.\n * @param propertyName - The CSS property name (e.g. `font-family`).\n * @returns The raw value string, or `null` if the property is not present.\n *\n * @example\n * ```ts\n * parseHTML: element => getStyleProperty(element, 'font-family')\n * ```\n */\nexport function getStyleProperty(element: HTMLElement, propertyName: string): string | null {\n  const styleAttr = element.getAttribute('style')\n\n  if (!styleAttr) {\n    return null\n  }\n\n  const decls = styleAttr\n    .split(';')\n    .map(decl => decl.trim())\n    .filter(Boolean)\n\n  const target = propertyName.toLowerCase()\n\n  for (let i = decls.length - 1; i >= 0; i -= 1) {\n    const decl = decls[i]\n    const colonIndex = decl.indexOf(':')\n\n    if (colonIndex === -1) {\n      continue\n    }\n\n    const prop = decl.slice(0, colonIndex).trim().toLowerCase()\n\n    if (prop === target) {\n      return decl.slice(colonIndex + 1).trim()\n    }\n  }\n\n  return null\n}\n", "const NAMED_ENTITIES: Record<string, string> = { lt: '<', gt: '>', quot: '\"', amp: '&' }\n\n/**\n * Decode common HTML entities in text content so they display as literal\n * characters inside the editor. Runs as a single pass so a decoded entity\n * (e.g. `&#38;` → `&`) is never re-scanned and decoded again.\n */\nexport function decodeHtmlEntities(text: string): string {\n  // Digit limits per CommonMark: decimal refs are 1-7 digits, hex refs are 1-6.\n  return text.replace(\n    /&(?:#(\\d{1,7})|#[xX]([0-9a-fA-F]{1,6})|(lt|gt|quot|amp));/g,\n    (match, dec, hex, name) => {\n      if (dec !== undefined) {\n        return decodeCodePoint(Number(dec))\n      }\n      if (hex !== undefined) {\n        return decodeCodePoint(parseInt(hex, 16))\n      }\n      return NAMED_ENTITIES[name]\n    },\n  )\n}\n\n// HTML5 maps numeric references in the C1 range (0x80-0x9F) to Windows-1252 characters.\nconst WINDOWS_1252 = new Map<number, number>([\n  [0x80, 0x20ac],\n  [0x82, 0x201a],\n  [0x83, 0x0192],\n  [0x84, 0x201e],\n  [0x85, 0x2026],\n  [0x86, 0x2020],\n  [0x87, 0x2021],\n  [0x88, 0x02c6],\n  [0x89, 0x2030],\n  [0x8a, 0x0160],\n  [0x8b, 0x2039],\n  [0x8c, 0x0152],\n  [0x8e, 0x017d],\n  [0x91, 0x2018],\n  [0x92, 0x2019],\n  [0x93, 0x201c],\n  [0x94, 0x201d],\n  [0x95, 0x2022],\n  [0x96, 0x2013],\n  [0x97, 0x2014],\n  [0x98, 0x02dc],\n  [0x99, 0x2122],\n  [0x9a, 0x0161],\n  [0x9b, 0x203a],\n  [0x9c, 0x0153],\n  [0x9e, 0x017e],\n  [0x9f, 0x0178],\n])\n\n// Replace invalid code points with U+FFFD, per the CommonMark spec.\nfunction decodeCodePoint(codePoint: number): string {\n  if (codePoint === 0 || codePoint > 0x10ffff || (codePoint >= 0xd800 && codePoint <= 0xdfff)) {\n    return '\\uFFFD'\n  }\n  return String.fromCodePoint(WINDOWS_1252.get(codePoint) ?? codePoint)\n}\n\n/**\n * Encode HTML special characters so they roundtrip safely through markdown.\n * `&` is encoded **first** to avoid double-encoding the ampersand in other\n * entities (e.g. `<` → `&lt;`, not `&amp;lt;`).\n *\n * Note: `\"` is intentionally NOT encoded here because double quotes are\n * ordinary characters in markdown and do not need escaping.  The decode\n * function still handles `&quot;` because the markdown tokenizer may emit it.\n */\nexport function encodeHtmlEntities(text: string): string {\n  return text.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;')\n}\n", "/**\n * Detects if the current browser is Firefox.\n * @returns `true` if the browser is Firefox, `false` otherwise.\n * @example\n * if (isFirefox()) {\n *   // Firefox-specific handling\n * }\n */\nexport function isFirefox(): boolean {\n  return typeof navigator !== 'undefined' ? /Firefox/.test(navigator.userAgent) : false\n}\n", "export function isNumber(value: any): value is number {\n  return typeof value === 'number'\n}\n", "// see: https://github.com/mesqueeb/is-what/blob/88d6e4ca92fb2baab6003c54e02eedf4e729e5ab/src/index.ts\n\nfunction getType(value: any): string {\n  return Object.prototype.toString.call(value).slice(8, -1)\n}\n\nexport function isPlainObject(value: any): value is Record<string, any> {\n  if (getType(value) !== 'Object') {\n    return false\n  }\n\n  return value.constructor === Object && Object.getPrototypeOf(value) === Object.prototype\n}\n", "export function isString(value: any): value is string {\n  return typeof value === 'string'\n}\n", "/**\n * Checks whether a value can be inserted into one CSS declaration.\n * @param value - The CSS property value.\n * @returns Whether the value stays inside one declaration.\n */\nexport function isValidCSSStyleValue(value: unknown): value is string {\n  return typeof value === 'string' && value.trim().length > 0 && !/[;{}]/.test(value)\n}\n", "export type AttributeToken =\n  | { type: 'class'; name: string }\n  | { type: 'id'; name: string }\n  | { type: 'keyValue'; name: string; value: string }\n  | { type: 'boolean'; name: string }\n\ntype AttributeSyntax = 'pandoc' | 'shortcode'\n\ntype TokenResult = {\n  token?: AttributeToken\n  nextIndex: number\n}\n\nfunction isWhitespace(character: string): boolean {\n  return /\\s/.test(character)\n}\n\nfunction isAsciiLetter(character: string): boolean {\n  return /^[a-zA-Z]$/.test(character)\n}\n\nfunction isWordCharacter(character: string): boolean {\n  return /^\\w$/.test(character)\n}\n\nfunction skipWhitespace(input: string, index: number): number {\n  while (index < input.length && isWhitespace(input[index])) {\n    index += 1\n  }\n\n  return index\n}\n\nfunction skipToWhitespace(input: string, index: number): number {\n  while (index < input.length && !isWhitespace(input[index])) {\n    index += 1\n  }\n\n  return index\n}\n\nfunction readName(input: string, index: number, allowHyphen: boolean): number {\n  while (\n    index < input.length &&\n    (isWordCharacter(input[index]) || (allowHyphen && input[index] === '-'))\n  ) {\n    index += 1\n  }\n\n  return index\n}\n\nfunction readShorthand(input: string, index: number): TokenResult {\n  const prefix = input[index]\n  const nameStart = index + 1\n  const nameEnd = readName(input, nameStart, true)\n\n  if (nameEnd === nameStart) {\n    return { nextIndex: skipToWhitespace(input, nameEnd) }\n  }\n\n  return {\n    token: {\n      type: prefix === '.' ? 'class' : 'id',\n      name: input.slice(nameStart, nameEnd),\n    },\n    nextIndex: skipToWhitespace(input, nameEnd),\n  }\n}\n\nfunction readQuotedSegment(input: string, index: number): TokenResult {\n  const closingQuote = input.indexOf(input[index], index + 1)\n  const segmentEnd = closingQuote === -1 ? index : closingQuote + 1\n\n  return { nextIndex: skipToWhitespace(input, segmentEnd) }\n}\n\nfunction readKeyValue(\n  input: string,\n  name: string,\n  index: number,\n  allowWhitespace: boolean,\n): TokenResult | undefined {\n  let valueStart = allowWhitespace ? skipWhitespace(input, index) : index\n  if (input[valueStart] !== '=') {\n    return undefined\n  }\n\n  valueStart = allowWhitespace ? skipWhitespace(input, valueStart + 1) : valueStart + 1\n  const quote = input[valueStart]\n  if (quote !== '\"' && quote !== \"'\") {\n    return undefined\n  }\n\n  const valueEnd = input.indexOf(quote, valueStart + 1)\n  if (valueEnd === -1) {\n    return undefined\n  }\n\n  return {\n    token: {\n      type: 'keyValue',\n      name,\n      value: input.slice(valueStart + 1, valueEnd),\n    },\n    nextIndex: skipToWhitespace(input, valueEnd + 1),\n  }\n}\n\nfunction readNamedAttribute(input: string, index: number, syntax: AttributeSyntax): TokenResult {\n  const isPandoc = syntax === 'pandoc'\n  const nameEnd = readName(input, index + 1, isPandoc)\n  const name = input.slice(index, nameEnd)\n  const keyValue = readKeyValue(input, name, nameEnd, isPandoc)\n\n  if (keyValue) {\n    return keyValue\n  }\n\n  const isStandalone = nameEnd === input.length || isWhitespace(input[nameEnd])\n  return {\n    token: isPandoc && isStandalone ? { type: 'boolean', name } : undefined,\n    nextIndex: syntax === 'shortcode' ? skipToWhitespace(input, nameEnd) : nameEnd,\n  }\n}\n\nfunction readAttribute(input: string, index: number, syntax: AttributeSyntax): TokenResult {\n  const prefix = input[index]\n\n  if (syntax === 'pandoc' && (prefix === '.' || prefix === '#')) {\n    return readShorthand(input, index)\n  }\n  if (prefix === '\"' || prefix === \"'\") {\n    return readQuotedSegment(input, index)\n  }\n\n  const hasValidStart = syntax === 'pandoc' ? isAsciiLetter(prefix) : isWordCharacter(prefix)\n  if (hasValidStart) {\n    return readNamedAttribute(input, index, syntax)\n  }\n\n  return { nextIndex: skipToWhitespace(input, index) }\n}\n\nexport function tokenizeAttributes(input: string, syntax: AttributeSyntax): AttributeToken[] {\n  const tokens: AttributeToken[] = []\n  let index = 0\n\n  while (index < input.length) {\n    index = skipWhitespace(input, index)\n    if (index >= input.length) {\n      break\n    }\n\n    const result = readAttribute(input, index, syntax)\n    if (result.token) {\n      tokens.push(result.token)\n    }\n    index = result.nextIndex\n  }\n\n  return tokens\n}\n", "import type { AttributeToken } from './tokenizeAttributes.js'\nimport { tokenizeAttributes } from './tokenizeAttributes.js'\n\nfunction applyTokens(tokens: AttributeToken[]): Record<string, any> {\n  const attributes: Record<string, any> = {}\n  const classes = tokens.filter(token => token.type === 'class').map(token => token.name)\n  const id = tokens.find(token => token.type === 'id')\n\n  if (classes.length > 0) {\n    attributes.class = classes.join(' ')\n  }\n  if (id) {\n    attributes.id = id.name\n  }\n\n  tokens.forEach(token => {\n    if (token.type === 'keyValue') {\n      attributes[token.name] = token.value\n    }\n  })\n  tokens.forEach(token => {\n    if (token.type === 'boolean') {\n      attributes[token.name] = true\n    }\n  })\n\n  return attributes\n}\n\n/**\n * Parses a Pandoc-style attribute string into an object.\n *\n * @param attrString - The attribute string to parse\n * @returns Parsed attributes object\n *\n * @example\n * ```ts\n * parseAttributes('.btn #submit disabled type=\"button\"')\n * // { class: 'btn', id: 'submit', disabled: true, type: 'button' }\n * ```\n */\nexport function parseAttributes(attrString: string): Record<string, any> {\n  if (!attrString?.trim()) {\n    return {}\n  }\n\n  return applyTokens(tokenizeAttributes(attrString, 'pandoc'))\n}\n", "/**\n * Serializes an attributes object to a Pandoc-style attribute string.\n *\n * @param attributes - The attributes object to serialize\n * @returns Serialized attribute string\n *\n * @example\n * ```ts\n * serializeAttributes({ class: 'btn primary', id: 'submit', disabled: true, type: 'button' })\n * // '.btn .primary #submit disabled type=\"button\"'\n * ```\n */\nexport function serializeAttributes(attributes: Record<string, any>): string {\n  if (!attributes || Object.keys(attributes).length === 0) {\n    return ''\n  }\n\n  const parts: string[] = []\n\n  if (attributes.class) {\n    const classes = String(attributes.class).split(/\\s+/).filter(Boolean)\n    classes.forEach(className => parts.push(`.${className}`))\n  }\n\n  if (attributes.id) {\n    parts.push(`#${attributes.id}`)\n  }\n\n  Object.entries(attributes).forEach(([key, value]) => {\n    if (key === 'class' || key === 'id') {\n      return\n    }\n\n    if (value === true) {\n      parts.push(key)\n    } else if (value !== false && value != null) {\n      parts.push(`${key}=\"${String(value)}\"`)\n    }\n  })\n\n  return parts.join(' ')\n}\n", "import type {\n  JSONContent,\n  MarkdownParseHelpers,\n  MarkdownParseResult,\n  MarkdownToken,\n  MarkdownTokenizer,\n} from '../../types.js'\nimport { parseAttributes as defaultParseAttributes } from './parseAttributes.js'\nimport { serializeAttributes as defaultSerializeAttributes } from './serializeAttributes.js'\n\nexport interface AtomBlockMarkdownSpecOptions {\n  /** The Tiptap node name this spec is for */\n  nodeName: string\n  /** The markdown syntax name (defaults to nodeName if not provided) */\n  name?: string\n  /** Function to parse attributes from token attribute string */\n  parseAttributes?: (attrString: string) => Record<string, any>\n  /** Function to serialize attributes back to string for rendering */\n  serializeAttributes?: (attrs: Record<string, any>) => string\n  /** Default attributes to apply when parsing */\n  defaultAttributes?: Record<string, any>\n  /** Required attributes that must be present for successful parsing */\n  requiredAttributes?: string[]\n  /** Attributes that are allowed to be rendered back to markdown (whitelist) */\n  allowedAttributes?: string[]\n}\n\n/**\n * Creates a complete markdown spec for atomic block nodes using Pandoc syntax.\n *\n * The generated spec handles:\n * - Parsing self-closing blocks with `:::blockName {attributes}`\n * - Extracting and parsing attributes\n * - Validating required attributes\n * - Rendering blocks back to markdown\n *\n * @param options - Configuration for the atomic block markdown spec\n * @returns Complete markdown specification object\n *\n * @example\n * ```ts\n * const youtubeSpec = createAtomBlockMarkdownSpec({\n *   nodeName: 'youtube',\n *   requiredAttributes: ['src'],\n *   defaultAttributes: { start: 0 },\n *   allowedAttributes: ['src', 'start', 'width', 'height'] // Only these get rendered to markdown\n * })\n *\n * // Usage in extension:\n * export const Youtube = Node.create({\n *   // ... other config\n *   markdown: youtubeSpec\n * })\n * ```\n */\nexport function createAtomBlockMarkdownSpec(options: AtomBlockMarkdownSpecOptions): {\n  parseMarkdown: (token: MarkdownToken, h: MarkdownParseHelpers) => MarkdownParseResult\n  markdownTokenizer: MarkdownTokenizer\n  renderMarkdown: (node: JSONContent) => string\n} {\n  const {\n    nodeName,\n    name: markdownName,\n    parseAttributes = defaultParseAttributes,\n    serializeAttributes = defaultSerializeAttributes,\n    defaultAttributes = {},\n    requiredAttributes = [],\n    allowedAttributes,\n  } = options\n\n  // Use markdownName for syntax, fallback to nodeName\n  const blockName = markdownName || nodeName\n\n  // Helper function to filter attributes based on allowlist\n  const filterAttributes = (attrs: Record<string, any>) => {\n    if (!allowedAttributes) {\n      return attrs\n    }\n\n    const filtered: Record<string, any> = {}\n    allowedAttributes.forEach(key => {\n      if (key in attrs) {\n        filtered[key] = attrs[key]\n      }\n    })\n    return filtered\n  }\n\n  return {\n    parseMarkdown: (token: MarkdownToken, h: MarkdownParseHelpers) => {\n      const attrs = { ...defaultAttributes, ...token.attributes }\n      return h.createNode(nodeName, attrs, [])\n    },\n\n    markdownTokenizer: {\n      name: nodeName,\n      level: 'block' as const,\n      start(src: string) {\n        // Four leading spaces start a code block\n        const regex = new RegExp(`^ {0,3}:::${blockName}(?:\\\\s|$)`, 'm')\n        const index = src.match(regex)?.index\n        return index !== undefined ? index : -1\n      },\n      tokenize(src, _tokens, _lexer) {\n        const regex = new RegExp(`^ {0,3}:::${blockName}(?:\\\\s+\\\\{([^}]*)\\\\})?\\\\s*:::(?:\\\\n|$)`)\n        const match = src.match(regex)\n\n        if (!match) {\n          return undefined\n        }\n\n        // Parse attributes if present\n        const attrString = match[1] || ''\n        const attributes = parseAttributes(attrString)\n\n        // Validate required attributes\n        const missingRequired = requiredAttributes.find(required => !(required in attributes))\n        if (missingRequired) {\n          return undefined\n        }\n\n        return {\n          type: nodeName,\n          raw: match[0],\n          attributes,\n        }\n      },\n    },\n\n    renderMarkdown: node => {\n      const filteredAttrs = filterAttributes(node.attrs || {})\n      const attrs = serializeAttributes(filteredAttrs)\n      const attrString = attrs ? ` {${attrs}}` : ''\n\n      return `:::${blockName}${attrString} :::`\n    },\n  }\n}\n", "import type {\n  JSONContent,\n  MarkdownParseHelpers,\n  MarkdownParseResult,\n  MarkdownRendererHelpers,\n  MarkdownToken,\n  MarkdownTokenizer,\n} from '../../types.js'\nimport { parseAttributes as defaultParseAttributes } from './parseAttributes.js'\nimport { serializeAttributes as defaultSerializeAttributes } from './serializeAttributes.js'\n\nexport interface BlockMarkdownSpecOptions {\n  /** The Tiptap node name this spec is for */\n  nodeName: string\n  /** The markdown syntax name (defaults to nodeName if not provided) */\n  name?: string\n  /** Function to extract content from the node for serialization */\n  getContent?: (token: MarkdownToken) => string\n  /** Function to parse attributes from the attribute string */\n  parseAttributes?: (attrString: string) => Record<string, any>\n  /** Function to serialize attributes to string */\n  serializeAttributes?: (attrs: Record<string, any>) => string\n  /** Default attributes to apply when parsing */\n  defaultAttributes?: Record<string, any>\n  /** Content type: 'block' allows paragraphs/lists/etc, 'inline' only allows bold/italic/links/etc */\n  content?: 'block' | 'inline'\n  /** Allowlist of attributes to include in markdown (if not provided, all attributes are included) */\n  allowedAttributes?: string[]\n}\n\n/**\n * Creates a complete markdown spec for block-level nodes using Pandoc syntax.\n *\n * The generated spec handles:\n * - Parsing blocks with `:::blockName {attributes}` syntax\n * - Extracting and parsing attributes\n * - Rendering blocks back to markdown with proper formatting\n * - Nested content support\n *\n * @param options - Configuration for the block markdown spec\n * @returns Complete markdown specification object\n *\n * @example\n * ```ts\n * const calloutSpec = createBlockMarkdownSpec({\n *   nodeName: 'callout',\n *   defaultAttributes: { type: 'info' },\n *   allowedAttributes: ['type', 'title'] // Only these get rendered to markdown\n * })\n *\n * // Usage in extension:\n * export const Callout = Node.create({\n *   // ... other config\n *   markdown: calloutSpec\n * })\n * ```\n */\nexport function createBlockMarkdownSpec(options: BlockMarkdownSpecOptions): {\n  parseMarkdown: (token: MarkdownToken, h: MarkdownParseHelpers) => MarkdownParseResult\n  markdownTokenizer: MarkdownTokenizer\n  renderMarkdown: (node: JSONContent, h: MarkdownRendererHelpers) => string\n} {\n  const {\n    nodeName,\n    name: markdownName,\n    getContent,\n    parseAttributes = defaultParseAttributes,\n    serializeAttributes = defaultSerializeAttributes,\n    defaultAttributes = {},\n    content = 'block',\n    allowedAttributes,\n  } = options\n\n  // Use markdownName for syntax, fallback to nodeName\n  const blockName = markdownName || nodeName\n\n  // Helper function to filter attributes based on allowlist\n  const filterAttributes = (attrs: Record<string, any>) => {\n    if (!allowedAttributes) {\n      return attrs\n    }\n\n    const filtered: Record<string, any> = {}\n    allowedAttributes.forEach(key => {\n      if (key in attrs) {\n        filtered[key] = attrs[key]\n      }\n    })\n    return filtered\n  }\n\n  return {\n    parseMarkdown: (token, h) => {\n      let nodeContent: JSONContent[]\n\n      if (getContent) {\n        const contentResult = getContent(token)\n        // If getContent returns a string, wrap it in a text node\n        nodeContent =\n          typeof contentResult === 'string'\n            ? [{ type: 'text', text: contentResult }]\n            : contentResult\n      } else if (content === 'block') {\n        nodeContent = h.parseChildren(token.tokens || [])\n      } else {\n        nodeContent = h.parseInline(token.tokens || [])\n      }\n\n      const attrs = { ...defaultAttributes, ...token.attributes }\n\n      return h.createNode(nodeName, attrs, nodeContent)\n    },\n\n    markdownTokenizer: {\n      name: nodeName,\n      level: 'block' as const,\n      start(src) {\n        const regex = new RegExp(`^:::${blockName}`, 'm')\n        const index = src.match(regex)?.index\n        return index !== undefined ? index : -1\n      },\n      tokenize(src, _tokens, lexer) {\n        // Match the opening tag with optional attributes\n        const openingRegex = new RegExp(`^:::${blockName}(?:\\\\s+\\\\{([^}]*)\\\\})?\\\\s*\\\\n`)\n        const openingMatch = src.match(openingRegex)\n\n        if (!openingMatch) {\n          return undefined\n        }\n\n        const [openingTag, attrString = ''] = openingMatch\n        const attributes = parseAttributes(attrString)\n\n        // Find the matching closing tag by tracking nesting level\n        let level = 1\n        const position = openingTag.length\n        let matchedContent = ''\n\n        // Pattern to match any block opening (:::word) or closing (:::)\n        const blockPattern = /^:::([\\w-]*)(\\s.*)?/gm\n        const remaining = src.slice(position)\n\n        blockPattern.lastIndex = 0\n\n        // run until no more matches are found\n        for (;;) {\n          const match = blockPattern.exec(remaining)\n          if (match === null) {\n            break\n          }\n          const matchPos = match.index\n          const blockType = match[1] // Empty string for closing tag, block name for opening\n\n          if (match[2]?.endsWith(':::')) {\n            // this is an atom ::: node, we skip it\n            continue\n          }\n\n          if (blockType) {\n            // Opening tag found - increase level\n            level += 1\n          } else {\n            // Closing tag found - decrease level\n            level -= 1\n\n            if (level === 0) {\n              // Found our matching closing tag\n              // Don't trim yet - keep newlines for tokenizer regex matching\n              const rawContent = remaining.slice(0, matchPos)\n              matchedContent = rawContent.trim()\n              const fullMatch = src.slice(0, position + matchPos + match[0].length)\n\n              // Tokenize the content\n              let contentTokens: MarkdownToken[] = []\n              if (matchedContent) {\n                if (content === 'block') {\n                  // Use rawContent for tokenization to preserve line boundaries for regex matching\n                  contentTokens = lexer.blockTokens(rawContent)\n\n                  // Parse inline tokens for any token that has text content but no tokens\n                  contentTokens.forEach(token => {\n                    if (token.text && (!token.tokens || token.tokens.length === 0)) {\n                      token.tokens = lexer.inlineTokens(token.text)\n                    }\n                  })\n\n                  // Clean up empty trailing paragraphs\n                  while (contentTokens.length > 0) {\n                    const lastToken = contentTokens[contentTokens.length - 1]\n                    if (\n                      lastToken.type === 'paragraph' &&\n                      (!lastToken.text || lastToken.text.trim() === '')\n                    ) {\n                      contentTokens.pop()\n                    } else {\n                      break\n                    }\n                  }\n                } else {\n                  contentTokens = lexer.inlineTokens(matchedContent)\n                }\n              }\n\n              return {\n                type: nodeName,\n                raw: fullMatch,\n                attributes,\n                content: matchedContent,\n                tokens: contentTokens,\n              }\n            }\n          }\n        }\n\n        // No matching closing tag found\n        return undefined\n      },\n    },\n\n    renderMarkdown: (node, h) => {\n      const filteredAttrs = filterAttributes(node.attrs || {})\n      const attrs = serializeAttributes(filteredAttrs)\n      const attrString = attrs ? ` {${attrs}}` : ''\n      const renderedContent = h.renderChildren(node.content || [], '\\n\\n')\n\n      return `:::${blockName}${attrString}\\n\\n${renderedContent}\\n\\n:::`\n    },\n  }\n}\n", "import { tokenizeAttributes } from './tokenizeAttributes.js'\n\nexport function parseShortcodeAttributes(attrString: string): Record<string, any> {\n  const attributes: Record<string, any> = {}\n\n  tokenizeAttributes(attrString, 'shortcode').forEach(token => {\n    if (token.type === 'keyValue') {\n      attributes[token.name] = token.value\n    }\n  })\n\n  return attributes\n}\n", "import type {\n  JSONContent,\n  MarkdownParseHelpers,\n  MarkdownParseResult,\n  MarkdownToken,\n  MarkdownTokenizer,\n} from '../../types.js'\nimport { parseShortcodeAttributes } from './parseShortcodeAttributes.js'\n\n/**\n * Serialize attributes back to shortcode format\n * Always quotes all values with double quotes\n */\nfunction serializeShortcodeAttributes(attrs: Record<string, any>): string {\n  return Object.entries(attrs)\n    .filter(([, value]) => value !== undefined && value !== null)\n    .map(([key, value]) => `${key}=\"${value}\"`)\n    .join(' ')\n}\n\n/**\n * Configuration for an allowed attribute in markdown serialization.\n * Can be a simple string (attribute name) or an object with additional options.\n */\nexport type AllowedAttribute =\n  | string\n  | {\n      /** The attribute name */\n      name: string\n      /**\n       * If provided, the attribute will be skipped during serialization when its value\n       * equals this default value. This keeps markdown output clean by omitting\n       * attributes that have their default values.\n       */\n      skipIfDefault?: any\n    }\n\nexport interface InlineMarkdownSpecOptions {\n  /** The Tiptap node name this spec is for */\n  nodeName: string\n  /** The shortcode name (defaults to nodeName if not provided) */\n  name?: string\n  /** Function to extract content from the node for serialization */\n  getContent?: (node: any) => string\n  /** Function to parse attributes from the attribute string */\n  parseAttributes?: (attrString: string) => Record<string, any>\n  /** Function to serialize attributes to string */\n  serializeAttributes?: (attrs: Record<string, any>) => string\n  /** Default attributes to apply when parsing */\n  defaultAttributes?: Record<string, any>\n  /** Whether this is a self-closing shortcode (no content, like [emoji name=party]) */\n  selfClosing?: boolean\n  /**\n   * Allowlist of attributes to include in markdown serialization.\n   * If not provided, all attributes are included.\n   *\n   * Each item can be either:\n   * - A string: the attribute name (always included if present)\n   * - An object: `{ name: string, skipIfDefault?: any }` for conditional inclusion\n   *\n   * @example\n   * // Simple string attributes (backward compatible)\n   * allowedAttributes: ['id', 'label']\n   *\n   * // Mixed with conditional attributes\n   * allowedAttributes: [\n   *   'id',\n   *   'label',\n   *   { name: 'mentionSuggestionChar', skipIfDefault: '@' }\n   * ]\n   */\n  allowedAttributes?: AllowedAttribute[]\n}\n\n/**\n * Creates a complete markdown spec for inline nodes using attribute syntax.\n *\n * The generated spec handles:\n * - Parsing shortcode syntax with `[nodeName attributes]content[/nodeName]` format\n * - Self-closing shortcodes like `[emoji name=party_popper]`\n * - Extracting and parsing attributes from the opening tag\n * - Rendering inline elements back to shortcode markdown\n * - Supporting both content-based and self-closing inline elements\n *\n * @param options - Configuration for the inline markdown spec\n * @returns Complete markdown specification object\n *\n * @example\n * ```ts\n * // Self-closing mention: [mention id=\"madonna\" label=\"Madonna\"]\n * const mentionSpec = createInlineMarkdownSpec({\n *   nodeName: 'mention',\n *   selfClosing: true,\n *   defaultAttributes: { type: 'user' },\n *   allowedAttributes: ['id', 'label'] // Only these get rendered to markdown\n * })\n *\n * // Self-closing emoji: [emoji name=\"party_popper\"]\n * const emojiSpec = createInlineMarkdownSpec({\n *   nodeName: 'emoji',\n *   selfClosing: true,\n *   allowedAttributes: ['name']\n * })\n *\n * // With content: [highlight color=\"yellow\"]text[/highlight]\n * const highlightSpec = createInlineMarkdownSpec({\n *   nodeName: 'highlight',\n *   selfClosing: false,\n *   allowedAttributes: ['color', 'style']\n * })\n *\n * // Usage in extension:\n * export const Mention = Node.create({\n *   name: 'mention', // Must match nodeName\n *   // ... other config\n *   markdown: mentionSpec\n * })\n * ```\n */\nexport function createInlineMarkdownSpec(options: InlineMarkdownSpecOptions): {\n  parseMarkdown: (token: MarkdownToken, h: MarkdownParseHelpers) => MarkdownParseResult\n  markdownTokenizer: MarkdownTokenizer\n  renderMarkdown: (node: JSONContent) => string\n} {\n  const {\n    nodeName,\n    name: shortcodeName,\n    getContent,\n    parseAttributes = parseShortcodeAttributes,\n    serializeAttributes = serializeShortcodeAttributes,\n    defaultAttributes = {},\n    selfClosing = false,\n    allowedAttributes,\n  } = options\n\n  // Use shortcodeName for markdown syntax, fallback to nodeName\n  const shortcode = shortcodeName || nodeName\n\n  // Helper function to filter attributes based on allowlist\n  const filterAttributes = (attrs: Record<string, any>) => {\n    if (!allowedAttributes) {\n      return attrs\n    }\n\n    const filtered: Record<string, any> = {}\n    allowedAttributes.forEach(attr => {\n      // Handle both string and object formats for backward compatibility\n      const attrName = typeof attr === 'string' ? attr : attr.name\n      const skipIfDefault = typeof attr === 'string' ? undefined : attr.skipIfDefault\n\n      if (attrName in attrs) {\n        const value = attrs[attrName]\n\n        // Skip if value equals the default (when skipIfDefault is specified)\n        if (skipIfDefault !== undefined && value === skipIfDefault) {\n          return\n        }\n\n        filtered[attrName] = value\n      }\n    })\n    return filtered\n  }\n\n  // Escape special regex characters in shortcode name\n  const escapedShortcode = shortcode.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&')\n\n  return {\n    parseMarkdown: (token: MarkdownToken, h: MarkdownParseHelpers) => {\n      const attrs = { ...defaultAttributes, ...token.attributes }\n\n      if (selfClosing) {\n        // Self-closing nodes like mentions are atomic - no content\n        return h.createNode(nodeName, attrs)\n      }\n\n      // Nodes with content\n      const content = getContent ? getContent(token) : token.content || ''\n      if (content) {\n        // For inline content, create text nodes using the proper helper\n        return h.createNode(nodeName, attrs, [h.createTextNode(content)])\n      }\n      return h.createNode(nodeName, attrs, [])\n    },\n\n    markdownTokenizer: {\n      name: nodeName,\n      level: 'inline' as const,\n      start(src: string) {\n        // Create a non-global version for finding the start position\n        const startPattern = selfClosing\n          ? new RegExp(`\\\\[${escapedShortcode}\\\\s*[^\\\\]]*\\\\]`)\n          : new RegExp(`\\\\[${escapedShortcode}\\\\s*[^\\\\]]*\\\\][\\\\s\\\\S]*?\\\\[\\\\/${escapedShortcode}\\\\]`)\n\n        const match = src.match(startPattern)\n        const index = match?.index\n        return index !== undefined ? index : -1\n      },\n      tokenize(src, _tokens, _lexer) {\n        // Use non-global regex to match from the start of the string\n        const tokenPattern = selfClosing\n          ? new RegExp(`^\\\\[${escapedShortcode}\\\\s*([^\\\\]]*)\\\\]`)\n          : new RegExp(\n              `^\\\\[${escapedShortcode}\\\\s*([^\\\\]]*)\\\\]([\\\\s\\\\S]*?)\\\\[\\\\/${escapedShortcode}\\\\]`,\n            )\n\n        const match = src.match(tokenPattern)\n\n        if (!match) {\n          return undefined\n        }\n\n        let content = ''\n        let attrString = ''\n\n        if (selfClosing) {\n          // Self-closing: [shortcode attr=\"value\"]\n          const [, attrs] = match\n          attrString = attrs\n        } else {\n          // With content: [shortcode attr=\"value\"]content[/shortcode]\n          const [, attrs, contentMatch] = match\n          attrString = attrs\n          content = contentMatch || ''\n        }\n\n        // Parse attributes from the attribute string\n        const attributes = parseAttributes(attrString.trim())\n\n        return {\n          type: nodeName,\n          raw: match[0],\n          content: content.trim(),\n          attributes,\n        }\n      },\n    },\n\n    renderMarkdown: (node: JSONContent) => {\n      let content = ''\n      if (getContent) {\n        content = getContent(node)\n      } else if (node.content && node.content.length > 0) {\n        // Extract text from content array for inline nodes\n        content = node.content\n          .filter((child: any) => child.type === 'text')\n          .map((child: any) => child.text)\n          .join('')\n      }\n\n      const filteredAttrs = filterAttributes(node.attrs || {})\n      const attrs = serializeAttributes(filteredAttrs)\n      const attrString = attrs ? ` ${attrs}` : ''\n\n      if (selfClosing) {\n        return `[${shortcode}${attrString}]`\n      }\n\n      return `[${shortcode}${attrString}]${content}[/${shortcode}]`\n    },\n  }\n}\n", "/**\n * @fileoverview Utility for parsing indented markdown blocks with hierarchical nesting.\n *\n * This utility handles the complex logic of parsing markdown blocks that can contain\n * nested content based on indentation levels, maintaining proper hierarchical structure\n * for lists, task lists, and other indented block types.\n */\n\nexport interface ParsedBlock {\n  type: string\n  raw: string\n  mainContent: string\n  indentLevel: number\n  nestedContent?: string\n  nestedTokens?: any[]\n  [key: string]: any\n}\n\nexport interface BlockParserConfig {\n  /** Regex pattern to match block items */\n  itemPattern: RegExp\n  /** Function to extract data from regex match */\n  extractItemData: (match: RegExpMatchArray) => {\n    mainContent: string\n    indentLevel: number\n    [key: string]: any\n  }\n  /** Function to create the final token */\n  createToken: (data: any, nestedTokens?: any[]) => ParsedBlock\n  /** Base indentation to remove from nested content (default: 2 spaces) */\n  baseIndentSize?: number\n  /**\n   * Custom parser for nested content. If provided, this will be called instead\n   * of the default lexer.blockTokens() for parsing nested content.\n   * This allows recursive parsing of the same block type.\n   */\n  customNestedParser?: (dedentedContent: string) => any[] | undefined\n}\n\nfunction dedentLine(line: string, indentSize: number) {\n  return line.replace(/^[ \\t]*/, whitespace => {\n    const tabSize = 4\n    let columns = 0\n\n    for (const character of whitespace) {\n      columns += character === '\\t' ? tabSize - (columns % tabSize) : 1\n    }\n\n    return ' '.repeat(Math.max(0, columns - indentSize))\n  })\n}\n\nfunction continuesParagraph(line: string, blockTokens: (src: string) => any[]) {\n  // \"text\" simulates an open paragraph and is never included in the result.\n  const source = `text\\n${line}\\n`\n  const token = blockTokens(source)[0]\n\n  return (token?.type === 'paragraph' || token?.type === 'text') && token.raw === source\n}\n\n/** Joins paragraph continuation lines and leaves nested blocks for separate parsing. */\nfunction parseContinuation(\n  mainContent: string,\n  nestedContent: string,\n  lexer: {\n    blockTokens: (src: string) => any[]\n    isParagraphContinuation?: (line: string) => boolean\n  },\n) {\n  const lines = nestedContent.split('\\n')\n  const isContinuation =\n    lexer.isParagraphContinuation ?? (line => continuesParagraph(line, lexer.blockTokens))\n  // Number of leading lines to merge into the opening paragraph.\n  let continuationLength = 0\n\n  for (const line of lines) {\n    if (!line.trim() || !isContinuation(line)) {\n      break\n    }\n\n    continuationLength += 1\n  }\n\n  return {\n    mainContent: [\n      mainContent,\n      ...lines.slice(0, continuationLength).map(line => line.trimStart()),\n    ].join('\\n'),\n    nestedContent: lines.slice(continuationLength).join('\\n'),\n  }\n}\n\n/**\n * Parses markdown text into hierarchical indented blocks with proper nesting.\n *\n * This utility handles:\n * - Line-by-line parsing with pattern matching\n * - Hierarchical nesting based on indentation levels\n * - Nested content collection and parsing\n * - Empty line handling\n * - Content dedenting for nested blocks\n *\n * The key difference from flat parsing is that this maintains the hierarchical\n * structure where nested items become `nestedTokens` of their parent items,\n * rather than being flattened into a single array.\n *\n * @param src - The markdown source text to parse\n * @param config - Configuration object defining how to parse and create tokens\n * @param lexer - Markdown lexer for parsing nested content\n * @returns Parsed result with hierarchical items, or undefined if no matches\n *\n * @example\n * ```ts\n * const result = parseIndentedBlocks(src, {\n *   itemPattern: /^(\\s*)([-+*])\\s+\\[([ xX])\\]\\s+(.*)$/,\n *   extractItemData: (match) => ({\n *     indentLevel: match[1].length,\n *     mainContent: match[4],\n *     checked: match[3].toLowerCase() === 'x'\n *   }),\n *   createToken: (data, nestedTokens) => ({\n *     type: 'taskItem',\n *     checked: data.checked,\n *     text: data.mainContent,\n *     nestedTokens\n *   })\n * }, lexer)\n * ```\n */\nexport function parseIndentedBlocks(\n  src: string,\n  config: BlockParserConfig,\n  lexer: {\n    inlineTokens: (src: string) => any[]\n    blockTokens: (src: string) => any[]\n    isParagraphContinuation?: (line: string) => boolean\n  },\n):\n  | {\n      items: ParsedBlock[]\n      raw: string\n    }\n  | undefined {\n  const lines = src.split('\\n')\n  const items: ParsedBlock[] = []\n  let totalRaw = ''\n  let i = 0\n  const baseIndentSize = config.baseIndentSize || 2\n\n  while (i < lines.length) {\n    const currentLine = lines[i]\n    const itemMatch = currentLine.match(config.itemPattern)\n\n    if (!itemMatch) {\n      // Not a matching item - stop if we have items, otherwise this isn't our block type\n      if (items.length > 0) {\n        break\n      } else if (currentLine.trim() === '') {\n        i += 1\n        totalRaw = `${totalRaw}${currentLine}\\n`\n        continue\n      } else {\n        return undefined\n      }\n    }\n\n    const itemData = config.extractItemData(itemMatch)\n    const { indentLevel, mainContent } = itemData\n    totalRaw = `${totalRaw}${currentLine}\\n`\n\n    // Collect content for this item (including nested items)\n    const itemContent = [mainContent] // Start with the main text\n    i += 1\n\n    // Look ahead for nested content (indented more than current item)\n    while (i < lines.length) {\n      const nextLine = lines[i]\n\n      if (nextLine.trim() === '') {\n        // Empty line - might be end of nested content\n        const nextNonEmptyIndex = lines.slice(i + 1).findIndex(l => l.trim() !== '')\n        if (nextNonEmptyIndex === -1) {\n          // No more content\n          break\n        }\n\n        const nextNonEmpty = lines[i + 1 + nextNonEmptyIndex]\n        const nextIndent = nextNonEmpty.match(/^(\\s*)/)?.[1]?.length || 0\n\n        if (nextIndent > indentLevel) {\n          // Nested content continues after empty line\n          itemContent.push(nextLine)\n          totalRaw = `${totalRaw}${nextLine}\\n`\n          i += 1\n          continue\n        } else {\n          // End of nested content\n          break\n        }\n      }\n\n      const nextIndent = nextLine.match(/^(\\s*)/)?.[1]?.length || 0\n\n      if (nextIndent > indentLevel) {\n        // This is nested content for the current item\n        itemContent.push(nextLine)\n        totalRaw = `${totalRaw}${nextLine}\\n`\n        i += 1\n      } else {\n        // Same or less indentation - this belongs to parent level\n        break\n      }\n    }\n\n    // Parse nested content if present\n    let nestedTokens: any[] | undefined\n    const nestedContent = itemContent.slice(1)\n\n    if (nestedContent.length > 0) {\n      const continuation = parseContinuation(\n        mainContent,\n        nestedContent\n          .map(nestedLine => dedentLine(nestedLine, indentLevel + baseIndentSize))\n          .join('\\n'),\n        lexer,\n      )\n      itemData.mainContent = continuation.mainContent\n      const dedentedNested = continuation.nestedContent\n\n      if (dedentedNested.trim()) {\n        // Use custom nested parser if provided, otherwise fall back to default\n        if (config.customNestedParser) {\n          nestedTokens = config.customNestedParser(dedentedNested)\n        } else {\n          nestedTokens = lexer.blockTokens(dedentedNested)\n        }\n      }\n    }\n\n    // Create the token using the provided factory function\n    const token = config.createToken(itemData, nestedTokens)\n    items.push(token)\n  }\n\n  if (items.length === 0) {\n    return undefined\n  }\n\n  return {\n    items,\n    raw: totalRaw.slice(0, src.length),\n  }\n}\n", "import type { JSONContent } from '@tiptap/core'\n\n/**\n * @fileoverview Utility functions for rendering nested content in markdown.\n *\n * This module provides reusable utilities for extensions that need to render\n * content with a prefix on the main line and properly indented nested content.\n */\n\n/**\n * Utility function for rendering content with a main line prefix and nested indented content.\n *\n * This function handles the common pattern of rendering content with:\n * 1. A main line with a prefix (like \"- \" for lists, \"> \" for blockquotes, etc.)\n * 2. Nested content that gets indented properly\n *\n * @param node - The ProseMirror node representing the content\n * @param h - The markdown renderer helper\n * @param prefixOrGenerator - Either a string prefix or a function that generates the prefix from context\n * @param ctx - Optional context object (used when prefixOrGenerator is a function)\n * @param options - Optional rendering options\n * @param options.alignNestedToPrefix - Indent nested content to the width of the prefix\n * instead of the configured indent size, when the configured one is narrower\n * @param options.indentMainContent - Indent continuation lines in the opening paragraph\n * @returns The rendered markdown string\n *\n * @example\n * ```ts\n * // For a bullet list item with static prefix\n * return renderNestedMarkdownContent(node, h, '- ')\n *\n * // For a task item with static prefix\n * const prefix = `- [${node.attrs?.checked ? 'x' : ' '}] `\n * return renderNestedMarkdownContent(node, h, prefix)\n *\n * // For an ordered list item, where the nested block has to line up with the marker\n * return renderNestedMarkdownContent(node, h, '10. ', ctx, { alignNestedToPrefix: true })\n *\n * // For a blockquote with static prefix\n * return renderNestedMarkdownContent(node, h, '> ')\n *\n * // For content with dynamic prefix based on context\n * return renderNestedMarkdownContent(node, h, ctx => {\n *   if (ctx.parentType === 'orderedList') {\n *     return `${ctx.index + 1}. `\n *   }\n *   return '- '\n * }, ctx)\n *\n * // Custom extension example\n * const CustomContainer = Node.create({\n *   name: 'customContainer',\n *   // ... other config\n *   markdown: {\n *     render: (node, h) => {\n *       const type = node.attrs?.type || 'info'\n *       return renderNestedMarkdownContent(node, h, `[${type}] `)\n *     }\n *   }\n * })\n * ```\n */\nconst TAB_STOP = 4\n\n/** Width of indentation in Markdown columns, where a tab runs to the next tab stop. */\nfunction columnWidth(text: string): number {\n  let width = 0\n\n  for (const character of text) {\n    width = character === '\\t' ? width + TAB_STOP - (width % TAB_STOP) : width + 1\n  }\n\n  return width\n}\n\nexport function renderNestedMarkdownContent(\n  node: JSONContent,\n  h: {\n    renderChildren: (nodes: JSONContent[]) => string\n    renderChild?: (node: JSONContent, index: number) => string\n    indent: (text: string) => string\n  },\n  prefixOrGenerator: string | ((ctx: any) => string),\n  ctx?: any,\n  options?: {\n    /** See the `@param` note above. */\n    alignNestedToPrefix?: boolean\n    /** Indent continuation lines in the opening paragraph. */\n    indentMainContent?: boolean\n  },\n): string {\n  if (!node || !Array.isArray(node.content)) {\n    return ''\n  }\n\n  // Determine the prefix based on the input\n  const prefix =\n    typeof prefixOrGenerator === 'function' ? prefixOrGenerator(ctx) : prefixOrGenerator\n\n  const [content, ...children] = node.content\n\n  // Render the main content (typically a paragraph)\n  const mainContent = h.renderChildren([content])\n  const indentedMain = options?.indentMainContent\n    ? mainContent\n        .split('\\n')\n        .map((line, index) => (index === 0 ? line : h.indent(line)))\n        .join('\\n')\n    : mainContent\n  let output = `${prefix}${indentedMain}`\n\n  // Handle nested children with proper indentation\n  if (children && children.length > 0) {\n    children.forEach((child, index) => {\n      const childContent = h.renderChild?.(child, index + 1) ?? h.renderChildren([child])\n      if (childContent !== undefined && childContent !== null) {\n        // Split the child content by lines and indent each line\n        const indentLine = (line: string) => {\n          if (!options?.alignNestedToPrefix) {\n            return h.indent(line)\n          }\n\n          // Keep the configured indentation when it already reaches the\n          // content column, so `Markdown.indentation` still applies. A tab\n          // runs to the next tab stop, so it is wider than its one character.\n          const configured = h.indent('')\n          const prefixWidth = columnWidth(prefix)\n\n          return (\n            (columnWidth(configured) >= prefixWidth ? configured : ' '.repeat(prefixWidth)) + line\n          )\n        }\n\n        const indentedChild = childContent\n          .split('\\n')\n          .map(line => (line ? indentLine(line) : indentLine('')))\n          .join('\\n')\n\n        output += child.type === 'paragraph' ? `\\n\\n${indentedChild}` : `\\n${indentedChild}`\n      }\n    })\n  }\n\n  return output\n}\n", "/**\n * @fileoverview Markdown utilities for creating standardized markdown specs.\n *\n * This module provides utilities for creating complete markdown specifications\n * for different types of nodes using unified syntax patterns.\n */\n\nexport * from './createAtomBlockMarkdownSpec.js'\nexport * from './createBlockMarkdownSpec.js'\nexport * from './createInlineMarkdownSpec.js'\nexport * from './parseAttributes.js'\nexport * from './parseIndentedBlocks.js'\nexport * from './renderNestedMarkdownContent.js'\nexport * from './serializeAttributes.js'\n", "import { attrsEqual } from './attrsEqual.js'\n\n/**\n * Shape accepted by marksEqual, works with both JSONContent marks\n * (`{ type: 'bold' }`) and ProseMirror Mark objects (`{ type: MarkType }`).\n */\nexport type MarkLike = {\n  type: string | { name: string }\n  attrs?: Record<string, any> | null\n}\n\nfunction markTypeName(mark: MarkLike): string {\n  return typeof mark.type === 'string' ? mark.type : mark.type.name\n}\n\n/**\n * Compare two arrays of mark objects for equality (order-insensitive).\n * Marks are matched by type name and attributes (via attrsEqual),\n * so key ordering in attrs does not matter, nor does mark array order.\n */\nexport function marksEqual(a: readonly MarkLike[], b: readonly MarkLike[]): boolean {\n  if (a.length !== b.length) {\n    return false\n  }\n\n  // Marks are matched by (type, attrs) identity, so greedy first-match works.\n  const consumed = Array.from({ length: b.length }, () => false)\n\n  return a.every(markA => {\n    const nameA = markTypeName(markA)\n\n    const idx = b.findIndex(\n      (markB, i) =>\n        !consumed[i] && nameA === markTypeName(markB) && attrsEqual(markA.attrs, markB.attrs),\n    )\n\n    if (idx === -1) {\n      return false\n    }\n\n    consumed[idx] = true\n    return true\n  })\n}\n", "import { isPlainObject } from './isPlainObject.js'\n\nexport function mergeDeep(\n  target: Record<string, any>,\n  source: Record<string, any>,\n): Record<string, any> {\n  const output = { ...target }\n\n  if (isPlainObject(target) && isPlainObject(source)) {\n    Object.keys(source).forEach(key => {\n      if (isPlainObject(source[key]) && isPlainObject(target[key])) {\n        output[key] = mergeDeep(target[key], source[key])\n      } else {\n        output[key] = source[key]\n      }\n    })\n  }\n\n  return output\n}\n", "import type { Mark } from '@tiptap/pm/model'\nimport type { ViewMutationRecord } from '@tiptap/pm/view'\n\nimport type { Editor } from './Editor.js'\nimport type { MarkViewProps, MarkViewRendererOptions } from './types.js'\nimport { isAndroid, isiOS } from './utilities/index.js'\n\nexport function updateMarkViewAttributes(\n  checkMark: Mark,\n  editor: Editor,\n  attrs: Record<string, any> = {},\n): void {\n  const { state } = editor\n  const { doc, tr } = state\n  const thisMark = checkMark\n\n  doc.descendants((node, pos) => {\n    const from = tr.mapping.map(pos)\n    const to = tr.mapping.map(pos) + node.nodeSize\n    let foundMark: Mark | null = null\n\n    // find the mark on the current node\n    node.marks.forEach(mark => {\n      if (mark !== thisMark) {\n        return false\n      }\n\n      foundMark = mark\n    })\n\n    if (!foundMark) {\n      return\n    }\n\n    // check if we need to update given the attributes\n    let needsUpdate = false\n    Object.keys(attrs).forEach(k => {\n      if (attrs[k] !== foundMark!.attrs[k]) {\n        needsUpdate = true\n      }\n    })\n\n    if (needsUpdate) {\n      const updatedMark = checkMark.type.create({\n        ...checkMark.attrs,\n        ...attrs,\n      })\n\n      tr.removeMark(from, to, checkMark.type)\n      tr.addMark(from, to, updatedMark)\n    }\n  })\n\n  if (tr.docChanged) {\n    editor.view.dispatch(tr)\n  }\n}\n\nexport class MarkView<\n  Component,\n  Options extends MarkViewRendererOptions = MarkViewRendererOptions,\n> {\n  component: Component\n  editor: Editor\n  options: Options\n  mark: MarkViewProps['mark']\n  HTMLAttributes: MarkViewProps['HTMLAttributes']\n\n  constructor(component: Component, props: MarkViewProps, options?: Partial<Options>) {\n    this.component = component\n    this.editor = props.editor\n    this.options = { ...options } as Options\n    this.mark = props.mark\n    this.HTMLAttributes = props.HTMLAttributes\n  }\n\n  get dom(): HTMLElement {\n    return this.editor.view.dom\n  }\n\n  get contentDOM(): HTMLElement | null {\n    return null\n  }\n\n  /**\n   * Update the attributes of the mark in the document.\n   * @param attrs The attributes to update.\n   */\n  updateAttributes(attrs: Record<string, any>, checkMark?: Mark): void {\n    updateMarkViewAttributes(checkMark || this.mark, this.editor, attrs)\n  }\n\n  ignoreMutation(mutation: ViewMutationRecord): boolean {\n    if (!this.dom || !this.contentDOM) {\n      return true\n    }\n\n    if (typeof this.options.ignoreMutation === 'function') {\n      return this.options.ignoreMutation({ mutation })\n    }\n\n    if (mutation.type === 'selection') {\n      return false\n    }\n\n    if (\n      this.contentDOM.contains(mutation.target) &&\n      mutation.type === 'childList' &&\n      (isiOS() || isAndroid()) &&\n      this.editor.isFocused\n    ) {\n      const changedNodes = [\n        ...Array.from(mutation.addedNodes),\n        ...Array.from(mutation.removedNodes),\n      ] as HTMLElement[]\n\n      if (changedNodes.every(node => node.isContentEditable)) {\n        return false\n      }\n    }\n\n    if (this.contentDOM === mutation.target && mutation.type === 'attributes') {\n      return true\n    }\n\n    if (this.contentDOM.contains(mutation.target)) {\n      return false\n    }\n\n    return true\n  }\n}\n", "import type { Node as ProseMirrorNode, ResolvedPos } from '@tiptap/pm/model'\nimport { Fragment } from '@tiptap/pm/model'\nimport { closeHistory } from '@tiptap/pm/history'\nimport type { TextSelection } from '@tiptap/pm/state'\nimport { EditorState, Plugin } from '@tiptap/pm/state'\nimport { Transform } from '@tiptap/pm/transform'\n\nimport { CommandManager } from './CommandManager.js'\nimport type { Editor } from './Editor.js'\nimport { createChainableState } from './helpers/createChainableState.js'\nimport { getHTMLFromFragment } from './helpers/getHTMLFromFragment.js'\nimport { getTextContentFromNodes } from './helpers/getTextContentFromNodes.js'\nimport type {\n  CanCommands,\n  ChainedCommands,\n  ExtendedRegExpMatchArray,\n  Range,\n  SingleCommands,\n} from './types.js'\nimport { isRegExp } from './utilities/isRegExp.js'\n\nexport type InputRuleMatch = {\n  index: number\n  text: string\n  replaceWith?: string\n  match?: RegExpMatchArray\n  data?: Record<string, any>\n}\n\nexport type InputRuleFinder = RegExp | ((text: string) => InputRuleMatch | null)\n\nexport class InputRule {\n  find: InputRuleFinder\n\n  handler: (props: {\n    state: EditorState\n    range: Range\n    match: ExtendedRegExpMatchArray\n    commands: SingleCommands\n    chain: () => ChainedCommands\n    can: () => CanCommands\n  }) => void | null\n\n  undoable: boolean\n\n  constructor(config: {\n    find: InputRuleFinder\n    handler: (props: {\n      state: EditorState\n      range: Range\n      match: ExtendedRegExpMatchArray\n      commands: SingleCommands\n      chain: () => ChainedCommands\n      can: () => CanCommands\n    }) => void | null\n    undoable?: boolean\n  }) {\n    this.find = config.find\n    this.handler = config.handler\n    this.undoable = config.undoable ?? true\n  }\n}\n\nconst inputRuleMatcherHandler = (\n  text: string,\n  find: InputRuleFinder,\n): ExtendedRegExpMatchArray | null => {\n  if (isRegExp(find)) {\n    return find.exec(text)\n  }\n\n  const inputRuleMatch = find(text)\n\n  if (!inputRuleMatch) {\n    return null\n  }\n\n  const result: ExtendedRegExpMatchArray = [inputRuleMatch.text]\n\n  result.index = inputRuleMatch.index\n  result.input = text\n  result.data = inputRuleMatch.data\n\n  if (inputRuleMatch.replaceWith) {\n    if (!inputRuleMatch.text.includes(inputRuleMatch.replaceWith)) {\n      console.warn(\n        '[tiptap warn]: \"inputRuleMatch.replaceWith\" must be part of \"inputRuleMatch.text\".',\n      )\n    }\n\n    result.push(inputRuleMatch.replaceWith)\n  }\n\n  return result\n}\n\n/**\n * Prepares the typed text so the rule handler can inspect the resulting document.\n */\nfunction createRuleTransaction(config: {\n  editor: Editor\n  from: number\n  to: number\n  text: string\n  insertText?: boolean\n}) {\n  const { editor, from, to, text, insertText } = config\n\n  if (!insertText) {\n    return { inputTransaction: null, tr: editor.view.state.tr }\n  }\n\n  const inputTransaction = editor.view.state.tr.insertText(text, from, to)\n  const inputState = EditorState.create({\n    doc: inputTransaction.doc,\n    selection: inputTransaction.selection,\n    storedMarks: inputTransaction.storedMarks,\n  })\n\n  return { inputTransaction, tr: inputState.tr }\n}\n\n/**\n * Runs a matching rule and dispatches the typed text before its conversion.\n */\nfunction applyRule(config: {\n  editor: Editor\n  from: number\n  to: number\n  text: string\n  rule: InputRule\n  match: ExtendedRegExpMatchArray\n  plugin: Plugin\n  insertText?: boolean\n}): boolean {\n  const { editor, from, to, text, rule, match, plugin, insertText } = config\n  const { view } = editor\n  const { inputTransaction, tr } = createRuleTransaction({ editor, from, to, text, insertText })\n  const inputEnd = inputTransaction ? from + text.length : to\n  const state = createChainableState({\n    state: view.state,\n    transaction: tr,\n  })\n  const range = {\n    from: from - (match[0].length - text.length),\n    to: inputEnd,\n  }\n\n  const { commands, chain, can } = new CommandManager({\n    editor,\n    state,\n  })\n\n  const handler = rule.handler({\n    state,\n    range,\n    match,\n    commands,\n    chain,\n    can,\n  })\n\n  if (handler === null || !tr.steps.length) {\n    return false\n  }\n\n  if (inputTransaction) {\n    view.dispatch(inputTransaction)\n\n    if (!view.state.doc.eq(inputTransaction.doc)) {\n      return true\n    }\n  }\n\n  closeHistory(tr)\n  tr.setMeta('inputRule', true)\n\n  if (rule.undoable) {\n    tr.setMeta(plugin, {\n      transform: tr,\n      from,\n      to: inputEnd,\n      text,\n    })\n  }\n\n  view.dispatch(tr)\n  return true\n}\n\n/**\n * Checks that the part of a match already in the document has matching positions.\n */\nfunction matchesDocument($from: ResolvedPos, match: ExtendedRegExpMatchArray, text: string) {\n  // Leaf nodes can have different text and document lengths.\n  const matchedDocLength = match[0].length - text.length\n\n  if (matchedDocLength <= 0) {\n    return true\n  }\n\n  const matchStartOffset = $from.parentOffset - matchedDocLength\n\n  return (\n    matchStartOffset >= 0 &&\n    $from.parent.textBetween(matchStartOffset, $from.parentOffset) ===\n      match[0].slice(0, matchedDocLength)\n  )\n}\n\nfunction run(config: {\n  editor: Editor\n  from: number\n  to: number\n  text: string\n  rules: InputRule[]\n  plugin: Plugin\n  insertText?: boolean\n}): boolean {\n  const { editor, from, to, text, rules, plugin, insertText } = config\n  const { view } = editor\n\n  if (view.composing) {\n    return false\n  }\n\n  const $from = view.state.doc.resolve(from)\n\n  if (\n    // check for code node\n    $from.parent.type.spec.code ||\n    // check for code mark\n    !!($from.nodeBefore || $from.nodeAfter)?.marks.find(mark => mark.type.spec.code)\n  ) {\n    return false\n  }\n\n  const textBefore = getTextContentFromNodes($from) + text\n\n  for (const rule of rules) {\n    const match = inputRuleMatcherHandler(textBefore, rule.find)\n\n    if (!match || !matchesDocument($from, match, text)) {\n      continue\n    }\n\n    if (applyRule({ editor, from, to, text, rule, match, plugin, insertText })) {\n      return true\n    }\n  }\n\n  return false\n}\n\n/**\n * Create an input rules plugin. When enabled, it will cause text\n * input that matches any of the given rules to trigger the rule’s\n * action.\n */\nexport function inputRulesPlugin(props: { editor: Editor; rules: InputRule[] }): Plugin {\n  const { editor, rules } = props\n  const plugin = new Plugin({\n    state: {\n      init() {\n        return null\n      },\n      apply(tr, prev, state) {\n        const stored = tr.getMeta(plugin)\n\n        if (stored) {\n          return stored\n        }\n\n        if (prev && tr.getMeta('appendedTransaction')?.getMeta(plugin)) {\n          const transform = new Transform(prev.transform.before)\n\n          // Undo appended changes before reversing the input rule.\n          for (const step of [...prev.transform.steps, ...tr.steps]) {\n            transform.step(step)\n          }\n\n          return { ...prev, transform }\n        }\n\n        // if InputRule is triggered by insertContent()\n        const simulatedInputMeta = tr.getMeta('applyInputRules') as\n          | undefined\n          | {\n              from: number\n              text: string | ProseMirrorNode | Fragment\n            }\n        const isSimulatedInput = !!simulatedInputMeta\n\n        if (isSimulatedInput) {\n          setTimeout(() => {\n            let { text } = simulatedInputMeta\n\n            if (typeof text === 'string') {\n              text = text as string\n            } else {\n              text = getHTMLFromFragment(Fragment.from(text), state.schema)\n            }\n\n            const { from } = simulatedInputMeta\n            const to = from + text.length\n\n            run({\n              editor,\n              from,\n              to,\n              text,\n              rules,\n              plugin,\n            })\n          })\n        }\n\n        return tr.selectionSet || tr.docChanged ? null : prev\n      },\n    },\n\n    props: {\n      handleTextInput(view, from, to, text) {\n        return run({\n          editor,\n          from,\n          to,\n          text,\n          rules,\n          plugin,\n          insertText: true,\n        })\n      },\n\n      handleDOMEvents: {\n        compositionend: view => {\n          setTimeout(() => {\n            const { $cursor } = view.state.selection as TextSelection\n\n            if ($cursor) {\n              run({\n                editor,\n                from: $cursor.pos,\n                to: $cursor.pos,\n                text: '',\n                rules,\n                plugin,\n              })\n            }\n          })\n\n          return false\n        },\n      },\n\n      // add support for input rules to trigger on enter\n      // this is useful for example for code blocks\n      handleKeyDown(view, event) {\n        if (event.key !== 'Enter') {\n          return false\n        }\n\n        const { $cursor } = view.state.selection as TextSelection\n\n        if ($cursor) {\n          return run({\n            editor,\n            from: $cursor.pos,\n            to: $cursor.pos,\n            text: '\\n',\n            rules,\n            plugin,\n          })\n        }\n\n        return false\n      },\n    },\n\n    // @ts-ignore\n    isInputRules: true,\n  }) as Plugin\n\n  return plugin\n}\n", "import type { Plugin } from '@tiptap/pm/state'\n\nimport type { Editor } from './Editor.js'\nimport type { DecorationSpec } from './decorations/index.js'\nimport { getExtensionField } from './helpers/getExtensionField.js'\nimport type { ExtensionConfig, MarkConfig, NodeConfig } from './index.js'\nimport type { InputRule } from './InputRule.js'\nimport type { Mark } from './Mark.js'\nimport type { Node } from './Node.js'\nimport type { PasteRule } from './PasteRule.js'\nimport type {\n  AnyConfig,\n  DispatchTransactionProps,\n  EditorEvents,\n  Extensions,\n  GlobalAttributes,\n  JSONContent,\n  KeyboardShortcutCommand,\n  MarkdownParseHelpers,\n  MarkdownParseResult,\n  MarkdownRendererHelpers,\n  MarkdownToken,\n  MarkdownTokenizer,\n  ParentConfig,\n  RawCommands,\n  RenderContext,\n} from './types.js'\nimport { callOrReturn } from './utilities/callOrReturn.js'\nimport { mergeDeep } from './utilities/mergeDeep.js'\n\nexport interface ExtendableConfig<\n  Options = any,\n  Storage = any,\n  Config extends\n    | ExtensionConfig<Options, Storage>\n    | NodeConfig<Options, Storage>\n    | MarkConfig<Options, Storage>\n    | ExtendableConfig<Options, Storage> = ExtendableConfig<Options, Storage, any, any>,\n  PMType = any,\n> {\n  /**\n   * The extension name - this must be unique.\n   * It will be used to identify the extension.\n   *\n   * @example 'myExtension'\n   */\n  name: string\n\n  /**\n   * The priority of your extension. The higher, the earlier it will be called\n   * and will take precedence over other extensions with a lower priority.\n   * @default 100\n   * @example 101\n   */\n  priority?: number\n\n  /**\n   * This method will add options to this extension\n   * @see https://tiptap.dev/docs/editor/guide/custom-extensions#settings\n   * @example\n   * addOptions() {\n   *  return {\n   *    myOption: 'foo',\n   *    myOtherOption: 10,\n   * }\n   */\n  addOptions?: (this: { name: string; parent: ParentConfig<Config>['addOptions'] }) => Options\n\n  /**\n   * The default storage this extension can save data to.\n   * @see https://tiptap.dev/docs/editor/guide/custom-extensions#storage\n   * @example\n   * defaultStorage: {\n   *   prefetchedUsers: [],\n   *   loading: false,\n   * }\n   */\n  addStorage?: (this: {\n    name: string\n    options: Options\n    parent: ParentConfig<Config>['addStorage']\n  }) => Storage\n\n  /**\n   * This function adds globalAttributes to specific nodes.\n   * @see https://tiptap.dev/docs/editor/guide/custom-extensions#global-attributes\n   * @example\n   * addGlobalAttributes() {\n   *   return [\n   *     {\n           // Extend the following extensions\n   *       types: [\n   *         'heading',\n   *         'paragraph',\n   *       ],\n   *       // … with those attributes\n   *       attributes: {\n   *         textAlign: {\n   *           default: 'left',\n   *           renderHTML: attributes => ({\n   *             style: `text-align: ${attributes.textAlign}`,\n   *           }),\n   *           parseHTML: element => element.style.textAlign || 'left',\n   *         },\n   *       },\n   *     },\n   *   ]\n   * }\n   */\n  addGlobalAttributes?: (this: {\n    name: string\n    options: Options\n    storage: Storage\n    extensions: (Node | Mark)[]\n    parent: ParentConfig<Config>['addGlobalAttributes']\n  }) => GlobalAttributes\n\n  /**\n   * This function adds commands to the editor\n   * @see https://tiptap.dev/docs/editor/guide/custom-extensions#commands\n   * @example\n   * addCommands() {\n   *   return {\n   *     myCommand: () => ({ chain }) => chain().setMark('type', 'foo').run(),\n   *   }\n   * }\n   */\n  addCommands?: (this: {\n    name: string\n    options: Options\n    storage: Storage\n    editor: Editor\n    type: PMType\n    parent: ParentConfig<Config>['addCommands']\n  }) => Partial<RawCommands>\n\n  /**\n   * This function registers keyboard shortcuts.\n   * @see https://tiptap.dev/docs/editor/guide/custom-extensions#keyboard-shortcuts\n   * @example\n   * addKeyboardShortcuts() {\n   *   return {\n   *     'Mod-l': () => this.editor.commands.toggleBulletList(),\n   *   }\n   * },\n   */\n  addKeyboardShortcuts?: (this: {\n    name: string\n    options: Options\n    storage: Storage\n    editor: Editor\n    type: PMType\n    parent: ParentConfig<Config>['addKeyboardShortcuts']\n  }) => {\n    [key: string]: KeyboardShortcutCommand\n  }\n\n  /**\n   * This function adds input rules to the editor.\n   * @see https://tiptap.dev/docs/editor/guide/custom-extensions#input-rules\n   * @example\n   * addInputRules() {\n   *   return [\n   *     markInputRule({\n   *       find: inputRegex,\n   *       type: this.type,\n   *     }),\n   *   ]\n   * },\n   */\n  addInputRules?: (this: {\n    name: string\n    options: Options\n    storage: Storage\n    editor: Editor\n    type: PMType\n    parent: ParentConfig<Config>['addInputRules']\n  }) => InputRule[]\n\n  /**\n   * This function adds paste rules to the editor.\n   * @see https://tiptap.dev/docs/editor/guide/custom-extensions#paste-rules\n   * @example\n   * addPasteRules() {\n   *   return [\n   *     markPasteRule({\n   *       find: pasteRegex,\n   *       type: this.type,\n   *     }),\n   *   ]\n   * },\n   */\n  addPasteRules?: (this: {\n    name: string\n    options: Options\n    storage: Storage\n    editor: Editor\n    type: PMType\n    parent: ParentConfig<Config>['addPasteRules']\n  }) => PasteRule[]\n\n  /**\n   * This function adds Prosemirror plugins to the editor\n   * @see https://tiptap.dev/docs/editor/guide/custom-extensions#prosemirror-plugins\n   * @example\n   * addProseMirrorPlugins() {\n   *   return [\n   *     customPlugin(),\n   *   ]\n   * }\n   */\n  addProseMirrorPlugins?: (this: {\n    name: string\n    options: Options\n    storage: Storage\n    editor: Editor\n    type: PMType\n    parent: ParentConfig<Config>['addProseMirrorPlugins']\n  }) => Plugin[]\n\n  /**\n   * Adds editor decorations (node, inline, widget). Return a spec with a `create`\n   * function that builds instances via `Decoration.Node`/`Inline`/`Widget`. Use\n   * `shouldUpdate`, `update: 'changedRanges'` + `createInRange`, or `update: 'manual'` to control recomputation.\n   * @see https://tiptap.dev/docs/editor/core-concepts/decorations\n   * @example\n   * addDecorations() {\n   *   return {\n   *     create: ({ state }) =>\n   *       findChildren(state.doc, node => node.type.name === 'heading').map(\n   *         ({ pos, node }) =>\n   *           Decoration.Node(pos, pos + node.nodeSize, { class: 'is-heading' }),\n   *       ),\n   *   }\n   * }\n   *\n   * For framework widgets, use `ReactWidgetRenderer` or `VueWidgetRenderer`\n   * from the matching framework package. Give stateful widgets a stable key.\n   *\n   * `create` and `createInRange` must not throw. An exception escapes through\n   * `editor.commands.*` and stops the document from updating until it stops.\n   */\n  addDecorations?: (this: {\n    name: string\n    options: Options\n    storage: Storage\n    editor: Editor\n    type: PMType\n    parent: ParentConfig<Config>['addDecorations']\n  }) => DecorationSpec | null\n\n  /**\n   * This function transforms pasted HTML content before it's parsed.\n   * Extensions can use this to modify or clean up pasted HTML.\n   * The transformations are chained - each extension's transform receives\n   * the output from the previous extension's transform.\n   * @see https://tiptap.dev/docs/editor/guide/custom-extensions#transform-pasted-html\n   * @example\n   * transformPastedHTML(html) {\n   *   // Remove all style attributes\n   *   return html.replace(/style=\"[^\"]*\"/g, '')\n   * }\n   */\n  transformPastedHTML?: (\n    this: {\n      name: string\n      options: Options\n      storage: Storage\n      editor: Editor\n      type: PMType\n      parent: ParentConfig<Config>['transformPastedHTML']\n    },\n    html: string,\n  ) => string\n\n  /**\n   * This function adds additional extensions to the editor. This is useful for\n   * building extension kits.\n   * @example\n   * addExtensions() {\n   *   return [\n   *     BulletList,\n   *     OrderedList,\n   *     ListItem\n   *   ]\n   * }\n   */\n  addExtensions?: (this: {\n    name: string\n    options: Options\n    storage: Storage\n    parent: ParentConfig<Config>['addExtensions']\n  }) => Extensions\n\n  /**\n   * The markdown token name\n   *\n   * This is the name of the token that this extension uses to parse and render markdown and comes from the Marked Lexer.\n   *\n   * @see https://github.com/markedjs/marked/blob/master/src/Tokens.ts\n   *\n   */\n  markdownTokenName?: string\n\n  /**\n   * The parse function used by the markdown parser to convert markdown tokens to ProseMirror nodes.\n   *\n   * Bound to the configured extension instance, so `this.name`, `this.options`\n   * and `this.storage` are available even when parsing without an Editor.\n   */\n  parseMarkdown?: (\n    this: {\n      name: string\n      options: Options\n      storage: Storage\n      parent: ParentConfig<Config>['parseMarkdown']\n    },\n    token: MarkdownToken,\n    helpers: MarkdownParseHelpers,\n  ) => MarkdownParseResult\n\n  /**\n   * The serializer function used by the markdown serializer to convert ProseMirror nodes to markdown tokens.\n   *\n   * Bound to the configured extension instance, so `this.name`, `this.options`\n   * and `this.storage` are available even when serializing without an Editor.\n   */\n  renderMarkdown?: (\n    this: {\n      name: string\n      options: Options\n      storage: Storage\n      parent: ParentConfig<Config>['renderMarkdown']\n    },\n    node: JSONContent,\n    helpers: MarkdownRendererHelpers,\n    ctx: RenderContext,\n  ) => string\n\n  /**\n   * The markdown tokenizer responsible for turning a markdown string into tokens\n   *\n   * Custom tokenizers are only needed when you want to parse non-standard markdown token.\n   */\n  markdownTokenizer?: MarkdownTokenizer\n\n  /**\n   * Optional markdown options for indentation\n   */\n  markdownOptions?: {\n    /**\n     * Defines if this markdown element should indent it's child elements\n     */\n    indentsContent?: boolean\n\n    /**\n     * Lets a mark tell the Markdown serializer which inline HTML tags it can\n     * safely use when plain markdown delimiters would become ambiguous.\n     *\n     * This is mainly useful for overlapping marks. For example, bold followed\n     * by bold+italic followed by italic cannot always be written back with only\n     * `*` and `**` in a way that still parses correctly. In that case, the\n     * serializer can close the overlapping section with markdown and reopen the\n     * remaining tail with HTML instead.\n     *\n     * Example:\n     * - desired formatting: `**123` + `*456*` + `789 italic`\n     * - serialized result: `**123*456***<em>789</em>`\n     *\n     * If your extension defines custom mark names, set `htmlReopen` on that\n     * extension so the serializer can reuse its HTML form for overlap cases.\n     */\n    htmlReopen?: {\n      open: string\n      close: string\n    }\n  }\n\n  /**\n   * This function extends the schema of the node.\n   * @example\n   * extendNodeSchema() {\n   *   return {\n   *     group: 'inline',\n   *     selectable: false,\n   *   }\n   * }\n   */\n  extendNodeSchema?:\n    | ((\n        this: {\n          name: string\n          options: Options\n          storage: Storage\n          parent: ParentConfig<Config>['extendNodeSchema']\n        },\n        extension: Node,\n      ) => Record<string, any>)\n    | null\n\n  /**\n   * This function extends the schema of the mark.\n   * @example\n   * extendMarkSchema() {\n   *   return {\n   *     group: 'inline',\n   *     selectable: false,\n   *   }\n   * }\n   */\n  extendMarkSchema?:\n    | ((\n        this: {\n          name: string\n          options: Options\n          storage: Storage\n          parent: ParentConfig<Config>['extendMarkSchema']\n        },\n        extension: Mark,\n      ) => Record<string, any>)\n    | null\n\n  /**\n   * The editor is not ready yet.\n   */\n  onBeforeCreate?:\n    | ((\n        this: {\n          name: string\n          options: Options\n          storage: Storage\n          editor: Editor\n          type: PMType\n          parent: ParentConfig<Config>['onBeforeCreate']\n        },\n        event: EditorEvents['beforeCreate'],\n      ) => void)\n    | null\n\n  /**\n   * The editor is ready.\n   */\n  onCreate?:\n    | ((\n        this: {\n          name: string\n          options: Options\n          storage: Storage\n          editor: Editor\n          type: PMType\n          parent: ParentConfig<Config>['onCreate']\n        },\n        event: EditorEvents['create'],\n      ) => void)\n    | null\n\n  /**\n   * The content has changed.\n   */\n  onUpdate?:\n    | ((\n        this: {\n          name: string\n          options: Options\n          storage: Storage\n          editor: Editor\n          type: PMType\n          parent: ParentConfig<Config>['onUpdate']\n        },\n        event: EditorEvents['update'],\n      ) => void)\n    | null\n\n  /**\n   * The selection has changed.\n   */\n  onSelectionUpdate?:\n    | ((\n        this: {\n          name: string\n          options: Options\n          storage: Storage\n          editor: Editor\n          type: PMType\n          parent: ParentConfig<Config>['onSelectionUpdate']\n        },\n        event: EditorEvents['selectionUpdate'],\n      ) => void)\n    | null\n\n  /**\n   * The editor state has changed.\n   */\n  onTransaction?:\n    | ((\n        this: {\n          name: string\n          options: Options\n          storage: Storage\n          editor: Editor\n          type: PMType\n          parent: ParentConfig<Config>['onTransaction']\n        },\n        event: EditorEvents['transaction'],\n      ) => void)\n    | null\n\n  /**\n   * The editor is focused.\n   */\n  onFocus?:\n    | ((\n        this: {\n          name: string\n          options: Options\n          storage: Storage\n          editor: Editor\n          type: PMType\n          parent: ParentConfig<Config>['onFocus']\n        },\n        event: EditorEvents['focus'],\n      ) => void)\n    | null\n\n  /**\n   * The editor isn’t focused anymore.\n   */\n  onBlur?:\n    | ((\n        this: {\n          name: string\n          options: Options\n          storage: Storage\n          editor: Editor\n          type: PMType\n          parent: ParentConfig<Config>['onBlur']\n        },\n        event: EditorEvents['blur'],\n      ) => void)\n    | null\n\n  /**\n   * The editor is destroyed.\n   */\n  onDestroy?:\n    | ((\n        this: {\n          name: string\n          options: Options\n          storage: Storage\n          editor: Editor\n          type: PMType\n          parent: ParentConfig<Config>['onDestroy']\n        },\n        event: EditorEvents['destroy'],\n      ) => void)\n    | null\n\n  /**\n   * This hook allows you to intercept and modify transactions before they are dispatched.\n   *\n   * Example\n   * ```ts\n   * dispatchTransaction({ transaction, next }) {\n   *   console.log('Dispatching transaction:', transaction)\n   *   next(transaction)\n   * }\n   * ```\n   *\n   * @param props - The dispatch transaction props\n   */\n  dispatchTransaction?:\n    | ((\n        this: {\n          name: string\n          options: Options\n          storage: Storage\n          editor: Editor\n          type: PMType\n          parent: ParentConfig<Config>['dispatchTransaction']\n        },\n        props: DispatchTransactionProps,\n      ) => void)\n    | null\n}\n\nexport class Extendable<\n  Options = any,\n  Storage = any,\n  Config =\n    | ExtensionConfig<Options, Storage>\n    | NodeConfig<Options, Storage>\n    | MarkConfig<Options, Storage>,\n> {\n  type = 'extendable'\n  parent: Extendable | null = null\n\n  child: Extendable | null = null\n\n  name = ''\n\n  config: Config = {\n    name: this.name,\n  } as Config\n\n  constructor(config: Partial<Config> = {}) {\n    this.config = {\n      ...this.config,\n      ...config,\n    }\n\n    this.name = (this.config as any).name\n  }\n\n  get options(): Options {\n    return {\n      ...callOrReturn(\n        getExtensionField<AnyConfig['addOptions']>(this as any, 'addOptions', {\n          name: this.name,\n        }),\n      ),\n    }\n  }\n\n  get storage(): Readonly<Storage> {\n    return {\n      ...callOrReturn(\n        getExtensionField<AnyConfig['addStorage']>(this as any, 'addStorage', {\n          name: this.name,\n          options: this.options,\n        }),\n      ),\n    }\n  }\n\n  configure(options: Partial<Options> = {}) {\n    const extension = this.extend<Options, Storage, Config>({\n      ...this.config,\n      addOptions: () => {\n        return mergeDeep(this.options as Record<string, any>, options) as Options\n      },\n    })\n\n    extension.name = this.name\n    extension.parent = this.parent\n\n    this.child = null\n\n    return extension\n  }\n\n  extend<\n    ExtendedOptions = Options,\n    ExtendedStorage = Storage,\n    ExtendedConfig =\n      | ExtensionConfig<ExtendedOptions, ExtendedStorage>\n      | NodeConfig<ExtendedOptions, ExtendedStorage>\n      | MarkConfig<ExtendedOptions, ExtendedStorage>,\n  >(extendedConfig: Partial<ExtendedConfig> = {}): Extendable<ExtendedOptions, ExtendedStorage> {\n    const extension = new (this.constructor as any)({ ...this.config, ...extendedConfig })\n\n    extension.parent = this\n    this.child = extension\n    extension.name = 'name' in extendedConfig ? extendedConfig.name : extension.parent.name\n\n    return extension\n  }\n}\n", "import type { DOMOutputSpec, Mark as ProseMirrorMark, MarkSpec, MarkType } from '@tiptap/pm/model'\n\nimport type { Editor } from './Editor.js'\nimport type { ExtendableConfig } from './Extendable.js'\nimport { Extendable } from './Extendable.js'\nimport type { Attributes, MarkViewRenderer, ParentConfig } from './types.js'\n\nexport interface MarkConfig<Options = any, Storage = any> extends ExtendableConfig<\n  Options,\n  Storage,\n  MarkConfig<Options, Storage>,\n  MarkType\n> {\n  /**\n   * Mark View\n   */\n  addMarkView?:\n    | ((this: {\n        name: string\n        options: Options\n        storage: Storage\n        editor: Editor\n        type: MarkType\n        parent: ParentConfig<MarkConfig<Options, Storage>>['addMarkView']\n      }) => MarkViewRenderer)\n    | null\n\n  /**\n   * Keep mark after split node\n   */\n  keepOnSplit?: boolean | (() => boolean)\n\n  /**\n   * Whether this mark is removed by `unsetAllMarks`.\n   * Set to `false` for semantic marks (comments, suggestions) that should survive \"clear formatting\".\n   * @default true\n   */\n  clearable?: boolean | (() => boolean)\n\n  /**\n   * Inclusive\n   */\n  inclusive?:\n    | MarkSpec['inclusive']\n    | ((this: {\n        name: string\n        options: Options\n        storage: Storage\n        parent: ParentConfig<MarkConfig<Options, Storage>>['inclusive']\n        editor?: Editor\n      }) => MarkSpec['inclusive'])\n\n  /**\n   * Excludes\n   */\n  excludes?:\n    | MarkSpec['excludes']\n    | ((this: {\n        name: string\n        options: Options\n        storage: Storage\n        parent: ParentConfig<MarkConfig<Options, Storage>>['excludes']\n        editor?: Editor\n      }) => MarkSpec['excludes'])\n\n  /**\n   * Marks this Mark as exitable\n   */\n  exitable?: boolean | (() => boolean)\n\n  /**\n   * Group\n   */\n  group?:\n    | MarkSpec['group']\n    | ((this: {\n        name: string\n        options: Options\n        storage: Storage\n        parent: ParentConfig<MarkConfig<Options, Storage>>['group']\n        editor?: Editor\n      }) => MarkSpec['group'])\n\n  /**\n   * Spanning\n   */\n  spanning?:\n    | MarkSpec['spanning']\n    | ((this: {\n        name: string\n        options: Options\n        storage: Storage\n        parent: ParentConfig<MarkConfig<Options, Storage>>['spanning']\n        editor?: Editor\n      }) => MarkSpec['spanning'])\n\n  /**\n   * Code\n   */\n  code?:\n    | boolean\n    | ((this: {\n        name: string\n        options: Options\n        storage: Storage\n        parent: ParentConfig<MarkConfig<Options, Storage>>['code']\n        editor?: Editor\n      }) => boolean)\n\n  /**\n   * Parse HTML\n   */\n  parseHTML?: (this: {\n    name: string\n    options: Options\n    storage: Storage\n    parent: ParentConfig<MarkConfig<Options, Storage>>['parseHTML']\n    editor?: Editor\n  }) => MarkSpec['parseDOM']\n\n  /**\n   * Render HTML\n   */\n  renderHTML?:\n    | ((\n        this: {\n          name: string\n          options: Options\n          storage: Storage\n          parent: ParentConfig<MarkConfig<Options, Storage>>['renderHTML']\n          editor?: Editor\n        },\n        props: {\n          mark: ProseMirrorMark\n          HTMLAttributes: Record<string, any>\n        },\n      ) => DOMOutputSpec)\n    | null\n\n  /**\n   * Attributes\n   */\n  addAttributes?: (this: {\n    name: string\n    options: Options\n    storage: Storage\n    parent: ParentConfig<MarkConfig<Options, Storage>>['addAttributes']\n    editor?: Editor\n    // oxlint-disable-next-lineno-empty-object-type\n  }) => Attributes | {}\n}\n\n/**\n * The Mark class is used to create custom mark extensions.\n * @see https://tiptap.dev/api/extensions#create-a-new-extension\n */\nexport class Mark<Options = any, Storage = any> extends Extendable<\n  Options,\n  Storage,\n  MarkConfig<Options, Storage>\n> {\n  type = 'mark'\n\n  /**\n   * Create a new Mark instance\n   * @param config - Mark configuration object or a function that returns a configuration object\n   */\n  static create<O = any, S = any>(\n    config: Partial<MarkConfig<O, S>> | (() => Partial<MarkConfig<O, S>>) = {},\n  ) {\n    // If the config is a function, execute it to get the configuration object\n    const resolvedConfig = typeof config === 'function' ? config() : config\n    return new Mark<O, S>(resolvedConfig)\n  }\n\n  static handleExit({ editor, mark }: { editor: Editor; mark: Mark }) {\n    const { tr } = editor.state\n    const currentPos = editor.state.selection.$from\n    const isAtEnd = currentPos.pos === currentPos.end()\n\n    if (isAtEnd) {\n      const currentMarks = currentPos.marks()\n      const isInMark = !!currentMarks.find(m => m?.type.name === mark.name)\n\n      if (!isInMark) {\n        return false\n      }\n\n      const removeMark = currentMarks.find(m => m?.type.name === mark.name)\n\n      if (removeMark) {\n        tr.removeStoredMark(removeMark)\n      }\n      tr.insertText(' ', currentPos.pos)\n\n      editor.view.dispatch(tr)\n\n      return true\n    }\n\n    return false\n  }\n\n  configure(options?: Partial<Options>) {\n    return super.configure(options) as Mark<Options, Storage>\n  }\n\n  extend<\n    ExtendedOptions = Options,\n    ExtendedStorage = Storage,\n    ExtendedConfig extends MarkConfig<ExtendedOptions, ExtendedStorage> = MarkConfig<\n      ExtendedOptions,\n      ExtendedStorage\n    >,\n  >(\n    extendedConfig?:\n      | (() => Partial<ExtendedConfig>)\n      | (Partial<ExtendedConfig> &\n          ThisType<{\n            name: string\n            options: ExtendedOptions\n            storage: ExtendedStorage\n            editor: Editor\n            type: MarkType\n          }>),\n  ): Mark<ExtendedOptions, ExtendedStorage> {\n    // If the extended config is a function, execute it to get the configuration object\n    const resolvedConfig = typeof extendedConfig === 'function' ? extendedConfig() : extendedConfig\n    return super.extend(resolvedConfig) as Mark<ExtendedOptions, ExtendedStorage>\n  }\n}\n", "import type { Node as ProseMirrorNode } from '@tiptap/pm/model'\nimport { Fragment } from '@tiptap/pm/model'\nimport type { EditorState } from '@tiptap/pm/state'\nimport { Plugin } from '@tiptap/pm/state'\n\nimport { CommandManager } from './CommandManager.js'\nimport type { Editor } from './Editor.js'\nimport { createChainableState } from './helpers/createChainableState.js'\nimport { getHTMLFromFragment } from './helpers/getHTMLFromFragment.js'\nimport type {\n  CanCommands,\n  ChainedCommands,\n  ExtendedRegExpMatchArray,\n  Range,\n  SingleCommands,\n} from './types.js'\nimport { isNumber } from './utilities/isNumber.js'\nimport { isRegExp } from './utilities/isRegExp.js'\n\nexport type PasteRuleMatch = {\n  index: number\n  text: string\n  replaceWith?: string\n  match?: RegExpMatchArray\n  data?: Record<string, any>\n}\n\nexport type PasteRuleFinder =\n  | RegExp\n  | ((text: string, event?: ClipboardEvent | null) => PasteRuleMatch[] | null | undefined)\n\n/**\n * Paste rules are used to react to pasted content.\n * @see https://tiptap.dev/docs/editor/extensions/custom-extensions/extend-existing#paste-rules\n */\nexport class PasteRule {\n  find: PasteRuleFinder\n\n  handler: (props: {\n    state: EditorState\n    range: Range\n    match: ExtendedRegExpMatchArray\n    commands: SingleCommands\n    chain: () => ChainedCommands\n    can: () => CanCommands\n    pasteEvent: ClipboardEvent | null\n    dropEvent: DragEvent | null\n  }) => void | null\n\n  constructor(config: {\n    find: PasteRuleFinder\n    handler: (props: {\n      can: () => CanCommands\n      chain: () => ChainedCommands\n      commands: SingleCommands\n      dropEvent: DragEvent | null\n      match: ExtendedRegExpMatchArray\n      pasteEvent: ClipboardEvent | null\n      range: Range\n      state: EditorState\n    }) => void | null\n  }) {\n    this.find = config.find\n    this.handler = config.handler\n  }\n}\n\nconst pasteRuleMatcherHandler = (\n  text: string,\n  find: PasteRuleFinder,\n  event?: ClipboardEvent | null,\n): ExtendedRegExpMatchArray[] => {\n  if (isRegExp(find)) {\n    return [...text.matchAll(find)]\n  }\n\n  const matches = find(text, event)\n\n  if (!matches) {\n    return []\n  }\n\n  return matches.map(pasteRuleMatch => {\n    const result: ExtendedRegExpMatchArray = [pasteRuleMatch.text]\n\n    result.index = pasteRuleMatch.index\n    result.input = text\n    result.data = pasteRuleMatch.data\n\n    if (pasteRuleMatch.replaceWith) {\n      if (!pasteRuleMatch.text.includes(pasteRuleMatch.replaceWith)) {\n        console.warn(\n          '[tiptap warn]: \"pasteRuleMatch.replaceWith\" must be part of \"pasteRuleMatch.text\".',\n        )\n      }\n\n      result.push(pasteRuleMatch.replaceWith)\n    }\n\n    return result\n  })\n}\n\nfunction run(config: {\n  editor: Editor\n  state: EditorState\n  from: number\n  to: number\n  rule: PasteRule\n  pasteEvent: ClipboardEvent | null\n  dropEvent: DragEvent | null\n}): boolean {\n  const { editor, state, from, to, rule, pasteEvent, dropEvent } = config\n\n  const { commands, chain, can } = new CommandManager({\n    editor,\n    state,\n  })\n\n  const handlers: (void | null)[] = []\n\n  state.doc.nodesBetween(from, to, (node, pos) => {\n    // Skip code blocks and non-textual nodes.\n    // Be defensive: `node` may be a Fragment without a `type`. Only text,\n    // inline, or textblock nodes are processed by paste rules.\n    if (node.type?.spec?.code || !(node.isText || node.isTextblock || node.isInline)) {\n      return\n    }\n\n    // For textblock and inline/text nodes, compute the range relative to the node.\n    // Prefer `node.nodeSize` when available (some Node shapes expose this),\n    // otherwise fall back to `node.content?.size`. Default to 0 if neither exists.\n    const contentSize = node.content?.size ?? node.nodeSize ?? 0\n    const resolvedFrom = Math.max(from, pos)\n    const resolvedTo = Math.min(to, pos + contentSize)\n\n    // If the resolved range is empty or invalid for this node, skip it. This\n    // avoids calling `textBetween` with start > end which can cause internal\n    // Fragment/Node traversal to access undefined `nodeSize` values.\n    if (resolvedFrom >= resolvedTo) {\n      return\n    }\n\n    const textToMatch = node.isText\n      ? node.text || ''\n      : node.textBetween(resolvedFrom - pos, resolvedTo - pos, undefined, '\\ufffc')\n\n    const matches = pasteRuleMatcherHandler(textToMatch, rule.find, pasteEvent)\n\n    matches.forEach(match => {\n      if (match.index === undefined) {\n        return\n      }\n\n      const start = resolvedFrom + match.index + 1\n      const end = start + match[0].length\n      const range = {\n        from: state.tr.mapping.map(start),\n        to: state.tr.mapping.map(end),\n      }\n\n      const handler = rule.handler({\n        state,\n        range,\n        match,\n        commands,\n        chain,\n        can,\n        pasteEvent,\n        dropEvent,\n      })\n\n      handlers.push(handler)\n    })\n  })\n\n  const success = handlers.every(handler => handler !== null)\n\n  return success\n}\n\n// When dragging across editors, must get another editor instance to delete selection content.\nlet tiptapDragFromOtherEditor: Editor | null = null\n\nconst createClipboardPasteEvent = (text: string) => {\n  const event = new ClipboardEvent('paste', {\n    clipboardData: new DataTransfer(),\n  })\n\n  event.clipboardData?.setData('text/html', text)\n\n  return event\n}\n\n/**\n * Create an paste rules plugin. When enabled, it will cause pasted\n * text that matches any of the given rules to trigger the rule’s\n * action.\n */\nexport function pasteRulesPlugin(props: { editor: Editor; rules: PasteRule[] }): Plugin[] {\n  const { editor, rules } = props\n  let dragSourceElement: Element | null = null\n  let isPastedFromProseMirror = false\n  let isDroppedFromProseMirror = false\n  let pasteEvent = typeof ClipboardEvent !== 'undefined' ? new ClipboardEvent('paste') : null\n  let dropEvent: DragEvent | null\n\n  try {\n    dropEvent = typeof DragEvent !== 'undefined' ? new DragEvent('drop') : null\n  } catch {\n    dropEvent = null\n  }\n\n  const processEvent = ({\n    state,\n    from,\n    to,\n    rule,\n    pasteEvt,\n  }: {\n    state: EditorState\n    from: number\n    to: { b: number }\n    rule: PasteRule\n    pasteEvt: ClipboardEvent | null\n  }) => {\n    const tr = state.tr\n    const chainableState = createChainableState({\n      state,\n      transaction: tr,\n    })\n\n    const handler = run({\n      editor,\n      state: chainableState,\n      from: Math.max(from - 1, 0),\n      to: to.b - 1,\n      rule,\n      pasteEvent: pasteEvt,\n      dropEvent,\n    })\n\n    if (!handler || !tr.steps.length) {\n      return\n    }\n\n    try {\n      dropEvent = typeof DragEvent !== 'undefined' ? new DragEvent('drop') : null\n    } catch {\n      dropEvent = null\n    }\n    pasteEvent = typeof ClipboardEvent !== 'undefined' ? new ClipboardEvent('paste') : null\n\n    return tr\n  }\n\n  editor.on('destroy', () => {\n    if (tiptapDragFromOtherEditor === editor) {\n      tiptapDragFromOtherEditor = null\n    }\n  })\n\n  const plugins = rules.map(rule => {\n    return new Plugin({\n      // we register a global drag handler to track the current drag source element\n      view(view) {\n        const handleDragstart = (event: DragEvent) => {\n          dragSourceElement = view.dom.parentElement?.contains(event.target as Element)\n            ? view.dom.parentElement\n            : null\n\n          if (dragSourceElement) {\n            tiptapDragFromOtherEditor = editor\n          }\n        }\n\n        const handleDragend = () => {\n          if (tiptapDragFromOtherEditor) {\n            tiptapDragFromOtherEditor = null\n          }\n        }\n\n        window.addEventListener('dragstart', handleDragstart)\n        window.addEventListener('dragend', handleDragend)\n\n        return {\n          destroy() {\n            window.removeEventListener('dragstart', handleDragstart)\n            window.removeEventListener('dragend', handleDragend)\n          },\n        }\n      },\n\n      props: {\n        handleDOMEvents: {\n          drop: (view, event: Event) => {\n            isDroppedFromProseMirror = dragSourceElement === view.dom.parentElement\n            dropEvent = event as DragEvent\n\n            if (!isDroppedFromProseMirror) {\n              const dragFromOtherEditor = tiptapDragFromOtherEditor\n\n              if (dragFromOtherEditor?.isEditable) {\n                // setTimeout to avoid the wrong content after drop, timeout arg can't be empty or 0\n                setTimeout(() => {\n                  if (dragFromOtherEditor.isDestroyed) {\n                    return\n                  }\n\n                  const selection = dragFromOtherEditor.state.selection\n\n                  if (selection) {\n                    dragFromOtherEditor.commands.deleteRange({\n                      from: selection.from,\n                      to: selection.to,\n                    })\n                  }\n                }, 10)\n              }\n            }\n            return false\n          },\n\n          paste: (_view, event: Event) => {\n            const html = (event as ClipboardEvent).clipboardData?.getData('text/html')\n\n            pasteEvent = event as ClipboardEvent\n\n            isPastedFromProseMirror = !!html?.includes('data-pm-slice')\n\n            return false\n          },\n        },\n      },\n\n      appendTransaction: (transactions, oldState, state) => {\n        const transaction = transactions[0]\n        const isPaste = transaction.getMeta('uiEvent') === 'paste' && !isPastedFromProseMirror\n        const isDrop = transaction.getMeta('uiEvent') === 'drop' && !isDroppedFromProseMirror\n\n        // if PasteRule is triggered by insertContent()\n        const simulatedPasteMeta = transaction.getMeta('applyPasteRules') as\n          | undefined\n          | { from: number; text: string | ProseMirrorNode | Fragment }\n        const isSimulatedPaste = !!simulatedPasteMeta\n\n        if (!isPaste && !isDrop && !isSimulatedPaste) {\n          return\n        }\n\n        // Handle simulated paste\n        if (isSimulatedPaste) {\n          let { text } = simulatedPasteMeta\n\n          if (typeof text === 'string') {\n            text = text as string\n          } else {\n            text = getHTMLFromFragment(Fragment.from(text), state.schema)\n          }\n\n          const { from } = simulatedPasteMeta\n          const to = from + text.length\n\n          const pasteEvt = createClipboardPasteEvent(text)\n\n          return processEvent({\n            rule,\n            state,\n            from,\n            to: { b: to },\n            pasteEvt,\n          })\n        }\n\n        // handle actual paste/drop\n        const from = oldState.doc.content.findDiffStart(state.doc.content)\n        const to = oldState.doc.content.findDiffEnd(state.doc.content)\n\n        // stop if there is no changed range\n        if (!isNumber(from) || !to || from === to.b) {\n          return\n        }\n\n        return processEvent({\n          rule,\n          state,\n          from,\n          to,\n          pasteEvt: pasteEvent,\n        })\n      },\n    })\n  })\n\n  return plugins\n}\n", "import { keymap } from '@tiptap/pm/keymap'\nimport type { Schema } from '@tiptap/pm/model'\nimport type { Plugin, Transaction } from '@tiptap/pm/state'\nimport type { EditorView, MarkViewConstructor, NodeViewConstructor } from '@tiptap/pm/view'\n\nimport type { Editor } from './Editor.js'\nimport { DecorationManager, type DecorationManagerEntry } from './decorations/DecorationManager.js'\nimport {\n  flattenExtensions,\n  getAttributesFromExtensions,\n  getExtensionField,\n  getMarkType,\n  getNodeType,\n  getRenderedAttributes,\n  getSchemaByResolvedExtensions,\n  getSchemaTypeByName,\n  isExtensionRulesEnabled,\n  resolveExtensions,\n  sortExtensions,\n  splitExtensions,\n} from './helpers/index.js'\nimport { updateMarkViewAttributes } from './MarkView.js'\nimport { inputRulesPlugin } from './InputRule.js'\nimport { Mark, type MarkConfig } from './Mark.js'\nimport { pasteRulesPlugin } from './PasteRule.js'\nimport { getSchemaAttributes } from './schema/getSchemaAttributes.js'\nimport type { AnyConfig, Extensions, RawCommands, Storage } from './types.js'\nimport { callOrReturn } from './utilities/callOrReturn.js'\nimport { type NodeConfig } from './Node.js'\n\nexport class ExtensionManager {\n  editor: Editor\n\n  schema: Schema\n\n  private readonly hasSchemaSpec: boolean\n\n  /**\n   * A flattened and sorted array of all extensions\n   */\n  extensions: Extensions\n\n  /**\n   * A non-flattened array of base extensions (no sub-extensions)\n   */\n  baseExtensions: Extensions\n\n  splittableMarks: string[] = []\n\n  nonClearableMarks: string[] = []\n\n  decorationManager: DecorationManager | null = null\n\n  constructor(extensions: Extensions, editor: Editor) {\n    this.editor = editor\n    this.baseExtensions = extensions\n    this.extensions = resolveExtensions(extensions)\n    this.hasSchemaSpec = editor.options.schemaSpec !== undefined\n    this.schema = getSchemaByResolvedExtensions(this.extensions, editor, editor.options.schemaSpec)\n    this.setupExtensions()\n  }\n\n  static resolve = resolveExtensions\n\n  static sort = sortExtensions\n\n  static flatten = flattenExtensions\n\n  /**\n   * Get all commands from the extensions.\n   * @returns An object with all commands where the key is the command name and the value is the command function\n   */\n  get commands(): RawCommands {\n    return this.extensions.reduce((commands, extension) => {\n      const context = {\n        name: extension.name,\n        options: extension.options,\n        storage: this.editor.extensionStorage[extension.name as keyof Storage],\n        editor: this.editor,\n        type: getSchemaTypeByName(extension.name, this.schema),\n      }\n\n      const addCommands = getExtensionField<AnyConfig['addCommands']>(\n        extension,\n        'addCommands',\n        context,\n      )\n\n      if (!addCommands) {\n        return commands\n      }\n\n      return {\n        ...commands,\n        ...addCommands(),\n      }\n    }, {} as RawCommands)\n  }\n\n  /**\n   * Get all registered Prosemirror plugins from the extensions.\n   * @returns An array of Prosemirror plugins\n   */\n  get plugins(): Plugin[] {\n    const { editor } = this\n\n    // With ProseMirror, first plugins within an array are executed first.\n    // In Tiptap, we provide the ability to override plugins,\n    // so it feels more natural to run plugins at the end of an array first.\n    // That’s why we have to reverse the `extensions` array and sort again\n    // based on the `priority` option.\n    const extensions = sortExtensions([...this.extensions].reverse())\n\n    const allPlugins = extensions.flatMap(extension => {\n      const context = {\n        name: extension.name,\n        options: extension.options,\n        storage: this.editor.extensionStorage[extension.name as keyof Storage],\n        editor,\n        type: getSchemaTypeByName(extension.name, this.schema),\n      }\n\n      const plugins: Plugin[] = []\n\n      const addKeyboardShortcuts = getExtensionField<AnyConfig['addKeyboardShortcuts']>(\n        extension,\n        'addKeyboardShortcuts',\n        context,\n      )\n\n      let defaultBindings: Record<string, () => boolean> = {}\n\n      // bind exit handling\n      if (\n        extension.type === 'mark' &&\n        getExtensionField<MarkConfig['exitable']>(extension, 'exitable', context)\n      ) {\n        defaultBindings.ArrowRight = () => Mark.handleExit({ editor, mark: extension as Mark })\n      }\n\n      if (addKeyboardShortcuts) {\n        const bindings = Object.fromEntries(\n          Object.entries(addKeyboardShortcuts()).map(([shortcut, method]) => {\n            return [shortcut, () => method({ editor })]\n          }),\n        )\n\n        defaultBindings = { ...defaultBindings, ...bindings }\n      }\n\n      const keyMapPlugin = keymap(defaultBindings)\n\n      plugins.push(keyMapPlugin)\n\n      const addInputRules = getExtensionField<AnyConfig['addInputRules']>(\n        extension,\n        'addInputRules',\n        context,\n      )\n\n      if (isExtensionRulesEnabled(extension, editor.options.enableInputRules) && addInputRules) {\n        const rules = addInputRules()\n\n        if (rules && rules.length) {\n          const inputResult = inputRulesPlugin({\n            editor,\n            rules,\n          })\n\n          const inputPlugins = Array.isArray(inputResult) ? inputResult : [inputResult]\n\n          plugins.push(...inputPlugins)\n        }\n      }\n\n      const addPasteRules = getExtensionField<AnyConfig['addPasteRules']>(\n        extension,\n        'addPasteRules',\n        context,\n      )\n\n      if (isExtensionRulesEnabled(extension, editor.options.enablePasteRules) && addPasteRules) {\n        const rules = addPasteRules()\n\n        if (rules && rules.length) {\n          const pasteRules = pasteRulesPlugin({ editor, rules })\n\n          plugins.push(...pasteRules)\n        }\n      }\n\n      const addProseMirrorPlugins = getExtensionField<AnyConfig['addProseMirrorPlugins']>(\n        extension,\n        'addProseMirrorPlugins',\n        context,\n      )\n\n      if (addProseMirrorPlugins) {\n        const proseMirrorPlugins = addProseMirrorPlugins()\n\n        plugins.push(...proseMirrorPlugins)\n      }\n\n      return plugins\n    })\n\n    const decorationPlugin = this.createDecorationPlugin()\n\n    if (decorationPlugin) {\n      allPlugins.push(decorationPlugin)\n    }\n\n    return allPlugins\n  }\n\n  /**\n   * Aggregates decorations from extensions into a single plugin, or returns null\n   * if none exist. Destroys the previous manager to avoid orphaned listeners.\n   * @returns A ProseMirror plugin or `null`\n   * @example\n   * const plugin = editor.extensionManager.createDecorationPlugin()\n   */\n  createDecorationPlugin(): Plugin | null {\n    const { editor } = this\n\n    this.decorationManager?.destroy()\n\n    const entries: DecorationManagerEntry[] = []\n\n    this.extensions.forEach(extension => {\n      const context = {\n        name: extension.name,\n        options: extension.options,\n        storage: this.editor.extensionStorage[extension.name as keyof Storage],\n        editor,\n        type: getSchemaTypeByName(extension.name, this.schema),\n      }\n\n      const addDecorations = getExtensionField<AnyConfig['addDecorations']>(\n        extension,\n        'addDecorations',\n        context,\n      )\n\n      if (!addDecorations) {\n        return\n      }\n\n      entries.push({ name: extension.name, addDecorations })\n    })\n\n    this.decorationManager = new DecorationManager({ editor, entries })\n\n    return this.decorationManager.plugin\n  }\n\n  /**\n   * Get all attributes from the extensions.\n   * @returns An array of attributes\n   */\n  get attributes() {\n    const attributes = getAttributesFromExtensions(this.extensions)\n\n    return this.hasSchemaSpec ? getSchemaAttributes(attributes, this.schema) : attributes\n  }\n\n  /**\n   * Get all node views from the extensions.\n   * @returns An object with all node views where the key is the node name and the value is the node view function\n   */\n  get nodeViews(): Record<string, NodeViewConstructor> {\n    const { editor } = this\n    const { nodeExtensions } = splitExtensions(this.extensions)\n\n    return Object.fromEntries(\n      nodeExtensions\n        .filter(extension => !!getExtensionField(extension, 'addNodeView'))\n        .map(extension => {\n          const extensionAttributes = this.attributes.filter(\n            attribute => attribute.type === extension.name,\n          )\n          const context = {\n            name: extension.name,\n            options: extension.options,\n            storage: this.editor.extensionStorage[extension.name as keyof Storage],\n            editor,\n            type: getNodeType(extension.name, this.schema),\n          }\n          const addNodeView = getExtensionField<NodeConfig['addNodeView']>(\n            extension,\n            'addNodeView',\n            context,\n          )\n\n          if (!addNodeView) {\n            return []\n          }\n\n          const nodeViewResult = addNodeView()\n\n          if (!nodeViewResult) {\n            return []\n          }\n\n          const nodeview: NodeViewConstructor = (\n            node,\n            view,\n            getPos,\n            decorations,\n            innerDecorations,\n          ) => {\n            const HTMLAttributes = getRenderedAttributes(node, extensionAttributes)\n\n            return nodeViewResult({\n              // pass-through\n              node,\n              view,\n              getPos: getPos as () => number,\n              decorations,\n              innerDecorations,\n              // tiptap-specific\n              editor,\n              extension,\n              HTMLAttributes,\n            })\n          }\n\n          return [extension.name, nodeview]\n        }),\n    )\n  }\n\n  /**\n   * Get the composed dispatchTransaction function from all extensions.\n   * @param baseDispatch The base dispatch function (e.g. from the editor or user props)\n   * @returns A composed dispatch function\n   */\n  dispatchTransaction(baseDispatch: (tr: Transaction) => void): (tr: Transaction) => void {\n    const { editor } = this\n    const extensions = sortExtensions([...this.extensions].reverse())\n\n    return extensions.reduceRight((next, extension) => {\n      const context = {\n        name: extension.name,\n        options: extension.options,\n        storage: this.editor.extensionStorage[extension.name as keyof Storage],\n        editor,\n        type: getSchemaTypeByName(extension.name, this.schema),\n      }\n\n      const dispatchTransaction = getExtensionField<AnyConfig['dispatchTransaction']>(\n        extension,\n        'dispatchTransaction',\n        context,\n      )\n\n      if (!dispatchTransaction) {\n        return next\n      }\n\n      return (transaction: Transaction) => {\n        dispatchTransaction.call(context, { transaction, next })\n      }\n    }, baseDispatch)\n  }\n\n  /**\n   * Get the composed transformPastedHTML function from all extensions.\n   * @param baseTransform The base transform function (e.g. from the editor props)\n   * @returns A composed transform function that chains all extension transforms\n   */\n  transformPastedHTML(\n    baseTransform?: (html: string, view?: any) => string,\n  ): (html: string, view?: EditorView) => string {\n    const { editor } = this\n    const extensions = sortExtensions([...this.extensions])\n\n    return extensions.reduce(\n      (transform, extension) => {\n        const context = {\n          name: extension.name,\n          options: extension.options,\n          storage: this.editor.extensionStorage[extension.name as keyof Storage],\n          editor,\n          type: getSchemaTypeByName(extension.name, this.schema),\n        }\n\n        const extensionTransform = getExtensionField<AnyConfig['transformPastedHTML']>(\n          extension,\n          'transformPastedHTML',\n          context,\n        )\n\n        if (!extensionTransform) {\n          return transform\n        }\n\n        return (html: string, view?: any) => {\n          // Chain the transforms: pass the result of the previous transform to the next\n          const transformedHtml = transform(html, view)\n          return extensionTransform.call(context, transformedHtml)\n        }\n      },\n      baseTransform || ((html: string) => html),\n    )\n  }\n\n  get markViews(): Record<string, MarkViewConstructor> {\n    const { editor } = this\n    const { markExtensions } = splitExtensions(this.extensions)\n\n    return Object.fromEntries(\n      markExtensions\n        .filter(extension => !!getExtensionField(extension, 'addMarkView'))\n        .map(extension => {\n          const extensionAttributes = this.attributes.filter(\n            attribute => attribute.type === extension.name,\n          )\n          const context = {\n            name: extension.name,\n            options: extension.options,\n            storage: this.editor.extensionStorage[extension.name as keyof Storage],\n            editor,\n            type: getMarkType(extension.name, this.schema),\n          }\n          const addMarkView = getExtensionField<MarkConfig['addMarkView']>(\n            extension,\n            'addMarkView',\n            context,\n          )\n\n          if (!addMarkView) {\n            return []\n          }\n\n          const markView: MarkViewConstructor = (mark, view, inline) => {\n            const HTMLAttributes = getRenderedAttributes(mark, extensionAttributes)\n\n            return addMarkView()({\n              // pass-through\n              mark,\n              view,\n              inline,\n              // tiptap-specific\n              editor,\n              extension,\n              HTMLAttributes,\n              updateAttributes: (attrs: Record<string, any>) => {\n                updateMarkViewAttributes(mark, editor, attrs)\n              },\n            })\n          }\n\n          return [extension.name, markView]\n        }),\n    )\n  }\n\n  /**\n   * Destroy the extension manager and clean up all extension references\n   * to prevent memory leaks through parent/child extension chains.\n   *\n   * Walks each extension's full parent chain and nulls every forward\n   * `parent.child → current` link where the parent still points to the\n   * current node. This breaks the retention path from module-scope\n   * singleton roots through deep extend() chains.\n   *\n   * Only ancestor `.child` links matching the current chain are cleared.\n   * The `.parent` pointer on ancestors is never touched — extensions\n   * may be shared across live editors, so their own backward references\n   * and non-matching forward links must remain intact.\n   */\n  destroy() {\n    this.decorationManager?.destroy()\n\n    this.extensions.forEach(extension => {\n      let current: any = extension\n\n      while (current.parent) {\n        const parent = current.parent\n\n        if (parent.child === current) {\n          parent.child = null\n        }\n\n        current = parent\n      }\n    })\n\n    this.extensions = []\n    this.baseExtensions = []\n    this.decorationManager = null\n    this.schema = null as any\n    this.editor = null as any\n  }\n\n  /**\n   * Go through all extensions, create extension storages & setup marks\n   * & bind editor event listener.\n   */\n  private setupExtensions() {\n    const extensions = this.extensions\n    // re-initialize the extension storage object instance\n    this.editor.extensionStorage = Object.fromEntries(\n      extensions.map(extension => [extension.name, extension.storage]),\n    ) as unknown as Storage\n\n    extensions.forEach(extension => {\n      const context = {\n        name: extension.name,\n        options: extension.options,\n        storage: this.editor.extensionStorage[extension.name as keyof Storage],\n        editor: this.editor,\n        type: getSchemaTypeByName(extension.name, this.schema),\n      }\n\n      if (extension.type === 'mark') {\n        const keepOnSplit =\n          callOrReturn(getExtensionField(extension, 'keepOnSplit', context)) ?? true\n\n        if (keepOnSplit) {\n          this.splittableMarks.push(extension.name)\n        }\n\n        const clearable =\n          callOrReturn(\n            getExtensionField<MarkConfig['clearable']>(extension, 'clearable', context),\n          ) ?? true\n\n        if (!clearable) {\n          this.nonClearableMarks.push(extension.name)\n        }\n      }\n\n      const onBeforeCreate = getExtensionField<AnyConfig['onBeforeCreate']>(\n        extension,\n        'onBeforeCreate',\n        context,\n      )\n      const onCreate = getExtensionField<AnyConfig['onCreate']>(extension, 'onCreate', context)\n      const onUpdate = getExtensionField<AnyConfig['onUpdate']>(extension, 'onUpdate', context)\n      const onSelectionUpdate = getExtensionField<AnyConfig['onSelectionUpdate']>(\n        extension,\n        'onSelectionUpdate',\n        context,\n      )\n      const onTransaction = getExtensionField<AnyConfig['onTransaction']>(\n        extension,\n        'onTransaction',\n        context,\n      )\n      const onFocus = getExtensionField<AnyConfig['onFocus']>(extension, 'onFocus', context)\n      const onBlur = getExtensionField<AnyConfig['onBlur']>(extension, 'onBlur', context)\n      const onDestroy = getExtensionField<AnyConfig['onDestroy']>(extension, 'onDestroy', context)\n\n      if (onBeforeCreate) {\n        this.editor.on('beforeCreate', onBeforeCreate)\n      }\n\n      if (onCreate) {\n        this.editor.on('create', onCreate)\n      }\n\n      if (onUpdate) {\n        this.editor.on('update', onUpdate)\n      }\n\n      if (onSelectionUpdate) {\n        this.editor.on('selectionUpdate', onSelectionUpdate)\n      }\n\n      if (onTransaction) {\n        this.editor.on('transaction', onTransaction)\n      }\n\n      if (onFocus) {\n        this.editor.on('focus', onFocus)\n      }\n\n      if (onBlur) {\n        this.editor.on('blur', onBlur)\n      }\n\n      if (onDestroy) {\n        this.editor.on('destroy', onDestroy)\n      }\n    })\n  }\n}\n", "import type { Editor } from './Editor.js'\nimport { type ExtendableConfig, Extendable } from './Extendable.js'\n\n// oxlint-disable-next-lineno-empty-object-type\nexport interface ExtensionConfig<Options = any, Storage = any> extends ExtendableConfig<\n  Options,\n  Storage,\n  ExtensionConfig<Options, Storage>,\n  null\n> {}\n\n/**\n * The Extension class is the base class for all extensions.\n * @see https://tiptap.dev/api/extensions#create-a-new-extension\n */\nexport class Extension<Options = any, Storage = any> extends Extendable<\n  Options,\n  Storage,\n  ExtensionConfig<Options, Storage>\n> {\n  type = 'extension'\n\n  /**\n   * Create a new Extension instance\n   * @param config - Extension configuration object or a function that returns a configuration object\n   */\n  static create<O = any, S = any>(\n    config: Partial<ExtensionConfig<O, S>> | (() => Partial<ExtensionConfig<O, S>>) = {},\n  ) {\n    // If the config is a function, execute it to get the configuration object\n    const resolvedConfig = typeof config === 'function' ? config() : config\n    return new Extension<O, S>(resolvedConfig)\n  }\n\n  configure(options?: Partial<Options>) {\n    return super.configure(options) as Extension<Options, Storage>\n  }\n\n  extend<\n    ExtendedOptions = Options,\n    ExtendedStorage = Storage,\n    ExtendedConfig = ExtensionConfig<ExtendedOptions, ExtendedStorage>,\n  >(\n    extendedConfig?:\n      | (() => Partial<ExtendedConfig>)\n      | (Partial<ExtendedConfig> &\n          ThisType<{\n            name: string\n            options: ExtendedOptions\n            storage: ExtendedStorage\n            editor: Editor\n            type: null\n          }>),\n  ): Extension<ExtendedOptions, ExtendedStorage> {\n    // If the extended config is a function, execute it to get the configuration object\n    const resolvedConfig = typeof extendedConfig === 'function' ? extendedConfig() : extendedConfig\n    return super.extend(resolvedConfig) as Extension<ExtendedOptions, ExtendedStorage>\n  }\n}\n", "import { Plugin, PluginKey } from '@tiptap/pm/state'\n\nimport { Extension } from '../Extension.js'\nimport { getTextBetween } from '../helpers/getTextBetween.js'\nimport { getTextSerializersFromSchema } from '../helpers/getTextSerializersFromSchema.js'\n\nexport type ClipboardTextSerializerOptions = {\n  blockSeparator?: string\n}\n\nexport const ClipboardTextSerializer = Extension.create<ClipboardTextSerializerOptions>({\n  name: 'clipboardTextSerializer',\n\n  addOptions() {\n    return {\n      blockSeparator: undefined,\n    }\n  },\n\n  addProseMirrorPlugins() {\n    return [\n      new Plugin({\n        key: new PluginKey('clipboardTextSerializer'),\n        props: {\n          clipboardTextSerializer: () => {\n            const { editor } = this\n            const { state, schema } = editor\n            const { doc, selection } = state\n            const textSerializers = getTextSerializersFromSchema(schema)\n            const { blockSeparator } = this.options\n            const options = {\n              ...(blockSeparator !== undefined ? { blockSeparator } : {}),\n              textSerializers,\n            }\n\n            // Serialize each selection range independently and join the results.\n            // CellSelection exposes one range per selected cell; flattening to\n            // min(from)/max(to) would pull in unselected cells between them.\n            // Sort by document position so reverse selections (e.g. dragging\n            // upward) still emit text in document order.\n            const sortedRanges = [...selection.ranges].sort((a, b) => a.$from.pos - b.$from.pos)\n\n            return sortedRanges\n              .map(({ $from, $to }) =>\n                getTextBetween(doc, { from: $from.pos, to: $to.pos }, options),\n              )\n              .join(blockSeparator ?? '\\n\\n')\n          },\n        },\n      }),\n    ]\n  },\n})\n", "import * as commands from '../commands/index.js'\nimport { Extension } from '../Extension.js'\n\nexport * from '../commands/index.js'\n\nexport const Commands = Extension.create({\n  name: 'commands',\n\n  addCommands() {\n    return {\n      ...commands,\n    }\n  },\n})\n", "import { RemoveMarkStep } from '@tiptap/pm/transform'\n\nimport { Extension } from '../Extension.js'\nimport { combineTransactionSteps, getChangedRanges } from '../helpers/index.js'\n\n/**\n * This extension allows you to be notified when the user deletes content you are interested in.\n */\nexport const Delete = Extension.create({\n  name: 'delete',\n\n  onUpdate({ transaction, appendedTransactions }) {\n    const callback = () => {\n      if (\n        this.editor.options.coreExtensionOptions?.delete?.filterTransaction?.(transaction) ??\n        transaction.getMeta('y-sync$')\n      ) {\n        return\n      }\n      const nextTransaction = combineTransactionSteps(transaction.before, [\n        transaction,\n        ...appendedTransactions,\n      ])\n      const changes = getChangedRanges(nextTransaction)\n\n      changes.forEach(change => {\n        if (\n          nextTransaction.mapping.mapResult(change.oldRange.from).deletedAfter &&\n          nextTransaction.mapping.mapResult(change.oldRange.to).deletedBefore\n        ) {\n          nextTransaction.before.nodesBetween(\n            change.oldRange.from,\n            change.oldRange.to,\n            (node, from) => {\n              const to = from + node.nodeSize - 2\n              const isFullyWithinRange = change.oldRange.from <= from && to <= change.oldRange.to\n\n              this.editor.emit('delete', {\n                type: 'node',\n                node,\n                from,\n                to,\n                newFrom: nextTransaction.mapping.map(from),\n                newTo: nextTransaction.mapping.map(to),\n                deletedRange: change.oldRange,\n                newRange: change.newRange,\n                partial: !isFullyWithinRange,\n                editor: this.editor,\n                transaction,\n                combinedTransform: nextTransaction,\n              })\n            },\n          )\n        }\n      })\n\n      const mapping = nextTransaction.mapping\n      nextTransaction.steps.forEach((step, index) => {\n        if (step instanceof RemoveMarkStep) {\n          const newStart = mapping.slice(index).map(step.from, -1)\n          const newEnd = mapping.slice(index).map(step.to)\n          const oldStart = mapping.invert().map(newStart, -1)\n          const oldEnd = mapping.invert().map(newEnd)\n\n          const foundBeforeMark =\n            newStart > 0\n              ? nextTransaction.doc.nodeAt(newStart - 1)?.marks.some(mark => mark.eq(step.mark))\n              : false\n          const foundAfterMark = nextTransaction.doc\n            .nodeAt(newEnd)\n            ?.marks.some(mark => mark.eq(step.mark))\n\n          this.editor.emit('delete', {\n            type: 'mark',\n            mark: step.mark,\n            from: step.from,\n            to: step.to,\n            deletedRange: {\n              from: oldStart,\n              to: oldEnd,\n            },\n            newRange: {\n              from: newStart,\n              to: newEnd,\n            },\n            partial: Boolean(foundAfterMark || foundBeforeMark),\n            editor: this.editor,\n            transaction,\n            combinedTransform: nextTransaction,\n          })\n        }\n      })\n    }\n\n    if (this.editor.options.coreExtensionOptions?.delete?.async ?? true) {\n      setTimeout(callback, 0)\n    } else {\n      callback()\n    }\n  },\n})\n", "import { Plugin, PluginKey } from '@tiptap/pm/state'\n\nimport { Extension } from '../Extension.js'\n\nexport const Drop = Extension.create({\n  name: 'drop',\n\n  addProseMirrorPlugins() {\n    return [\n      new Plugin({\n        key: new PluginKey('tiptapDrop'),\n\n        props: {\n          handleDrop: (_, e, slice, moved) => {\n            this.editor.emit('drop', {\n              editor: this.editor,\n              event: e,\n              slice,\n              moved,\n            })\n          },\n        },\n      }),\n    ]\n  },\n})\n", "import { Plugin, PluginKey } from '@tiptap/pm/state'\n\nimport { Extension } from '../Extension.js'\n\nexport const Editable = Extension.create({\n  name: 'editable',\n\n  addProseMirrorPlugins() {\n    return [\n      new Plugin({\n        key: new PluginKey('editable'),\n        props: {\n          editable: () => this.editor.options.editable,\n        },\n      }),\n    ]\n  },\n})\n", "import { Plugin, PluginKey } from '@tiptap/pm/state'\n\nimport { Extension } from '../Extension.js'\n\nexport const focusEventsPluginKey = new PluginKey('focusEvents')\n\nexport const FocusEvents = Extension.create({\n  name: 'focusEvents',\n\n  addProseMirrorPlugins() {\n    const { editor } = this\n\n    return [\n      new Plugin({\n        key: focusEventsPluginKey,\n        props: {\n          handleDOMEvents: {\n            focus: (view, event: Event) => {\n              editor.isFocused = true\n\n              const transaction = editor.state.tr\n                .setMeta('focus', { event })\n                .setMeta('addToHistory', false)\n\n              view.dispatch(transaction)\n\n              return false\n            },\n            blur: (view, event: Event) => {\n              editor.isFocused = false\n\n              const transaction = editor.state.tr\n                .setMeta('blur', { event })\n                .setMeta('addToHistory', false)\n\n              view.dispatch(transaction)\n\n              return false\n            },\n          },\n        },\n      }),\n    ]\n  },\n})\n", "import { Plugin, PluginKey } from '@tiptap/pm/state'\nimport type { EditorView } from '@tiptap/pm/view'\n\nimport { isAndroid } from '../utilities/isAndroid.js'\n\nexport function createAndroidDeletePlugin() {\n  return new Plugin({\n    key: new PluginKey('androidDelete'),\n    props: {\n      handleDOMEvents: {\n        input(view, event) {\n          if (!isAndroid() || event.inputType !== 'deleteContentBackward') {\n            return false\n          }\n\n          const { domObserver } = view as EditorView & {\n            domObserver: { forceFlush: () => void; flush: () => void }\n          }\n\n          // Reconcile native deletion before the delayed focus handler restores the caret.\n          domObserver.forceFlush()\n          domObserver.flush()\n\n          return false\n        },\n      },\n    },\n  })\n}\n", "import type { EditorState } from '@tiptap/pm/state'\nimport { Plugin, PluginKey, Selection } from '@tiptap/pm/state'\n\nimport { CommandManager } from '../CommandManager.js'\nimport { Extension } from '../Extension.js'\nimport { createChainableState } from '../helpers/createChainableState.js'\nimport { isNodeEmpty } from '../helpers/isNodeEmpty.js'\nimport { isiOS } from '../utilities/isiOS.js'\nimport { isMacOS } from '../utilities/isMacOS.js'\n\nimport { createAndroidDeletePlugin } from './createAndroidDeletePlugin.js'\n\n/** Checks if a non-empty selection spans the whole document. */\nfunction isWholeDocumentSelected(state: EditorState) {\n  const { empty, from, to } = state.selection\n\n  if (empty) {\n    return false\n  }\n\n  return from === Selection.atStart(state.doc).from && to === Selection.atEnd(state.doc).to\n}\n\nexport const Keymap = Extension.create({\n  name: 'keymap',\n\n  addKeyboardShortcuts() {\n    const handleBackspace = () =>\n      this.editor.commands.first(({ commands }) => [\n        () => commands.undoInputRule(),\n\n        // maybe convert first text block node to default node\n        () =>\n          commands.command(({ tr }) => {\n            const { selection, doc } = tr\n            const { empty, $anchor } = selection\n            const { pos, parent } = $anchor\n            const $parentPos =\n              $anchor.parent.isTextblock && pos > 0 ? tr.doc.resolve(pos - 1) : $anchor\n            const parentIsIsolating = $parentPos.parent.type.spec.isolating\n\n            const parentPos = $anchor.pos - $anchor.parentOffset\n\n            const isAtStart =\n              parentIsIsolating && $parentPos.parent.childCount === 1\n                ? parentPos === $anchor.pos\n                : Selection.atStart(doc).from === pos\n\n            if (\n              !empty ||\n              !parent.type.isTextblock ||\n              parent.textContent.length ||\n              !isAtStart ||\n              (isAtStart && $anchor.parent.type.name === 'paragraph') // prevent clearNodes when no nodes to clear, otherwise history stack is appended\n            ) {\n              return false\n            }\n\n            return commands.clearNodes()\n          }),\n\n        () => commands.deleteSelection(),\n        () => commands.joinBackward(),\n        () => commands.selectNodeBackward(),\n      ])\n\n    const handleDelete = () =>\n      this.editor.commands.first(({ commands }) => [\n        () => commands.deleteSelection(),\n        () => commands.deleteCurrentNode(),\n        () => commands.joinForward(),\n        () => commands.selectNodeForward(),\n      ])\n\n    const handleEnter = () =>\n      this.editor.commands.first(({ commands }) => [\n        () => commands.newlineInCode(),\n        () => commands.createParagraphNear(),\n        () => commands.liftEmptyBlock(),\n        () => commands.splitBlock(),\n      ])\n\n    const baseKeymap = {\n      Enter: handleEnter,\n      'Mod-Enter': () => this.editor.commands.exitCode(),\n      Backspace: handleBackspace,\n      'Mod-Backspace': handleBackspace,\n      'Shift-Backspace': handleBackspace,\n      Delete: handleDelete,\n      'Mod-Delete': handleDelete,\n      'Mod-a': () => this.editor.commands.selectAll(),\n    }\n\n    const pcKeymap = {\n      ...baseKeymap,\n    }\n\n    const macKeymap = {\n      ...baseKeymap,\n      'Ctrl-h': handleBackspace,\n      'Alt-Backspace': handleBackspace,\n      'Ctrl-d': handleDelete,\n      'Ctrl-Alt-Backspace': handleDelete,\n      'Alt-Delete': handleDelete,\n      'Alt-d': handleDelete,\n      'Ctrl-a': () => this.editor.commands.selectTextblockStart(),\n      'Ctrl-e': () => this.editor.commands.selectTextblockEnd(),\n    }\n\n    if (isiOS() || isMacOS()) {\n      return macKeymap\n    }\n\n    return pcKeymap\n  },\n\n  addProseMirrorPlugins() {\n    return [\n      createAndroidDeletePlugin(),\n      // With this plugin we check if the whole document was selected and deleted.\n      // In this case we will additionally call `clearNodes()` to convert e.g. a heading\n      // to a paragraph if necessary.\n      // This is an alternative to ProseMirror's `AllSelection`, which doesn’t work well\n      // with many other commands.\n      new Plugin({\n        key: new PluginKey('clearDocument'),\n        appendTransaction: (transactions, oldState, newState) => {\n          if (transactions.some(tr => tr.getMeta('composition'))) {\n            return\n          }\n\n          const docChanges =\n            transactions.some(transaction => transaction.docChanged) &&\n            !oldState.doc.eq(newState.doc)\n\n          const ignoreTr = transactions.some(transaction =>\n            transaction.getMeta('preventClearDocument'),\n          )\n\n          if (!docChanges || ignoreTr) {\n            return\n          }\n\n          if (!isWholeDocumentSelected(oldState)) {\n            return\n          }\n\n          const isEmpty = isNodeEmpty(newState.doc)\n\n          if (!isEmpty) {\n            return\n          }\n\n          const tr = newState.tr\n          const state = createChainableState({\n            state: newState,\n            transaction: tr,\n          })\n          const { commands } = new CommandManager({\n            editor: this.editor,\n            state,\n          })\n\n          commands.clearNodes()\n\n          if (!tr.steps.length && !newState.storedMarks) {\n            return\n          }\n\n          // Don't carry marks of the deleted text into the empty document\n          return tr.setStoredMarks(null)\n        },\n      }),\n    ]\n  },\n})\n", "import { Plugin, PluginKey } from '@tiptap/pm/state'\n\nimport { Extension } from '../Extension.js'\n\nexport const Paste = Extension.create({\n  name: 'paste',\n\n  addProseMirrorPlugins() {\n    return [\n      new Plugin({\n        key: new PluginKey('tiptapPaste'),\n\n        props: {\n          handlePaste: (_view, e, slice) => {\n            this.editor.emit('paste', {\n              editor: this.editor,\n              event: e,\n              slice,\n            })\n          },\n        },\n      }),\n    ]\n  },\n})\n", "import { Plugin, PluginKey } from '@tiptap/pm/state'\n\nimport { Extension } from '../Extension.js'\n\n/**\n * Options for the Tabindex extension.\n */\nexport type TabindexOptions = {\n  /**\n   * The value for the `tabindex` attribute on the editor element.\n   * When undefined, editable editors default to `0` and non-editable editors get no tabindex.\n   */\n  value?: string\n}\n\n/**\n * The Tabindex extension adds a configurable tabindex attribute to the editor.\n *\n * By default, the editor gets tabindex=\"0\" when editable. This can be customized\n * via coreExtensionOptions to support specific focus ordering requirements in forms\n * or to enable focusing on non-editable editors.\n *\n * @example\n * ```ts\n * new Editor({\n *   coreExtensionOptions: {\n *     tabindex: {\n *       value: '-1',\n *     },\n *   },\n * })\n * ```\n */\nexport const Tabindex = Extension.create<TabindexOptions>({\n  name: 'tabindex',\n\n  addOptions() {\n    return {\n      value: undefined,\n    }\n  },\n\n  addProseMirrorPlugins() {\n    return [\n      new Plugin({\n        key: new PluginKey('tabindex'),\n        props: {\n          attributes: (): { [name: string]: string } => {\n            if (!this.editor.isEditable && this.options.value === undefined) {\n              return {}\n            }\n            return { tabindex: this.options.value ?? '0' }\n          },\n        },\n      }),\n    ]\n  },\n})\n", "import { Plugin, PluginKey } from '@tiptap/pm/state'\n\nimport { Extension } from '../Extension.js'\nimport { splitExtensions } from '../helpers/splitExtensions.js'\n\nexport interface TextDirectionOptions {\n  direction: 'ltr' | 'rtl' | 'auto' | undefined\n}\n\n/**\n * The TextDirection extension adds support for setting text direction (LTR/RTL/auto)\n * on all nodes in the editor.\n *\n * This extension adds a global `dir` attribute to all node types, which can be used\n * to control bidirectional text rendering. The direction can be set globally via\n * editor options or per-node using commands.\n */\nexport const TextDirection = Extension.create<TextDirectionOptions>({\n  name: 'textDirection',\n\n  addOptions() {\n    return {\n      direction: undefined,\n    }\n  },\n\n  addGlobalAttributes() {\n    // Only add the dir attribute to nodes if text direction is configured\n    // This prevents null/undefined values from appearing in JSON exports\n    if (!this.options.direction) {\n      return []\n    }\n\n    const { nodeExtensions } = splitExtensions(this.extensions)\n\n    return [\n      {\n        types: nodeExtensions\n          .filter(extension => extension.name !== 'text')\n          .map(extension => extension.name),\n        attributes: {\n          dir: {\n            default: this.options.direction,\n            parseHTML: element => {\n              const dir = element.getAttribute('dir')\n\n              if (dir && (dir === 'ltr' || dir === 'rtl' || dir === 'auto')) {\n                return dir\n              }\n\n              return this.options.direction\n            },\n            renderHTML: attributes => {\n              if (!attributes.dir) {\n                return {}\n              }\n\n              return {\n                dir: attributes.dir,\n              }\n            },\n          },\n        },\n      },\n    ]\n  },\n\n  addProseMirrorPlugins() {\n    return [\n      new Plugin({\n        key: new PluginKey('textDirection'),\n        props: {\n          attributes: (): { [name: string]: string } => {\n            const direction = this.options.direction\n\n            if (!direction) {\n              return {}\n            }\n\n            return {\n              dir: direction,\n            }\n          },\n        },\n      }),\n    ]\n  },\n})\n", "export { ClipboardTextSerializer } from './clipboardTextSerializer.js'\nexport { Commands } from './commands.js'\nexport { Delete } from './delete.js'\nexport { Drop } from './drop.js'\nexport { Editable } from './editable.js'\nexport { FocusEvents, focusEventsPluginKey } from './focusEvents.js'\nexport { Keymap } from './keymap.js'\nexport { Paste } from './paste.js'\nexport { Tabindex } from './tabindex.js'\nexport { TextDirection } from './textDirection.js'\n", "import type { Schema } from '@tiptap/pm/model'\nimport { Fragment } from '@tiptap/pm/model'\nimport { ReplaceStep } from '@tiptap/pm/transform'\n\nimport { isProseMirrorReplaceStep } from './isProseMirrorReplaceStep.js'\n\nlet hasChecked = false\n\n/**\n * Warns once when prosemirror-model is loaded twice\n * @param schema The editor schema\n * @returns void\n * @example ```js\n * warnOnDuplicatedProseMirrorModel(editor.schema)\n * ```\n */\nexport function warnOnDuplicatedProseMirrorModel(schema: Schema): void {\n  if (hasChecked) {\n    return\n  }\n\n  hasChecked = true\n\n  let content\n\n  try {\n    // Read the fragment from the model copy resolved by prosemirror-transform.\n    const step = ReplaceStep.fromJSON(schema, { from: 0, to: 0 })\n\n    if (!isProseMirrorReplaceStep(step)) {\n      return\n    }\n\n    content = step.slice.content\n  } catch {\n    // A warning we cannot stand behind is worse than no warning.\n    return\n  }\n\n  if (content instanceof Fragment) {\n    return\n  }\n\n  console.warn(\n    '[tiptap warn]: prosemirror-model is loaded more than once. Wrapping and splitting nodes will fail. Deduplicate it in your lock file, or alias it to a single copy in your bundler.',\n  )\n}\n", "import type { Fragment, Node, ResolvedPos } from '@tiptap/pm/model'\n\nimport type { Editor } from './Editor.js'\nimport type { Content, Range } from './types.js'\n\nexport class NodePos {\n  private resolvedPos: ResolvedPos\n\n  private isBlock: boolean\n\n  private editor: Editor\n\n  private get name(): string {\n    return this.node.type.name\n  }\n\n  constructor(pos: ResolvedPos, editor: Editor, isBlock = false, node: Node | null = null) {\n    this.isBlock = isBlock\n    this.resolvedPos = pos\n    this.editor = editor\n    this.currentNode = node\n  }\n\n  private currentNode: Node | null = null\n\n  get node(): Node {\n    return this.currentNode || this.resolvedPos.node()\n  }\n\n  get element(): HTMLElement {\n    return this.editor.view.domAtPos(this.pos).node as HTMLElement\n  }\n\n  public actualDepth: number | null = null\n\n  get depth(): number {\n    return this.actualDepth ?? this.resolvedPos.depth\n  }\n\n  get pos(): number {\n    return this.resolvedPos.pos\n  }\n\n  get content(): Fragment {\n    return this.node.content\n  }\n\n  set content(content: Content) {\n    let from = this.from\n    let to = this.to\n\n    if (this.isBlock) {\n      if (this.content.size === 0) {\n        console.error(\n          `You can’t set content on a block node. Tried to set content on ${this.name} at ${this.pos}`,\n        )\n        return\n      }\n\n      from = this.from + 1\n      to = this.to - 1\n    }\n\n    this.editor.commands.insertContentAt({ from, to }, content)\n  }\n\n  get attributes(): { [key: string]: any } {\n    return this.node.attrs\n  }\n\n  get textContent(): string {\n    return this.node.textContent\n  }\n\n  get size(): number {\n    return this.node.nodeSize\n  }\n\n  get from(): number {\n    if (this.isBlock) {\n      return this.pos\n    }\n\n    return this.resolvedPos.start(this.resolvedPos.depth)\n  }\n\n  get range(): Range {\n    return {\n      from: this.from,\n      to: this.to,\n    }\n  }\n\n  get to(): number {\n    if (this.isBlock) {\n      return this.pos + this.size\n    }\n\n    return this.resolvedPos.end(this.resolvedPos.depth) + (this.node.isText ? 0 : 1)\n  }\n\n  get parent(): NodePos | null {\n    if (this.depth === 0) {\n      return null\n    }\n\n    const parentPos = this.resolvedPos.start(this.resolvedPos.depth - 1)\n    const $pos = this.resolvedPos.doc.resolve(parentPos)\n\n    return new NodePos($pos, this.editor)\n  }\n\n  get before(): NodePos | null {\n    let $pos = this.resolvedPos.doc.resolve(this.from - (this.isBlock ? 1 : 2))\n\n    if ($pos.depth !== this.depth) {\n      $pos = this.resolvedPos.doc.resolve(this.from - 3)\n    }\n\n    return new NodePos($pos, this.editor)\n  }\n\n  get after(): NodePos | null {\n    let $pos = this.resolvedPos.doc.resolve(this.to + (this.isBlock ? 2 : 1))\n\n    if ($pos.depth !== this.depth) {\n      $pos = this.resolvedPos.doc.resolve(this.to + 3)\n    }\n\n    return new NodePos($pos, this.editor)\n  }\n\n  get children(): NodePos[] {\n    const children: NodePos[] = []\n\n    this.node.content.forEach((node, offset) => {\n      const isBlock = node.isBlock && !node.isTextblock\n      const isNonTextAtom = node.isAtom && !node.isText\n      const isInline = node.isInline\n\n      const targetPos = this.pos + offset + (isNonTextAtom ? 0 : 1)\n\n      // Check if targetPos is within valid document range\n      if (targetPos < 0 || targetPos > this.resolvedPos.doc.nodeSize - 2) {\n        return\n      }\n\n      const $pos = this.resolvedPos.doc.resolve(targetPos)\n\n      // Only apply depth check for non-block, non-inline nodes (i.e., textblocks)\n      // Inline nodes should always be included as children since we're iterating\n      // over direct children via this.node.content\n      if (!isBlock && !isInline && $pos.depth <= this.depth) {\n        return\n      }\n\n      // Pass the node for both block and inline nodes to ensure correct node reference\n      const childNodePos = new NodePos(\n        $pos,\n        this.editor,\n        isBlock,\n        isBlock || isInline ? node : null,\n      )\n\n      if (isBlock) {\n        childNodePos.actualDepth = this.depth + 1\n      }\n\n      children.push(childNodePos)\n    })\n\n    return children\n  }\n\n  get firstChild(): NodePos | null {\n    return this.children[0] || null\n  }\n\n  get lastChild(): NodePos | null {\n    const children = this.children\n\n    return children[children.length - 1] || null\n  }\n\n  closest(selector: string, attributes: { [key: string]: any } = {}): NodePos | null {\n    let node: NodePos | null = null\n    let currentNode = this.parent\n\n    while (currentNode && !node) {\n      if (currentNode.node.type.name === selector) {\n        if (Object.keys(attributes).length > 0) {\n          const nodeAttributes = currentNode.node.attrs\n          const attrKeys = Object.keys(attributes)\n\n          for (let index = 0; index < attrKeys.length; index += 1) {\n            const key = attrKeys[index]\n\n            if (nodeAttributes[key] !== attributes[key]) {\n              break\n            }\n          }\n        } else {\n          node = currentNode\n        }\n      }\n\n      currentNode = currentNode.parent\n    }\n\n    return node\n  }\n\n  querySelector(selector: string, attributes: { [key: string]: any } = {}): NodePos | null {\n    return this.querySelectorAll(selector, attributes, true)[0] || null\n  }\n\n  querySelectorAll(\n    selector: string,\n    attributes: { [key: string]: any } = {},\n    firstItemOnly = false,\n  ): NodePos[] {\n    let nodes: NodePos[] = []\n\n    if (!this.children || this.children.length === 0) {\n      return nodes\n    }\n    const attrKeys = Object.keys(attributes)\n\n    /**\n     * Finds all children recursively that match the selector and attributes\n     * If firstItemOnly is true, it will return the first item found\n     */\n    this.children.forEach(childPos => {\n      // If we already found a node and we only want the first item, we dont need to keep going\n      if (firstItemOnly && nodes.length > 0) {\n        return\n      }\n\n      if (childPos.node.type.name === selector) {\n        const doesAllAttributesMatch = attrKeys.every(\n          key => attributes[key] === childPos.node.attrs[key],\n        )\n\n        if (doesAllAttributesMatch) {\n          nodes.push(childPos)\n        }\n      }\n\n      // If we already found a node and we only want the first item, we can stop here and skip the recursion\n      if (firstItemOnly && nodes.length > 0) {\n        return\n      }\n\n      nodes = nodes.concat(childPos.querySelectorAll(selector, attributes, firstItemOnly))\n    })\n\n    return nodes\n  }\n\n  setAttribute(attributes: { [key: string]: any }) {\n    const { tr } = this.editor.state\n\n    tr.setNodeMarkup(this.from, undefined, {\n      ...this.node.attrs,\n      ...attributes,\n    })\n\n    this.editor.view.dispatch(tr)\n  }\n}\n", "export const style = `.ProseMirror {\n  position: relative;\n}\n\n.ProseMirror {\n  word-wrap: break-word;\n  white-space: pre-wrap;\n  white-space: break-spaces;\n  -webkit-font-variant-ligatures: none;\n  font-variant-ligatures: none;\n  font-feature-settings: \"liga\" 0; /* the above doesn't seem to work in Edge */\n}\n\n.ProseMirror [contenteditable=\"false\"] {\n  white-space: normal;\n}\n\n.ProseMirror [contenteditable=\"false\"] [contenteditable=\"true\"] {\n  white-space: pre-wrap;\n}\n\n.ProseMirror pre {\n  white-space: pre-wrap;\n}\n\nimg.ProseMirror-separator {\n  display: inline !important;\n  border: none !important;\n  margin: 0 !important;\n  width: 0 !important;\n  height: 0 !important;\n}\n\n.ProseMirror-gapcursor {\n  display: none;\n  pointer-events: none;\n  position: absolute;\n  margin: 0;\n}\n\n.ProseMirror-gapcursor:after {\n  content: \"\";\n  display: block;\n  position: absolute;\n  top: -2px;\n  width: 20px;\n  border-top: 1px solid black;\n  animation: ProseMirror-cursor-blink 1.1s steps(2, start) infinite;\n}\n\n@keyframes ProseMirror-cursor-blink {\n  to {\n    visibility: hidden;\n  }\n}\n\n.ProseMirror-hideselection *::selection {\n  background: transparent;\n}\n\n.ProseMirror-hideselection *::-moz-selection {\n  background: transparent;\n}\n\n.ProseMirror-hideselection * {\n  caret-color: transparent;\n}\n\n.ProseMirror-focused .ProseMirror-gapcursor {\n  display: block;\n}`\n", "/* oslint-disableno-empty-object-type */\nimport type { MarkType, Node as ProseMirrorNode, NodeType, Schema } from '@tiptap/pm/model'\nimport type { Plugin, PluginKey, Transaction } from '@tiptap/pm/state'\nimport { EditorState } from '@tiptap/pm/state'\nimport { type DirectEditorProps, EditorView } from '@tiptap/pm/view'\n\nimport { CommandManager } from './CommandManager.js'\nimport { isInDecorationApplyScope } from './decorations/decorationApplyScope.js'\nimport { EventEmitter } from './EventEmitter.js'\nimport { ExtensionManager } from './ExtensionManager.js'\nimport {\n  ClipboardTextSerializer,\n  Commands,\n  Delete,\n  Drop,\n  Editable,\n  FocusEvents,\n  Keymap,\n  Paste,\n  Tabindex,\n  TextDirection,\n} from './extensions/index.js'\nimport { createDocument } from './helpers/createDocument.js'\nimport { getAttributes } from './helpers/getAttributes.js'\nimport { getHTMLFromFragment } from './helpers/getHTMLFromFragment.js'\nimport { getText } from './helpers/getText.js'\nimport { getTextSerializersFromSchema } from './helpers/getTextSerializersFromSchema.js'\nimport { isActive } from './helpers/isActive.js'\nimport { isNodeEmpty } from './helpers/isNodeEmpty.js'\nimport { createMappablePosition, getUpdatedPosition } from './helpers/MappablePosition.js'\nimport { resolveFocusPosition } from './helpers/resolveFocusPosition.js'\nimport { warnOnDuplicatedProseMirrorModel } from './helpers/warnOnDuplicatedProseMirrorModel.js'\nimport type { Storage } from './index.js'\nimport { NodePos } from './NodePos.js'\nimport { style } from './style.js'\nimport type {\n  CanCommands,\n  ChainedCommands,\n  DocumentType,\n  EditorEvents,\n  EditorOptions,\n  NodeType as TNodeType,\n  SingleCommands,\n  TextSerializer,\n  TextType as TTextType,\n  Utils,\n} from './types.js'\nimport { createStyleTag } from './utilities/createStyleTag.js'\nimport { isDev } from './utilities/isDev.js'\nimport { isFunction } from './utilities/isFunction.js'\n\nexport * as extensions from './extensions/index.js'\n\n// @ts-ignore\nexport interface TiptapEditorHTMLElement extends HTMLElement {\n  editor?: Editor\n}\n\nexport class Editor extends EventEmitter<EditorEvents> {\n  private commandManager!: CommandManager\n\n  public extensionManager!: ExtensionManager\n\n  private css: HTMLStyleElement | null = null\n\n  private className = 'tiptap'\n\n  public schema!: Schema\n\n  private editorView: EditorView | null = null\n\n  public isFocused = false\n\n  private destroyed = false\n\n  private editorState!: EditorState\n\n  /**\n   * The editor is considered initialized after the `create` event has been emitted.\n   */\n  public isInitialized = false\n\n  public extensionStorage: Storage = {} as Storage\n\n  /**\n   * A unique ID for this editor instance.\n   */\n  public instanceId = Math.random().toString(36).slice(2, 9)\n\n  private hasWarnedStaleDecorationRead = false\n\n  public options: EditorOptions = {\n    element: typeof document !== 'undefined' ? document.createElement('div') : null,\n    content: '',\n    injectCSS: true,\n    injectNonce: undefined,\n    extensions: [],\n    autofocus: false,\n    editable: true,\n    textDirection: undefined,\n    editorProps: {},\n    parseOptions: {},\n    coreExtensionOptions: {},\n    enableInputRules: true,\n    enablePasteRules: true,\n    enableCoreExtensions: true,\n    enableContentCheck: false,\n    emitContentError: false,\n    onBeforeCreate: () => null,\n    onCreate: () => null,\n    onMount: () => null,\n    onUnmount: () => null,\n    onUpdate: () => null,\n    onSelectionUpdate: () => null,\n    onTransaction: () => null,\n    onFocus: () => null,\n    onBlur: () => null,\n    onDestroy: () => null,\n    onContentError: ({ error }) => {\n      throw error\n    },\n    onPaste: () => null,\n    onDrop: () => null,\n    onDelete: () => null,\n    enableExtensionDispatchTransaction: true,\n  }\n\n  constructor(options: Partial<EditorOptions> = {}) {\n    super()\n    this.setOptions(options)\n    this.createExtensionManager()\n    this.createCommandManager()\n    this.createSchema()\n    this.on('beforeCreate', this.options.onBeforeCreate)\n    this.emit('beforeCreate', { editor: this })\n    this.on('mount', this.options.onMount)\n    this.on('unmount', this.options.onUnmount)\n    this.on('contentError', this.options.onContentError)\n    this.on('create', this.options.onCreate)\n    this.on('update', this.options.onUpdate)\n    this.on('selectionUpdate', this.options.onSelectionUpdate)\n    this.on('transaction', this.options.onTransaction)\n    this.on('focus', this.options.onFocus)\n    this.on('blur', this.options.onBlur)\n    this.on('destroy', this.options.onDestroy)\n    this.on('drop', ({ event, slice, moved }) => this.options.onDrop(event, slice, moved))\n    this.on('paste', ({ event, slice }) => this.options.onPaste(event, slice))\n    this.on('delete', this.options.onDelete)\n\n    const initialDoc = this.createDoc()\n\n    // createDoc() already seeds editorState from the fallback doc on a content error\n    if (!this.editorState) {\n      const selection = resolveFocusPosition(initialDoc, this.options.autofocus)\n\n      this.editorState = EditorState.create({\n        doc: initialDoc,\n        schema: this.schema,\n        selection: selection || undefined,\n      })\n    }\n\n    warnOnDuplicatedProseMirrorModel(this.schema)\n\n    if (this.options.element) {\n      this.mount(this.options.element)\n    }\n  }\n\n  /**\n   * Attach the editor to the DOM, creating a new editor view.\n   */\n  public mount(el: NonNullable<EditorOptions['element']> & {}) {\n    if (typeof document === 'undefined') {\n      throw new Error(\n        `[tiptap error]: The editor cannot be mounted because there is no 'document' defined in this environment.`,\n      )\n    }\n    this.createView(el)\n    this.emit('mount', { editor: this })\n\n    if (this.css && !document.head.contains(this.css)) {\n      document.head.appendChild(this.css)\n    }\n\n    window.setTimeout(() => {\n      if (this.isDestroyed) {\n        return\n      }\n\n      if (this.options.autofocus !== false && this.options.autofocus !== null) {\n        this.commands.focus(this.options.autofocus)\n      }\n      this.emit('create', { editor: this })\n      this.isInitialized = true\n    }, 0)\n  }\n\n  /**\n   * Remove the editor from the DOM, but still allow remounting at a different point in time\n   */\n  public unmount() {\n    if (this.editorView) {\n      // Keep the cached state in sync so plugin state stays available after unmount.\n      this.editorState = this.editorView.state\n\n      // Cleanup our reference to prevent circular references which caused memory leaks\n      // @ts-ignore\n      const dom = this.editorView.dom as TiptapEditorHTMLElement\n\n      if (dom?.editor) {\n        delete dom.editor\n      }\n      this.editorView.destroy()\n    }\n    this.editorView = null\n    this.isInitialized = false\n\n    // Safely remove CSS element with fallback for test environments\n    // Only remove CSS if no other editors exist in the document after unmount\n    if (this.css && !document.querySelectorAll(`.${this.className}`).length) {\n      try {\n        if (typeof this.css.remove === 'function') {\n          this.css.remove()\n        } else if (this.css.parentNode) {\n          this.css.parentNode.removeChild(this.css)\n        }\n      } catch (error) {\n        // Silently handle any unexpected DOM removal errors in test environments\n        console.warn('Failed to remove CSS element:', error)\n      }\n    }\n    this.css = null\n    this.emit('unmount', { editor: this })\n  }\n\n  /**\n   * Returns the editor storage.\n   */\n  public get storage(): Storage {\n    return this.extensionStorage\n  }\n\n  /**\n   * An object of all registered commands.\n   */\n  public get commands(): SingleCommands {\n    return this.commandManager.commands\n  }\n\n  /**\n   * Create a command chain to call multiple commands at once.\n   */\n  public chain(): ChainedCommands {\n    if (!this.commandManager) {\n      return CommandManager.createFakeChain()\n    }\n\n    return this.commandManager.chain()\n  }\n\n  /**\n   * Check if a command or a command chain can be executed. Without executing it.\n   */\n  public can(): CanCommands {\n    if (!this.commandManager) {\n      return CommandManager.createFallbackCan()\n    }\n\n    return this.commandManager.can()\n  }\n\n  /**\n   * Inject CSS styles.\n   */\n  private injectCSS(): void {\n    if (this.options.injectCSS && typeof document !== 'undefined') {\n      this.css = createStyleTag(style, this.options.injectNonce)\n    }\n  }\n\n  /**\n   * Update editor options.\n   *\n   * @param options A list of options\n   */\n  public setOptions(options: Partial<EditorOptions> = {}): void {\n    this.options = {\n      ...this.options,\n      ...options,\n    }\n\n    if (!this.editorView || !this.state || this.isDestroyed) {\n      return\n    }\n\n    if (this.options.editorProps) {\n      this.view.setProps({\n        ...this.options.editorProps,\n        attributes: this.getEditorViewAttributes(),\n      })\n    }\n\n    this.view.updateState(this.state)\n  }\n\n  /**\n   * Update editable state of the editor.\n   */\n  public setEditable(editable: boolean, emitUpdate = true): void {\n    this.setOptions({ editable })\n\n    if (emitUpdate) {\n      this.emit('update', { editor: this, transaction: this.state.tr, appendedTransactions: [] })\n    }\n  }\n\n  /**\n   * Returns whether the editor is editable.\n   */\n  public get isEditable(): boolean {\n    // since plugins are applied after creating the view\n    // `editable` is always `true` for one tick.\n    // that’s why we also have to check for `options.editable`\n    return this.options.editable && this.view && this.view.editable\n  }\n\n  /**\n   * Returns the editor view.\n   */\n  public get view(): EditorView {\n    if (this.editorView) {\n      return this.editorView\n    }\n\n    return new Proxy(\n      {\n        state: this.editorState,\n        updateState: (state: EditorState): ReturnType<EditorView['updateState']> => {\n          this.editorState = state\n        },\n        dispatch: (tr: Transaction): ReturnType<EditorView['dispatch']> => {\n          this.dispatchTransaction(tr)\n        },\n\n        // Stub some commonly accessed properties to prevent errors\n        composing: false,\n        dragging: null,\n        editable: true,\n        isDestroyed: false,\n      } as EditorView,\n      {\n        get: (obj, key) => {\n          if (this.editorView) {\n            // If the editor view is available, but the caller has a stale reference to the proxy,\n            // Just return what the editor view has.\n            return this.editorView[key as keyof EditorView]\n          }\n          // Specifically always return the most recent editorState\n          if (key === 'state') {\n            return this.editorState\n          }\n          if (key in obj) {\n            return Reflect.get(obj, key)\n          }\n\n          // We throw an error here, because we know the view is not available\n          throw new Error(\n            `[tiptap error]: The editor view is not available. Cannot access view['${key as string}']. The editor may not be mounted yet.`,\n          )\n        },\n      },\n    ) as EditorView\n  }\n\n  /**\n   * Returns the editor state.\n   */\n  public get state(): EditorState {\n    if (isDev && !this.hasWarnedStaleDecorationRead && isInDecorationApplyScope(this)) {\n      // Warn once per editor. The same read repeats on every transaction, and\n      // a decoration that dispatches from `create()` would flood the console.\n      this.hasWarnedStaleDecorationRead = true\n\n      console.warn(\n        '[tiptap warn]: `editor.state` was read while decoration `create()` was running. ' +\n          'It returns the pre-transaction document. Use the `state` argument passed to ' +\n          '`create()` instead. Helpers like `editor.isActive()` read `editor.state` too, ' +\n          'so pass `state` to their standalone versions instead of calling them on the editor.',\n      )\n    }\n\n    if (this.editorView) {\n      this.editorState = this.view.state\n    }\n\n    return this.editorState\n  }\n\n  /**\n   * Register a ProseMirror plugin.\n   *\n   * @param plugin A ProseMirror plugin\n   * @param handlePlugins Control how to merge the plugin into the existing plugins.\n   * @returns The new editor state\n   */\n  public registerPlugin(\n    plugin: Plugin,\n    handlePlugins?: (newPlugin: Plugin, plugins: Plugin[]) => Plugin[],\n  ): EditorState {\n    const plugins = isFunction(handlePlugins)\n      ? handlePlugins(plugin, [...this.state.plugins])\n      : [...this.state.plugins, plugin]\n\n    const state = this.state.reconfigure({ plugins })\n\n    this.view.updateState(state)\n\n    return state\n  }\n\n  /**\n   * Unregister a ProseMirror plugin.\n   *\n   * @param nameOrPluginKeyToRemove The plugins name\n   * @returns The new editor state or undefined if the editor is destroyed\n   */\n  public unregisterPlugin(\n    nameOrPluginKeyToRemove: string | PluginKey | (string | PluginKey)[],\n  ): EditorState | undefined {\n    if (this.isDestroyed) {\n      return undefined\n    }\n\n    const prevPlugins = this.state.plugins\n    let plugins = prevPlugins\n\n    ;([] as (string | PluginKey)[]).concat(nameOrPluginKeyToRemove).forEach(nameOrPluginKey => {\n      // @ts-ignore\n      const name = typeof nameOrPluginKey === 'string' ? `${nameOrPluginKey}$` : nameOrPluginKey.key\n\n      // @ts-ignore\n      plugins = plugins.filter(plugin => !plugin.key.startsWith(name))\n    })\n\n    if (prevPlugins.length === plugins.length) {\n      // No plugin was removed, so we don’t need to update the state\n      return undefined\n    }\n\n    const state = this.state.reconfigure({\n      plugins,\n    })\n\n    this.view.updateState(state)\n\n    return state\n  }\n\n  /**\n   * Creates an extension manager.\n   */\n  private createExtensionManager(): void {\n    const coreExtensions = this.options.enableCoreExtensions\n      ? [\n          Editable,\n          ClipboardTextSerializer.configure({\n            blockSeparator:\n              this.options.coreExtensionOptions?.clipboardTextSerializer?.blockSeparator,\n          }),\n          Commands,\n          FocusEvents,\n          Keymap,\n          Tabindex.configure({\n            value: this.options.coreExtensionOptions?.tabindex?.value,\n          }),\n          Drop,\n          Paste,\n          Delete,\n          TextDirection.configure({\n            direction: this.options.textDirection,\n          }),\n        ].filter(ext => {\n          if (typeof this.options.enableCoreExtensions === 'object') {\n            return (\n              this.options.enableCoreExtensions[\n                ext.name as keyof typeof this.options.enableCoreExtensions\n              ] !== false\n            )\n          }\n          return true\n        })\n      : []\n    const allExtensions = [...coreExtensions, ...this.options.extensions].filter(extension => {\n      return ['extension', 'node', 'mark'].includes(extension?.type)\n    })\n\n    this.extensionManager = new ExtensionManager(allExtensions, this)\n  }\n\n  /**\n   * Creates an command manager.\n   */\n  private createCommandManager(): void {\n    this.commandManager = new CommandManager({\n      editor: this,\n    })\n  }\n\n  /**\n   * Creates a ProseMirror schema.\n   */\n  private createSchema(): void {\n    this.schema = this.extensionManager.schema\n  }\n\n  /**\n   * Creates the initial document.\n   */\n  private createDoc(): ProseMirrorNode {\n    let doc: ProseMirrorNode\n\n    try {\n      doc = createDocument(this.options.content, this.schema, this.options.parseOptions, {\n        errorOnInvalidContent: this.options.enableContentCheck,\n      })\n    } catch (e) {\n      if (\n        !(e instanceof Error) ||\n        !['[tiptap error]: Invalid JSON content', '[tiptap error]: Invalid HTML content'].includes(\n          e.message,\n        )\n      ) {\n        // Not the content error we were expecting\n        throw e\n      }\n\n      // Content is invalid, but attempt to create it anyway, stripping out the invalid parts\n      const fallbackDoc = createDocument(\n        this.options.content,\n        this.schema,\n        this.options.parseOptions,\n        {\n          errorOnInvalidContent: false,\n        },\n      )\n\n      // Seed editorState with the fallback doc so a handler can safely use `editor.commands`\n      this.editorState = EditorState.create({\n        doc: fallbackDoc,\n        schema: this.schema,\n        selection: resolveFocusPosition(fallbackDoc, this.options.autofocus) || undefined,\n      })\n\n      this.emit('contentError', {\n        editor: this,\n        error: e as Error,\n        disableCollaboration: () => {\n          if (\n            'collaboration' in this.storage &&\n            typeof this.storage.collaboration === 'object' &&\n            this.storage.collaboration\n          ) {\n            ;(this.storage.collaboration as any).isDisabled = true\n          }\n          // To avoid syncing back invalid content, reinitialize the extensions without the collaboration extension\n          this.options.extensions = this.options.extensions.filter(\n            extension => extension.name !== 'collaboration',\n          )\n\n          // Restart the initialization process by recreating the extension manager with the new set of extensions\n          this.createExtensionManager()\n        },\n      })\n\n      return this.editorState.doc\n    }\n    return doc\n  }\n\n  /**\n   * Returns the attributes for the editor element.\n   * Merges the default `role=\"textbox\"` with the attributes from `editorProps`,\n   * so the role is kept no matter when the props are applied.\n   */\n  private getEditorViewAttributes(): NonNullable<DirectEditorProps['attributes']> {\n    const attributes = this.options.editorProps?.attributes\n\n    if (isFunction(attributes)) {\n      return state => ({\n        role: 'textbox',\n        ...attributes(state),\n      })\n    }\n\n    return {\n      role: 'textbox',\n      ...attributes,\n    }\n  }\n\n  /**\n   * Creates a ProseMirror view.\n   */\n  private createView(element: NonNullable<EditorOptions['element']>): void {\n    const { editorProps, enableExtensionDispatchTransaction } = this.options\n    // If a user provided a custom `dispatchTransaction` through `editorProps`,\n    // we use that as the base dispatch function.\n    // Otherwise, we use Tiptap's internal `dispatchTransaction` method.\n    const baseDispatch =\n      (editorProps as DirectEditorProps).dispatchTransaction || this.dispatchTransaction.bind(this)\n    const dispatch = enableExtensionDispatchTransaction\n      ? this.extensionManager.dispatchTransaction(baseDispatch)\n      : baseDispatch\n\n    // Compose transformPastedHTML from extensions and user-provided editorProps\n    const baseTransformPastedHTML = (editorProps as DirectEditorProps).transformPastedHTML\n    const transformPastedHTML = this.extensionManager.transformPastedHTML(baseTransformPastedHTML)\n\n    this.editorView = new EditorView(element, {\n      ...editorProps,\n      attributes: this.getEditorViewAttributes(),\n      dispatchTransaction: dispatch,\n      transformPastedHTML,\n      state: this.editorState,\n      markViews: this.extensionManager.markViews,\n      nodeViews: this.extensionManager.nodeViews,\n    })\n\n    // `editor.view` is not yet available at this time.\n    // Therefore we will add all plugins and node views directly afterwards.\n    const newState = this.state.reconfigure({\n      plugins: this.extensionManager.plugins,\n    })\n\n    this.view.updateState(newState)\n\n    this.prependClass()\n    this.injectCSS()\n\n    // Let’s store the editor instance in the DOM element.\n    // So we’ll have access to it for tests.\n    // @ts-ignore\n    const dom = this.view.dom as TiptapEditorHTMLElement\n\n    dom.editor = this\n  }\n\n  /**\n   * Creates all node and mark views.\n   */\n  public createNodeViews(): void {\n    if (this.view.isDestroyed) {\n      return\n    }\n\n    this.view.setProps({\n      markViews: this.extensionManager.markViews,\n      nodeViews: this.extensionManager.nodeViews,\n    })\n  }\n\n  /**\n   * Prepend class name to element.\n   */\n  public prependClass(): void {\n    this.view.dom.className = `${this.className} ${this.view.dom.className}`\n  }\n\n  public isCapturingTransaction = false\n\n  private capturedTransaction: Transaction | null = null\n\n  public captureTransaction(fn: () => void) {\n    this.isCapturingTransaction = true\n    fn()\n    this.isCapturingTransaction = false\n\n    const tr = this.capturedTransaction\n\n    this.capturedTransaction = null\n\n    return tr\n  }\n\n  /**\n   * The callback over which to send transactions (state updates) produced by the view.\n   *\n   * @param transaction An editor state transaction\n   */\n  private dispatchTransaction(transaction: Transaction): void {\n    // if the editor / the view of the editor was destroyed\n    // the transaction should not be dispatched as there is no view anymore.\n    if (this.view.isDestroyed) {\n      return\n    }\n\n    if (this.isCapturingTransaction) {\n      if (!this.capturedTransaction) {\n        this.capturedTransaction = transaction\n\n        return\n      }\n\n      transaction.steps.forEach(step => this.capturedTransaction?.step(step))\n\n      return\n    }\n\n    // Apply transaction and get resulting state and transactions\n    const { state, transactions } = this.state.applyTransaction(transaction)\n    const selectionHasChanged = !this.state.selection.eq(state.selection)\n    const rootTrWasApplied = transactions.includes(transaction)\n    const prevState = this.state\n\n    this.emit('beforeTransaction', {\n      editor: this,\n      transaction,\n      nextState: state,\n    })\n\n    // If transaction was filtered out, we can return early\n    if (!rootTrWasApplied) {\n      return\n    }\n\n    this.view.updateState(state)\n\n    // Emit transaction event with appended transactions info\n    this.emit('transaction', {\n      editor: this,\n      transaction,\n      appendedTransactions: transactions.slice(1),\n    })\n\n    if (selectionHasChanged) {\n      this.emit('selectionUpdate', {\n        editor: this,\n        transaction,\n      })\n    }\n\n    // Only emit the latest between focus and blur events\n    const mostRecentFocusTr = transactions.findLast(tr => tr.getMeta('focus') || tr.getMeta('blur'))\n    const focus = mostRecentFocusTr?.getMeta('focus')\n    const blur = mostRecentFocusTr?.getMeta('blur')\n\n    if (focus) {\n      this.emit('focus', {\n        editor: this,\n        event: focus.event,\n        // oxlint-disable-next-lineno-non-null-assertion\n        transaction: mostRecentFocusTr!,\n      })\n    }\n\n    if (blur) {\n      this.emit('blur', {\n        editor: this,\n        event: blur.event,\n        // oxlint-disable-next-lineno-non-null-assertion\n        transaction: mostRecentFocusTr!,\n      })\n    }\n\n    // Compare states for update event\n    if (\n      transaction.getMeta('preventUpdate') ||\n      !transactions.some(tr => tr.docChanged) ||\n      prevState.doc.eq(state.doc)\n    ) {\n      return\n    }\n\n    this.emit('update', {\n      editor: this,\n      transaction,\n      appendedTransactions: transactions.slice(1),\n    })\n  }\n\n  /**\n   * Get attributes of the currently selected node or mark.\n   */\n  public getAttributes(nameOrType: string | NodeType | MarkType): Record<string, any> {\n    return getAttributes(this.state, nameOrType)\n  }\n\n  /**\n   * Returns if the currently selected node or mark is active.\n   *\n   * @param name Name of the node or mark\n   * @param attributes Attributes of the node or mark\n   */\n  public isActive(name: string, attributes?: {}): boolean\n  public isActive(attributes: {}): boolean\n  public isActive(nameOrAttributes: string, attributesOrUndefined?: {}): boolean {\n    const name = typeof nameOrAttributes === 'string' ? nameOrAttributes : null\n\n    const attributes =\n      typeof nameOrAttributes === 'string' ? attributesOrUndefined : nameOrAttributes\n\n    return isActive(this.state, name, attributes)\n  }\n\n  /**\n   * Get the document as JSON.\n   */\n  public getJSON(): DocumentType<\n    Record<string, any> | undefined,\n    TNodeType<string, undefined | Record<string, any>, any, (TNodeType | TTextType)[]>[]\n  > {\n    return this.state.doc.toJSON()\n  }\n\n  /**\n   * Get the document as HTML.\n   */\n  public getHTML(): string {\n    return getHTMLFromFragment(this.state.doc.content, this.schema)\n  }\n\n  /**\n   * Get the document as text.\n   */\n  public getText(options?: {\n    blockSeparator?: string\n    textSerializers?: Record<string, TextSerializer>\n  }): string {\n    const { blockSeparator = '\\n\\n', textSerializers = {} } = options || {}\n\n    return getText(this.state.doc, {\n      blockSeparator,\n      textSerializers: {\n        ...getTextSerializersFromSchema(this.schema),\n        ...textSerializers,\n      },\n    })\n  }\n\n  /**\n   * Check if there is no content.\n   */\n  public get isEmpty(): boolean {\n    return isNodeEmpty(this.state.doc)\n  }\n\n  /**\n   * Destroy the editor.\n   */\n  public destroy(): void {\n    if (this.destroyed) {\n      return\n    }\n\n    this.destroyed = true\n\n    this.emit('destroy')\n    this.unmount()\n    this.removeAllListeners()\n\n    this.extensionManager.destroy()\n    this.extensionManager = null as any\n    this.schema = null as any\n    this.commandManager = null as unknown as CommandManager\n    this.extensionStorage = {} as Storage\n  }\n\n  /**\n   * Check if the editor is already destroyed.\n   */\n  public get isDestroyed(): boolean {\n    return this.editorView?.isDestroyed ?? true\n  }\n\n  public $node(selector: string, attributes?: { [key: string]: any }): NodePos | null {\n    return this.$doc?.querySelector(selector, attributes) || null\n  }\n\n  public $nodes(selector: string, attributes?: { [key: string]: any }): NodePos[] | null {\n    return this.$doc?.querySelectorAll(selector, attributes) || null\n  }\n\n  public $pos(pos: number) {\n    const $pos = this.state.doc.resolve(pos)\n    // For positions directly before a non-text atom, resolvedPos.node() returns\n    // the parent, so pass the atom explicitly. Container nodes and $pos(0) keep\n    // resolving to the parent.\n    const node =\n      pos > 0 && $pos.nodeAfter && !$pos.nodeAfter.isText && $pos.nodeAfter.isAtom\n        ? $pos.nodeAfter\n        : null\n\n    return new NodePos($pos, this, false, node)\n  }\n\n  get $doc() {\n    return this.$pos(0)\n  }\n\n  /**\n   * Returns a set of utilities for working with positions and ranges.\n   */\n  public utils: Utils = {\n    getUpdatedPosition,\n    createMappablePosition,\n  }\n}\n", "import type { Mark } from '@tiptap/pm/model'\nimport { DecorationAttrs, Decoration as PMDecoration, type EditorView } from '@tiptap/pm/view'\n\nexport interface WidgetDecorationOptions {\n  side?: number\n  relaxedSide?: boolean\n  marks?: readonly Mark[]\n  stopEvent?: (event: Event) => boolean\n  ignoreSelection?: boolean\n  /**\n   * runs when ProseMirror drops the widget, also on editor destroy and unmount.\n   * skipped on teardown for widgets made with the React or Vue widget renderer.\n   * receives the DOM node, not a ProseMirror node.\n   */\n  destroy?: (node: globalThis.Node) => void\n}\n\nexport type DecorationKind = 'inline' | 'node' | 'widget'\n\n/**\n * Base class for decorations built in `addDecorations()`. Shadows `Decoration`\n * from `@tiptap/pm/view`, like core's `Node` and `Mark` do, so alias one of them\n * in files that need both.\n *\n * @example\n * import { Decoration } from '@tiptap/core'\n * import { Decoration as PMDecoration } from '@tiptap/pm/view'\n *\n * const highlight = Decoration.Inline(1, 5, { class: 'highlight' })\n */\nexport abstract class Decoration {\n  abstract kind: DecorationKind\n  abstract get anchor(): number\n\n  /**\n   * Builds the ProseMirror decoration. When `extensionName` is provided,\n   * it is embedded into the decoration spec for incremental merge tracking.\n   * @param extensionName The name of the extension that produced this decoration.\n   * @returns The ProseMirror decoration.\n   */\n  abstract toPMDecoration(extensionName?: string): PMDecoration\n\n  static Inline(\n    from: number,\n    to: number,\n    attrs: DecorationAttrs = {},\n    spec?: Record<string, any>,\n  ): InlineDecoration {\n    return new InlineDecoration(from, to, attrs, spec)\n  }\n\n  static Node(\n    pos: number,\n    to: number,\n    attrs: DecorationAttrs = {},\n    spec?: Record<string, any>,\n  ): NodeDecoration {\n    return new NodeDecoration(pos, to, attrs, spec)\n  }\n\n  /**\n   * Creates a widget decoration: a DOM node drawn at a document position.\n   *\n   * The `key` is the widget's identity. While it stays the same, ProseMirror\n   * keeps the widget mounted and only its position tracks the document.\n   * `render`, `side`, `destroy` and other options are fixed on first mount.\n   * Change the key to remount with new options.\n   *\n   * @param pos The document position where the widget is drawn.\n   * @param render Called once on first mount. Returns the DOM node.\n   * @param options Must include a unique `key`. See `WidgetDecorationOptions`.\n   * @returns The widget decoration.\n   */\n  static Widget(\n    pos: number,\n    render: (view: EditorView, getPos: () => number | undefined) => HTMLElement,\n    options: { key: string } & WidgetDecorationOptions & Record<string, any>,\n  ): WidgetDecoration {\n    const { key, ...spec } = options\n\n    return new WidgetDecoration(pos, render, key, spec)\n  }\n}\n\n/**\n * Represents an inline decoration (text-level highlighting, etc.).\n */\nexport class InlineDecoration extends Decoration {\n  kind = 'inline' as const\n  from: number\n  to: number\n  attrs: DecorationAttrs\n  spec?: Record<string, any>\n\n  constructor(from: number, to: number, attrs: DecorationAttrs = {}, spec?: Record<string, any>) {\n    super()\n    this.from = from\n    this.to = to\n    this.attrs = attrs\n    this.spec = spec\n  }\n\n  get anchor(): number {\n    return this.from\n  }\n\n  toPMDecoration(extensionName?: string): PMDecoration {\n    const spec = extensionName ? { ...this.spec, extensionName } : this.spec\n\n    return PMDecoration.inline(this.from, this.to, this.attrs, spec)\n  }\n}\n\n/**\n * Represents a node-level decoration (block-level highlights, etc.).\n */\nexport class NodeDecoration extends Decoration {\n  kind = 'node' as const\n  from: number\n  to: number\n  attrs: DecorationAttrs\n  spec?: Record<string, any>\n\n  constructor(pos: number, to: number, attrs: DecorationAttrs = {}, spec?: Record<string, any>) {\n    super()\n    this.from = pos\n    this.to = to\n    this.attrs = attrs\n    this.spec = spec\n  }\n\n  get anchor(): number {\n    return this.from\n  }\n\n  toPMDecoration(extensionName?: string): PMDecoration {\n    const spec = extensionName ? { ...this.spec, extensionName } : this.spec\n\n    return PMDecoration.node(this.from, this.to, this.attrs, spec)\n  }\n}\n\n/**\n * Represents a widget decoration (inline widgets, etc.).\n */\nexport class WidgetDecoration extends Decoration {\n  kind = 'widget' as const\n  pos: number\n  key: string\n  render: (view: EditorView, getPos: () => number | undefined) => HTMLElement\n  spec?: WidgetDecorationOptions & Record<string, any>\n\n  constructor(\n    pos: number,\n    render: (view: EditorView, getPos: () => number | undefined) => HTMLElement,\n    key: string,\n    spec?: WidgetDecorationOptions & Record<string, any>,\n  ) {\n    super()\n    this.pos = pos\n    this.render = render\n    this.key = key\n    this.spec = spec\n  }\n\n  get anchor(): number {\n    return this.pos\n  }\n\n  toPMDecoration(extensionName?: string): PMDecoration {\n    const spec = extensionName\n      ? { ...this.spec, key: this.key, extensionName }\n      : { ...this.spec, key: this.key }\n\n    return PMDecoration.widget(this.pos, this.render, spec)\n  }\n}\n", "import type { EditorView } from '@tiptap/pm/view'\n\nimport type { Editor } from '../Editor.js'\nimport { attrsEqual } from '../utilities/attrsEqual.js'\nimport { Decoration } from './Decoration.js'\nimport type { WidgetDecoration, WidgetDecorationOptions } from './Decoration.js'\nimport { liveWidgetKeys } from './DecorationManager.js'\n\n/**\n * The minimum a framework renderer must provide to be driven by\n * {@link createWidgetDecoration}. Both `ReactRenderer` and `VueRenderer` match it.\n */\nexport interface WidgetRenderer {\n  updateProps: (props: Record<string, any>) => void\n  destroy: () => void\n}\n\ninterface WidgetCache<TRenderer extends WidgetRenderer> {\n  /**\n   * The live renderer for each widget key, reused across recomputes so the\n   * component and its state are preserved instead of remounted.\n   */\n  renderers: Map<string, TRenderer>\n  /**\n   * Last props pushed to each widget. Skips updates when nothing changed.\n   */\n  props: Map<string, Record<string, any>>\n  /**\n   * Props queued during `create()` and pushed on the next microtask.\n   * Last write wins per key.\n   */\n  pendingProps: Map<string, Record<string, any>>\n  flushScheduled: boolean\n}\n\nexport interface CreateWidgetDecorationOptions<\n  TRenderer extends WidgetRenderer,\n> extends WidgetDecorationOptions {\n  /**\n   * The editor instance. The renderer cache is stored on it, so widgets are\n   * swept when the editor is destroyed.\n   */\n  editor: Editor\n  /**\n   * The document position the widget is rendered at.\n   */\n  pos: number\n  /**\n   * A stable, position-independent identifier for the widget. Reusing the same\n   * key keeps the component mounted across recomputes.\n   */\n  key: string\n  /**\n   * Props passed to the component, merged with {@link context} on every render.\n   */\n  props: Record<string, any>\n  /**\n   * The symbol the renderer cache is stored under on the editor. Use one\n   * dedicated symbol per framework package so caches never mix.\n   */\n  cacheKey: symbol\n  /**\n   * Extra props merged into every render, for example `editor` and `getPos`.\n   * Called on each materialization because `getPos` is view-bound.\n   */\n  context: (getPos: () => number | undefined) => Record<string, any>\n  /**\n   * Creates the renderer on first mount. Receives `props` and `context`\n   * already merged.\n   */\n  create: (props: Record<string, any>) => TRenderer\n  /**\n   * Returns the element ProseMirror inserts, plus any work that has to happen\n   * on every materialization (React re-registers its portal here).\n   */\n  materialize: (renderer: TRenderer) => HTMLElement\n}\n\nfunction getCache<TRenderer extends WidgetRenderer>(\n  editor: Editor,\n  cacheKey: symbol,\n): WidgetCache<TRenderer> {\n  const host = editor as Editor & Record<symbol, WidgetCache<TRenderer> | undefined>\n\n  let cache = host[cacheKey]\n\n  if (!cache) {\n    cache = {\n      renderers: new Map(),\n      props: new Map(),\n      pendingProps: new Map(),\n      flushScheduled: false,\n    }\n\n    host[cacheKey] = cache\n\n    const sweep = cache\n\n    // Sweep any widgets still mounted when the editor goes away.\n    editor.on('destroy', () => {\n      sweep.pendingProps.clear()\n      sweep.renderers.forEach(renderer => renderer.destroy())\n      sweep.renderers.clear()\n      sweep.props.clear()\n    })\n  }\n\n  return cache\n}\n\nfunction flushPendingProps<TRenderer extends WidgetRenderer>(cache: WidgetCache<TRenderer>): void {\n  cache.flushScheduled = false\n\n  for (const [key, props] of cache.pendingProps) {\n    const renderer = cache.renderers.get(key)\n\n    if (renderer) {\n      renderer.updateProps(props)\n      cache.props.set(key, { ...props })\n    }\n  }\n\n  cache.pendingProps.clear()\n}\n\n/**\n * Builds a widget decoration backed by a framework component renderer.\n *\n * Owns everything that is not framework specific: the per-editor renderer\n * cache, prop diffing, the deferred prop flush, the key reassignment guard and\n * the ProseMirror option pass-through. Framework packages supply only `create`,\n * `context` and `materialize`.\n *\n * @param options The widget options plus the three framework hooks.\n * @returns The widget decoration to return from `addDecorations`.\n * @example\n * createWidgetDecoration<ReactRenderer>({\n *   editor, pos, key, props, cacheKey: WIDGET_CACHE,\n *   context: getPos => ({ editor, getPos }),\n *   create: renderProps => new ReactRenderer(component, { editor, props: renderProps }),\n *   materialize: renderer => renderer.element,\n * })\n */\nexport function createWidgetDecoration<TRenderer extends WidgetRenderer>(\n  options: CreateWidgetDecorationOptions<TRenderer>,\n): WidgetDecoration {\n  const {\n    editor,\n    pos,\n    key,\n    props,\n    cacheKey,\n    context,\n    create,\n    materialize,\n    side,\n    relaxedSide,\n    marks,\n    stopEvent,\n    ignoreSelection,\n    destroy,\n  } = options\n  const cache = getCache<TRenderer>(editor, cacheKey)\n\n  // Queue prop updates for already-mounted widgets. This code runs inside\n  // ProseMirror's `state.apply`, which must stay pure, so the renderer is only\n  // touched on the next microtask. ProseMirror skips `render` when it reuses\n  // DOM, so the flush is the only update path for a mounted widget.\n  if (cache.renderers.has(key)) {\n    const previous = cache.pendingProps.get(key) ?? cache.props.get(key)\n\n    if (!previous || !attrsEqual(previous, props)) {\n      cache.pendingProps.set(key, props)\n\n      if (!cache.flushScheduled) {\n        cache.flushScheduled = true\n        queueMicrotask(() => flushPendingProps(cache))\n      }\n    }\n  }\n\n  const render = (_view: EditorView, getPos: () => number | undefined): HTMLElement => {\n    const renderProps = { ...props, ...context(getPos) }\n    let renderer = cache.renderers.get(key)\n\n    if (renderer) {\n      renderer.updateProps(renderProps)\n    } else {\n      renderer = create(renderProps)\n      cache.renderers.set(key, renderer)\n      cache.props.set(key, { ...props })\n    }\n\n    return materialize(renderer)\n  }\n\n  return Decoration.Widget(pos, render, {\n    key,\n    side,\n    relaxedSide,\n    marks,\n    stopEvent,\n    ignoreSelection,\n    destroy: (rendererElement: globalThis.Node) => {\n      // Keep the renderer if the widget is still live (being reassigned, not removed).\n      // Only correct because ProseMirror sets `view.state` before dropping widget descs.\n      if (liveWidgetKeys(editor).has(key)) {\n        return\n      }\n\n      try {\n        cache.renderers.get(key)?.destroy()\n        cache.renderers.delete(key)\n        cache.props.delete(key)\n        cache.pendingProps.delete(key)\n      } finally {\n        destroy?.(rendererElement)\n      }\n    },\n  })\n}\n", "import type { MarkType } from '@tiptap/pm/model'\n\nimport { getMarksBetween } from '../helpers/getMarksBetween.js'\nimport type { InputRuleFinder } from '../InputRule.js'\nimport { InputRule } from '../InputRule.js'\nimport type { ExtendedRegExpMatchArray } from '../types.js'\nimport { callOrReturn } from '../utilities/callOrReturn.js'\n\n/**\n * Build an input rule that adds a mark when the\n * matched text is typed into it.\n * @see https://tiptap.dev/docs/editor/extensions/custom-extensions/extend-existing#input-rules\n */\nexport function markInputRule(config: {\n  find: InputRuleFinder\n  type: MarkType\n  undoable?: boolean\n  getAttributes?:\n    | Record<string, any>\n    | ((match: ExtendedRegExpMatchArray) => Record<string, any>)\n    | false\n    | null\n}) {\n  return new InputRule({\n    find: config.find,\n    handler: ({ state, range, match }) => {\n      const attributes = callOrReturn(config.getAttributes, undefined, match)\n\n      if (attributes === false || attributes === null) {\n        return null\n      }\n\n      const { tr } = state\n      const captureGroup = match[match.length - 1]\n      const fullMatch = match[0]\n\n      if (captureGroup) {\n        const startSpaces = fullMatch.search(/\\S/)\n        const textStart = range.from + fullMatch.indexOf(captureGroup)\n        const textEnd = textStart + captureGroup.length\n\n        const excludedMarks = getMarksBetween(range.from, range.to, state.doc)\n          .filter(item => {\n            // @ts-ignore\n            const excluded = item.mark.type.excluded as MarkType[]\n\n            return excluded.find(type => type === config.type && type !== item.mark.type)\n          })\n          .filter(item => item.to > textStart)\n\n        if (excludedMarks.length) {\n          return null\n        }\n\n        if (textEnd < range.to) {\n          tr.delete(textEnd, range.to)\n        }\n\n        if (textStart > range.from) {\n          tr.delete(range.from + startSpaces, textStart)\n        }\n\n        const markEnd = range.from + startSpaces + captureGroup.length\n\n        tr.addMark(range.from + startSpaces, markEnd, config.type.create(attributes || {}))\n\n        tr.removeStoredMark(config.type)\n      }\n    },\n    undoable: config.undoable,\n  })\n}\n", "import type { NodeType } from '@tiptap/pm/model'\n\nimport type { InputRuleFinder } from '../InputRule.js'\nimport { InputRule } from '../InputRule.js'\nimport type { ExtendedRegExpMatchArray } from '../types.js'\nimport { callOrReturn } from '../utilities/callOrReturn.js'\n\n/**\n * Build an input rule that adds a node when the\n * matched text is typed into it.\n * @see https://tiptap.dev/docs/editor/extensions/custom-extensions/extend-existing#input-rules\n */\nexport function nodeInputRule(config: {\n  /**\n   * The regex to match.\n   */\n  find: InputRuleFinder\n\n  /**\n   * The node type to add.\n   */\n  type: NodeType\n\n  /**\n   * Whether the input rule should be undoable\n   * when the user presses backspace.\n   */\n  undoable?: boolean\n\n  /**\n   * A function that returns the attributes for the node\n   * can also be an object of attributes\n   */\n  getAttributes?:\n    | Record<string, any>\n    | ((match: ExtendedRegExpMatchArray) => Record<string, any>)\n    | false\n    | null\n}) {\n  return new InputRule({\n    find: config.find,\n    handler: ({ state, range, match }) => {\n      const attributes = callOrReturn(config.getAttributes, undefined, match) || {}\n      const { tr } = state\n      const start = range.from\n      let end = range.to\n\n      const newNode = config.type.create(attributes)\n\n      if (match[1]) {\n        const offset = match[0].lastIndexOf(match[1])\n        let matchStart = start + offset\n\n        if (matchStart > end) {\n          matchStart = end\n        } else {\n          end = matchStart + match[1].length\n        }\n\n        // Typed text is already in the document when the range covers the\n        // whole match (text input); otherwise insert the last typed character.\n        if (range.to - range.from < match[0].length) {\n          const lastChar = match[0][match[0].length - 1]\n\n          tr.insertText(lastChar, start + match[0].length - 1)\n        }\n\n        // insert node from input rule\n        tr.replaceWith(matchStart, end, newNode)\n      } else if (match[0]) {\n        const insertionStart = config.type.isInline ? start : start - 1\n\n        tr.insert(insertionStart, config.type.create(attributes)).delete(\n          tr.mapping.map(start),\n          tr.mapping.map(end),\n        )\n      }\n\n      tr.scrollIntoView()\n    },\n    undoable: config.undoable,\n  })\n}\n", "import type { NodeType } from '@tiptap/pm/model'\n\nimport type { InputRuleFinder } from '../InputRule.js'\nimport { InputRule } from '../InputRule.js'\nimport type { ExtendedRegExpMatchArray } from '../types.js'\nimport { callOrReturn } from '../utilities/callOrReturn.js'\n\n/**\n * Build an input rule that changes the type of a textblock when the\n * matched text is typed into it. When using a regular expresion you’ll\n * probably want the regexp to start with `^`, so that the pattern can\n * only occur at the start of a textblock.\n * @see https://tiptap.dev/docs/editor/extensions/custom-extensions/extend-existing#input-rules\n */\nexport function textblockTypeInputRule(config: {\n  find: InputRuleFinder\n  type: NodeType\n  undoable?: boolean\n  getAttributes?:\n    | Record<string, any>\n    | ((match: ExtendedRegExpMatchArray) => Record<string, any>)\n    | false\n    | null\n}) {\n  return new InputRule({\n    find: config.find,\n    handler: ({ state, range, match }) => {\n      const $start = state.doc.resolve(range.from)\n      const attributes = callOrReturn(config.getAttributes, undefined, match) || {}\n\n      if (!$start.node(-1).canReplaceWith($start.index(-1), $start.indexAfter(-1), config.type)) {\n        return null\n      }\n\n      state.tr\n        .delete(range.from, range.to)\n        .setBlockType(range.from, range.from, config.type, attributes)\n    },\n    undoable: config.undoable,\n  })\n}\n", "import type { InputRuleFinder } from '../InputRule.js'\nimport { InputRule } from '../InputRule.js'\n\n/**\n * Build an input rule that replaces text when the\n * matched text is typed into it.\n * @see https://tiptap.dev/docs/editor/extensions/custom-extensions/extend-existing#input-rules\n */\nexport function textInputRule(config: {\n  find: InputRuleFinder\n  replace: string\n  undoable?: boolean\n}) {\n  return new InputRule({\n    find: config.find,\n    handler: ({ state, range, match }) => {\n      let insert = config.replace\n      let start = range.from\n      const end = range.to\n\n      if (match[1]) {\n        const offset = match[0].lastIndexOf(match[1])\n\n        insert += match[0].slice(offset + match[1].length)\n        start += offset\n\n        const cutOff = start - end\n\n        if (cutOff > 0) {\n          insert = match[0].slice(offset - cutOff, offset) + insert\n          start = end\n        }\n      }\n\n      state.tr.insertText(insert, start, end)\n    },\n    undoable: config.undoable,\n  })\n}\n", "import type { Node as ProseMirrorNode, NodeType } from '@tiptap/pm/model'\nimport { canJoin, findWrapping } from '@tiptap/pm/transform'\n\nimport type { Editor } from '../Editor.js'\nimport type { InputRuleFinder } from '../InputRule.js'\nimport { InputRule } from '../InputRule.js'\nimport type { ExtendedRegExpMatchArray } from '../types.js'\nimport { callOrReturn } from '../utilities/callOrReturn.js'\n\n/**\n * Build an input rule for automatically wrapping a textblock when a\n * given string is typed. When using a regular expresion you’ll\n * probably want the regexp to start with `^`, so that the pattern can\n * only occur at the start of a textblock.\n *\n * `type` is the type of node to wrap in.\n *\n * By default, if there’s a node with the same type above the newly\n * wrapped node, the rule will try to join those\n * two nodes. You can pass a join predicate, which takes a regular\n * expression match and the node before the wrapped node, and can\n * return a boolean to indicate whether a join should happen.\n * @see https://tiptap.dev/docs/editor/extensions/custom-extensions/extend-existing#input-rules\n */\nexport function wrappingInputRule(config: {\n  find: InputRuleFinder\n  type: NodeType\n  keepMarks?: boolean\n  keepAttributes?: boolean\n  editor?: Editor\n  undoable?: boolean\n  getAttributes?:\n    | Record<string, any>\n    | ((match: ExtendedRegExpMatchArray) => Record<string, any>)\n    | false\n    | null\n  joinPredicate?: (match: ExtendedRegExpMatchArray, node: ProseMirrorNode) => boolean\n}) {\n  return new InputRule({\n    find: config.find,\n    handler: ({ state, range, match, chain }) => {\n      const attributes = callOrReturn(config.getAttributes, undefined, match) || {}\n      const tr = state.tr.delete(range.from, range.to)\n      const $start = tr.doc.resolve(range.from)\n      const blockRange = $start.blockRange()\n      const wrapping = blockRange && findWrapping(blockRange, config.type, attributes)\n\n      if (!wrapping) {\n        return null\n      }\n\n      tr.wrap(blockRange, wrapping)\n\n      if (config.keepMarks && config.editor) {\n        const { selection, storedMarks } = state\n        const { splittableMarks } = config.editor.extensionManager\n        const marks = storedMarks || (selection.$to.parentOffset && selection.$from.marks())\n\n        if (marks) {\n          const filteredMarks = marks.filter(mark => splittableMarks.includes(mark.type.name))\n\n          tr.ensureMarks(filteredMarks)\n        }\n      }\n      if (config.keepAttributes) {\n        /** If the nodeType is `bulletList` or `orderedList` set the `nodeType` as `listItem` */\n        const nodeType =\n          config.type.name === 'bulletList' || config.type.name === 'orderedList'\n            ? 'listItem'\n            : 'taskList'\n\n        chain().updateAttributes(nodeType, attributes).run()\n      }\n\n      const before = tr.doc.resolve(range.from - 1).nodeBefore\n\n      if (\n        before &&\n        before.type === config.type &&\n        canJoin(tr.doc, range.from - 1) &&\n        (!config.joinPredicate || config.joinPredicate(match, before))\n      ) {\n        tr.join(range.from - 1)\n      }\n    },\n    undoable: config.undoable,\n  })\n}\n", "export type Attributes = Record<string, any>\n\nexport type DOMOutputSpecElement = 0 | Attributes | DOMOutputSpecArray\n/**\n * Better describes the output of a `renderHTML` function in prosemirror\n * @see https://prosemirror.net/docs/ref/#model.DOMOutputSpec\n */\nexport type DOMOutputSpecArray =\n  | [string]\n  | [string, Attributes]\n  | [string, 0]\n  | [string, Attributes, 0]\n  | [string, Attributes, DOMOutputSpecArray | 0]\n  | [string, DOMOutputSpecArray]\n\n// Child lists and DOM output specs are both arrays, so track JSX boundaries by identity.\nconst jsxElements = new WeakSet<DOMOutputSpecArray>()\nconst jsxFragments = new WeakSet<unknown[]>()\n\n/** Create a new JSX element from the given spec */\nfunction createJSXElement(spec: unknown[]): DOMOutputSpecArray {\n  const element = spec as DOMOutputSpecArray\n\n  jsxElements.add(element)\n\n  return element\n}\n\n/** Check if a spec is a JSX element */\nfunction isJSXElement(value: unknown): value is DOMOutputSpecArray {\n  return Array.isArray(value) && jsxElements.has(value as DOMOutputSpecArray)\n}\n\nfunction flattenFragmentChildren(children: unknown[]): unknown[] {\n  return children.flatMap(child => {\n    if (child == null) {\n      return []\n    }\n\n    if (Array.isArray(child) && jsxFragments.has(child) && !isJSXElement(child)) {\n      return flattenFragmentChildren(child)\n    }\n\n    return [child]\n  })\n}\n\n// JSX types for Tiptap's JSX runtime\n// These types only apply when using @jsxImportSource @tiptap/core\nexport declare namespace JSX {\n  export type Element = DOMOutputSpecArray\n  export interface IntrinsicElements {\n    [key: string]: any\n  }\n  export interface ElementChildrenAttribute {\n    children: unknown\n  }\n}\n\ntype JSXChild = DOMOutputSpecElement | string | null | undefined | JSXChild[]\n\nexport type JSXRenderer = (\n  tag: 'slot' | string | ((props?: Attributes) => DOMOutputSpecArray | DOMOutputSpecElement),\n  props?: Attributes,\n  ...children: JSXChild[]\n) => DOMOutputSpecArray | DOMOutputSpecElement\n\nexport function Fragment(props: { children: JSXChild[] }) {\n  jsxFragments.add(props.children)\n\n  return props.children\n}\n\nfunction render(tag: Parameters<JSXRenderer>[0], attributes: Attributes | undefined) {\n  // Treat the slot tag as the Prosemirror hole to render content into\n  if (tag === 'slot') {\n    return 0\n  }\n\n  // If the tag is a function, call it with the props\n  if (tag instanceof Function) {\n    const result = tag(attributes)\n\n    if (Array.isArray(result) && !isJSXElement(result) && !jsxFragments.has(result)) {\n      return createJSXElement(result)\n    }\n\n    return result\n  }\n\n  const { children, ...rest } = attributes ?? {}\n\n  if (tag === 'svg') {\n    throw new Error(\n      'SVG elements are not supported in the JSX syntax, use the array syntax instead',\n    )\n  }\n\n  // Handle children array by spreading elements\n  if (Array.isArray(children)) {\n    if (isJSXElement(children)) {\n      return createJSXElement([tag, rest, children])\n    }\n\n    if (children.length === 0) {\n      // Empty array means no children\n      return createJSXElement([tag, rest])\n    }\n\n    const flattenedChildren = flattenFragmentChildren(children)\n\n    if (flattenedChildren.length === 0) {\n      return createJSXElement([tag, rest])\n    }\n\n    // Spread children into the result array\n    return createJSXElement([tag, rest, ...flattenedChildren])\n  }\n\n  // Single child or no children\n  if (children !== undefined && children !== null) {\n    return createJSXElement([tag, rest, children])\n  }\n\n  return createJSXElement([tag, rest])\n}\n\nexport const h: JSXRenderer = (tag, attributes) => render(tag, attributes)\n\nexport const jsxs: JSXRenderer = (tag, attributes) => render(tag, attributes)\n\nexport const jsxDEV = (\n  tag: Parameters<JSXRenderer>[0],\n  attributes?: Attributes,\n  _key?: unknown,\n  _isStaticChildren?: boolean,\n) => {\n  return render(tag, attributes)\n}\n\n// See\n// https://esbuild.github.io/api/#jsx-import-source\n// https://www.typescriptlang.org/tsconfig/#jsxImportSource\n\nexport { h as createElement, h as jsx }\n", "import type { Node as PMNode } from '@tiptap/pm/model'\nimport type { Decoration, DecorationSource, NodeView } from '@tiptap/pm/view'\n\nimport type { Editor } from '../Editor.js'\n\nconst isTouchEvent = (e: MouseEvent | TouchEvent): e is TouchEvent => {\n  return 'touches' in e\n}\n\n/**\n * Directions where resize handles can be placed\n *\n * @example\n * - `'top'` - Top edge handle\n * - `'bottom-right'` - Bottom-right corner handle\n */\nexport type ResizableNodeViewDirection =\n  | 'top'\n  | 'right'\n  | 'bottom'\n  | 'left'\n  | 'top-right'\n  | 'top-left'\n  | 'bottom-right'\n  | 'bottom-left'\n\n/**\n * Dimensions for the resizable node in pixels\n */\nexport type ResizableNodeDimensions = {\n  /** Width in pixels */\n  width: number\n  /** Height in pixels */\n  height: number\n}\n\n/**\n * Configuration options for creating a ResizableNodeView\n *\n * @example\n * ```ts\n * new ResizableNodeView({\n *   element: imgElement,\n *   node,\n *   getPos,\n *   onResize: (width, height) => {\n *     imgElement.style.width = `${width}px`\n *     imgElement.style.height = `${height}px`\n *   },\n *   onCommit: (width, height) => {\n *     editor.commands.updateAttributes('image', { width, height })\n *   },\n *   onUpdate: (node) => true,\n *   options: {\n *     directions: ['bottom-right', 'bottom-left'],\n *     min: { width: 100, height: 100 },\n *     preserveAspectRatio: true\n *   }\n * })\n * ```\n */\nexport type ResizableNodeViewOptions = {\n  /**\n   * The DOM element to make resizable (e.g., an img, video, or iframe element)\n   */\n  element: HTMLElement\n\n  /**\n   * The DOM element that will hold the editable content element\n   */\n  contentElement?: HTMLElement\n\n  /**\n   * The ProseMirror node instance\n   */\n  node: PMNode\n\n  /**\n   * The Tiptap editor instance\n   */\n  editor: Editor\n\n  /**\n   * Function that returns the current position of the node in the document\n   */\n  getPos: () => number | undefined\n\n  /**\n   * Callback fired continuously during resize with current dimensions.\n   * Use this to update the element's visual size in real-time.\n   *\n   * @param width - Current width in pixels\n   * @param height - Current height in pixels\n   *\n   * @example\n   * ```ts\n   * onResize: (width, height) => {\n   *   element.style.width = `${width}px`\n   *   element.style.height = `${height}px`\n   * }\n   * ```\n   */\n  onResize?: (width: number, height: number) => void\n\n  /**\n   * Callback fired once when resize completes with final dimensions.\n   * Use this to persist the new size to the node's attributes.\n   *\n   * @param width - Final width in pixels\n   * @param height - Final height in pixels\n   *\n   * @example\n   * ```ts\n   * onCommit: (width, height) => {\n   *   const pos = getPos()\n   *   if (pos !== undefined) {\n   *     editor.commands.updateAttributes('image', { width, height })\n   *   }\n   * }\n   * ```\n   */\n  onCommit: (width: number, height: number) => void\n\n  /**\n   * Callback for handling node updates.\n   * Return `true` to accept the update, `false` to reject it.\n   *\n   * @example\n   * ```ts\n   * onUpdate: (node, decorations, innerDecorations) => {\n   *   if (node.type !== this.node.type) return false\n   *   return true\n   * }\n   * ```\n   */\n  onUpdate: NodeView['update']\n\n  /**\n   * Optional configuration for resize behavior and styling\n   */\n  options?: {\n    /**\n     * Which resize handles to display.\n     * @default ['bottom-left', 'bottom-right', 'top-left', 'top-right']\n     *\n     * @example\n     * ```ts\n     * // Only show corner handles\n     * directions: ['top-left', 'top-right', 'bottom-left', 'bottom-right']\n     *\n     * // Only show right edge handle\n     * directions: ['right']\n     * ```\n     */\n    directions?: ResizableNodeViewDirection[]\n\n    /**\n     * Minimum dimensions in pixels\n     * @default { width: 8, height: 8 }\n     *\n     * @example\n     * ```ts\n     * min: { width: 100, height: 50 }\n     * ```\n     */\n    min?: Partial<ResizableNodeDimensions>\n\n    /**\n     * Maximum dimensions in pixels\n     * @default undefined (no maximum)\n     *\n     * @example\n     * ```ts\n     * max: { width: 1000, height: 800 }\n     * ```\n     */\n    max?: Partial<ResizableNodeDimensions>\n\n    /**\n     * Always preserve aspect ratio when resizing.\n     * When `false`, aspect ratio is preserved only when Shift key is pressed.\n     * @default false\n     *\n     * @example\n     * ```ts\n     * preserveAspectRatio: true // Always lock aspect ratio\n     * ```\n     */\n    preserveAspectRatio?: boolean\n\n    /**\n     * Custom CSS class names for styling\n     *\n     * @example\n     * ```ts\n     * className: {\n     *   container: 'resize-container',\n     *   wrapper: 'resize-wrapper',\n     *   handle: 'resize-handle',\n     *   resizing: 'is-resizing'\n     * }\n     * ```\n     */\n    className?: {\n      /** Class for the outer container element */\n      container?: string\n      /** Class for the wrapper element that contains the resizable element */\n      wrapper?: string\n      /** Class applied to all resize handles */\n      handle?: string\n      /** Class added to container while actively resizing */\n      resizing?: string\n    }\n\n    /**\n     * Optional callback for creating custom resize handle elements.\n     *\n     * This function allows developers to define their own handle element\n     * (e.g., custom icons, classes, or styles) for a given resize direction.\n     * It is called internally for each handle direction.\n     *\n     * @param direction - The direction of the handle being created (e.g., 'top', 'bottom-right').\n     * @returns The custom handle HTMLElement.\n     *\n     * @example\n     * ```ts\n     * createCustomHandle: (direction) => {\n     *   const handle = document.createElement('div')\n     *   handle.dataset.resizeHandle = direction\n     *   handle.style.position = 'absolute'\n     *   handle.className = 'tiptap-custom-handle'\n     *\n     *   const isTop = direction.includes('top')\n     *   const isBottom = direction.includes('bottom')\n     *   const isLeft = direction.includes('left')\n     *   const isRight = direction.includes('right')\n     *\n     *   if (isTop) handle.style.top = '0'\n     *   if (isBottom) handle.style.bottom = '0'\n     *   if (isLeft) handle.style.left = '0'\n     *   if (isRight) handle.style.right = '0'\n     *\n     *   // Edge handles span the full width or height\n     *   if (direction === 'top' || direction === 'bottom') {\n     *     handle.style.left = '0'\n     *     handle.style.right = '0'\n     *   }\n     *\n     *   if (direction === 'left' || direction === 'right') {\n     *     handle.style.top = '0'\n     *     handle.style.bottom = '0'\n     *   }\n     *\n     *   return handle\n     * }\n     * ```\n     */\n    createCustomHandle?: (direction: ResizableNodeViewDirection) => HTMLElement\n  }\n}\n\n/**\n * A NodeView implementation that adds resize handles to any DOM element.\n *\n * This class creates a resizable node view for Tiptap/ProseMirror editors.\n * It wraps your element with resize handles and manages the resize interaction,\n * including aspect ratio preservation, min/max constraints, and keyboard modifiers.\n *\n * @example\n * ```ts\n * // Basic usage in a Tiptap extension\n * addNodeView() {\n *   return ({ node, getPos }) => {\n *     const img = document.createElement('img')\n *     img.src = node.attrs.src\n *\n *     return new ResizableNodeView({\n *       element: img,\n *       node,\n *       getPos,\n *       onResize: (width, height) => {\n *         img.style.width = `${width}px`\n *         img.style.height = `${height}px`\n *       },\n *       onCommit: (width, height) => {\n *         this.editor.commands.updateAttributes('image', { width, height })\n *       },\n *       onUpdate: () => true,\n *       options: {\n *         min: { width: 100, height: 100 },\n *         preserveAspectRatio: true\n *       }\n *     })\n *   }\n * }\n * ```\n */\nexport class ResizableNodeView {\n  /** The ProseMirror node instance */\n  node: PMNode\n\n  /** The Tiptap editor instance */\n  editor: Editor\n\n  /** The DOM element being made resizable */\n  element: HTMLElement\n\n  /** The editable DOM element inside the DOM */\n  contentElement?: HTMLElement\n\n  /** The outer container element (returned as NodeView.dom) */\n  container: HTMLElement\n\n  /** The wrapper element that contains the element and handles */\n  wrapper: HTMLElement\n\n  /** Function to get the current node position */\n  getPos: () => number | undefined\n\n  /** Callback fired during resize */\n  onResize?: (width: number, height: number) => void\n\n  /** Callback fired when resize completes */\n  onCommit: (width: number, height: number) => void\n\n  /** Callback for node updates */\n  onUpdate?: NodeView['update']\n\n  /** Active resize handle directions */\n  directions: ResizableNodeViewDirection[] = [\n    'bottom-left',\n    'bottom-right',\n    'top-left',\n    'top-right',\n  ]\n\n  /** Minimum allowed dimensions */\n  minSize: ResizableNodeDimensions = {\n    height: 8,\n    width: 8,\n  }\n\n  /** Maximum allowed dimensions (optional) */\n  maxSize?: Partial<ResizableNodeDimensions>\n\n  /** Whether to always preserve aspect ratio */\n  preserveAspectRatio: boolean = false\n\n  /** CSS class names for elements */\n  classNames = {\n    container: '',\n    wrapper: '',\n    handle: '',\n    resizing: '',\n  }\n\n  /** Optional callback for creating custom resize handles */\n  createCustomHandle?: (direction: ResizableNodeViewDirection) => HTMLElement\n\n  /** Initial width of the element (for aspect ratio calculation) */\n  private initialWidth: number = 0\n\n  /** Initial height of the element (for aspect ratio calculation) */\n  private initialHeight: number = 0\n\n  /** Calculated aspect ratio (width / height) */\n  private aspectRatio: number = 1\n\n  /** Whether a resize operation is currently active */\n  private isResizing: boolean = false\n\n  /** The handle currently being dragged */\n  private activeHandle: ResizableNodeViewDirection | null = null\n\n  /** Starting mouse X position when resize began */\n  private startX: number = 0\n\n  /** Starting mouse Y position when resize began */\n  private startY: number = 0\n\n  /** Element width when resize began */\n  private startWidth: number = 0\n\n  /** Element height when resize began */\n  private startHeight: number = 0\n\n  /** Whether Shift key is currently pressed (for temporary aspect ratio lock) */\n  private isShiftKeyPressed: boolean = false\n\n  /** Last known editable state of the editor */\n  private lastEditableState: boolean | undefined = undefined\n\n  /** Map of handle elements by direction */\n  private handleMap = new Map<ResizableNodeViewDirection, HTMLElement>()\n\n  /**\n   * Creates a new ResizableNodeView instance.\n   *\n   * The constructor sets up the resize handles, applies initial sizing from\n   * node attributes, and configures all resize behavior options.\n   *\n   * @param options - Configuration options for the resizable node view\n   */\n  constructor(options: ResizableNodeViewOptions) {\n    this.node = options.node\n    this.editor = options.editor\n    this.element = options.element\n    this.element.draggable = false\n    this.contentElement = options.contentElement\n\n    this.getPos = options.getPos\n\n    this.onResize = options.onResize\n    this.onCommit = options.onCommit\n    this.onUpdate = options.onUpdate\n\n    if (options.options?.min) {\n      this.minSize = {\n        ...this.minSize,\n        ...options.options.min,\n      }\n    }\n\n    if (options.options?.max) {\n      this.maxSize = options.options.max\n    }\n\n    if (options?.options?.directions) {\n      this.directions = options.options.directions\n    }\n\n    if (options.options?.preserveAspectRatio) {\n      this.preserveAspectRatio = options.options.preserveAspectRatio\n    }\n\n    if (options.options?.className) {\n      this.classNames = {\n        container: options.options.className.container || '',\n        wrapper: options.options.className.wrapper || '',\n        handle: options.options.className.handle || '',\n        resizing: options.options.className.resizing || '',\n      }\n    }\n\n    if (options.options?.createCustomHandle) {\n      this.createCustomHandle = options.options.createCustomHandle\n    }\n\n    this.wrapper = this.createWrapper()\n    this.container = this.createContainer()\n\n    this.applyInitialSize()\n    this.attachHandles()\n\n    this.editor.on('update', this.handleEditorUpdate)\n  }\n\n  /**\n   * Returns the top-level DOM node that should be placed in the editor.\n   *\n   * This is required by the ProseMirror NodeView interface. The container\n   * includes the wrapper, handles, and the actual content element.\n   *\n   * @returns The container element to be inserted into the editor\n   */\n  get dom() {\n    return this.container\n  }\n\n  get contentDOM(): HTMLElement | null {\n    return this.contentElement ?? null\n  }\n\n  private handleEditorUpdate = () => {\n    const isEditable = this.editor.isEditable\n\n    // Only if state actually changed\n    if (isEditable === this.lastEditableState) {\n      return\n    }\n\n    this.lastEditableState = isEditable\n\n    if (!isEditable) {\n      this.removeHandles()\n    } else if (isEditable && this.handleMap.size === 0) {\n      this.attachHandles()\n    }\n  }\n\n  /**\n   * Called when the node's content or attributes change.\n   *\n   * Updates the internal node reference. If a custom `onUpdate` callback\n   * was provided, it will be called to handle additional update logic.\n   *\n   * @param node - The new/updated node\n   * @param decorations - Node decorations\n   * @param innerDecorations - Inner decorations\n   * @returns `false` if the node type has changed (requires full rebuild), otherwise the result of `onUpdate` or `true`\n   */\n  update(\n    node: PMNode,\n    decorations: readonly Decoration[],\n    innerDecorations: DecorationSource,\n  ): boolean {\n    if (node.type !== this.node.type) {\n      return false\n    }\n\n    this.node = node\n\n    if (this.onUpdate) {\n      return this.onUpdate(node, decorations, innerDecorations)\n    }\n\n    return true\n  }\n\n  /**\n   * Cleanup method called when the node view is being removed.\n   *\n   * Removes all event listeners to prevent memory leaks. This is required\n   * by the ProseMirror NodeView interface. If a resize is active when\n   * destroy is called, it will be properly cancelled.\n   */\n  destroy() {\n    if (this.isResizing) {\n      this.container.dataset.resizeState = 'false'\n\n      if (this.classNames.resizing) {\n        this.container.classList.remove(this.classNames.resizing)\n      }\n\n      document.removeEventListener('mousemove', this.handleMouseMove)\n      document.removeEventListener('mouseup', this.handleMouseUp)\n      document.removeEventListener('keydown', this.handleKeyDown)\n      document.removeEventListener('keyup', this.handleKeyUp)\n      this.isResizing = false\n      this.activeHandle = null\n    }\n\n    this.editor.off('update', this.handleEditorUpdate)\n\n    this.container.remove()\n  }\n\n  /**\n   * Creates the outer container element.\n   *\n   * The container is the top-level element returned by the NodeView and\n   * wraps the entire resizable node. It's set up with flexbox to handle\n   * alignment and includes data attributes for styling and identification.\n   *\n   * @returns The container element\n   */\n  createContainer() {\n    const element = document.createElement('div')\n    element.dataset.resizeContainer = ''\n    element.dataset.node = this.node.type.name\n    element.style.display = this.node.type.isInline ? 'inline-flex' : 'flex'\n\n    if (this.classNames.container) {\n      element.className = this.classNames.container\n    }\n\n    element.appendChild(this.wrapper)\n\n    return element\n  }\n\n  /**\n   * Creates the wrapper element that contains the content and handles.\n   *\n   * The wrapper uses relative positioning so that resize handles can be\n   * positioned absolutely within it. This is the direct parent of the\n   * content element being made resizable.\n   *\n   * @returns The wrapper element\n   */\n  createWrapper() {\n    const element = document.createElement('div')\n    element.style.position = 'relative'\n    element.style.display = 'block'\n    element.dataset.resizeWrapper = ''\n\n    if (this.classNames.wrapper) {\n      element.className = this.classNames.wrapper\n    }\n\n    element.appendChild(this.element)\n\n    return element\n  }\n\n  /**\n   * Creates a resize handle element for a specific direction.\n   *\n   * Each handle is absolutely positioned and includes a data attribute\n   * identifying its direction for styling purposes.\n   *\n   * @param direction - The resize direction for this handle\n   * @returns The handle element\n   */\n  private createHandle(direction: ResizableNodeViewDirection): HTMLElement {\n    const handle = document.createElement('div')\n    handle.dataset.resizeHandle = direction\n    handle.style.position = 'absolute'\n\n    if (this.classNames.handle) {\n      handle.className = this.classNames.handle\n    }\n\n    return handle\n  }\n\n  /**\n   * Positions a handle element according to its direction.\n   *\n   * Corner handles (e.g., 'top-left') are positioned at the intersection\n   * of two edges. Edge handles (e.g., 'top') span the full width or height.\n   *\n   * @param handle - The handle element to position\n   * @param direction - The direction determining the position\n   */\n  private positionHandle(handle: HTMLElement, direction: ResizableNodeViewDirection): void {\n    const isTop = direction.includes('top')\n    const isBottom = direction.includes('bottom')\n    const isLeft = direction.includes('left')\n    const isRight = direction.includes('right')\n\n    if (isTop) {\n      handle.style.top = '0'\n    }\n\n    if (isBottom) {\n      handle.style.bottom = '0'\n    }\n\n    if (isLeft) {\n      handle.style.left = '0'\n    }\n\n    if (isRight) {\n      handle.style.right = '0'\n    }\n\n    // Edge handles span the full width or height\n    if (direction === 'top' || direction === 'bottom') {\n      handle.style.left = '0'\n      handle.style.right = '0'\n    }\n\n    if (direction === 'left' || direction === 'right') {\n      handle.style.top = '0'\n      handle.style.bottom = '0'\n    }\n  }\n\n  /**\n   * Creates and attaches all resize handles to the wrapper.\n   *\n   * Iterates through the configured directions, creates a handle for each,\n   * positions it, attaches the mousedown listener, and appends it to the DOM.\n   */\n  private attachHandles(): void {\n    this.directions.forEach(direction => {\n      let handle: HTMLElement\n\n      if (this.createCustomHandle) {\n        handle = this.createCustomHandle(direction)\n      } else {\n        handle = this.createHandle(direction)\n      }\n\n      if (!(handle instanceof HTMLElement)) {\n        console.warn(\n          `[ResizableNodeView] createCustomHandle(\"${direction}\") did not return an HTMLElement. Falling back to default handle.`,\n        )\n        handle = this.createHandle(direction)\n      }\n\n      if (!this.createCustomHandle) {\n        this.positionHandle(handle, direction)\n      }\n\n      handle.addEventListener('mousedown', event => this.handleResizeStart(event, direction))\n      handle.addEventListener('touchstart', event =>\n        this.handleResizeStart(event as unknown as MouseEvent, direction),\n      )\n\n      this.handleMap.set(direction, handle)\n\n      this.wrapper.appendChild(handle)\n    })\n  }\n\n  /**\n   * Removes all resize handles from the wrapper.\n   *\n   * Cleans up the handle map and removes each handle element from the DOM.\n   */\n  private removeHandles(): void {\n    this.handleMap.forEach(el => el.remove())\n    this.handleMap.clear()\n  }\n\n  /**\n   * Applies initial sizing from node attributes to the element.\n   *\n   * If width/height attributes exist on the node, they're applied to the element.\n   * Otherwise, the element's natural/current dimensions are measured. The aspect\n   * ratio is calculated for later use in aspect-ratio-preserving resizes.\n   */\n  private applyInitialSize(): void {\n    const width = this.node.attrs.width as number | undefined\n    const height = this.node.attrs.height as number | undefined\n\n    if (width) {\n      this.element.style.width = `${width}px`\n      this.initialWidth = width\n    } else {\n      this.initialWidth = this.element.offsetWidth\n    }\n\n    if (height) {\n      this.element.style.height = `${height}px`\n      this.initialHeight = height\n    } else {\n      this.initialHeight = this.element.offsetHeight\n    }\n\n    // Calculate aspect ratio for use during resizing\n    if (this.initialWidth > 0 && this.initialHeight > 0) {\n      this.aspectRatio = this.initialWidth / this.initialHeight\n    }\n  }\n\n  /**\n   * Initiates a resize operation when a handle is clicked.\n   *\n   * Captures the starting mouse position and element dimensions, sets up\n   * the resize state, adds the resizing class and state attribute, and\n   * attaches document-level listeners for mouse movement and keyboard input.\n   *\n   * @param event - The mouse down event\n   * @param direction - The direction of the handle being dragged\n   */\n  private handleResizeStart(\n    event: MouseEvent | TouchEvent,\n    direction: ResizableNodeViewDirection,\n  ): void {\n    event.preventDefault()\n    event.stopPropagation()\n\n    // Capture initial state\n    this.isResizing = true\n    this.activeHandle = direction\n\n    if (isTouchEvent(event)) {\n      this.startX = event.touches[0].clientX\n      this.startY = event.touches[0].clientY\n    } else {\n      this.startX = event.clientX\n      this.startY = event.clientY\n    }\n\n    this.startWidth = this.element.offsetWidth\n    this.startHeight = this.element.offsetHeight\n\n    // Recalculate aspect ratio at resize start for accuracy\n    if (this.startWidth > 0 && this.startHeight > 0) {\n      this.aspectRatio = this.startWidth / this.startHeight\n    }\n\n    const pos = this.getPos()\n    if (pos !== undefined) {\n      // TODO: Select the node in the editor\n    }\n\n    // Update UI state\n    this.container.dataset.resizeState = 'true'\n\n    if (this.classNames.resizing) {\n      this.container.classList.add(this.classNames.resizing)\n    }\n\n    // Attach document-level listeners for resize\n    document.addEventListener('mousemove', this.handleMouseMove)\n    document.addEventListener('touchmove', this.handleTouchMove)\n    document.addEventListener('mouseup', this.handleMouseUp)\n    document.addEventListener('keydown', this.handleKeyDown)\n    document.addEventListener('keyup', this.handleKeyUp)\n  }\n\n  /**\n   * Handles mouse movement during an active resize.\n   *\n   * Calculates the delta from the starting position, computes new dimensions\n   * based on the active handle direction, applies constraints and aspect ratio,\n   * then updates the element's style and calls the onResize callback.\n   *\n   * @param event - The mouse move event\n   */\n  private handleMouseMove = (event: MouseEvent): void => {\n    if (!this.isResizing || !this.activeHandle) {\n      return\n    }\n\n    const deltaX = event.clientX - this.startX\n    const deltaY = event.clientY - this.startY\n\n    this.handleResize(deltaX, deltaY)\n  }\n\n  private handleTouchMove = (event: TouchEvent): void => {\n    if (!this.isResizing || !this.activeHandle) {\n      return\n    }\n\n    const touch = event.touches[0]\n    if (!touch) {\n      return\n    }\n\n    const deltaX = touch.clientX - this.startX\n    const deltaY = touch.clientY - this.startY\n\n    this.handleResize(deltaX, deltaY)\n  }\n\n  private handleResize(deltaX: number, deltaY: number) {\n    if (!this.activeHandle) {\n      return\n    }\n\n    const shouldPreserveAspectRatio = this.preserveAspectRatio || this.isShiftKeyPressed\n    const { width, height } = this.calculateNewDimensions(this.activeHandle, deltaX, deltaY)\n    const constrained = this.applyConstraints(width, height, shouldPreserveAspectRatio)\n\n    this.element.style.width = `${constrained.width}px`\n    this.element.style.height = `${constrained.height}px`\n\n    if (this.onResize) {\n      this.onResize(constrained.width, constrained.height)\n    }\n  }\n\n  /**\n   * Completes the resize operation when the mouse button is released.\n   *\n   * Captures final dimensions, calls the onCommit callback to persist changes,\n   * removes the resizing state and class, and cleans up document-level listeners.\n   */\n  private handleMouseUp = (): void => {\n    if (!this.isResizing) {\n      return\n    }\n\n    const finalWidth = this.element.offsetWidth\n    const finalHeight = this.element.offsetHeight\n\n    this.onCommit(finalWidth, finalHeight)\n\n    this.isResizing = false\n    this.activeHandle = null\n\n    // Remove UI state\n    this.container.dataset.resizeState = 'false'\n\n    if (this.classNames.resizing) {\n      this.container.classList.remove(this.classNames.resizing)\n    }\n\n    // Clean up document-level listeners\n    document.removeEventListener('mousemove', this.handleMouseMove)\n    document.removeEventListener('mouseup', this.handleMouseUp)\n    document.removeEventListener('keydown', this.handleKeyDown)\n    document.removeEventListener('keyup', this.handleKeyUp)\n  }\n\n  /**\n   * Tracks Shift key state to enable temporary aspect ratio locking.\n   *\n   * When Shift is pressed during resize, aspect ratio is preserved even if\n   * preserveAspectRatio is false.\n   *\n   * @param event - The keyboard event\n   */\n  private handleKeyDown = (event: KeyboardEvent): void => {\n    if (event.key === 'Shift') {\n      this.isShiftKeyPressed = true\n    }\n  }\n\n  /**\n   * Tracks Shift key release to disable temporary aspect ratio locking.\n   *\n   * @param event - The keyboard event\n   */\n  private handleKeyUp = (event: KeyboardEvent): void => {\n    if (event.key === 'Shift') {\n      this.isShiftKeyPressed = false\n    }\n  }\n\n  /**\n   * Calculates new dimensions based on mouse delta and resize direction.\n   *\n   * Takes the starting dimensions and applies the mouse movement delta\n   * according to the handle direction. For corner handles, both dimensions\n   * are affected. For edge handles, only one dimension changes. If aspect\n   * ratio should be preserved, delegates to applyAspectRatio.\n   *\n   * @param direction - The active resize handle direction\n   * @param deltaX - Horizontal mouse movement since resize start\n   * @param deltaY - Vertical mouse movement since resize start\n   * @returns The calculated width and height\n   */\n  private calculateNewDimensions(\n    direction: ResizableNodeViewDirection,\n    deltaX: number,\n    deltaY: number,\n  ): ResizableNodeDimensions {\n    let newWidth = this.startWidth\n    let newHeight = this.startHeight\n\n    const isRight = direction.includes('right')\n    const isLeft = direction.includes('left')\n    const isBottom = direction.includes('bottom')\n    const isTop = direction.includes('top')\n\n    // Apply horizontal delta\n    if (isRight) {\n      newWidth = this.startWidth + deltaX\n    } else if (isLeft) {\n      newWidth = this.startWidth - deltaX\n    }\n\n    // Apply vertical delta\n    if (isBottom) {\n      newHeight = this.startHeight + deltaY\n    } else if (isTop) {\n      newHeight = this.startHeight - deltaY\n    }\n\n    // For pure horizontal/vertical handles, only one dimension changes\n    if (direction === 'right' || direction === 'left') {\n      newWidth = this.startWidth + (isRight ? deltaX : -deltaX)\n    }\n\n    if (direction === 'top' || direction === 'bottom') {\n      newHeight = this.startHeight + (isBottom ? deltaY : -deltaY)\n    }\n\n    const shouldPreserveAspectRatio = this.preserveAspectRatio || this.isShiftKeyPressed\n\n    if (shouldPreserveAspectRatio) {\n      return this.applyAspectRatio(newWidth, newHeight, direction)\n    }\n\n    return { width: newWidth, height: newHeight }\n  }\n\n  /**\n   * Applies min/max constraints to dimensions.\n   *\n   * When aspect ratio is NOT preserved, constraints are applied independently\n   * to width and height. When aspect ratio IS preserved, constraints are\n   * applied while maintaining the aspect ratio—if one dimension hits a limit,\n   * the other is recalculated proportionally.\n   *\n   * This ensures that aspect ratio is never broken when constrained.\n   *\n   * @param width - The unconstrained width\n   * @param height - The unconstrained height\n   * @param preserveAspectRatio - Whether to maintain aspect ratio while constraining\n   * @returns The constrained dimensions\n   */\n  private applyConstraints(\n    width: number,\n    height: number,\n    preserveAspectRatio: boolean,\n  ): ResizableNodeDimensions {\n    if (!preserveAspectRatio) {\n      // Independent constraints for each dimension\n      let constrainedWidth = Math.max(this.minSize.width, width)\n      let constrainedHeight = Math.max(this.minSize.height, height)\n\n      if (this.maxSize?.width) {\n        constrainedWidth = Math.min(this.maxSize.width, constrainedWidth)\n      }\n\n      if (this.maxSize?.height) {\n        constrainedHeight = Math.min(this.maxSize.height, constrainedHeight)\n      }\n\n      return { width: constrainedWidth, height: constrainedHeight }\n    }\n\n    // Aspect-ratio-aware constraints: adjust both dimensions proportionally\n    let constrainedWidth = width\n    let constrainedHeight = height\n\n    // Check minimum constraints\n    if (constrainedWidth < this.minSize.width) {\n      constrainedWidth = this.minSize.width\n      constrainedHeight = constrainedWidth / this.aspectRatio\n    }\n\n    if (constrainedHeight < this.minSize.height) {\n      constrainedHeight = this.minSize.height\n      constrainedWidth = constrainedHeight * this.aspectRatio\n    }\n\n    // Check maximum constraints\n    if (this.maxSize?.width && constrainedWidth > this.maxSize.width) {\n      constrainedWidth = this.maxSize.width\n      constrainedHeight = constrainedWidth / this.aspectRatio\n    }\n\n    if (this.maxSize?.height && constrainedHeight > this.maxSize.height) {\n      constrainedHeight = this.maxSize.height\n      constrainedWidth = constrainedHeight * this.aspectRatio\n    }\n\n    return { width: constrainedWidth, height: constrainedHeight }\n  }\n\n  /**\n   * Adjusts dimensions to maintain the original aspect ratio.\n   *\n   * For horizontal handles (left/right), uses width as the primary dimension\n   * and calculates height from it. For vertical handles (top/bottom), uses\n   * height as primary and calculates width. For corner handles, uses width\n   * as the primary dimension.\n   *\n   * @param width - The new width\n   * @param height - The new height\n   * @param direction - The active resize direction\n   * @returns Dimensions adjusted to preserve aspect ratio\n   */\n  private applyAspectRatio(\n    width: number,\n    height: number,\n    direction: ResizableNodeViewDirection,\n  ): ResizableNodeDimensions {\n    const isHorizontal = direction === 'left' || direction === 'right'\n    const isVertical = direction === 'top' || direction === 'bottom'\n\n    if (isHorizontal) {\n      // For horizontal resize, width is primary\n      return {\n        width,\n        height: width / this.aspectRatio,\n      }\n    }\n\n    if (isVertical) {\n      // For vertical resize, height is primary\n      return {\n        width: height * this.aspectRatio,\n        height,\n      }\n    }\n\n    // For corner resize, width is primary\n    return {\n      width,\n      height: width / this.aspectRatio,\n    }\n  }\n}\n\n/**\n * Alias for ResizableNodeView to maintain consistent naming.\n * @deprecated Use ResizableNodeView instead - will be removed in future versions.\n */\nexport const ResizableNodeview = ResizableNodeView\n", "import type { DOMOutputSpec, Node as ProseMirrorNode, NodeSpec, NodeType } from '@tiptap/pm/model'\n\nimport type { Editor } from './Editor.js'\nimport type { ExtendableConfig } from './Extendable.js'\nimport { Extendable } from './Extendable.js'\nimport type { Attributes, NodeViewRenderer, ParentConfig } from './types.js'\n\nexport interface NodeConfig<Options = any, Storage = any> extends ExtendableConfig<\n  Options,\n  Storage,\n  NodeConfig<Options, Storage>,\n  NodeType\n> {\n  /**\n   * Node View\n   */\n  addNodeView?:\n    | ((this: {\n        name: string\n        options: Options\n        storage: Storage\n        editor: Editor\n        type: NodeType\n        parent: ParentConfig<NodeConfig<Options, Storage>>['addNodeView']\n      }) => NodeViewRenderer | null)\n    | null\n\n  /**\n   * Defines if this node should be a top level node (doc)\n   * @default false\n   * @example true\n   */\n  topNode?: boolean\n\n  /**\n   * The content expression for this node, as described in the [schema\n   * guide](/docs/guide/#schema.content_expressions). When not given,\n   * the node does not allow any content.\n   *\n   * You can read more about it on the Prosemirror documentation here\n   * @see https://prosemirror.net/docs/guide/#schema.content_expressions\n   * @default undefined\n   * @example content: 'block+'\n   * @example content: 'headline paragraph block*'\n   */\n  content?:\n    | NodeSpec['content']\n    | ((this: {\n        name: string\n        options: Options\n        storage: Storage\n        parent: ParentConfig<NodeConfig<Options, Storage>>['content']\n        editor?: Editor\n      }) => NodeSpec['content'])\n\n  /**\n   * The marks that are allowed inside of this node. May be a\n   * space-separated string referring to mark names or groups, `\"_\"`\n   * to explicitly allow all marks, or `\"\"` to disallow marks. When\n   * not given, nodes with inline content default to allowing all\n   * marks, other nodes default to not allowing marks.\n   *\n   * @example marks: 'strong em'\n   */\n  marks?:\n    | NodeSpec['marks']\n    | ((this: {\n        name: string\n        options: Options\n        storage: Storage\n        parent: ParentConfig<NodeConfig<Options, Storage>>['marks']\n        editor?: Editor\n      }) => NodeSpec['marks'])\n\n  /**\n   * The group or space-separated groups to which this node belongs,\n   * which can be referred to in the content expressions for the\n   * schema.\n   *\n   * By default Tiptap uses the groups 'block' and 'inline' for nodes. You\n   * can also use custom groups if you want to group specific nodes together\n   * and handle them in your schema.\n   * @example group: 'block'\n   * @example group: 'inline'\n   * @example group: 'customBlock' // this uses a custom group\n   */\n  group?:\n    | NodeSpec['group']\n    | ((this: {\n        name: string\n        options: Options\n        storage: Storage\n        parent: ParentConfig<NodeConfig<Options, Storage>>['group']\n        editor?: Editor\n      }) => NodeSpec['group'])\n\n  /**\n   * Should be set to true for inline nodes. (Implied for text nodes.)\n   */\n  inline?:\n    | NodeSpec['inline']\n    | ((this: {\n        name: string\n        options: Options\n        storage: Storage\n        parent: ParentConfig<NodeConfig<Options, Storage>>['inline']\n        editor?: Editor\n      }) => NodeSpec['inline'])\n\n  /**\n   * Can be set to true to indicate that, though this isn't a [leaf\n   * node](https://prosemirror.net/docs/ref/#model.NodeType.isLeaf), it doesn't have directly editable\n   * content and should be treated as a single unit in the view.\n   *\n   * @example atom: true\n   */\n  atom?:\n    | NodeSpec['atom']\n    | ((this: {\n        name: string\n        options: Options\n        storage: Storage\n        parent: ParentConfig<NodeConfig<Options, Storage>>['atom']\n        editor?: Editor\n      }) => NodeSpec['atom'])\n\n  /**\n   * Controls whether nodes of this type can be selected as a [node\n   * selection](https://prosemirror.net/docs/ref/#state.NodeSelection). Defaults to true for non-text\n   * nodes.\n   *\n   * @default true\n   * @example selectable: false\n   */\n  selectable?:\n    | NodeSpec['selectable']\n    | ((this: {\n        name: string\n        options: Options\n        storage: Storage\n        parent: ParentConfig<NodeConfig<Options, Storage>>['selectable']\n        editor?: Editor\n      }) => NodeSpec['selectable'])\n\n  /**\n   * Determines whether nodes of this type can be dragged without\n   * being selected. Defaults to false.\n   *\n   * @default: false\n   * @example: draggable: true\n   */\n  draggable?:\n    | NodeSpec['draggable']\n    | ((this: {\n        name: string\n        options: Options\n        storage: Storage\n        parent: ParentConfig<NodeConfig<Options, Storage>>['draggable']\n        editor?: Editor\n      }) => NodeSpec['draggable'])\n\n  /**\n   * Can be used to indicate that this node contains code, which\n   * causes some commands to behave differently.\n   */\n  code?:\n    | NodeSpec['code']\n    | ((this: {\n        name: string\n        options: Options\n        storage: Storage\n        parent: ParentConfig<NodeConfig<Options, Storage>>['code']\n        editor?: Editor\n      }) => NodeSpec['code'])\n\n  /**\n   * Controls way whitespace in this a node is parsed. The default is\n   * `\"normal\"`, which causes the [DOM parser](https://prosemirror.net/docs/ref/#model.DOMParser) to\n   * collapse whitespace in normal mode, and normalize it (replacing\n   * newlines and such with spaces) otherwise. `\"pre\"` causes the\n   * parser to preserve spaces inside the node. When this option isn't\n   * given, but [`code`](https://prosemirror.net/docs/ref/#model.NodeSpec.code) is true, `whitespace`\n   * will default to `\"pre\"`. Note that this option doesn't influence\n   * the way the node is rendered—that should be handled by `toDOM`\n   * and/or styling.\n   */\n  whitespace?:\n    | NodeSpec['whitespace']\n    | ((this: {\n        name: string\n        options: Options\n        storage: Storage\n        parent: ParentConfig<NodeConfig<Options, Storage>>['whitespace']\n        editor?: Editor\n      }) => NodeSpec['whitespace'])\n\n  /**\n   * Allows a **single** node to be set as linebreak equivalent (e.g. hardBreak).\n   * When converting between block types that have whitespace set to \"pre\"\n   * and don't support the linebreak node (e.g. codeBlock) and other block types\n   * that do support the linebreak node (e.g. paragraphs) - this node will be used\n   * as the linebreak instead of stripping the newline.\n   *\n   * See [linebreakReplacement](https://prosemirror.net/docs/ref/#model.NodeSpec.linebreakReplacement).\n   */\n  linebreakReplacement?:\n    | NodeSpec['linebreakReplacement']\n    | ((this: {\n        name: string\n        options: Options\n        storage: Storage\n        parent: ParentConfig<NodeConfig<Options, Storage>>['linebreakReplacement']\n        editor?: Editor\n      }) => NodeSpec['linebreakReplacement'])\n\n  /**\n   * When enabled, enables both\n   * [`definingAsContext`](https://prosemirror.net/docs/ref/#model.NodeSpec.definingAsContext) and\n   * [`definingForContent`](https://prosemirror.net/docs/ref/#model.NodeSpec.definingForContent).\n   *\n   * @default false\n   * @example isolating: true\n   */\n  defining?:\n    | NodeSpec['defining']\n    | ((this: {\n        name: string\n        options: Options\n        storage: Storage\n        parent: ParentConfig<NodeConfig<Options, Storage>>['defining']\n        editor?: Editor\n      }) => NodeSpec['defining'])\n\n  /**\n   * When enabled (default is false), the sides of nodes of this type\n   * count as boundaries that regular editing operations, like\n   * backspacing or lifting, won't cross. An example of a node that\n   * should probably have this enabled is a table cell.\n   */\n  isolating?:\n    | NodeSpec['isolating']\n    | ((this: {\n        name: string\n        options: Options\n        storage: Storage\n        parent: ParentConfig<NodeConfig<Options, Storage>>['isolating']\n        editor?: Editor\n      }) => NodeSpec['isolating'])\n\n  /**\n   * Associates DOM parser information with this node, which can be\n   * used by [`DOMParser.fromSchema`](https://prosemirror.net/docs/ref/#model.DOMParser^fromSchema) to\n   * automatically derive a parser. The `node` field in the rules is\n   * implied (the name of this node will be filled in automatically).\n   * If you supply your own parser, you do not need to also specify\n   * parsing rules in your schema.\n   *\n   * @example parseHTML: [{ tag: 'div', attrs: { 'data-id': 'my-block' } }]\n   */\n  parseHTML?: (this: {\n    name: string\n    options: Options\n    storage: Storage\n    parent: ParentConfig<NodeConfig<Options, Storage>>['parseHTML']\n    editor?: Editor\n  }) => NodeSpec['parseDOM']\n\n  /**\n   * A description of a DOM structure. Can be either a string, which is\n   * interpreted as a text node, a DOM node, which is interpreted as\n   * itself, a `{dom, contentDOM}` object, or an array.\n   *\n   * An array describes a DOM element. The first value in the array\n   * should be a string—the name of the DOM element, optionally prefixed\n   * by a namespace URL and a space. If the second element is plain\n   * object, it is interpreted as a set of attributes for the element.\n   * Any elements after that (including the 2nd if it's not an attribute\n   * object) are interpreted as children of the DOM elements, and must\n   * either be valid `DOMOutputSpec` values, or the number zero.\n   *\n   * The number zero (pronounced “hole”) is used to indicate the place\n   * where a node's child nodes should be inserted. If it occurs in an\n   * output spec, it should be the only child element in its parent\n   * node.\n   *\n   * @example toDOM: ['div[data-id=\"my-block\"]', { class: 'my-block' }, 0]\n   */\n  renderHTML?:\n    | ((\n        this: {\n          name: string\n          options: Options\n          storage: Storage\n          parent: ParentConfig<NodeConfig<Options, Storage>>['renderHTML']\n          editor?: Editor\n        },\n        props: {\n          node: ProseMirrorNode\n          HTMLAttributes: Record<string, any>\n        },\n      ) => DOMOutputSpec)\n    | null\n\n  /**\n   * renders the node as text\n   * @example renderText: () => 'foo\n   */\n  renderText?:\n    | ((\n        this: {\n          name: string\n          options: Options\n          storage: Storage\n          parent: ParentConfig<NodeConfig<Options, Storage>>['renderText']\n          editor?: Editor\n        },\n        props: {\n          node: ProseMirrorNode\n          pos: number\n          parent: ProseMirrorNode\n          index: number\n        },\n      ) => string)\n    | null\n\n  /**\n   * Add attributes to the node\n   * @example addAttributes: () => ({ class: 'foo' })\n   */\n  addAttributes?: (this: {\n    name: string\n    options: Options\n    storage: Storage\n    parent: ParentConfig<NodeConfig<Options, Storage>>['addAttributes']\n    editor?: Editor\n    // oxlint-disable-next-lineno-empty-object-type\n  }) => Attributes | {}\n}\n\n/**\n * The Node class is used to create custom node extensions.\n * @see https://tiptap.dev/api/extensions#create-a-new-extension\n */\nexport class Node<Options = any, Storage = any> extends Extendable<\n  Options,\n  Storage,\n  NodeConfig<Options, Storage>\n> {\n  type = 'node'\n\n  /**\n   * Create a new Node instance\n   * @param config - Node configuration object or a function that returns a configuration object\n   */\n  static create<O = any, S = any>(\n    config: Partial<NodeConfig<O, S>> | (() => Partial<NodeConfig<O, S>>) = {},\n  ) {\n    // If the config is a function, execute it to get the configuration object\n    const resolvedConfig = typeof config === 'function' ? config() : config\n    return new Node<O, S>(resolvedConfig)\n  }\n\n  configure(options?: Partial<Options>) {\n    return super.configure(options) as Node<Options, Storage>\n  }\n\n  extend<\n    ExtendedOptions = Options,\n    ExtendedStorage = Storage,\n    ExtendedConfig extends NodeConfig<ExtendedOptions, ExtendedStorage> = NodeConfig<\n      ExtendedOptions,\n      ExtendedStorage\n    >,\n  >(\n    extendedConfig?:\n      | (() => Partial<ExtendedConfig>)\n      | (Partial<ExtendedConfig> &\n          ThisType<{\n            name: string\n            options: ExtendedOptions\n            storage: ExtendedStorage\n            editor: Editor\n            type: NodeType\n          }>),\n  ): Node<ExtendedOptions, ExtendedStorage> {\n    // If the extended config is a function, execute it to get the configuration object\n    const resolvedConfig = typeof extendedConfig === 'function' ? extendedConfig() : extendedConfig\n    return super.extend(resolvedConfig) as Node<ExtendedOptions, ExtendedStorage>\n  }\n}\n", "import { NodeSelection } from '@tiptap/pm/state'\nimport type { NodeView as ProseMirrorNodeView, ViewMutationRecord } from '@tiptap/pm/view'\n\nimport type { Editor as CoreEditor } from './Editor.js'\nimport type { DecorationWithType, NodeViewRendererOptions, NodeViewRendererProps } from './types.js'\nimport { isAndroid } from './utilities/isAndroid.js'\nimport { isiOS } from './utilities/isiOS.js'\n\n/**\n * Node views are used to customize the rendered DOM structure of a node.\n * @see https://tiptap.dev/guide/node-views\n */\nexport class NodeView<\n  Component,\n  NodeEditor extends CoreEditor = CoreEditor,\n  Options extends NodeViewRendererOptions = NodeViewRendererOptions,\n> implements ProseMirrorNodeView {\n  component: Component\n\n  editor: NodeEditor\n\n  options: Options\n\n  extension: NodeViewRendererProps['extension']\n\n  node: NodeViewRendererProps['node']\n\n  decorations: NodeViewRendererProps['decorations']\n\n  innerDecorations: NodeViewRendererProps['innerDecorations']\n\n  view: NodeViewRendererProps['view']\n\n  getPos: NodeViewRendererProps['getPos']\n\n  HTMLAttributes: NodeViewRendererProps['HTMLAttributes']\n\n  isDragging = false\n\n  constructor(component: Component, props: NodeViewRendererProps, options?: Partial<Options>) {\n    this.component = component\n    this.editor = props.editor as NodeEditor\n    this.options = {\n      stopEvent: null,\n      ignoreMutation: null,\n      ...options,\n    } as Options\n    this.extension = props.extension\n    this.node = props.node\n    this.decorations = props.decorations as DecorationWithType[]\n    this.innerDecorations = props.innerDecorations\n    this.view = props.view\n    this.HTMLAttributes = props.HTMLAttributes\n    this.getPos = () => {\n      // ProseMirror throws while this node view is not attached to its parent yet.\n      try {\n        return props.getPos()\n      } catch {\n        return undefined\n      }\n    }\n    this.mount()\n  }\n\n  mount() {\n    // oxlint-disable-next-line\n    return\n  }\n\n  get dom(): HTMLElement {\n    return this.editor.view.dom as HTMLElement\n  }\n\n  get contentDOM(): HTMLElement | null {\n    return null\n  }\n\n  onDragStart(event: DragEvent) {\n    const { view } = this.editor\n    const target = event.target as HTMLElement\n\n    // get the drag handle element\n    // `closest` is not available for text nodes so we may have to use its parent\n    const dragHandle =\n      target.nodeType === 3\n        ? target.parentElement?.closest('[data-drag-handle]')\n        : target.closest('[data-drag-handle]')\n\n    if (!this.dom || this.contentDOM?.contains(target) || !dragHandle) {\n      return\n    }\n\n    let x = 0\n    let y = 0\n\n    // calculate offset for drag element if we use a different drag handle element\n    if (this.dom !== dragHandle) {\n      const domBox = this.dom.getBoundingClientRect()\n      const handleBox = dragHandle.getBoundingClientRect()\n\n      // In React, we have to go through nativeEvent to reach offsetX/offsetY.\n      const offsetX = event.offsetX ?? (event as any).nativeEvent?.offsetX\n      const offsetY = event.offsetY ?? (event as any).nativeEvent?.offsetY\n\n      x = handleBox.x - domBox.x + offsetX\n      y = handleBox.y - domBox.y + offsetY\n    }\n\n    const clonedNode = this.dom.cloneNode(true) as HTMLElement\n\n    // Preserve the visual size of the original when using the clone as\n    // the drag image.\n    try {\n      const domBox = this.dom.getBoundingClientRect()\n      clonedNode.style.width = `${Math.round(domBox.width)}px`\n      clonedNode.style.height = `${Math.round(domBox.height)}px`\n      clonedNode.style.boxSizing = 'border-box'\n      // Ensure the clone doesn't capture pointer events while offscreen\n      clonedNode.style.pointerEvents = 'none'\n    } catch {\n      // ignore measurement errors (e.g. if element not in DOM)\n    }\n\n    // Some browsers (notably Safari) require the element passed to\n    // setDragImage to be present in the DOM. Using a detached node can\n    // cause the drag to immediately end.\n    let dragImageWrapper: HTMLElement | null = null\n\n    try {\n      dragImageWrapper = document.createElement('div')\n      dragImageWrapper.style.position = 'absolute'\n      dragImageWrapper.style.top = '-9999px'\n      dragImageWrapper.style.left = '-9999px'\n      dragImageWrapper.style.pointerEvents = 'none'\n      dragImageWrapper.appendChild(clonedNode)\n      document.body.appendChild(dragImageWrapper)\n\n      event.dataTransfer?.setDragImage(clonedNode, x, y)\n    } finally {\n      // Remove the wrapper on the next tick so the browser can use the\n      // element as the drag image. A 0ms timeout is enough in practice.\n      if (dragImageWrapper) {\n        setTimeout(() => {\n          try {\n            dragImageWrapper?.remove()\n          } catch {\n            // ignore removal errors\n          }\n        }, 0)\n      }\n    }\n\n    const pos = this.getPos()\n\n    if (typeof pos !== 'number') {\n      return\n    }\n    // we need to tell ProseMirror that we want to move the whole node\n    // so we create a NodeSelection\n    const selection = NodeSelection.create(view.state.doc, pos)\n    const transaction = view.state.tr.setSelection(selection)\n\n    view.dispatch(transaction)\n  }\n\n  stopEvent(event: Event) {\n    if (!this.dom) {\n      return false\n    }\n\n    if (typeof this.options.stopEvent === 'function') {\n      return this.options.stopEvent({ event })\n    }\n\n    const target = event.target as HTMLElement\n    const isInElement = this.dom.contains(target) && !this.contentDOM?.contains(target)\n\n    // any event from child nodes should be handled by ProseMirror\n    if (!isInElement) {\n      return false\n    }\n\n    const isDragEvent = event.type.startsWith('drag')\n    const isDragOverEnterEvent = event.type === 'dragover' || event.type === 'dragenter'\n    const isDropEvent = event.type === 'drop'\n    const isInput =\n      ['INPUT', 'BUTTON', 'SELECT', 'TEXTAREA'].includes(target.tagName) || target.isContentEditable\n\n    // any input event within node views should be ignored by ProseMirror\n    if (isInput && !isDropEvent && !isDragEvent) {\n      return true\n    }\n\n    const { isEditable } = this.editor\n    const { isDragging } = this\n    const isDraggable = !!this.node.type.spec.draggable\n    const isSelectable = NodeSelection.isSelectable(this.node)\n    const isCopyEvent = event.type === 'copy'\n    const isPasteEvent = event.type === 'paste'\n    const isCutEvent = event.type === 'cut'\n    const isClickEvent = event.type === 'mousedown'\n\n    // ProseMirror tries to drag selectable nodes\n    // even if `draggable` is set to `false`\n    // this fix prevents that\n    if (!isDraggable && isSelectable && isDragEvent && event.target === this.dom) {\n      event.preventDefault()\n    }\n\n    if (isDraggable && isDragEvent && !isDragging && event.target === this.dom) {\n      event.preventDefault()\n      return false\n    }\n\n    // we have to store that dragging started\n    if (isDraggable && isEditable && !isDragging && isClickEvent) {\n      const dragHandle = target.closest('[data-drag-handle]')\n      const isValidDragHandle =\n        dragHandle && (this.dom === dragHandle || this.dom.contains(dragHandle))\n\n      if (isValidDragHandle) {\n        this.isDragging = true\n\n        document.addEventListener(\n          'dragend',\n          () => {\n            this.isDragging = false\n          },\n          { once: true },\n        )\n\n        document.addEventListener(\n          'drop',\n          () => {\n            this.isDragging = false\n          },\n          { once: true },\n        )\n\n        document.addEventListener(\n          'mouseup',\n          () => {\n            this.isDragging = false\n          },\n          { once: true },\n        )\n      }\n    }\n\n    // these events are handled by prosemirror\n    if (\n      isDragging ||\n      isDragOverEnterEvent ||\n      isDropEvent ||\n      isCopyEvent ||\n      isPasteEvent ||\n      isCutEvent ||\n      (isClickEvent && isSelectable)\n    ) {\n      return false\n    }\n\n    return true\n  }\n\n  /**\n   * Called when a DOM [mutation](https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver) or a selection change happens within the view.\n   * @return `false` if the editor should re-read the selection or re-parse the range around the mutation\n   * @return `true` if it can safely be ignored.\n   */\n  ignoreMutation(mutation: ViewMutationRecord) {\n    if (!this.dom) {\n      return true\n    }\n\n    if (!this.contentDOM) {\n      // ProseMirror has to see selection changes inside a leaf node view, otherwise\n      // the browser caret can get stuck inside its non-editable DOM and typed text is lost\n      return mutation.type !== 'selection'\n    }\n\n    if (typeof this.options.ignoreMutation === 'function') {\n      return this.options.ignoreMutation({ mutation })\n    }\n\n    // a leaf/atom node is like a black box for ProseMirror\n    // and should be fully handled by the node view\n    if (this.node.isLeaf || this.node.isAtom) {\n      return true\n    }\n\n    // ProseMirror should handle any selections\n    if (mutation.type === 'selection') {\n      return false\n    }\n\n    // try to prevent a bug on iOS and Android that will break node views on enter\n    // this is because ProseMirror can’t preventDispatch on enter\n    // this will lead to a re-render of the node view on enter\n    // see: https://github.com/ueberdosis/tiptap/issues/1214\n    // see: https://github.com/ueberdosis/tiptap/issues/2534\n    if (\n      this.contentDOM.contains(mutation.target) &&\n      mutation.type === 'childList' &&\n      (isiOS() || isAndroid()) &&\n      this.editor.isFocused\n    ) {\n      const changedNodes = [\n        ...Array.from(mutation.addedNodes),\n        ...Array.from(mutation.removedNodes),\n      ] as HTMLElement[]\n\n      // we’ll check if every changed node is contentEditable\n      // to make sure it’s probably mutated by ProseMirror\n      if (changedNodes.every(node => node.isContentEditable)) {\n        return false\n      }\n    }\n\n    // we will allow mutation contentDOM with attributes\n    // so we can for example adding classes within our node view\n    if (this.contentDOM === mutation.target && mutation.type === 'attributes') {\n      return true\n    }\n\n    // ProseMirror should handle any changes within contentDOM\n    if (this.contentDOM.contains(mutation.target)) {\n      return false\n    }\n\n    return true\n  }\n\n  /**\n   * Update the attributes of the prosemirror node.\n   */\n  updateAttributes(attributes: Record<string, any>): void {\n    this.editor.commands.command(({ tr }) => {\n      const pos = this.getPos()\n\n      if (typeof pos !== 'number') {\n        return false\n      }\n\n      tr.setNodeMarkup(pos, undefined, {\n        ...this.node.attrs,\n        ...attributes,\n      })\n\n      return true\n    })\n  }\n\n  /**\n   * Delete the node.\n   */\n  deleteNode(): void {\n    const from = this.getPos()\n\n    if (typeof from !== 'number') {\n      return\n    }\n    const to = from + this.node.nodeSize\n\n    this.editor.commands.deleteRange({ from, to })\n  }\n}\n", "import type { MarkType } from '@tiptap/pm/model'\n\nimport { getMarksBetween } from '../helpers/getMarksBetween.js'\nimport type { PasteRuleFinder } from '../PasteRule.js'\nimport { PasteRule } from '../PasteRule.js'\nimport type { ExtendedRegExpMatchArray } from '../types.js'\nimport { callOrReturn } from '../utilities/callOrReturn.js'\n\n/**\n * Build an paste rule that adds a mark when the\n * matched text is pasted into it.\n * @see https://tiptap.dev/docs/editor/extensions/custom-extensions/extend-existing#paste-rules\n */\nexport function markPasteRule(config: {\n  find: PasteRuleFinder\n  type: MarkType\n  getAttributes?:\n    | Record<string, any>\n    | ((match: ExtendedRegExpMatchArray, event: ClipboardEvent) => Record<string, any>)\n    | false\n    | null\n}) {\n  return new PasteRule({\n    find: config.find,\n    handler: ({ state, range, match, pasteEvent }) => {\n      const attributes = callOrReturn(config.getAttributes, undefined, match, pasteEvent)\n\n      if (attributes === false || attributes === null) {\n        return null\n      }\n\n      const { tr } = state\n      const captureGroup = match[match.length - 1]\n      const fullMatch = match[0]\n      let markEnd = range.to\n\n      if (captureGroup) {\n        const startSpaces = fullMatch.search(/\\S/)\n        const textStart = range.from + fullMatch.indexOf(captureGroup)\n        const textEnd = textStart + captureGroup.length\n\n        const excludedMarks = getMarksBetween(range.from, range.to, state.doc)\n          .filter(item => {\n            // @ts-ignore\n            const excluded = item.mark.type.excluded as MarkType[]\n\n            return excluded.find(type => type === config.type && type !== item.mark.type)\n          })\n          .filter(item => item.to > textStart)\n\n        if (excludedMarks.length) {\n          return null\n        }\n\n        if (textEnd < range.to) {\n          tr.delete(textEnd, range.to)\n        }\n\n        if (textStart > range.from) {\n          tr.delete(range.from + startSpaces, textStart)\n        }\n\n        markEnd = range.from + startSpaces + captureGroup.length\n\n        tr.addMark(range.from + startSpaces, markEnd, config.type.create(attributes || {}))\n\n        // Only remove the stored mark if the match is not at the end of the\n        // pasted text. When a mark extends to the end of the content, removing\n        // it overrides the mark's `inclusive` behavior and incorrectly places\n        // the cursor outside the mark.\n        const isMatchAtEndOfText =\n          match.index !== undefined &&\n          match.input !== undefined &&\n          match.index + match[0].length >= match.input.length\n\n        if (!isMatchAtEndOfText) {\n          tr.removeStoredMark(config.type)\n        }\n      }\n    },\n  })\n}\n", "import type { NodeType } from '@tiptap/pm/model'\n\nimport type { PasteRuleFinder } from '../PasteRule.js'\nimport { PasteRule } from '../PasteRule.js'\nimport type { ExtendedRegExpMatchArray, JSONContent } from '../types.js'\nimport { callOrReturn } from '../utilities/index.js'\n\n/**\n * Build an paste rule that adds a node when the\n * matched text is pasted into it.\n * @see https://tiptap.dev/docs/editor/api/paste-rules\n */\nexport function nodePasteRule(config: {\n  find: PasteRuleFinder\n  type: NodeType\n  getAttributes?:\n    | Record<string, any>\n    | ((match: ExtendedRegExpMatchArray, event: ClipboardEvent) => Record<string, any>)\n    | false\n    | null\n  getContent?: JSONContent[] | ((attrs: Record<string, any>) => JSONContent[]) | false | null\n}) {\n  return new PasteRule({\n    find: config.find,\n    handler({ match, chain, range, pasteEvent }) {\n      const attributes = callOrReturn(config.getAttributes, undefined, match, pasteEvent)\n      const content = callOrReturn(config.getContent, undefined, attributes)\n\n      if (attributes === false || attributes === null) {\n        return null\n      }\n\n      const node = { type: config.type.name, attrs: attributes } as JSONContent\n\n      if (content) {\n        node.content = content\n      }\n\n      if (match.input) {\n        chain().deleteRange(range).insertContentAt(range.from, node)\n      }\n    },\n  })\n}\n", "import type { PasteRuleFinder } from '../PasteRule.js'\nimport { PasteRule } from '../PasteRule.js'\n\n/**\n * Build an paste rule that replaces text when the\n * matched text is pasted into it.\n * @see https://tiptap.dev/docs/editor/extensions/custom-extensions/extend-existing#paste-rules\n */\nexport function textPasteRule(config: { find: PasteRuleFinder; replace: string }) {\n  return new PasteRule({\n    find: config.find,\n    handler: ({ state, range, match }) => {\n      let insert = config.replace\n      let start = range.from\n      const end = range.to\n\n      if (match[1]) {\n        const offset = match[0].lastIndexOf(match[1])\n\n        insert += match[0].slice(offset + match[1].length)\n        start += offset\n\n        const cutOff = start - end\n\n        if (cutOff > 0) {\n          insert = match[0].slice(offset - cutOff, offset) + insert\n          start = end\n        }\n      }\n\n      state.tr.insertText(insert, start, end)\n    },\n  })\n}\n", "import type { Transaction } from '@tiptap/pm/state'\n\nexport interface TrackerResult {\n  position: number\n  deleted: boolean\n}\n\nexport class Tracker {\n  transaction: Transaction\n\n  currentStep: number\n\n  constructor(transaction: Transaction) {\n    this.transaction = transaction\n    this.currentStep = this.transaction.steps.length\n  }\n\n  map(position: number): TrackerResult {\n    let deleted = false\n\n    const mappedPosition = this.transaction.steps\n      .slice(this.currentStep)\n      .reduce((newPosition, step) => {\n        const mapResult = step.getMap().mapResult(newPosition)\n\n        if (mapResult.deleted) {\n          deleted = true\n        }\n\n        return mapResult.pos\n      }, position)\n\n    return {\n      position: mappedPosition,\n      deleted,\n    }\n  }\n}\n", "export type Attributes = Record<string, any>\n\nexport type DOMOutputSpecElement = 0 | Attributes | DOMOutputSpecArray\n/**\n * Better describes the output of a `renderHTML` function in prosemirror\n * @see https://prosemirror.net/docs/ref/#model.DOMOutputSpec\n */\nexport type DOMOutputSpecArray =\n  | [string]\n  | [string, Attributes]\n  | [string, 0]\n  | [string, Attributes, 0]\n  | [string, Attributes, DOMOutputSpecArray | 0]\n  | [string, DOMOutputSpecArray]\n\n// Child lists and DOM output specs are both arrays, so track JSX boundaries by identity.\nconst jsxElements = new WeakSet<DOMOutputSpecArray>()\nconst jsxFragments = new WeakSet<unknown[]>()\n\n/** Create a new JSX element from the given spec */\nfunction createJSXElement(spec: unknown[]): DOMOutputSpecArray {\n  const element = spec as DOMOutputSpecArray\n\n  jsxElements.add(element)\n\n  return element\n}\n\n/** Check if a spec is a JSX element */\nfunction isJSXElement(value: unknown): value is DOMOutputSpecArray {\n  return Array.isArray(value) && jsxElements.has(value as DOMOutputSpecArray)\n}\n\nfunction flattenFragmentChildren(children: unknown[]): unknown[] {\n  return children.flatMap(child => {\n    if (child == null) {\n      return []\n    }\n\n    if (Array.isArray(child) && jsxFragments.has(child) && !isJSXElement(child)) {\n      return flattenFragmentChildren(child)\n    }\n\n    return [child]\n  })\n}\n\n// JSX types for Tiptap's JSX runtime\n// These types only apply when using @jsxImportSource @tiptap/core\nexport declare namespace JSX {\n  export type Element = DOMOutputSpecArray\n  export interface IntrinsicElements {\n    [key: string]: any\n  }\n  export interface ElementChildrenAttribute {\n    children: unknown\n  }\n}\n\ntype JSXChild = DOMOutputSpecElement | string | null | undefined | JSXChild[]\n\nexport type JSXRenderer = (\n  tag: 'slot' | string | ((props?: Attributes) => DOMOutputSpecArray | DOMOutputSpecElement),\n  props?: Attributes,\n  ...children: JSXChild[]\n) => DOMOutputSpecArray | DOMOutputSpecElement\n\nexport function Fragment(props: { children: JSXChild[] }) {\n  jsxFragments.add(props.children)\n\n  return props.children\n}\n\nfunction render(tag: Parameters<JSXRenderer>[0], attributes: Attributes | undefined) {\n  // Treat the slot tag as the Prosemirror hole to render content into\n  if (tag === 'slot') {\n    return 0\n  }\n\n  // If the tag is a function, call it with the props\n  if (tag instanceof Function) {\n    const result = tag(attributes)\n\n    if (Array.isArray(result) && !isJSXElement(result) && !jsxFragments.has(result)) {\n      return createJSXElement(result)\n    }\n\n    return result\n  }\n\n  const { children, ...rest } = attributes ?? {}\n\n  if (tag === 'svg') {\n    throw new Error(\n      'SVG elements are not supported in the JSX syntax, use the array syntax instead',\n    )\n  }\n\n  // Handle children array by spreading elements\n  if (Array.isArray(children)) {\n    if (isJSXElement(children)) {\n      return createJSXElement([tag, rest, children])\n    }\n\n    if (children.length === 0) {\n      // Empty array means no children\n      return createJSXElement([tag, rest])\n    }\n\n    const flattenedChildren = flattenFragmentChildren(children)\n\n    if (flattenedChildren.length === 0) {\n      return createJSXElement([tag, rest])\n    }\n\n    // Spread children into the result array\n    return createJSXElement([tag, rest, ...flattenedChildren])\n  }\n\n  // Single child or no children\n  if (children !== undefined && children !== null) {\n    return createJSXElement([tag, rest, children])\n  }\n\n  return createJSXElement([tag, rest])\n}\n\nexport const h: JSXRenderer = (tag, attributes) => render(tag, attributes)\n\nexport const jsxs: JSXRenderer = (tag, attributes) => render(tag, attributes)\n\nexport const jsxDEV = (\n  tag: Parameters<JSXRenderer>[0],\n  attributes?: Attributes,\n  _key?: unknown,\n  _isStaticChildren?: boolean,\n) => {\n  return render(tag, attributes)\n}\n\n// See\n// https://esbuild.github.io/api/#jsx-import-source\n// https://www.typescriptlang.org/tsconfig/#jsxImportSource\n\nexport { h as createElement, h as jsx }\n", "import type { Editor } from '@tiptap/core'\nimport { Slice, type NodeType } from '@tiptap/pm/model'\nimport { TextSelection } from '@tiptap/pm/state'\n\n/**\n * Restructure the blockquote boundary at the caret.\n *\n * Two cases are handled in a single backspace:\n *\n * 1. Caret at the start of a non-first child of a blockquote — lift the\n *    current child out, splitting the blockquote around it.\n * 2. Caret at the start of a top-level textblock whose previous sibling is\n *    a blockquote with a textblock last child — merge the current\n *    textblock's inline content into the blockquote's last textblock\n *    instead of letting joinBackward pull the paragraph back inside.\n *\n * Returns true when the backspace was consumed.\n */\nexport const handleBackspace = (editor: Editor, type: NodeType): boolean => {\n  const { state } = editor\n  const { selection } = state\n  if (!selection.empty) return false\n\n  const { $from } = selection\n  if ($from.parentOffset !== 0) return false\n\n  const parentDepth = $from.depth - 1\n  // At the very start of the document the caret can resolve to the top (doc)\n  // level — for example a gap cursor before a leading image — where there is\n  // no parent block. Bail out so backspace is a no-op instead of dereferencing\n  // an undefined parent at a negative depth. (#7973)\n  if (parentDepth < 0) return false\n\n  const parent = $from.node(parentDepth)\n  const index = $from.index(parentDepth)\n  if (index === 0) return false\n\n  // Non-first child of a blockquote: lift to split the blockquote around it.\n  if (parent.type === type) {\n    return editor.commands.lift(type.name)\n  }\n\n  // Previous sibling is a blockquote whose last child is a textblock:\n  // merge the inline content in instead of letting joinBackward pull the\n  // paragraph back inside the blockquote.\n  const previous = parent.child(index - 1)\n  if (previous.type !== type || !previous.lastChild?.isTextblock) {\n    return false\n  }\n\n  const blockStart = $from.before()\n  // `blockStart` sits in the shared parent at the position right after\n  // the previous blockquote. In ProseMirror coordinates, each closing\n  // token costs one position: step one back to land inside the blockquote\n  // right after its last child, then one more to land inside that last\n  // child at the end of its inline content.\n  const insideBlockquoteEnd = blockStart - 1\n  const targetPos = insideBlockquoteEnd - 1\n\n  return editor.commands.command(({ tr, dispatch }) => {\n    if (!dispatch) {\n      return true\n    }\n\n    const content = $from.parent.content\n    const slice = new Slice(content, 0, 0)\n\n    tr.replace(targetPos, $from.after(), slice)\n    tr.setSelection(TextSelection.create(tr.doc, targetPos))\n    tr.scrollIntoView()\n    dispatch(tr)\n\n    return true\n  })\n}\n", "/** @jsxImportSource @tiptap/core */\nimport { mergeAttributes, Node, wrappingInputRule } from '@tiptap/core'\n\nimport { handleBackspace } from './handleBackspace.js'\n\nexport interface BlockquoteOptions {\n  /**\n   * HTML attributes to add to the blockquote element\n   * @default {}\n   * @example { class: 'foo' }\n   */\n  HTMLAttributes: Record<string, any>\n}\n\ndeclare module '@tiptap/core' {\n  interface Commands<ReturnType> {\n    blockQuote: {\n      /**\n       * Set a blockquote node\n       */\n      setBlockquote: () => ReturnType\n      /**\n       * Toggle a blockquote node\n       */\n      toggleBlockquote: () => ReturnType\n      /**\n       * Unset a blockquote node\n       */\n      unsetBlockquote: () => ReturnType\n    }\n  }\n}\n\n/**\n * Matches a blockquote to a `>` as input.\n */\nexport const inputRegex = /^\\s*>\\s$/\n\n/**\n * This extension allows you to create blockquotes.\n * @see https://tiptap.dev/api/nodes/blockquote\n */\nexport const Blockquote = Node.create<BlockquoteOptions>({\n  name: 'blockquote',\n\n  addOptions() {\n    return {\n      HTMLAttributes: {},\n    }\n  },\n\n  content: 'block+',\n\n  group: 'block',\n\n  defining: true,\n\n  parseHTML() {\n    return [{ tag: 'blockquote' }]\n  },\n\n  renderHTML({ HTMLAttributes }) {\n    return (\n      <blockquote {...mergeAttributes(this.options.HTMLAttributes, HTMLAttributes)}>\n        <slot />\n      </blockquote>\n    )\n  },\n\n  parseMarkdown: (token, helpers) => {\n    const parseBlockChildren = helpers.parseBlockChildren ?? helpers.parseChildren\n\n    return helpers.createNode('blockquote', undefined, parseBlockChildren(token.tokens || []))\n  },\n\n  renderMarkdown: (node, h) => {\n    if (!node.content) {\n      return ''\n    }\n\n    // Use a single '>' prefix regardless of nesting level\n    // Nested blockquotes will add their own '>' prefix recursively\n    const prefix = '>'\n    const result: string[] = []\n\n    node.content.forEach((child, index) => {\n      const childContent = h.renderChild?.(child, index) ?? h.renderChildren([child])\n      const lines = childContent.split('\\n')\n\n      const linesWithPrefix = lines.map(line => {\n        // Don't add prefix to empty lines\n        if (line.trim() === '') {\n          return prefix\n        }\n\n        // Nested blockquotes will already have their own prefixes\n        // We just need to add our own prefix at the start\n        return `${prefix} ${line}`\n      })\n\n      result.push(linesWithPrefix.join('\\n'))\n    })\n\n    // Add separator lines between children\n    return result.join(`\\n${prefix}\\n`)\n  },\n\n  addCommands() {\n    return {\n      setBlockquote:\n        () =>\n        ({ commands }) => {\n          return commands.wrapIn(this.name)\n        },\n      toggleBlockquote:\n        () =>\n        ({ commands }) => {\n          return commands.toggleWrap(this.name)\n        },\n      unsetBlockquote:\n        () =>\n        ({ commands }) => {\n          return commands.lift(this.name)\n        },\n    }\n  },\n\n  addKeyboardShortcuts() {\n    return {\n      'Mod-Shift-b': () => this.editor.commands.toggleBlockquote(),\n      Backspace: () => handleBackspace(this.editor, this.type),\n    }\n  },\n\n  addInputRules() {\n    return [\n      wrappingInputRule({\n        find: inputRegex,\n        type: this.type,\n      }),\n    ]\n  },\n})\n", "import { Blockquote } from './blockquote.jsx'\n\nexport * from './blockquote.jsx'\n\nexport default Blockquote\n", "/** @jsxImportSource @tiptap/core */\nimport { Mark, markInputRule, markPasteRule, mergeAttributes } from '@tiptap/core'\n\nexport interface BoldOptions {\n  /**\n   * HTML attributes to add to the bold element.\n   * @default {}\n   * @example { class: 'foo' }\n   */\n  HTMLAttributes: Record<string, any>\n}\n\ndeclare module '@tiptap/core' {\n  interface Commands<ReturnType> {\n    bold: {\n      /**\n       * Set a bold mark\n       */\n      setBold: () => ReturnType\n      /**\n       * Toggle a bold mark\n       */\n      toggleBold: () => ReturnType\n      /**\n       * Unset a bold mark\n       */\n      unsetBold: () => ReturnType\n    }\n  }\n}\n\n/**\n * Matches bold text via `**` as input.\n */\nexport const starInputRegex = /(?:^|\\s)(\\*\\*(?!\\s+\\*\\*)((?:[^*]+))\\*\\*(?!\\s+\\*\\*))$/\n\n/**\n * Matches bold text via `**` while pasting.\n */\nexport const starPasteRegex = /(?:^|\\s)(\\*\\*(?!\\s+\\*\\*)((?:[^*]+))\\*\\*(?!\\s+\\*\\*))/g\n\n/**\n * Matches bold text via `__` as input.\n */\nexport const underscoreInputRegex = /(?:^|\\s)(__(?!\\s+__)((?:[^_]+))__(?!\\s+__))$/\n\n/**\n * Matches bold text via `__` while pasting.\n */\nexport const underscorePasteRegex = /(?:^|\\s)(__(?!\\s+__)((?:[^_]+))__(?!\\s+__))/g\n\n/**\n * This extension allows you to mark text as bold.\n * @see https://tiptap.dev/api/marks/bold\n */\nexport const Bold = Mark.create<BoldOptions>({\n  name: 'bold',\n\n  addOptions() {\n    return {\n      HTMLAttributes: {},\n    }\n  },\n\n  parseHTML() {\n    return [\n      {\n        tag: 'strong',\n      },\n      {\n        tag: 'b',\n        getAttrs: node => (node as HTMLElement).style.fontWeight !== 'normal' && null,\n      },\n      {\n        style: 'font-weight=400',\n        clearMark: mark => mark.type.name === this.name,\n      },\n      {\n        style: 'font-weight',\n        getAttrs: value => /^(bold(er)?|[5-9]\\d{2,})$/.test(value as string) && null,\n      },\n    ]\n  },\n\n  renderHTML({ HTMLAttributes }) {\n    return (\n      <strong {...mergeAttributes(this.options.HTMLAttributes, HTMLAttributes)}>\n        <slot />\n      </strong>\n    )\n  },\n\n  markdownTokenName: 'strong',\n\n  parseMarkdown: (token, helpers) => {\n    // Convert 'strong' token to bold mark\n    return helpers.applyMark('bold', helpers.parseInline(token.tokens || []))\n  },\n\n  markdownOptions: {\n    htmlReopen: {\n      open: '<strong>',\n      close: '</strong>',\n    },\n  },\n\n  renderMarkdown: (node, h) => {\n    return `**${h.renderChildren(node)}**`\n  },\n\n  addCommands() {\n    return {\n      setBold:\n        () =>\n        ({ commands }) => {\n          return commands.setMark(this.name)\n        },\n      toggleBold:\n        () =>\n        ({ commands }) => {\n          return commands.toggleMark(this.name)\n        },\n      unsetBold:\n        () =>\n        ({ commands }) => {\n          return commands.unsetMark(this.name)\n        },\n    }\n  },\n\n  addKeyboardShortcuts() {\n    return {\n      'Mod-b': () => this.editor.commands.toggleBold(),\n      'Mod-B': () => this.editor.commands.toggleBold(),\n    }\n  },\n\n  addInputRules() {\n    return [\n      markInputRule({\n        find: starInputRegex,\n        type: this.type,\n      }),\n      markInputRule({\n        find: underscoreInputRegex,\n        type: this.type,\n      }),\n    ]\n  },\n\n  addPasteRules() {\n    return [\n      markPasteRule({\n        find: starPasteRegex,\n        type: this.type,\n      }),\n      markPasteRule({\n        find: underscorePasteRegex,\n        type: this.type,\n      }),\n    ]\n  },\n})\n", "import { Bold } from './bold.jsx'\n\nexport * from './bold.jsx'\n\nexport default Bold\n", "import type { InputRuleMatch, PasteRuleMatch } from '@tiptap/core'\nimport { Mark, markInputRule, markPasteRule, mergeAttributes } from '@tiptap/core'\n\nexport interface CodeOptions {\n  /**\n   * The HTML attributes applied to the code element.\n   * @default {}\n   * @example { class: 'foo' }\n   */\n  HTMLAttributes: Record<string, any>\n}\n\ndeclare module '@tiptap/core' {\n  interface Commands<ReturnType> {\n    code: {\n      /**\n       * Set a code mark\n       */\n      setCode: () => ReturnType\n      /**\n       * Toggle inline code\n       */\n      toggleCode: () => ReturnType\n      /**\n       * Unset a code mark\n       */\n      unsetCode: () => ReturnType\n    }\n  }\n}\n\n/**\n * The regular expression used for the inline code input rule.\n * @deprecated The extension now uses a function-based finder internally.\n * This regex is kept for backward compatibility.\n */\nexport const inputRegex = /(^|[^`])`([^`]+)`(?!`)$/\n\n/**\n * The regular expression used for the inline code paste rule.\n * @deprecated The extension now uses a function-based finder internally.\n * This regex is kept for backward compatibility.\n */\nexport const pasteRegex = /(^|[^`])`([^`]+)`(?!`)/g\n\n/**\n * A function-based finder for the inline code input rule.\n * Used internally by the extension to ensure the preceding character\n * is not consumed as part of the match, preventing it from being deleted.\n */\nexport const inputRegexMatch = (text: string): InputRuleMatch | null => {\n  const match = /`([^`]+)`(?!`)$/.exec(text)\n\n  if (!match) {\n    return null\n  }\n\n  // Ensure the opening backtick isn't preceded by another backtick\n  if (match.index > 0 && text[match.index - 1] === '`') {\n    return null\n  }\n\n  return {\n    index: match.index,\n    text: match[0],\n    replaceWith: match[1],\n  }\n}\n\n/**\n * A function-based finder for the inline code paste rule.\n * Used internally by the extension to avoid consuming the preceding\n * character as part of the match.\n */\nexport const pasteRegexMatch = (text: string): PasteRuleMatch[] => {\n  const regex = /`([^`]+)`(?!`)/g\n  const matches: PasteRuleMatch[] = []\n  let match: RegExpExecArray | null\n\n  while ((match = regex.exec(text)) !== null) {\n    // Ensure the opening backtick isn't preceded by another backtick\n    if (match.index > 0 && text[match.index - 1] === '`') {\n      continue\n    }\n\n    matches.push({\n      index: match.index,\n      text: match[0],\n      replaceWith: match[1],\n    })\n  }\n\n  return matches\n}\n\n// A code span must be fenced by a backtick run its own content does not contain\nfunction shortestUnusedBacktickRun(text: string): number {\n  const runs = new Set((text.match(/`+/g) || []).map(run => run.length))\n  let length = 1\n\n  while (runs.has(length)) {\n    length += 1\n  }\n\n  return length\n}\n\n/**\n * This extension allows you to mark text as inline code.\n * @see https://tiptap.dev/api/marks/code\n */\nexport const Code = Mark.create<CodeOptions>({\n  name: 'code',\n\n  addOptions() {\n    return {\n      HTMLAttributes: {},\n    }\n  },\n\n  excludes: '_',\n\n  code: true,\n\n  exitable: true,\n\n  parseHTML() {\n    return [{ tag: 'code' }]\n  },\n\n  renderHTML({ HTMLAttributes }) {\n    return ['code', mergeAttributes(this.options.HTMLAttributes, HTMLAttributes), 0]\n  },\n\n  markdownTokenName: 'codespan',\n\n  parseMarkdown: (token, helpers) => {\n    // Convert 'codespan' token to code mark\n    // For codespan tokens, we use the raw text content, not tokens\n    return helpers.applyMark('code', [{ type: 'text', text: token.text || '' }])\n  },\n\n  renderMarkdown: (node, h, context) => {\n    if (!node.content) {\n      return ''\n    }\n\n    // Children are a placeholder here, so the fence comes from the full span text\n    const markText = typeof context?.meta?.markText === 'string' ? context.meta.markText : ''\n    const fence = '`'.repeat(shortestUnusedBacktickRun(markText))\n    // CommonMark strips one space on each side, so padding keeps backticks apart\n    const padding = markText.startsWith('`') || markText.endsWith('`') ? ' ' : ''\n\n    return `${fence}${padding}${h.renderChildren(node.content)}${padding}${fence}`\n  },\n\n  addCommands() {\n    return {\n      setCode:\n        () =>\n        ({ commands }) => {\n          return commands.setMark(this.name)\n        },\n      toggleCode:\n        () =>\n        ({ commands }) => {\n          return commands.toggleMark(this.name)\n        },\n      unsetCode:\n        () =>\n        ({ commands }) => {\n          return commands.unsetMark(this.name)\n        },\n    }\n  },\n\n  addKeyboardShortcuts() {\n    return {\n      'Mod-e': () => this.editor.commands.toggleCode(),\n    }\n  },\n\n  addInputRules() {\n    return [\n      markInputRule({\n        find: inputRegexMatch,\n        type: this.type,\n      }),\n    ]\n  },\n\n  addPasteRules() {\n    return [\n      markPasteRule({\n        find: pasteRegexMatch,\n        type: this.type,\n      }),\n    ]\n  },\n})\n", "import { Code } from './code.js'\n\nexport * from './code.js'\n\nexport default Code\n", "import { mergeAttributes, Node, textblockTypeInputRule } from '@tiptap/core'\nimport { Plugin, PluginKey, Selection, TextSelection } from '@tiptap/pm/state'\n\nconst DEFAULT_TAB_SIZE = 4\n\nexport interface CodeBlockOptions {\n  /**\n   * Adds a prefix to language classes that are applied to code tags.\n   * @default 'language-'\n   */\n  languageClassPrefix: string | null | undefined\n  /**\n   * Define whether the node should be exited on triple enter.\n   * @default true\n   */\n  exitOnTripleEnter: boolean | null | undefined\n  /**\n   * Define whether the node should be exited on arrow down if there is no node after it.\n   * @default true\n   */\n  exitOnArrowDown: boolean | null | undefined\n  /**\n   * Define whether the node should be exited on arrow up if there is no node before it.\n   * @default true\n   */\n  exitOnArrowUp: boolean | null | undefined\n  /**\n   * The default language.\n   * @default null\n   * @example 'js'\n   */\n  defaultLanguage: string | null | undefined\n  /**\n   * Enable tab key for indentation in code blocks.\n   * @default false\n   */\n  enableTabIndentation: boolean | null | undefined\n  /**\n   * The number of spaces to use for tab indentation.\n   * @default 4\n   */\n  tabSize: number | null | undefined\n  /**\n   * Custom HTML attributes that should be added to the rendered HTML tag.\n   * @default {}\n   * @example { class: 'foo' }\n   */\n  HTMLAttributes: Record<string, any>\n}\n\ndeclare module '@tiptap/core' {\n  interface Commands<ReturnType> {\n    codeBlock: {\n      /**\n       * Set a code block\n       * @param attributes Code block attributes\n       * @example editor.commands.setCodeBlock({ language: 'javascript' })\n       */\n      setCodeBlock: (attributes?: { language: string }) => ReturnType\n      /**\n       * Toggle a code block\n       * @param attributes Code block attributes\n       * @example editor.commands.toggleCodeBlock({ language: 'javascript' })\n       */\n      toggleCodeBlock: (attributes?: { language: string }) => ReturnType\n    }\n  }\n}\n\n/**\n * Matches a code block with backticks.\n */\nexport const backtickInputRegex = /^```([a-z]+)?[\\s\\n]$/\n\n/**\n * Matches a code block with tildes.\n */\nexport const tildeInputRegex = /^~~~([a-z]+)?[\\s\\n]$/\n\n/**\n * This extension allows you to create code blocks.\n * @see https://tiptap.dev/api/nodes/code-block\n */\nexport const CodeBlock = Node.create<CodeBlockOptions>({\n  name: 'codeBlock',\n\n  addOptions() {\n    return {\n      languageClassPrefix: 'language-',\n      exitOnTripleEnter: true,\n      exitOnArrowDown: true,\n      exitOnArrowUp: true,\n      defaultLanguage: null,\n      enableTabIndentation: false,\n      tabSize: DEFAULT_TAB_SIZE,\n      HTMLAttributes: {},\n    }\n  },\n\n  content: 'text*',\n\n  marks: '',\n\n  group: 'block',\n\n  code: true,\n\n  defining: true,\n\n  addAttributes() {\n    return {\n      language: {\n        default: this.options.defaultLanguage,\n        parseHTML: element => {\n          const { languageClassPrefix } = this.options\n\n          if (!languageClassPrefix) {\n            return null\n          }\n\n          const classNames = [...(element.firstElementChild?.classList || [])]\n          const languages = classNames\n            .filter(className => className.startsWith(languageClassPrefix))\n            .map(className => className.replace(languageClassPrefix, ''))\n          const language = languages[0]\n\n          if (!language) {\n            return null\n          }\n\n          return language\n        },\n        rendered: false,\n      },\n    }\n  },\n\n  parseHTML() {\n    return [\n      {\n        tag: 'pre',\n        preserveWhitespace: 'full',\n      },\n    ]\n  },\n\n  renderHTML({ node, HTMLAttributes }) {\n    return [\n      'pre',\n      mergeAttributes(this.options.HTMLAttributes, HTMLAttributes),\n      [\n        'code',\n        {\n          class: node.attrs.language\n            ? this.options.languageClassPrefix + node.attrs.language\n            : null,\n        },\n        0,\n      ],\n    ]\n  },\n\n  markdownTokenName: 'code',\n\n  parseMarkdown: (token, helpers) => {\n    if (\n      token.raw?.startsWith('```') === false &&\n      token.raw?.startsWith('~~~') === false &&\n      token.codeBlockStyle !== 'indented'\n    ) {\n      return []\n    }\n\n    return helpers.createNode(\n      'codeBlock',\n      { language: token.lang || null },\n      token.text ? [helpers.createTextNode(token.text)] : [],\n    )\n  },\n\n  renderMarkdown: (node, h) => {\n    let output = ''\n    const language = node.attrs?.language || ''\n\n    if (!node.content) {\n      output = `\\`\\`\\`${language}\\n\\n\\`\\`\\``\n    } else {\n      const lines = [`\\`\\`\\`${language}`, h.renderChildren(node.content), '```']\n      output = lines.join('\\n')\n    }\n\n    return output\n  },\n\n  addCommands() {\n    return {\n      setCodeBlock:\n        attributes =>\n        ({ commands }) => {\n          return commands.setNode(this.name, attributes)\n        },\n      toggleCodeBlock:\n        attributes =>\n        ({ commands }) => {\n          return commands.toggleNode(this.name, 'paragraph', attributes)\n        },\n    }\n  },\n\n  addKeyboardShortcuts() {\n    return {\n      'Mod-Alt-c': () => this.editor.commands.toggleCodeBlock(),\n\n      // remove code block when at start of document or code block is empty\n      Backspace: () => {\n        const { empty, $anchor } = this.editor.state.selection\n        const isAtStart = $anchor.pos === 1\n\n        if (!empty || $anchor.parent.type.name !== this.name) {\n          return false\n        }\n\n        if (isAtStart || !$anchor.parent.textContent.length) {\n          return this.editor.commands.clearNodes()\n        }\n\n        return false\n      },\n\n      // handle tab indentation\n      Tab: ({ editor }) => {\n        if (!this.options.enableTabIndentation) {\n          return false\n        }\n\n        const tabSize = this.options.tabSize ?? DEFAULT_TAB_SIZE\n        const { state } = editor\n        const { selection } = state\n        const { $from, empty } = selection\n\n        if ($from.parent.type !== this.type) {\n          return false\n        }\n\n        const indent = ' '.repeat(tabSize)\n\n        if (empty) {\n          return editor.commands.insertContent(indent)\n        }\n\n        return editor.commands.command(({ tr }) => {\n          const { from, to } = selection\n          const text = state.doc.textBetween(from, to, '\\n', '\\n')\n          const lines = text.split('\\n')\n          const indentedText = lines.map(line => indent + line).join('\\n')\n\n          tr.replaceWith(from, to, state.schema.text(indentedText))\n          return true\n        })\n      },\n\n      // handle shift+tab reverse indentation\n      'Shift-Tab': ({ editor }) => {\n        if (!this.options.enableTabIndentation) {\n          return false\n        }\n\n        const tabSize = this.options.tabSize ?? DEFAULT_TAB_SIZE\n        const { state } = editor\n        const { selection } = state\n        const { $from, empty } = selection\n\n        if ($from.parent.type !== this.type) {\n          return false\n        }\n\n        if (empty) {\n          return editor.commands.command(({ tr }) => {\n            const { pos } = $from\n            const codeBlockStart = $from.start()\n            const codeBlockEnd = $from.end()\n\n            const allText = state.doc.textBetween(codeBlockStart, codeBlockEnd, '\\n', '\\n')\n            const lines = allText.split('\\n')\n\n            let currentLineIndex = 0\n            let charCount = 0\n            const relativeCursorPos = pos - codeBlockStart\n\n            for (let i = 0; i < lines.length; i += 1) {\n              if (charCount + lines[i].length >= relativeCursorPos) {\n                currentLineIndex = i\n                break\n              }\n              charCount += lines[i].length + 1\n            }\n\n            const currentLine = lines[currentLineIndex]\n            const leadingSpaces = currentLine.match(/^ */)?.[0] || ''\n            const spacesToRemove = Math.min(leadingSpaces.length, tabSize)\n\n            if (spacesToRemove === 0) {\n              return true\n            }\n\n            let lineStartPos = codeBlockStart\n            for (let i = 0; i < currentLineIndex; i += 1) {\n              lineStartPos += lines[i].length + 1\n            }\n\n            tr.delete(lineStartPos, lineStartPos + spacesToRemove)\n\n            const cursorPosInLine = pos - lineStartPos\n            if (cursorPosInLine <= spacesToRemove) {\n              tr.setSelection(TextSelection.create(tr.doc, lineStartPos))\n            }\n\n            return true\n          })\n        }\n\n        return editor.commands.command(({ tr }) => {\n          const { from, to } = selection\n          const text = state.doc.textBetween(from, to, '\\n', '\\n')\n          const lines = text.split('\\n')\n          const reverseIndentText = lines\n            .map(line => {\n              const leadingSpaces = line.match(/^ */)?.[0] || ''\n              const spacesToRemove = Math.min(leadingSpaces.length, tabSize)\n              return line.slice(spacesToRemove)\n            })\n            .join('\\n')\n\n          tr.replaceWith(from, to, state.schema.text(reverseIndentText))\n          return true\n        })\n      },\n\n      // exit node on triple enter\n      Enter: ({ editor }) => {\n        if (!this.options.exitOnTripleEnter) {\n          return false\n        }\n\n        const { state } = editor\n        const { selection } = state\n        const { $from, empty } = selection\n\n        if (!empty || $from.parent.type !== this.type) {\n          return false\n        }\n\n        const isAtEnd = $from.parentOffset === $from.parent.nodeSize - 2\n        const endsWithDoubleNewline = $from.parent.textContent.endsWith('\\n\\n')\n\n        if (!isAtEnd || !endsWithDoubleNewline) {\n          return false\n        }\n\n        return editor\n          .chain()\n          .command(({ tr }) => {\n            tr.delete($from.pos - 2, $from.pos)\n\n            return true\n          })\n          .exitCode()\n          .run()\n      },\n\n      // exit node on arrow up if there is no node before it\n      ArrowUp: ({ editor }) => {\n        if (!this.options.exitOnArrowUp) {\n          return false\n        }\n\n        const { state } = editor\n        const { selection } = state\n        const { $from, empty } = selection\n\n        if (!empty || $from.parent.type !== this.type) {\n          return false\n        }\n\n        if ($from.parentOffset !== 0) {\n          return false\n        }\n\n        const before = $from.before()\n\n        if (before > 0) {\n          return false\n        }\n\n        return editor.commands.insertDefaultBlock({ pos: before })\n      },\n\n      // exit node on arrow down\n      ArrowDown: ({ editor }) => {\n        if (!this.options.exitOnArrowDown) {\n          return false\n        }\n\n        const { state } = editor\n        const { selection, doc } = state\n        const { $from, empty } = selection\n\n        if (!empty || $from.parent.type !== this.type) {\n          return false\n        }\n\n        const isAtEnd = $from.parentOffset === $from.parent.nodeSize - 2\n\n        if (!isAtEnd) {\n          return false\n        }\n\n        const after = $from.after()\n\n        if (after === undefined) {\n          return false\n        }\n\n        const nodeAfter = doc.nodeAt(after)\n\n        if (nodeAfter) {\n          return editor.commands.command(({ tr }) => {\n            tr.setSelection(Selection.near(doc.resolve(after)))\n            return true\n          })\n        }\n\n        return editor.commands.exitCode()\n      },\n    }\n  },\n\n  addInputRules() {\n    return [\n      textblockTypeInputRule({\n        find: backtickInputRegex,\n        type: this.type,\n        getAttributes: match => ({\n          language: match[1],\n        }),\n      }),\n      textblockTypeInputRule({\n        find: tildeInputRegex,\n        type: this.type,\n        getAttributes: match => ({\n          language: match[1],\n        }),\n      }),\n    ]\n  },\n\n  addProseMirrorPlugins() {\n    return [\n      // this plugin creates a code block for pasted content from VS Code\n      // we can also detect the copied code language\n      new Plugin({\n        key: new PluginKey('codeBlockVSCodeHandler'),\n        props: {\n          handlePaste: (view, event) => {\n            if (!event.clipboardData) {\n              return false\n            }\n\n            // don’t create a new code block within code blocks\n            if (this.editor.isActive(this.type.name)) {\n              return false\n            }\n\n            const text = event.clipboardData.getData('text/plain')\n            const vscode = event.clipboardData.getData('vscode-editor-data')\n            const vscodeData = vscode ? JSON.parse(vscode) : undefined\n            const language = vscodeData?.mode\n\n            if (!text || !language) {\n              return false\n            }\n\n            const { tr, schema } = view.state\n\n            // prepare a text node\n            // strip carriage return chars from text pasted as code\n            // see: https://github.com/ProseMirror/prosemirror-view/commit/a50a6bcceb4ce52ac8fcc6162488d8875613aacd\n            const textNode = schema.text(text.replace(/\\r\\n?/g, '\\n'))\n\n            // create a code block with the text node\n            // replace selection with the code block\n            tr.replaceSelectionWith(this.type.create({ language }, textNode))\n\n            if (tr.selection.$from.parent.type !== this.type) {\n              // put cursor inside the newly created code block\n              tr.setSelection(\n                TextSelection.near(tr.doc.resolve(Math.max(0, tr.selection.from - 2))),\n              )\n            }\n\n            // store meta information\n            // this is useful for other plugins that depends on the paste event\n            // like the paste rule plugin\n            tr.setMeta('paste', true)\n\n            view.dispatch(tr)\n\n            return true\n          },\n        },\n      }),\n    ]\n  },\n})\n", "import { CodeBlock } from './code-block.js'\n\nexport * from './code-block.js'\n\nexport default CodeBlock\n", "import { Node } from '@tiptap/core'\n\n/**\n * The default document node which represents the top level node of the editor.\n * @see https://tiptap.dev/api/nodes/document\n */\nexport const Document = Node.create({\n  name: 'doc',\n  topNode: true,\n  content: 'block+',\n\n  renderMarkdown: (node, h) => {\n    if (!node.content) {\n      return ''\n    }\n\n    return h.renderChildren(node.content, '\\n\\n')\n  },\n})\n", "import { Document } from './document.js'\n\nexport * from './document.js'\n\nexport default Document\n", "import { mergeAttributes, Node } from '@tiptap/core'\n\nexport interface HardBreakOptions {\n  /**\n   * Controls if marks should be kept after being split by a hard break.\n   * @default true\n   * @example false\n   */\n  keepMarks: boolean\n\n  /**\n   * HTML attributes to add to the hard break element.\n   * @default {}\n   * @example { class: 'foo' }\n   */\n  HTMLAttributes: Record<string, any>\n}\n\ndeclare module '@tiptap/core' {\n  interface Commands<ReturnType> {\n    hardBreak: {\n      /**\n       * Add a hard break\n       * @example editor.commands.setHardBreak()\n       */\n      setHardBreak: () => ReturnType\n    }\n  }\n}\n\n/**\n * This extension allows you to insert hard breaks.\n * @see https://www.tiptap.dev/api/nodes/hard-break\n */\nexport const HardBreak = Node.create<HardBreakOptions>({\n  name: 'hardBreak',\n\n  markdownTokenName: 'br',\n\n  addOptions() {\n    return {\n      keepMarks: true,\n      HTMLAttributes: {},\n    }\n  },\n\n  inline: true,\n\n  group: 'inline',\n\n  selectable: false,\n\n  linebreakReplacement: true,\n\n  parseHTML() {\n    return [{ tag: 'br' }]\n  },\n\n  renderHTML({ HTMLAttributes }) {\n    return ['br', mergeAttributes(this.options.HTMLAttributes, HTMLAttributes)]\n  },\n\n  renderText() {\n    return '\\n'\n  },\n\n  renderMarkdown: () => `  \\n`,\n\n  parseMarkdown: () => {\n    return {\n      type: 'hardBreak',\n    }\n  },\n\n  addCommands() {\n    return {\n      setHardBreak:\n        () =>\n        ({ commands, chain, state, editor }) => {\n          return commands.first([\n            () => commands.exitCode(),\n            () =>\n              commands.command(() => {\n                const { selection, storedMarks } = state\n\n                if (selection.$from.parent.type.spec.isolating) {\n                  return false\n                }\n\n                const { keepMarks } = this.options\n                const { splittableMarks } = editor.extensionManager\n                const marks = storedMarks || (selection.$to.parentOffset && selection.$from.marks())\n\n                return chain()\n                  .insertContent({ type: this.name })\n                  .command(({ tr, dispatch }) => {\n                    if (dispatch && marks && keepMarks) {\n                      const filteredMarks = marks.filter(mark =>\n                        splittableMarks.includes(mark.type.name),\n                      )\n\n                      tr.ensureMarks(filteredMarks)\n                    }\n\n                    return true\n                  })\n                  .scrollIntoView()\n                  .run()\n              }),\n          ])\n        },\n    }\n  },\n\n  addKeyboardShortcuts() {\n    return {\n      'Mod-Enter': () => this.editor.commands.setHardBreak(),\n      'Shift-Enter': () => this.editor.commands.setHardBreak(),\n    }\n  },\n})\n", "import { HardBreak } from './hard-break.js'\n\nexport * from './hard-break.js'\n\nexport default HardBreak\n", "import { mergeAttributes, Node, textblockTypeInputRule } from '@tiptap/core'\n\n/**\n * The heading level options.\n */\nexport type Level = 1 | 2 | 3 | 4 | 5 | 6\n\nexport interface HeadingOptions {\n  /**\n   * The available heading levels.\n   * @default [1, 2, 3, 4, 5, 6]\n   * @example [1, 2, 3]\n   */\n  levels: Level[]\n\n  /**\n   * The HTML attributes for a heading node.\n   * @default {}\n   * @example { class: 'foo' }\n   */\n  HTMLAttributes: Record<string, any>\n}\n\ndeclare module '@tiptap/core' {\n  interface Commands<ReturnType> {\n    heading: {\n      /**\n       * Set a heading node\n       * @param attributes The heading attributes\n       * @example editor.commands.setHeading({ level: 1 })\n       */\n      setHeading: (attributes: { level: Level }) => ReturnType\n      /**\n       * Toggle a heading node\n       * @param attributes The heading attributes\n       * @example editor.commands.toggleHeading({ level: 1 })\n       */\n      toggleHeading: (attributes: { level: Level }) => ReturnType\n    }\n  }\n}\n\n/**\n * This extension allows you to create headings.\n * @see https://www.tiptap.dev/api/nodes/heading\n */\nexport const Heading = Node.create<HeadingOptions>({\n  name: 'heading',\n\n  addOptions() {\n    return {\n      levels: [1, 2, 3, 4, 5, 6],\n      HTMLAttributes: {},\n    }\n  },\n\n  content: 'inline*',\n\n  group: 'block',\n\n  defining: true,\n\n  addAttributes() {\n    return {\n      level: {\n        default: 1,\n        rendered: false,\n      },\n    }\n  },\n\n  parseHTML() {\n    return this.options.levels.map((level: Level) => ({\n      tag: `h${level}`,\n      attrs: { level },\n    }))\n  },\n\n  renderHTML({ node, HTMLAttributes }) {\n    const hasLevel = this.options.levels.includes(node.attrs.level)\n    const level = hasLevel ? node.attrs.level : this.options.levels[0]\n\n    return [`h${level}`, mergeAttributes(this.options.HTMLAttributes, HTMLAttributes), 0]\n  },\n\n  parseMarkdown(token, helpers) {\n    const level = (token.depth || 1) as Level\n\n    if (!this.options.levels.includes(level)) {\n      return helpers.createNode('paragraph', undefined, helpers.parseInline(token.tokens || []))\n    }\n\n    // Convert 'heading' token to heading node\n    // marked provides 'depth' property (1-6) for heading level\n    return helpers.createNode('heading', { level }, helpers.parseInline(token.tokens || []))\n  },\n\n  renderMarkdown: (node, h) => {\n    const level = node.attrs?.level ? parseInt(node.attrs.level as string, 10) : 1\n    const headingChars = '#'.repeat(level)\n\n    if (!node.content) {\n      return ''\n    }\n\n    // Use current context for proper joining/spacing\n    return `${headingChars} ${h.renderChildren(node.content)}`\n  },\n\n  addCommands() {\n    return {\n      setHeading:\n        attributes =>\n        ({ commands }) => {\n          if (!this.options.levels.includes(attributes.level)) {\n            return false\n          }\n\n          return commands.setNode(this.name, attributes)\n        },\n      toggleHeading:\n        attributes =>\n        ({ commands }) => {\n          if (!this.options.levels.includes(attributes.level)) {\n            return false\n          }\n\n          return commands.toggleNode(this.name, 'paragraph', attributes)\n        },\n    }\n  },\n\n  addKeyboardShortcuts() {\n    return this.options.levels.reduce(\n      (items, level) => ({\n        ...items,\n        [`Mod-Alt-${level}`]: () => this.editor.commands.toggleHeading({ level }),\n      }),\n      {},\n    )\n  },\n\n  addInputRules() {\n    return this.options.levels.map(level => {\n      return textblockTypeInputRule({\n        find: new RegExp(`^(#{${Math.min(...this.options.levels)},${level}})\\\\s$`),\n        type: this.type,\n        getAttributes: {\n          level,\n        },\n      })\n    })\n  },\n})\n", "import { Heading } from './heading.js'\n\nexport * from './heading.js'\n\nexport default Heading\n", "import { canInsertNode, isNodeSelection, mergeAttributes, Node, nodeInputRule } from '@tiptap/core'\nimport { NodeSelection, TextSelection } from '@tiptap/pm/state'\n\nexport interface HorizontalRuleOptions {\n  /**\n   * The HTML attributes for a horizontal rule node.\n   * @default {}\n   * @example { class: 'foo' }\n   */\n  HTMLAttributes: Record<string, any>\n  /**\n   * The default type to insert after the horizontal rule.\n   * @default \"paragraph\"\n   * @example \"heading\"\n   */\n  nextNodeType: string\n}\n\ndeclare module '@tiptap/core' {\n  interface Commands<ReturnType> {\n    horizontalRule: {\n      /**\n       * Add a horizontal rule\n       * @example editor.commands.setHorizontalRule()\n       */\n      setHorizontalRule: () => ReturnType\n    }\n  }\n}\n\n/**\n * This extension allows you to insert horizontal rules.\n * @see https://www.tiptap.dev/api/nodes/horizontal-rule\n */\nexport const HorizontalRule = Node.create<HorizontalRuleOptions>({\n  name: 'horizontalRule',\n\n  addOptions() {\n    return {\n      HTMLAttributes: {},\n      nextNodeType: 'paragraph',\n    }\n  },\n\n  group: 'block',\n\n  parseHTML() {\n    return [{ tag: 'hr' }]\n  },\n\n  renderHTML({ HTMLAttributes }) {\n    return ['hr', mergeAttributes(this.options.HTMLAttributes, HTMLAttributes)]\n  },\n\n  markdownTokenName: 'hr',\n\n  parseMarkdown: (token, helpers) => {\n    return helpers.createNode('horizontalRule')\n  },\n\n  renderMarkdown: () => {\n    return '---'\n  },\n\n  addCommands() {\n    return {\n      setHorizontalRule:\n        () =>\n        ({ chain, state }) => {\n          // Check if we can insert the node at the current selection\n          if (!canInsertNode(state, state.schema.nodes[this.name])) {\n            return false\n          }\n\n          const { selection } = state\n          const { $to: $originTo } = selection\n\n          const currentChain = chain()\n\n          if (isNodeSelection(selection)) {\n            currentChain.insertContentAt($originTo.pos, {\n              type: this.name,\n            })\n          } else {\n            currentChain.insertContent({ type: this.name })\n          }\n\n          return (\n            currentChain\n              // set cursor after horizontal rule\n              .command(({ state: chainState, tr, dispatch }) => {\n                if (dispatch) {\n                  const { $to } = tr.selection\n                  const posAfter = $to.end()\n\n                  if ($to.nodeAfter) {\n                    if ($to.nodeAfter.isTextblock) {\n                      tr.setSelection(TextSelection.create(tr.doc, $to.pos + 1))\n                    } else if ($to.nodeAfter.isBlock) {\n                      tr.setSelection(NodeSelection.create(tr.doc, $to.pos))\n                    } else {\n                      tr.setSelection(TextSelection.create(tr.doc, $to.pos))\n                    }\n                  } else {\n                    // add node after horizontal rule if it’s the end of the document\n                    const nodeType =\n                      chainState.schema.nodes[this.options.nextNodeType] ||\n                      $to.parent.type.contentMatch.defaultType\n                    const node = nodeType?.create()\n\n                    if (node) {\n                      tr.insert(posAfter, node)\n                      tr.setSelection(TextSelection.create(tr.doc, posAfter + 1))\n                    }\n                  }\n\n                  tr.scrollIntoView()\n                }\n\n                return true\n              })\n              .run()\n          )\n        },\n    }\n  },\n\n  addInputRules() {\n    return [\n      nodeInputRule({\n        find: /^(?:---|—-|___\\s|\\*\\*\\*\\s)$/,\n        type: this.type,\n      }),\n    ]\n  },\n})\n", "import { HorizontalRule } from './horizontal-rule.js'\n\nexport * from './horizontal-rule.js'\n\nexport default HorizontalRule\n", "import { Mark, markInputRule, markPasteRule, mergeAttributes } from '@tiptap/core'\n\nexport interface ItalicOptions {\n  /**\n   * HTML attributes to add to the italic element.\n   * @default {}\n   * @example { class: 'foo' }\n   */\n  HTMLAttributes: Record<string, any>\n}\n\ndeclare module '@tiptap/core' {\n  interface Commands<ReturnType> {\n    italic: {\n      /**\n       * Set an italic mark\n       * @example editor.commands.setItalic()\n       */\n      setItalic: () => ReturnType\n      /**\n       * Toggle an italic mark\n       * @example editor.commands.toggleItalic()\n       */\n      toggleItalic: () => ReturnType\n      /**\n       * Unset an italic mark\n       * @example editor.commands.unsetItalic()\n       */\n      unsetItalic: () => ReturnType\n    }\n  }\n}\n\n/**\n * Matches an italic to a *italic* on input.\n */\nexport const starInputRegex = /(?:^|\\s)(\\*(?!\\s+\\*)((?:[^*]+))\\*(?!\\s+\\*))$/\n\n/**\n * Matches an italic to a *italic* on paste.\n */\nexport const starPasteRegex = /(?:^|\\s)(\\*(?!\\s+\\*)((?:[^*]+))\\*(?!\\s+\\*))/g\n\n/**\n * Matches an italic to a _italic_ on input.\n */\nexport const underscoreInputRegex = /(?:^|\\s)(_(?!\\s+_)((?:[^_]+))_(?!\\s+_))$/\n\n/**\n * Matches an italic to a _italic_ on paste.\n */\nexport const underscorePasteRegex = /(?:^|\\s)(_(?!\\s+_)((?:[^_]+))_(?!\\s+_))/g\n\n/**\n * This extension allows you to create italic text.\n * @see https://www.tiptap.dev/api/marks/italic\n */\nexport const Italic = Mark.create<ItalicOptions>({\n  name: 'italic',\n\n  addOptions() {\n    return {\n      HTMLAttributes: {},\n    }\n  },\n\n  parseHTML() {\n    return [\n      {\n        tag: 'em',\n      },\n      {\n        tag: 'i',\n        getAttrs: node => (node as HTMLElement).style.fontStyle !== 'normal' && null,\n      },\n      {\n        style: 'font-style=normal',\n        clearMark: mark => mark.type.name === this.name,\n      },\n      {\n        style: 'font-style=italic',\n      },\n    ]\n  },\n\n  renderHTML({ HTMLAttributes }) {\n    return ['em', mergeAttributes(this.options.HTMLAttributes, HTMLAttributes), 0]\n  },\n\n  addCommands() {\n    return {\n      setItalic:\n        () =>\n        ({ commands }) => {\n          return commands.setMark(this.name)\n        },\n      toggleItalic:\n        () =>\n        ({ commands }) => {\n          return commands.toggleMark(this.name)\n        },\n      unsetItalic:\n        () =>\n        ({ commands }) => {\n          return commands.unsetMark(this.name)\n        },\n    }\n  },\n\n  markdownTokenName: 'em',\n\n  parseMarkdown: (token, helpers) => {\n    // Convert 'em' token to italic mark\n    return helpers.applyMark('italic', helpers.parseInline(token.tokens || []))\n  },\n\n  markdownOptions: {\n    htmlReopen: {\n      open: '<em>',\n      close: '</em>',\n    },\n  },\n\n  renderMarkdown: (node, h) => {\n    return `*${h.renderChildren(node)}*`\n  },\n\n  addKeyboardShortcuts() {\n    return {\n      'Mod-i': () => this.editor.commands.toggleItalic(),\n      'Mod-I': () => this.editor.commands.toggleItalic(),\n    }\n  },\n\n  addInputRules() {\n    return [\n      markInputRule({\n        find: starInputRegex,\n        type: this.type,\n      }),\n      markInputRule({\n        find: underscoreInputRegex,\n        type: this.type,\n      }),\n    ]\n  },\n\n  addPasteRules() {\n    return [\n      markPasteRule({\n        find: starPasteRegex,\n        type: this.type,\n      }),\n      markPasteRule({\n        find: underscorePasteRegex,\n        type: this.type,\n      }),\n    ]\n  },\n})\n", "import { Italic } from './italic.js'\n\nexport * from './italic.js'\n\nexport default Italic\n", "// THIS FILE IS AUTOMATICALLY GENERATED DO NOT EDIT DIRECTLY\n// See update-tlds.js for encoding/decoding format\n// https://data.iana.org/TLD/tlds-alpha-by-domain.txt\nconst encodedTlds = 'aaa1rp3bb0ott3vie4c1le2ogado5udhabi7c0ademy5centure6ountant0s9o1tor4d0s1ult4e0g1ro2tna4f0l1rica5g0akhan5ency5i0g1rbus3force5tel5kdn3l0ibaba4pay4lfinanz6state5y2sace3tom5m0azon4ericanexpress7family11x2fam3ica3sterdam8nalytics7droid5quan4z2o0l2partments8p0le4q0uarelle8r0ab1mco4chi3my2pa2t0e3s0da2ia2sociates9t0hleta5torney7u0ction5di0ble3o3spost5thor3o0s4w0s2x0a2z0ure5ba0by2idu3namex4d1k2r0celona5laycard4s5efoot5gains6seball5ketball8uhaus5yern5b0c1t1va3cg1n2d1e0ats2uty4er2rlin4st0buy5t2f1g1h0arti5i0ble3d1ke2ng0o3o1z2j1lack0friday9ockbuster8g1omberg7ue3m0s1w2n0pparibas9o0ats3ehringer8fa2m1nd2o0k0ing5sch2tik2on4t1utique6x2r0adesco6idgestone9oadway5ker3ther5ussels7s1t1uild0ers6siness6y1zz3v1w1y1z0h3ca0b1fe2l0l1vinklein9m0era3p2non3petown5ital0one8r0avan4ds2e0er0s4s2sa1e1h1ino4t0ering5holic7ba1n1re3c1d1enter4o1rn3f0a1d2g1h0anel2nel4rity4se2t2eap3intai5ristmas6ome4urch5i0priani6rcle4sco3tadel4i0c2y3k1l0aims4eaning6ick2nic1que6othing5ud3ub0med6m1n1o0ach3des3ffee4llege4ogne5m0mbank4unity6pany2re3uter5sec4ndos3struction8ulting7tact3ractors9oking4l1p2rsica5untry4pon0s4rses6pa2r0edit0card4union9icket5own3s1uise0s6u0isinella9v1w1x1y0mru3ou3z2dad1nce3ta1e1ing3sun4y2clk3ds2e0al0er2s3gree4livery5l1oitte5ta3mocrat6ntal2ist5si0gn4v2hl2iamonds6et2gital5rect0ory7scount3ver5h2y2j1k1m1np2o0cs1tor4g1mains5t1wnload7rive4tv2ubai3pont4rban5vag2r2z2earth3t2c0o2deka3u0cation8e1g1mail3erck5nergy4gineer0ing9terprises10pson4quipment8r0icsson6ni3s0q1tate5t1u0rovision8s2vents5xchange6pert3osed4ress5traspace10fage2il1rwinds6th3mily4n0s2rm0ers5shion4t3edex3edback6rrari3ero6i0delity5o2lm2nal1nce1ial7re0stone6mdale6sh0ing5t0ness6j1k1lickr3ghts4r2orist4wers5y2m1o0o0d1tball6rd1ex2sale4um3undation8x2r0ee1senius7l1ogans4ntier7tr2ujitsu5n0d2rniture7tbol5yi3ga0l0lery3o1up4me0s3p1rden4y2b0iz3d0n2e0a1nt0ing5orge5f1g0ee3h1i0ft0s3ves2ing5l0ass3e1obal2o4m0ail3bh2o1x2n1odaddy5ld0point6f2odyear5g0le4p1t1v2p1q1r0ainger5phics5tis4een3ipe3ocery4up4s1t1u0cci3ge2ide2tars5ru3w1y2hair2mburg5ngout5us3bo2dfc0bank7ealth0care8lp1sinki6re1mes5iphop4samitsu7tachi5v2k0t2m1n1ockey4ldings5iday5medepot5goods5s0ense7nda3rse3spital5t0ing5t0els3mail5use3w2r1sbc3t1u0ghes5yatt3undai7ibm2cbc2e1u2d1e0ee3fm2kano4l1m0amat4db2mo0bilien9n0c1dustries8finiti5o2g1k1stitute6urance4e4t0ernational10uit4vestments10o1piranga7q1r0ish4s0maili5t0anbul7t0au2v3jaguar4va3cb2e0ep2tzt3welry6io2ll2m0p2nj2o0bs1urg4t1y2p0morgan6rs3uegos6kaufen5ddi3e0rryhotels6properties14fh2g1h1i0a1ds2m1ndle4tchen5wi3m1n1oeln3matsu5sher5p0mg2n2r0d1ed3uokgroup8w1y0oto4z2la0caixa5mborghini8er3nd0rover6xess5salle5t0ino3robe5w0yer5b1c1ds2ease3clerc5frak4gal2o2xus4gbt3i0dl2fe0insurance9style7ghting6ke2lly3mited4o2ncoln4k2ve1ing5k1lc1p2oan0s3cker3us3l1ndon4tte1o3ve3pl0financial11r1s1t0d0a3u0ndbeck6xe1ury5v1y2ma0drid4if1son4keup4n0agement7go3p1rket0ing3s4riott5shalls7ttel5ba2c0kinsey7d1e0d0ia3et2lbourne7me1orial6n0u2rck0msd7g1h1iami3crosoft7l1ni1t2t0subishi9k1l0b1s2m0a2n1o0bi0le4da2e1i1m1nash3ey2ster5rmon3tgage6scow4to0rcycles9v0ie4p1q1r1s0d2t0n1r2u0seum3ic4v1w1x1y1z2na0b1goya4me2vy3ba2c1e0c1t0bank4flix4work5ustar5w0s2xt0direct7us4f0l2g0o2hk2i0co2ke1on3nja3ssan1y5l1o0kia3rton4w0ruz3tv4p1r0a1w2tt2u1yc2z2obi1server7ffice5kinawa6layan0group9lo3m0ega4ne1g1l0ine5oo2pen3racle3nge4g0anic5igins6saka4tsuka4t2vh3pa0ge2nasonic7ris2s1tners4s1y3y2ccw3e0t2f0izer5g1h0armacy6d1ilips5one2to0graphy6s4ysio5ics1tet2ures6d1n0g1k2oneer5zza4k1l0ace2y0station9umbing5s3m1n0c2ohl2ker3litie5rn2st3r0axi3ess3ime3o0d0uctions8f1gressive8mo2perties3y5tection8u0dential9s1t1ub2w0c2y2qa1pon3uebec3st5racing4dio4e0ad1lestate6tor2y4cipes5d0umbrella9hab3ise0n3t2liance6n0t0als5pair3ort3ublican8st0aurant8view0s5xroth6ich0ardli6oh3l1o1p2o0cks3deo3gers4om3s0vp3u0gby3hr2n2w0e2yukyu6sa0arland6fe0ty4kura4le1on3msclub4ung5ndvik0coromant12ofi4p1rl2s1ve2xo3b0i1s2c0b1haeffler7midt4olarships8ol3ule3warz5ience5ot3d1e0arch3t2cure1ity6ek2lect4ner3rvices6ven3w1x0y3fr2g1h0angrila6rp3ell3ia1ksha5oes2p0ping5uji3w3i0lk2na1gles5te3j1k0i0n2y0pe4l0ing4m0art3ile4n0cf3o0ccer3ial4ftbank4ware6hu2lar2utions7ng1y2y2pa0ce3ort2t3r0l2s1t0ada2ples4r1tebank4farm7c0group6ockholm6rage3e3ream4udio2y3yle4u0cks3pplies3y2ort5rf1gery5zuki5v1watch4iss4x1y0dney4stems6z2tab1ipei4lk2obao4rget4tamotors6r2too4x0i3c0i2d0k2eam2ch0nology8l1masek5nnis4va3f1g1h0d1eater2re6iaa2ckets5enda4ps2res2ol4j0maxx4x2k0maxx5l1m0all4n1o0day3kyo3ols3p1ray3shiba5tal3urs3wn2yota3s3r0ade1ing4ining5vel0ers0insurance16ust3v2t1ube2i1nes3shu4v0s2w1z2ua1bank3s2g1k1nicom3versity8o2ol2ps2s1y1z2va0cations7na1guard7c1e0gas3ntures6risign5m\u00F6gensberater2ung14sicherung10t2g1i0ajes4deo3g1king4llas4n1p1rgin4sa1ion4va1o3laanderen9n1odka3lvo3te1ing3o2yage5u2wales2mart4ter4ng0gou5tch0es6eather0channel12b0cam3er2site5d0ding5ibo2r3f1hoswho6ien2ki2lliamhill9n0dows4e1ners6me2oodside6rk0s2ld3w2s1tc1f3xbox3erox4ihuan4n2xx2yz3yachts4hoo3maxun5ndex5e1odobashi7ga2kohama6u0tube6t1un3za0ppos4ra3ero3ip2m1one3uerich6w2';\n// Internationalized domain names containing non-ASCII\nconst encodedUtlds = '\u03B5\u03BB1\u03C52\u0431\u04331\u0435\u043B3\u0434\u0435\u0442\u04384\u0435\u044E2\u043A\u0430\u0442\u043E\u043B\u0438\u043A6\u043E\u043C3\u043C\u043A\u04342\u043E\u043D1\u0441\u043A\u0432\u04306\u043E\u043D\u043B\u0430\u0439\u043D5\u0440\u04333\u0440\u0443\u04412\u04442\u0441\u0430\u0439\u04423\u0440\u04313\u0443\u043A\u04403\u049B\u0430\u04373\u0570\u0561\u05753\u05D9\u05E9\u05E8\u05D0\u05DC5\u05E7\u05D5\u05DD3\u0627\u0628\u0648\u0638\u0628\u064A5\u0631\u0627\u0645\u0643\u06485\u0644\u0627\u0631\u062F\u06464\u0628\u062D\u0631\u064A\u06465\u062C\u0632\u0627\u0626\u06315\u0633\u0639\u0648\u062F\u064A\u06296\u0639\u0644\u064A\u0627\u06465\u0645\u063A\u0631\u06285\u0645\u0627\u0631\u0627\u062A5\u06CC\u0631\u0627\u06465\u0628\u0627\u0631\u062A2\u0632\u0627\u06314\u064A\u062A\u06433\u06BE\u0627\u0631\u062A5\u062A\u0648\u0646\u06334\u0633\u0648\u062F\u0627\u06463\u0631\u064A\u06295\u0634\u0628\u0643\u06294\u0639\u0631\u0627\u06422\u06282\u0645\u0627\u06464\u0641\u0644\u0633\u0637\u064A\u06466\u0642\u0637\u06313\u0643\u0627\u062B\u0648\u0644\u064A\u06436\u0648\u06453\u0645\u0635\u06312\u0644\u064A\u0633\u064A\u06275\u0648\u0631\u064A\u062A\u0627\u0646\u064A\u06277\u0642\u06394\u0647\u0645\u0631\u0627\u06475\u067E\u0627\u06A9\u0633\u062A\u0627\u06467\u0680\u0627\u0631\u062A4\u0915\u0949\u092E3\u0928\u0947\u091F3\u092D\u093E\u0930\u09240\u092E\u094D3\u094B\u09245\u0938\u0902\u0917\u0920\u09285\u09AC\u09BE\u0982\u09B2\u09BE5\u09AD\u09BE\u09B0\u09A42\u09F0\u09A44\u0A2D\u0A3E\u0A30\u0A244\u0AAD\u0ABE\u0AB0\u0AA44\u0B2D\u0B3E\u0B30\u0B244\u0B87\u0BA8\u0BCD\u0BA4\u0BBF\u0BAF\u0BBE6\u0BB2\u0B99\u0BCD\u0B95\u0BC86\u0B9A\u0BBF\u0B99\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0BC2\u0BB0\u0BCD11\u0C2D\u0C3E\u0C30\u0C24\u0C4D5\u0CAD\u0CBE\u0CB0\u0CA44\u0D2D\u0D3E\u0D30\u0D24\u0D025\u0DBD\u0D82\u0D9A\u0DCF4\u0E04\u0E2D\u0E213\u0E44\u0E17\u0E223\u0EA5\u0EB2\u0EA73\u10D2\u10D42\u307F\u3093\u306A3\u30A2\u30DE\u30BE\u30F34\u30AF\u30E9\u30A6\u30C94\u30B0\u30FC\u30B0\u30EB4\u30B3\u30E02\u30B9\u30C8\u30A23\u30BB\u30FC\u30EB3\u30D5\u30A1\u30C3\u30B7\u30E7\u30F36\u30DD\u30A4\u30F3\u30C84\u4E16\u754C2\u4E2D\u4FE11\u56FD1\u570B1\u6587\u7F513\u4E9A\u9A6C\u900A3\u4F01\u4E1A2\u4F5B\u5C712\u4FE1\u606F2\u5065\u5EB72\u516B\u53662\u516C\u53F81\u76CA2\u53F0\u6E7E1\u70632\u5546\u57CE1\u5E971\u68072\u5609\u91CC0\u5927\u9152\u5E975\u5728\u7EBF2\u5927\u62FF2\u5929\u4E3B\u65593\u5A31\u4E502\u5BB6\u96FB2\u5E7F\u4E1C2\u5FAE\u535A2\u6148\u55842\u6211\u7231\u4F603\u624B\u673A2\u62DB\u80582\u653F\u52A11\u5E9C2\u65B0\u52A0\u57612\u95FB2\u65F6\u5C1A2\u66F8\u7C4D2\u673A\u67842\u6DE1\u9A6C\u95213\u6E38\u620F2\u6FB3\u95802\u70B9\u770B2\u79FB\u52A82\u7EC4\u7EC7\u673A\u67844\u7F51\u57401\u5E971\u7AD91\u7EDC2\u8054\u901A2\u8C37\u6B4C2\u8D2D\u72692\u901A\u8CA92\u96C6\u56E22\u96FB\u8A0A\u76C8\u79D14\u98DE\u5229\u6D663\u98DF\u54C12\u9910\u53852\u9999\u683C\u91CC\u62C93\u6E2F2\uB2F7\uB1371\uCEF42\uC0BC\uC1312\uD55C\uAD6D2';\n\n/**\n * Finite State Machine generation utilities\n */\n\n/**\n * @template T\n * @typedef {{ [group: string]: T[] }} Collections\n */\n\n/**\n * @typedef {{ [group: string]: true }} Flags\n */\n\n// Keys in scanner Collections instances\nconst numeric = 'numeric';\nconst ascii = 'ascii';\nconst alpha = 'alpha';\nconst asciinumeric = 'asciinumeric';\nconst alphanumeric = 'alphanumeric';\nconst domain = 'domain';\nconst emoji = 'emoji';\nconst scheme = 'scheme';\nconst slashscheme = 'slashscheme';\nconst whitespace = 'whitespace';\n\n/**\n * @template T\n * @param {string} name\n * @param {Collections<T>} groups to register in\n * @returns {T[]} Current list of tokens in the given collection\n */\nfunction registerGroup(name, groups) {\n  if (!(name in groups)) {\n    groups[name] = [];\n  }\n  return groups[name];\n}\n\n/**\n * @template T\n * @param {T} t token to add\n * @param {Collections<T>} groups\n * @param {Flags} flags\n */\nfunction addToGroups(t, flags, groups) {\n  if (flags[numeric]) {\n    flags[asciinumeric] = true;\n    flags[alphanumeric] = true;\n  }\n  if (flags[ascii]) {\n    flags[asciinumeric] = true;\n    flags[alpha] = true;\n  }\n  if (flags[asciinumeric]) {\n    flags[alphanumeric] = true;\n  }\n  if (flags[alpha]) {\n    flags[alphanumeric] = true;\n  }\n  if (flags[alphanumeric]) {\n    flags[domain] = true;\n  }\n  if (flags[emoji]) {\n    flags[domain] = true;\n  }\n  for (const k in flags) {\n    const group = registerGroup(k, groups);\n    if (group.indexOf(t) < 0) {\n      group.push(t);\n    }\n  }\n}\n\n/**\n * @template T\n * @param {T} t token to check\n * @param {Collections<T>} groups\n * @returns {Flags} group flags that contain this token\n */\nfunction flagsForToken(t, groups) {\n  const result = {};\n  for (const c in groups) {\n    if (groups[c].indexOf(t) >= 0) {\n      result[c] = true;\n    }\n  }\n  return result;\n}\n\n/**\n * @template T\n * @typedef {null | T } Transition\n */\n\n/**\n * Define a basic state machine state. j is the list of character transitions,\n * jr is the list of regex-match transitions, jd is the default state to\n * transition to t is the accepting token type, if any. If this is the terminal\n * state, then it does not emit a token.\n *\n * The template type T represents the type of the token this state accepts. This\n * should be a string (such as of the token exports in `text.js`) or a\n * MultiToken subclass (from `multi.js`)\n *\n * @template T\n * @param {T} [token] Token that this state emits\n */\nfunction State(token = null) {\n  // this.n = null; // DEBUG: State name\n  /** @type {{ [input: string]: State<T> }} j */\n  this.j = {}; // IMPLEMENTATION 1\n  // this.j = []; // IMPLEMENTATION 2\n  /** @type {[RegExp, State<T>][]} jr */\n  this.jr = [];\n  /** @type {?State<T>} jd */\n  this.jd = null;\n  /** @type {?T} t */\n  this.t = token;\n}\n\n/**\n * Scanner token groups\n * @type Collections<string>\n */\nState.groups = {};\nState.prototype = {\n  accepts() {\n    return !!this.t;\n  },\n  /**\n   * Follow an existing transition from the given input to the next state.\n   * Does not mutate.\n   * @param {string} input character or token type to transition on\n   * @returns {?State<T>} the next state, if any\n   */\n  go(input) {\n    const state = this;\n    const nextState = state.j[input];\n    if (nextState) {\n      return nextState;\n    }\n    for (let i = 0; i < state.jr.length; i++) {\n      const regex = state.jr[i][0];\n      const nextState = state.jr[i][1]; // note: might be empty to prevent default jump\n      if (nextState && regex.test(input)) {\n        return nextState;\n      }\n    }\n    // Nowhere left to jump! Return default, if any\n    return state.jd;\n  },\n  /**\n   * Whether the state has a transition for the given input. Set the second\n   * argument to true to only look for an exact match (and not a default or\n   * regular-expression-based transition)\n   * @param {string} input\n   * @param {boolean} exactOnly\n   */\n  has(input, exactOnly = false) {\n    return exactOnly ? input in this.j : !!this.go(input);\n  },\n  /**\n   * Short for \"transition all\"; create a transition from the array of items\n   * in the given list to the same final resulting state.\n   * @param {string | string[]} inputs Group of inputs to transition on\n   * @param {Transition<T> | State<T>} [next] Transition options\n   * @param {Flags} [flags] Collections flags to add token to\n   * @param {Collections<T>} [groups] Master list of token groups\n   */\n  ta(inputs, next, flags, groups) {\n    for (let i = 0; i < inputs.length; i++) {\n      this.tt(inputs[i], next, flags, groups);\n    }\n  },\n  /**\n   * Short for \"take regexp transition\"; defines a transition for this state\n   * when it encounters a token which matches the given regular expression\n   * @param {RegExp} regexp Regular expression transition (populate first)\n   * @param {T | State<T>} [next] Transition options\n   * @param {Flags} [flags] Collections flags to add token to\n   * @param {Collections<T>} [groups] Master list of token groups\n   * @returns {State<T>} taken after the given input\n   */\n  tr(regexp, next, flags, groups) {\n    groups = groups || State.groups;\n    let nextState;\n    if (next && next.j) {\n      nextState = next;\n    } else {\n      // Token with maybe token groups\n      nextState = new State(next);\n      if (flags && groups) {\n        addToGroups(next, flags, groups);\n      }\n    }\n    this.jr.push([regexp, nextState]);\n    return nextState;\n  },\n  /**\n   * Short for \"take transitions\", will take as many sequential transitions as\n   * the length of the given input and returns the\n   * resulting final state.\n   * @param {string | string[]} input\n   * @param {T | State<T>} [next] Transition options\n   * @param {Flags} [flags] Collections flags to add token to\n   * @param {Collections<T>} [groups] Master list of token groups\n   * @returns {State<T>} taken after the given input\n   */\n  ts(input, next, flags, groups) {\n    let state = this;\n    const len = input.length;\n    if (!len) {\n      return state;\n    }\n    for (let i = 0; i < len - 1; i++) {\n      state = state.tt(input[i]);\n    }\n    return state.tt(input[len - 1], next, flags, groups);\n  },\n  /**\n   * Short for \"take transition\", this is a method for building/working with\n   * state machines.\n   *\n   * If a state already exists for the given input, returns it.\n   *\n   * If a token is specified, that state will emit that token when reached by\n   * the linkify engine.\n   *\n   * If no state exists, it will be initialized with some default transitions\n   * that resemble existing default transitions.\n   *\n   * If a state is given for the second argument, that state will be\n   * transitioned to on the given input regardless of what that input\n   * previously did.\n   *\n   * Specify a token group flags to define groups that this token belongs to.\n   * The token will be added to corresponding entires in the given groups\n   * object.\n   *\n   * @param {string} input character, token type to transition on\n   * @param {T | State<T>} [next] Transition options\n   * @param {Flags} [flags] Collections flags to add token to\n   * @param {Collections<T>} [groups] Master list of groups\n   * @returns {State<T>} taken after the given input\n   */\n  tt(input, next, flags, groups) {\n    groups = groups || State.groups;\n    const state = this;\n\n    // Check if existing state given, just a basic transition\n    if (next && next.j) {\n      state.j[input] = next;\n      return next;\n    }\n    const t = next;\n\n    // Take the transition with the usual default mechanisms and use that as\n    // a template for creating the next state\n    let nextState,\n      templateState = state.go(input);\n    if (templateState) {\n      nextState = new State();\n      Object.assign(nextState.j, templateState.j);\n      nextState.jr.push.apply(nextState.jr, templateState.jr);\n      nextState.jd = templateState.jd;\n      nextState.t = templateState.t;\n    } else {\n      nextState = new State();\n    }\n    if (t) {\n      // Ensure newly token is in the same groups as the old token\n      if (groups) {\n        if (nextState.t && typeof nextState.t === 'string') {\n          const allFlags = Object.assign(flagsForToken(nextState.t, groups), flags);\n          addToGroups(t, allFlags, groups);\n        } else if (flags) {\n          addToGroups(t, flags, groups);\n        }\n      }\n      nextState.t = t; // overwrite anything that was previously there\n    }\n    state.j[input] = nextState;\n    return nextState;\n  }\n};\n\n// Helper functions to improve minification (not exported outside linkifyjs module)\n\n/**\n * @template T\n * @param {State<T>} state\n * @param {string | string[]} input\n * @param {Flags} [flags]\n * @param {Collections<T>} [groups]\n */\nconst ta = (state, input, next, flags, groups) => state.ta(input, next, flags, groups);\n\n/**\n * @template T\n * @param {State<T>} state\n * @param {RegExp} regexp\n * @param {T | State<T>} [next]\n * @param {Flags} [flags]\n * @param {Collections<T>} [groups]\n */\nconst tr = (state, regexp, next, flags, groups) => state.tr(regexp, next, flags, groups);\n\n/**\n * @template T\n * @param {State<T>} state\n * @param {string | string[]} input\n * @param {T | State<T>} [next]\n * @param {Flags} [flags]\n * @param {Collections<T>} [groups]\n */\nconst ts = (state, input, next, flags, groups) => state.ts(input, next, flags, groups);\n\n/**\n * @template T\n * @param {State<T>} state\n * @param {string} input\n * @param {T | State<T>} [next]\n * @param {Collections<T>} [groups]\n * @param {Flags} [flags]\n */\nconst tt = (state, input, next, flags, groups) => state.tt(input, next, flags, groups);\n\n/******************************************************************************\nText Tokens\nIdentifiers for token outputs from the regexp scanner\n******************************************************************************/\n\n// A valid web domain token\nconst WORD = 'WORD'; // only contains a-z\nconst UWORD = 'UWORD'; // contains letters other than a-z, used for IDN\nconst ASCIINUMERICAL = 'ASCIINUMERICAL'; // contains a-z, 0-9\nconst ALPHANUMERICAL = 'ALPHANUMERICAL'; // contains numbers and letters other than a-z, used for IDN\n\n// Special case of word\nconst LOCALHOST = 'LOCALHOST';\n\n// Valid top-level domain, special case of WORD (see tlds.js)\nconst TLD = 'TLD';\n\n// Valid IDN TLD, special case of UWORD (see tlds.js)\nconst UTLD = 'UTLD';\n\n// The scheme portion of a web URI protocol. Supported types include: `mailto`,\n// `file`, and user-defined custom protocols. Limited to schemes that contain\n// only letters\nconst SCHEME = 'SCHEME';\n\n// Similar to SCHEME, except makes distinction for schemes that must always be\n// followed by `://`, not just `:`. Supported types include `http`, `https`,\n// `ftp`, `ftps`\nconst SLASH_SCHEME = 'SLASH_SCHEME';\n\n// Any sequence of digits 0-9\nconst NUM = 'NUM';\n\n// Any number of consecutive whitespace characters that are not newline\nconst WS = 'WS';\n\n// New line (unix style)\nconst NL = 'NL'; // \\n\n\n// Opening/closing bracket classes\n// TODO: Rename OPEN -> LEFT and CLOSE -> RIGHT in v5 to fit with Unicode names\n// Also rename angle brackes to LESSTHAN and GREATER THAN\nconst OPENBRACE = 'OPENBRACE'; // {\nconst CLOSEBRACE = 'CLOSEBRACE'; // }\nconst OPENBRACKET = 'OPENBRACKET'; // [\nconst CLOSEBRACKET = 'CLOSEBRACKET'; // ]\nconst OPENPAREN = 'OPENPAREN'; // (\nconst CLOSEPAREN = 'CLOSEPAREN'; // )\nconst OPENANGLEBRACKET = 'OPENANGLEBRACKET'; // <\nconst CLOSEANGLEBRACKET = 'CLOSEANGLEBRACKET'; // >\nconst FULLWIDTHLEFTPAREN = 'FULLWIDTHLEFTPAREN'; // \uFF08\nconst FULLWIDTHRIGHTPAREN = 'FULLWIDTHRIGHTPAREN'; // \uFF09\nconst LEFTCORNERBRACKET = 'LEFTCORNERBRACKET'; // \u300C\nconst RIGHTCORNERBRACKET = 'RIGHTCORNERBRACKET'; // \u300D\nconst LEFTWHITECORNERBRACKET = 'LEFTWHITECORNERBRACKET'; // \u300E\nconst RIGHTWHITECORNERBRACKET = 'RIGHTWHITECORNERBRACKET'; // \u300F\nconst FULLWIDTHLESSTHAN = 'FULLWIDTHLESSTHAN'; // \uFF1C\nconst FULLWIDTHGREATERTHAN = 'FULLWIDTHGREATERTHAN'; // \uFF1E\n\n// Various symbols\nconst AMPERSAND = 'AMPERSAND'; // &\nconst APOSTROPHE = 'APOSTROPHE'; // '\nconst ASTERISK = 'ASTERISK'; // *\nconst AT = 'AT'; // @\nconst BACKSLASH = 'BACKSLASH'; // \\\nconst BACKTICK = 'BACKTICK'; // `\nconst CARET = 'CARET'; // ^\nconst COLON = 'COLON'; // :\nconst COMMA = 'COMMA'; // ,\nconst DOLLAR = 'DOLLAR'; // $\nconst DOT = 'DOT'; // .\nconst EQUALS = 'EQUALS'; // =\nconst EXCLAMATION = 'EXCLAMATION'; // !\nconst HYPHEN = 'HYPHEN'; // -\nconst PERCENT = 'PERCENT'; // %\nconst PIPE = 'PIPE'; // |\nconst PLUS = 'PLUS'; // +\nconst POUND = 'POUND'; // #\nconst QUERY = 'QUERY'; // ?\nconst QUOTE = 'QUOTE'; // \"\nconst FULLWIDTHMIDDLEDOT = 'FULLWIDTHMIDDLEDOT'; // \u30FB\n\nconst SEMI = 'SEMI'; // ;\nconst SLASH = 'SLASH'; // /\nconst TILDE = 'TILDE'; // ~\nconst UNDERSCORE = 'UNDERSCORE'; // _\n\n// Emoji symbol\nconst EMOJI$1 = 'EMOJI';\n\n// Default token - anything that is not one of the above\nconst SYM = 'SYM';\n\nvar tk = /*#__PURE__*/Object.freeze({\n\t__proto__: null,\n\tALPHANUMERICAL: ALPHANUMERICAL,\n\tAMPERSAND: AMPERSAND,\n\tAPOSTROPHE: APOSTROPHE,\n\tASCIINUMERICAL: ASCIINUMERICAL,\n\tASTERISK: ASTERISK,\n\tAT: AT,\n\tBACKSLASH: BACKSLASH,\n\tBACKTICK: BACKTICK,\n\tCARET: CARET,\n\tCLOSEANGLEBRACKET: CLOSEANGLEBRACKET,\n\tCLOSEBRACE: CLOSEBRACE,\n\tCLOSEBRACKET: CLOSEBRACKET,\n\tCLOSEPAREN: CLOSEPAREN,\n\tCOLON: COLON,\n\tCOMMA: COMMA,\n\tDOLLAR: DOLLAR,\n\tDOT: DOT,\n\tEMOJI: EMOJI$1,\n\tEQUALS: EQUALS,\n\tEXCLAMATION: EXCLAMATION,\n\tFULLWIDTHGREATERTHAN: FULLWIDTHGREATERTHAN,\n\tFULLWIDTHLEFTPAREN: FULLWIDTHLEFTPAREN,\n\tFULLWIDTHLESSTHAN: FULLWIDTHLESSTHAN,\n\tFULLWIDTHMIDDLEDOT: FULLWIDTHMIDDLEDOT,\n\tFULLWIDTHRIGHTPAREN: FULLWIDTHRIGHTPAREN,\n\tHYPHEN: HYPHEN,\n\tLEFTCORNERBRACKET: LEFTCORNERBRACKET,\n\tLEFTWHITECORNERBRACKET: LEFTWHITECORNERBRACKET,\n\tLOCALHOST: LOCALHOST,\n\tNL: NL,\n\tNUM: NUM,\n\tOPENANGLEBRACKET: OPENANGLEBRACKET,\n\tOPENBRACE: OPENBRACE,\n\tOPENBRACKET: OPENBRACKET,\n\tOPENPAREN: OPENPAREN,\n\tPERCENT: PERCENT,\n\tPIPE: PIPE,\n\tPLUS: PLUS,\n\tPOUND: POUND,\n\tQUERY: QUERY,\n\tQUOTE: QUOTE,\n\tRIGHTCORNERBRACKET: RIGHTCORNERBRACKET,\n\tRIGHTWHITECORNERBRACKET: RIGHTWHITECORNERBRACKET,\n\tSCHEME: SCHEME,\n\tSEMI: SEMI,\n\tSLASH: SLASH,\n\tSLASH_SCHEME: SLASH_SCHEME,\n\tSYM: SYM,\n\tTILDE: TILDE,\n\tTLD: TLD,\n\tUNDERSCORE: UNDERSCORE,\n\tUTLD: UTLD,\n\tUWORD: UWORD,\n\tWORD: WORD,\n\tWS: WS\n});\n\n// Note that these two Unicode ones expand into a really big one with Babel\nconst ASCII_LETTER = /[a-z]/;\n// `\\p{}` property escapes need ICU, which some embedded JS runtimes ship\n// without (e.g. NativeScript's V8). The literal form throws a SyntaxError\n// at parse time \u2014 before any user code can catch it \u2014 so build them\n// dynamically and keep ASCII-range fallbacks for engines without Unicode\n// property escapes.\nlet LETTER = /[a-z]/i; // Any Unicode character with letter data type\nlet EMOJI = /[\\u{1F000}-\\u{1FAFF}\\u{2600}-\\u{27BF}]|\\u{FE0F}/u; // Any Unicode emoji character\n\ntry {\n  LETTER = new RegExp('\\\\p{L}', 'u');\n  EMOJI = new RegExp('\\\\p{Emoji}', 'u');\n} catch {\n  // use ASCII fallbacks\n}\nconst EMOJI_VARIATION$1 = /\\ufe0f/;\nconst DIGIT = /\\d/;\nconst SPACE = /\\s/;\n\nvar regexp = /*#__PURE__*/Object.freeze({\n\t__proto__: null,\n\tASCII_LETTER: ASCII_LETTER,\n\tDIGIT: DIGIT,\n\tget EMOJI () { return EMOJI; },\n\tEMOJI_VARIATION: EMOJI_VARIATION$1,\n\tget LETTER () { return LETTER; },\n\tSPACE: SPACE\n});\n\n/**\n\tThe scanner provides an interface that takes a string of text as input, and\n\toutputs an array of tokens instances that can be used for easy URL parsing.\n*/\n\nconst CR = '\\r'; // carriage-return character\nconst LF = '\\n'; // line-feed character\nconst EMOJI_VARIATION = '\\ufe0f'; // Variation selector, follows heart and others\nconst EMOJI_JOINER = '\\u200d'; // zero-width joiner\nconst OBJECT_REPLACEMENT = '\\ufffc'; // whitespace placeholder that sometimes appears in rich text editors\n\nlet tlds = null,\n  utlds = null; // don't change so only have to be computed once\n\n/**\n * Scanner output token:\n * - `t` is the token name (e.g., 'NUM', 'EMOJI', 'TLD')\n * - `v` is the value of the token (e.g., '123', '\u2764\uFE0F', 'com')\n * - `s` is the start index of the token in the original string\n * - `e` is the end index of the token in the original string\n * @typedef {{t: string, v: string, s: number, e: number}} Token\n */\n\n/**\n * @template T\n * @typedef {{ [collection: string]: T[] }} Collections\n */\n\n/**\n * Initialize the scanner character-based state machine for the given start\n * state\n * @param {[string, boolean][]} customSchemes List of custom schemes, where each\n * item is a length-2 tuple with the first element set to the string scheme, and\n * the second element set to `true` if the `://` after the scheme is optional\n */\nfunction init$2(customSchemes = []) {\n  // Frequently used states (name argument removed during minification)\n  /** @type Collections<string> */\n  const groups = {}; // of tokens\n  State.groups = groups;\n  /** @type State<string> */\n  const Start = new State();\n  if (tlds == null) {\n    tlds = decodeTlds(encodedTlds);\n  }\n  if (utlds == null) {\n    utlds = decodeTlds(encodedUtlds);\n  }\n\n  // States for special URL symbols that accept immediately after start\n  tt(Start, \"'\", APOSTROPHE);\n  tt(Start, '{', OPENBRACE);\n  tt(Start, '}', CLOSEBRACE);\n  tt(Start, '[', OPENBRACKET);\n  tt(Start, ']', CLOSEBRACKET);\n  tt(Start, '(', OPENPAREN);\n  tt(Start, ')', CLOSEPAREN);\n  tt(Start, '<', OPENANGLEBRACKET);\n  tt(Start, '>', CLOSEANGLEBRACKET);\n  tt(Start, '\uFF08', FULLWIDTHLEFTPAREN);\n  tt(Start, '\uFF09', FULLWIDTHRIGHTPAREN);\n  tt(Start, '\u300C', LEFTCORNERBRACKET);\n  tt(Start, '\u300D', RIGHTCORNERBRACKET);\n  tt(Start, '\u300E', LEFTWHITECORNERBRACKET);\n  tt(Start, '\u300F', RIGHTWHITECORNERBRACKET);\n  tt(Start, '\uFF1C', FULLWIDTHLESSTHAN);\n  tt(Start, '\uFF1E', FULLWIDTHGREATERTHAN);\n  tt(Start, '&', AMPERSAND);\n  tt(Start, '*', ASTERISK);\n  tt(Start, '@', AT);\n  tt(Start, '`', BACKTICK);\n  tt(Start, '^', CARET);\n  tt(Start, ':', COLON);\n  tt(Start, ',', COMMA);\n  tt(Start, '$', DOLLAR);\n  tt(Start, '.', DOT);\n  tt(Start, '=', EQUALS);\n  tt(Start, '!', EXCLAMATION);\n  tt(Start, '-', HYPHEN);\n  tt(Start, '%', PERCENT);\n  tt(Start, '|', PIPE);\n  tt(Start, '+', PLUS);\n  tt(Start, '#', POUND);\n  tt(Start, '?', QUERY);\n  tt(Start, '\"', QUOTE);\n  tt(Start, '/', SLASH);\n  tt(Start, ';', SEMI);\n  tt(Start, '~', TILDE);\n  tt(Start, '_', UNDERSCORE);\n  tt(Start, '\\\\', BACKSLASH);\n  tt(Start, '\u30FB', FULLWIDTHMIDDLEDOT);\n  const Num = tr(Start, DIGIT, NUM, {\n    [numeric]: true\n  });\n  tr(Num, DIGIT, Num);\n  const Asciinumeric = tr(Num, ASCII_LETTER, ASCIINUMERICAL, {\n    [asciinumeric]: true\n  });\n  const Alphanumeric = tr(Num, LETTER, ALPHANUMERICAL, {\n    [alphanumeric]: true\n  });\n\n  // State which emits a word token\n  const Word = tr(Start, ASCII_LETTER, WORD, {\n    [ascii]: true\n  });\n  tr(Word, DIGIT, Asciinumeric);\n  tr(Word, ASCII_LETTER, Word);\n  tr(Asciinumeric, DIGIT, Asciinumeric);\n  tr(Asciinumeric, ASCII_LETTER, Asciinumeric);\n\n  // Same as previous, but specific to non-fsm.ascii alphabet words\n  const UWord = tr(Start, LETTER, UWORD, {\n    [alpha]: true\n  });\n  tr(UWord, ASCII_LETTER); // Non-accepting\n  tr(UWord, DIGIT, Alphanumeric);\n  tr(UWord, LETTER, UWord);\n  tr(Alphanumeric, DIGIT, Alphanumeric);\n  tr(Alphanumeric, ASCII_LETTER); // Non-accepting\n  tr(Alphanumeric, LETTER, Alphanumeric); // Non-accepting\n\n  // Whitespace jumps\n  // Tokens of only non-newline whitespace are arbitrarily long\n  // If any whitespace except newline, more whitespace!\n  const Nl = tt(Start, LF, NL, {\n    [whitespace]: true\n  });\n  const Cr = tt(Start, CR, WS, {\n    [whitespace]: true\n  });\n  const Ws = tr(Start, SPACE, WS, {\n    [whitespace]: true\n  });\n  tt(Start, OBJECT_REPLACEMENT, Ws);\n  tt(Cr, LF, Nl); // \\r\\n\n  tt(Cr, OBJECT_REPLACEMENT, Ws);\n  tr(Cr, SPACE, Ws);\n  tt(Ws, CR); // non-accepting state to avoid mixing whitespaces\n  tt(Ws, LF); // non-accepting state to avoid mixing whitespaces\n  tr(Ws, SPACE, Ws);\n  tt(Ws, OBJECT_REPLACEMENT, Ws);\n\n  // Emoji tokens. They are not grouped by the scanner except in cases where a\n  // zero-width joiner is present\n  const Emoji = tr(Start, EMOJI, EMOJI$1, {\n    [emoji]: true\n  });\n  tt(Emoji, '#'); // no transition, emoji regex seems to match #\n  tr(Emoji, EMOJI, Emoji);\n  tt(Emoji, EMOJI_VARIATION, Emoji);\n  // tt(Start, EMOJI_VARIATION, Emoji); // This one is sketchy\n\n  const EmojiJoiner = tt(Emoji, EMOJI_JOINER);\n  tt(EmojiJoiner, '#');\n  tr(EmojiJoiner, EMOJI, Emoji);\n  // tt(EmojiJoiner, EMOJI_VARIATION, Emoji); // also sketchy\n\n  // Generates states for top-level domains\n  // Note that this is most accurate when tlds are in alphabetical order\n  const wordjr = [[ASCII_LETTER, Word], [DIGIT, Asciinumeric]];\n  const uwordjr = [[ASCII_LETTER, null], [LETTER, UWord], [DIGIT, Alphanumeric]];\n  for (let i = 0; i < tlds.length; i++) {\n    fastts(Start, tlds[i], TLD, WORD, wordjr);\n  }\n  for (let i = 0; i < utlds.length; i++) {\n    fastts(Start, utlds[i], UTLD, UWORD, uwordjr);\n  }\n  addToGroups(TLD, {\n    tld: true,\n    ascii: true\n  }, groups);\n  addToGroups(UTLD, {\n    utld: true,\n    alpha: true\n  }, groups);\n\n  // Collect the states generated by different protocols. NOTE: If any new TLDs\n  // get added that are also protocols, set the token to be the same as the\n  // protocol to ensure parsing works as expected.\n  fastts(Start, 'file', SCHEME, WORD, wordjr);\n  fastts(Start, 'mailto', SCHEME, WORD, wordjr);\n  fastts(Start, 'http', SLASH_SCHEME, WORD, wordjr);\n  fastts(Start, 'https', SLASH_SCHEME, WORD, wordjr);\n  fastts(Start, 'ftp', SLASH_SCHEME, WORD, wordjr);\n  fastts(Start, 'ftps', SLASH_SCHEME, WORD, wordjr);\n  addToGroups(SCHEME, {\n    scheme: true,\n    ascii: true\n  }, groups);\n  addToGroups(SLASH_SCHEME, {\n    slashscheme: true,\n    ascii: true\n  }, groups);\n\n  // Register custom schemes. Assumes each scheme is asciinumeric with hyphens\n  customSchemes = customSchemes.sort((a, b) => a[0] > b[0] ? 1 : -1);\n  for (let i = 0; i < customSchemes.length; i++) {\n    const sch = customSchemes[i][0];\n    const optionalSlashSlash = customSchemes[i][1];\n    const flags = optionalSlashSlash ? {\n      [scheme]: true\n    } : {\n      [slashscheme]: true\n    };\n    if (sch.indexOf('-') >= 0) {\n      flags[domain] = true;\n    } else if (!ASCII_LETTER.test(sch)) {\n      flags[numeric] = true; // numbers only\n    } else if (DIGIT.test(sch)) {\n      flags[asciinumeric] = true;\n    } else {\n      flags[ascii] = true;\n    }\n    ts(Start, sch, sch, flags);\n  }\n\n  // Localhost token\n  ts(Start, 'localhost', LOCALHOST, {\n    ascii: true\n  });\n\n  // Set default transition for start state (some symbol)\n  Start.jd = new State(SYM);\n  return {\n    start: Start,\n    tokens: Object.assign({\n      groups\n    }, tk)\n  };\n}\n\n/**\n\tGiven a string, returns an array of TOKEN instances representing the\n\tcomposition of that string.\n\n\t@method run\n\t@param {State<string>} start scanner starting state\n\t@param {string} str input string to scan\n\t@return {Token[]} list of tokens, each with a type and value\n*/\nfunction run$1(start, str) {\n  // State machine is not case sensitive, so input is tokenized in lowercased\n  // form (still returns regular case). Uses selective `toLowerCase` because\n  // lowercasing the entire string causes the length and character position to\n  // vary in some non-English strings with V8-based runtimes.\n  const iterable = stringToArray(str.replace(/[A-Z]/g, c => c.toLowerCase()));\n  const charCount = iterable.length; // <= len if there are emojis, etc\n  const tokens = []; // return value\n\n  // cursor through the string itself, accounting for characters that have\n  // width with length 2 such as emojis\n  let cursor = 0;\n\n  // Cursor through the array-representation of the string\n  let charCursor = 0;\n\n  // Tokenize the string\n  while (charCursor < charCount) {\n    let state = start;\n    let nextState = null;\n    let tokenLength = 0;\n    let latestAccepting = null;\n    let sinceAccepts = -1;\n    let charsSinceAccepts = -1;\n    while (charCursor < charCount && (nextState = state.go(iterable[charCursor]))) {\n      state = nextState;\n\n      // Keep track of the latest accepting state\n      if (state.accepts()) {\n        sinceAccepts = 0;\n        charsSinceAccepts = 0;\n        latestAccepting = state;\n      } else if (sinceAccepts >= 0) {\n        sinceAccepts += iterable[charCursor].length;\n        charsSinceAccepts++;\n      }\n      tokenLength += iterable[charCursor].length;\n      cursor += iterable[charCursor].length;\n      charCursor++;\n    }\n\n    // Roll back to the latest accepting state\n    cursor -= sinceAccepts;\n    charCursor -= charsSinceAccepts;\n    tokenLength -= sinceAccepts;\n\n    // No more jumps, just make a new token from the last accepting one\n    tokens.push({\n      t: latestAccepting.t,\n      // token type/name\n      v: str.slice(cursor - tokenLength, cursor),\n      // string value\n      s: cursor - tokenLength,\n      // start index\n      e: cursor // end index (excluding)\n    });\n  }\n  return tokens;\n}\n\n/**\n * Convert a String to an Array of characters, taking into account that some\n * characters like emojis take up two string indexes.\n *\n * Adapted from core-js (MIT license)\n * https://github.com/zloirock/core-js/blob/2d69cf5f99ab3ea3463c395df81e5a15b68f49d9/packages/core-js/internals/string-multibyte.js\n *\n * @function stringToArray\n * @param {string} str\n * @returns {string[]}\n */\nfunction stringToArray(str) {\n  const result = [];\n  const len = str.length;\n  let index = 0;\n  while (index < len) {\n    let first = str.charCodeAt(index);\n    let second;\n    let char = first < 0xd800 || first > 0xdbff || index + 1 === len || (second = str.charCodeAt(index + 1)) < 0xdc00 || second > 0xdfff ? str[index] // single character\n    : str.slice(index, index + 2); // two-index characters\n    result.push(char);\n    index += char.length;\n  }\n  return result;\n}\n\n/**\n * Fast version of ts function for when transition defaults are well known\n * @param {State<string>} state\n * @param {string} input\n * @param {string} t\n * @param {string} defaultt\n * @param {[RegExp, State<string>][]} jr\n * @returns {State<string>}\n */\nfunction fastts(state, input, t, defaultt, jr) {\n  let next;\n  const len = input.length;\n  for (let i = 0; i < len - 1; i++) {\n    const char = input[i];\n    if (state.j[char]) {\n      next = state.j[char];\n    } else {\n      next = new State(defaultt);\n      next.jr = jr.slice();\n      state.j[char] = next;\n    }\n    state = next;\n  }\n  next = new State(t);\n  next.jr = jr.slice();\n  state.j[input[len - 1]] = next;\n  return next;\n}\n\n/**\n * Converts a string of Top-Level Domain names encoded in update-tlds.js back\n * into a list of strings.\n * @param {str} encoded encoded TLDs string\n * @returns {str[]} original TLDs list\n */\nfunction decodeTlds(encoded) {\n  const words = [];\n  const stack = [];\n  let i = 0;\n  let digits = '0123456789';\n  while (i < encoded.length) {\n    let popDigitCount = 0;\n    while (digits.indexOf(encoded[i + popDigitCount]) >= 0) {\n      popDigitCount++; // encountered some digits, have to pop to go one level up trie\n    }\n    if (popDigitCount > 0) {\n      words.push(stack.join('')); // whatever preceded the pop digits must be a word\n      for (let popCount = parseInt(encoded.substring(i, i + popDigitCount), 10); popCount > 0; popCount--) {\n        stack.pop();\n      }\n      i += popDigitCount;\n    } else {\n      stack.push(encoded[i]); // drop down a level into the trie\n      i++;\n    }\n  }\n  return words;\n}\n\n/**\n * An object where each key is a valid DOM Event Name such as `click` or `focus`\n * and each value is an event handler function.\n *\n * https://developer.mozilla.org/en-US/docs/Web/API/Element#events\n * @typedef {?{ [event: string]: Function }} EventListeners\n */\n\n/**\n * All formatted properties required to render a link, including `tagName`,\n * `attributes`, `content` and `eventListeners`.\n * @typedef {{ tagName: any, attributes: {[attr: string]: any}, content: string,\n * eventListeners: EventListeners }} IntermediateRepresentation\n */\n\n/**\n * Specify either an object described by the template type `O` or a function.\n *\n * The function takes a string value (usually the link's href attribute), the\n * link type (`'url'`, `'hashtag`', etc.) and an internal token representation\n * of the link. It should return an object of the template type `O`\n * @template O\n * @typedef {O | ((value: string, type: string, token: MultiToken) => O)} OptObj\n */\n\n/**\n * Specify either a function described by template type `F` or an object.\n *\n * Each key in the object should be a link type (`'url'`, `'hashtag`', etc.). Each\n * value should be a function with template type `F` that is called when the\n * corresponding link type is encountered.\n * @template F\n * @typedef {F | { [type: string]: F}} OptFn\n */\n\n/**\n * Specify either a value with template type `V`, a function that returns `V` or\n * an object where each value resolves to `V`.\n *\n * The function takes a string value (usually the link's href attribute), the\n * link type (`'url'`, `'hashtag`', etc.) and an internal token representation\n * of the link. It should return an object of the template type `V`\n *\n * For the object, each key should be a link type (`'url'`, `'hashtag`', etc.).\n * Each value should either have type `V` or a function that returns V. This\n * function similarly takes a string value and a token.\n *\n * Example valid types for `Opt<string>`:\n *\n * ```js\n * 'hello'\n * (value, type, token) => 'world'\n * { url: 'hello', email: (value, token) => 'world'}\n * ```\n * @template V\n * @typedef {V | ((value: string, type: string, token: MultiToken) => V) | { [type: string]: V | ((value: string, token: MultiToken) => V) }} Opt\n */\n\n/**\n * See available options: https://linkify.js.org/docs/options.html\n * @typedef {{\n * \tdefaultProtocol?: string,\n *  events?: OptObj<EventListeners>,\n * \tformat?: Opt<string>,\n * \tformatHref?: Opt<string>,\n * \tnl2br?: boolean,\n * \ttagName?: Opt<any>,\n * \ttarget?: Opt<string>,\n * \trel?: Opt<string>,\n * \tvalidate?: Opt<boolean>,\n * \ttruncate?: Opt<number>,\n * \tclassName?: Opt<string>,\n * \tattributes?: OptObj<({ [attr: string]: any })>,\n *  ignoreTags?: string[],\n *  ignoreClasses?: string[],\n * \trender?: OptFn<((ir: IntermediateRepresentation) => any)>\n * }} Opts\n */\n\n/**\n * @type Required<Opts>\n */\nconst defaults = {\n  defaultProtocol: 'http',\n  events: null,\n  format: noop,\n  formatHref: noop,\n  nl2br: false,\n  tagName: 'a',\n  target: null,\n  rel: null,\n  validate: true,\n  truncate: Infinity,\n  className: null,\n  attributes: null,\n  ignoreTags: [],\n  ignoreClasses: [],\n  render: null\n};\n\n/**\n * Utility class for linkify interfaces to apply specified\n * {@link Opts formatting and rendering options}.\n *\n * @param {Opts | Options} [opts] Option value overrides.\n * @param {(ir: IntermediateRepresentation) => any} [defaultRender] (For\n *   internal use) default render function that determines how to generate an\n *   HTML element based on a link token's derived tagName, attributes and HTML.\n *   Similar to render option\n */\nfunction Options(opts, defaultRender = null) {\n  let o = Object.assign({}, defaults);\n  if (opts) {\n    o = Object.assign(o, opts instanceof Options ? opts.o : opts);\n  }\n\n  // Ensure all ignored tags are uppercase\n  const ignoredTags = o.ignoreTags;\n  const uppercaseIgnoredTags = [];\n  for (let i = 0; i < ignoredTags.length; i++) {\n    uppercaseIgnoredTags.push(ignoredTags[i].toUpperCase());\n  }\n  /** @protected */\n  this.o = o;\n  if (defaultRender) {\n    this.defaultRender = defaultRender;\n  }\n  this.ignoreTags = uppercaseIgnoredTags;\n  this.ignoreClasses = o.ignoreClasses.slice();\n}\nOptions.prototype = {\n  o: defaults,\n  /**\n   * @type string[]\n   */\n  ignoreTags: [],\n  /**\n   * @type string[]\n   */\n  ignoreClasses: [],\n  /**\n   * Returns whether a whitespace-separated class attribute contains an\n   * ignored class name.\n   * @param {unknown} classNames\n   * @returns {boolean}\n   */\n  isIgnoredClass(classNames) {\n    if (typeof classNames !== 'string' || this.ignoreClasses.length === 0) {\n      return false;\n    }\n    const classes = classNames.split(/\\s+/);\n    for (let i = 0; i < classes.length; i++) {\n      if (this.ignoreClasses.indexOf(classes[i]) >= 0) {\n        return true;\n      }\n    }\n    return false;\n  },\n  /**\n   * @param {IntermediateRepresentation} ir\n   * @returns {any}\n   */\n  defaultRender(ir) {\n    return ir;\n  },\n  /**\n   * Returns true or false based on whether a token should be displayed as a\n   * link based on the user options.\n   * @param {MultiToken} token\n   * @returns {boolean}\n   */\n  check(token) {\n    return this.get('validate', token.toString(), token);\n  },\n  // Private methods\n\n  /**\n   * Resolve an option's value based on the value of the option and the given\n   * params. If operator and token are specified and the target option is\n   * callable, automatically calls the function with the given argument.\n   * @template {keyof Opts} K\n   * @param {K} key Name of option to use\n   * @param {string} [operator] will be passed to the target option if it's a\n   * function. If not specified, RAW function value gets returned\n   * @param {MultiToken} [token] The token from linkify.tokenize\n   * @returns {Opts[K] | any}\n   */\n  get(key, operator, token) {\n    const isCallable = operator != null;\n    let option = this.o[key];\n    if (!option) {\n      return option;\n    }\n    if (typeof option === 'object') {\n      option = token.t in option ? option[token.t] : defaults[key];\n      if (typeof option === 'function' && isCallable) {\n        option = option(operator, token);\n      }\n    } else if (typeof option === 'function' && isCallable) {\n      option = option(operator, token.t, token);\n    }\n    return option;\n  },\n  /**\n   * @template {keyof Opts} L\n   * @param {L} key Name of options object to use\n   * @param {string} [operator]\n   * @param {MultiToken} [token]\n   * @returns {Opts[L] | any}\n   */\n  getObj(key, operator, token) {\n    let obj = this.o[key];\n    if (typeof obj === 'function' && operator != null) {\n      obj = obj(operator, token.t, token);\n    }\n    return obj;\n  },\n  /**\n   * Convert the given token to a rendered element that may be added to the\n   * calling-interface's DOM\n   * @param {MultiToken} token Token to render to an HTML element\n   * @returns {any} Render result; e.g., HTML string, DOM element, React\n   *   Component, etc.\n   */\n  render(token) {\n    const ir = token.render(this); // intermediate representation\n    const renderFn = this.get('render', null, token) || this.defaultRender;\n    return renderFn(ir, token.t, token);\n  }\n};\nfunction noop(val) {\n  return val;\n}\n\nvar options = /*#__PURE__*/Object.freeze({\n\t__proto__: null,\n\tOptions: Options,\n\tdefaults: defaults\n});\n\n/******************************************************************************\n\tMulti-Tokens\n\tTokens composed of arrays of TextTokens\n******************************************************************************/\n\n/**\n * @param {string} value\n * @param {Token[]} tokens\n */\nfunction MultiToken(value, tokens) {\n  this.t = 'token';\n  this.v = value;\n  this.tk = tokens;\n}\n\n/**\n * Abstract class used for manufacturing tokens of text tokens. That is rather\n * than the value for a token being a small string of text, it's value an array\n * of text tokens.\n *\n * Used for grouping together URLs, emails, hashtags, and other potential\n * creations.\n * @class MultiToken\n * @property {string} t\n * @property {string} v\n * @property {Token[]} tk\n * @abstract\n */\nMultiToken.prototype = {\n  isLink: false,\n  /**\n   * Return the string this token represents.\n   * @return {string}\n   */\n  toString() {\n    return this.v;\n  },\n  /**\n   * What should the value for this token be in the `href` HTML attribute?\n   * Returns the `.toString` value by default.\n   * @param {string} [scheme]\n   * @return {string}\n   */\n  toHref(scheme) {\n    return this.toString();\n  },\n  /**\n   * @param {Options} options Formatting options\n   * @returns {string}\n   */\n  toFormattedString(options) {\n    const val = this.toString();\n    const truncate = options.get('truncate', val, this);\n    const formatted = options.get('format', val, this);\n    return truncate && formatted.length > truncate ? formatted.substring(0, truncate) + '\u2026' : formatted;\n  },\n  /**\n   *\n   * @param {Options} options\n   * @returns {string}\n   */\n  toFormattedHref(options) {\n    return options.get('formatHref', this.toHref(options.get('defaultProtocol')), this);\n  },\n  /**\n   * The start index of this token in the original input string\n   * @returns {number}\n   */\n  startIndex() {\n    return this.tk[0].s;\n  },\n  /**\n   * The end index of this token in the original input string (up to this\n   * index but not including it)\n   * @returns {number}\n   */\n  endIndex() {\n    return this.tk[this.tk.length - 1].e;\n  },\n  /**\n  \tReturns an object  of relevant values for this token, which includes keys\n  \t* type - Kind of token ('url', 'email', etc.)\n  \t* value - Original text\n  \t* href - The value that should be added to the anchor tag's href\n  \t\tattribute\n  \t\t@method toObject\n  \t@param {string} [protocol] `'http'` by default\n  */\n  toObject(protocol = defaults.defaultProtocol) {\n    return {\n      type: this.t,\n      value: this.toString(),\n      isLink: this.isLink,\n      href: this.toHref(protocol),\n      start: this.startIndex(),\n      end: this.endIndex()\n    };\n  },\n  /**\n   *\n   * @param {Options} options Formatting option\n   */\n  toFormattedObject(options) {\n    return {\n      type: this.t,\n      value: this.toFormattedString(options),\n      isLink: this.isLink,\n      href: this.toFormattedHref(options),\n      start: this.startIndex(),\n      end: this.endIndex()\n    };\n  },\n  /**\n   * Whether this token should be rendered as a link according to the given options\n   * @param {Options} options\n   * @returns {boolean}\n   */\n  validate(options) {\n    return options.get('validate', this.toString(), this);\n  },\n  /**\n   * Return an object that represents how this link should be rendered.\n   * @param {Options} options Formattinng options\n   */\n  render(options) {\n    const token = this;\n    const href = this.toHref(options.get('defaultProtocol'));\n    const formattedHref = options.get('formatHref', href, this);\n    const tagName = options.get('tagName', href, token);\n    const content = this.toFormattedString(options);\n    const attributes = {};\n    const className = options.get('className', href, token);\n    const target = options.get('target', href, token);\n    const rel = options.get('rel', href, token);\n    const attrs = options.getObj('attributes', href, token);\n    const eventListeners = options.getObj('events', href, token);\n    attributes.href = formattedHref;\n    if (className) {\n      attributes.class = className;\n    }\n    if (target) {\n      attributes.target = target;\n    }\n    if (rel) {\n      attributes.rel = rel;\n    }\n    if (attrs) {\n      Object.assign(attributes, attrs);\n    }\n    return {\n      tagName,\n      attributes,\n      content,\n      eventListeners\n    };\n  }\n};\n\n/**\n * Create a new token that can be emitted by the parser state machine\n * @param {string} type readable type of the token\n * @param {object} props properties to assign or override, including isLink = true or false\n * @returns {new (value: string, tokens: Token[]) => MultiToken} new token class\n */\nfunction createTokenClass(type, props) {\n  class Token extends MultiToken {\n    constructor(value, tokens) {\n      super(value, tokens);\n      this.t = type;\n    }\n  }\n  for (const p in props) {\n    Token.prototype[p] = props[p];\n  }\n  Token.t = type;\n  return Token;\n}\n\n/**\n\tRepresents a list of tokens making up a valid email address\n*/\nconst Email = createTokenClass('email', {\n  isLink: true,\n  toHref() {\n    return 'mailto:' + this.toString();\n  }\n});\n\n/**\n\tRepresents some plain text\n*/\nconst Text = createTokenClass('text');\n\n/**\n\tMulti-linebreak token - represents a line break\n\t@class Nl\n*/\nconst Nl = createTokenClass('nl');\n\n/**\n\tRepresents a list of text tokens making up a valid URL\n\t@class Url\n*/\nconst Url = createTokenClass('url', {\n  isLink: true,\n  /**\n  \tLowercases relevant parts of the domain and adds the protocol if\n  \trequired. Note that this will not escape unsafe HTML characters in the\n  \tURL.\n  \t\t@param {string} [scheme] default scheme (e.g., 'https')\n  \t@return {string} the full href\n  */\n  toHref(scheme = defaults.defaultProtocol) {\n    // Check if already has a prefix scheme\n    return this.hasProtocol() ? this.v : `${scheme}://${this.v}`;\n  },\n  /**\n   * Check whether this URL token has a protocol\n   * @return {boolean}\n   */\n  hasProtocol() {\n    const tokens = this.tk;\n    return tokens.length >= 2 && tokens[0].t !== LOCALHOST && tokens[1].t === COLON;\n  }\n});\n\nvar multi = /*#__PURE__*/Object.freeze({\n\t__proto__: null,\n\tBase: MultiToken,\n\tEmail: Email,\n\tMultiToken: MultiToken,\n\tNl: Nl,\n\tText: Text,\n\tUrl: Url,\n\tcreateTokenClass: createTokenClass\n});\n\n/**\n\tNot exactly parser, more like the second-stage scanner (although we can\n\ttheoretically hotswap the code here with a real parser in the future... but\n\tfor a little URL-finding utility abstract syntax trees may be a little\n\toverkill).\n\n\tURL format: http://en.wikipedia.org/wiki/URI_scheme\n\tEmail format: http://en.wikipedia.org/wiki/EmailAddress (links to RFC in\n\treference)\n\n\t@module linkify\n\t@submodule parser\n\t@main run\n*/\n\nconst makeState = arg => new State(arg);\n\n/**\n * Generate the parser multi token-based state machine\n * @param {{ groups: Collections<string> }} tokens\n */\nfunction init$1({\n  groups\n}) {\n  // Types of characters the URL can definitely end in\n  const qsAccepting = groups.domain.concat([AMPERSAND, ASTERISK, AT, BACKSLASH, BACKTICK, CARET, DOLLAR, EQUALS, HYPHEN, NUM, PERCENT, PIPE, PLUS, POUND, SLASH, SYM, TILDE, UNDERSCORE]);\n\n  // Types of tokens that can follow a URL and be part of the query string\n  // but cannot be the very last characters\n  // Characters that cannot appear in the URL at all should be excluded\n  const qsNonAccepting = [APOSTROPHE, COLON, COMMA, DOT, EXCLAMATION, PERCENT, QUERY, QUOTE, SEMI, OPENANGLEBRACKET, CLOSEANGLEBRACKET, OPENBRACE, CLOSEBRACE, CLOSEBRACKET, OPENBRACKET, OPENPAREN, CLOSEPAREN, FULLWIDTHLEFTPAREN, FULLWIDTHRIGHTPAREN, LEFTCORNERBRACKET, RIGHTCORNERBRACKET, LEFTWHITECORNERBRACKET, RIGHTWHITECORNERBRACKET, FULLWIDTHLESSTHAN, FULLWIDTHGREATERTHAN];\n\n  // For addresses without the mailto prefix\n  // Tokens allowed in the localpart of the email\n  const localpartAccepting = [AMPERSAND, APOSTROPHE, ASTERISK, BACKSLASH, BACKTICK, CARET, DOLLAR, EQUALS, HYPHEN, OPENBRACE, CLOSEBRACE, PERCENT, PIPE, PLUS, POUND, QUERY, SLASH, SYM, TILDE, UNDERSCORE];\n\n  // The universal starting state.\n  /**\n   * @type State<Token>\n   */\n  const Start = makeState();\n  const Localpart = tt(Start, TILDE); // Local part of the email address\n  ta(Localpart, localpartAccepting, Localpart);\n  ta(Localpart, groups.domain, Localpart);\n  const Domain = makeState(),\n    Scheme = makeState(),\n    SlashScheme = makeState();\n  ta(Start, groups.domain, Domain); // parsed string ends with a potential domain name (A)\n  ta(Start, groups.scheme, Scheme); // e.g., 'mailto'\n  ta(Start, groups.slashscheme, SlashScheme); // e.g., 'http'\n\n  ta(Domain, localpartAccepting, Localpart);\n  ta(Domain, groups.domain, Domain);\n  const LocalpartAt = tt(Domain, AT); // Local part of the email address plus @\n\n  tt(Localpart, AT, LocalpartAt); // close to an email address now\n\n  // Local part of an email address can be e.g. 'http' or 'mailto'\n  tt(Scheme, AT, LocalpartAt);\n  tt(SlashScheme, AT, LocalpartAt);\n  const LocalpartDot = tt(Localpart, DOT); // Local part of the email address plus '.' (localpart cannot end in .)\n  ta(LocalpartDot, localpartAccepting, Localpart);\n  ta(LocalpartDot, groups.domain, Localpart);\n  const EmailDomain = makeState();\n  ta(LocalpartAt, groups.domain, EmailDomain); // parsed string starts with local email info + @ with a potential domain name\n  ta(EmailDomain, groups.domain, EmailDomain);\n  const EmailDomainDot = tt(EmailDomain, DOT); // domain followed by DOT\n  ta(EmailDomainDot, groups.domain, EmailDomain);\n  const Email$1 = makeState(Email); // Possible email address (could have more tlds)\n  ta(EmailDomainDot, groups.tld, Email$1);\n  ta(EmailDomainDot, groups.utld, Email$1);\n  tt(LocalpartAt, LOCALHOST, Email$1);\n\n  // Hyphen can jump back to a domain name\n  const EmailDomainHyphen = tt(EmailDomain, HYPHEN); // parsed string starts with local email info + @ with a potential domain name\n  tt(EmailDomainHyphen, HYPHEN, EmailDomainHyphen);\n  ta(EmailDomainHyphen, groups.domain, EmailDomain);\n  ta(Email$1, groups.domain, EmailDomain);\n  tt(Email$1, DOT, EmailDomainDot);\n  tt(Email$1, HYPHEN, EmailDomainHyphen);\n\n  // Account for dots and hyphens. Hyphens are usually parts of domain names\n  // (but not TLDs)\n  const DomainHyphen = tt(Domain, HYPHEN); // domain followed by hyphen\n  const DomainDot = tt(Domain, DOT); // domain followed by DOT\n  tt(DomainHyphen, HYPHEN, DomainHyphen);\n  ta(DomainHyphen, groups.domain, Domain);\n  ta(DomainDot, localpartAccepting, Localpart);\n  ta(DomainDot, groups.domain, Domain);\n  const DomainDotTld = makeState(Url); // Simplest possible URL with no query string\n  ta(DomainDot, groups.tld, DomainDotTld);\n  ta(DomainDot, groups.utld, DomainDotTld);\n  ta(DomainDotTld, groups.domain, Domain);\n  ta(DomainDotTld, localpartAccepting, Localpart);\n  tt(DomainDotTld, DOT, DomainDot);\n  tt(DomainDotTld, HYPHEN, DomainHyphen);\n  tt(DomainDotTld, AT, LocalpartAt);\n  const DomainDotTldColon = tt(DomainDotTld, COLON); // URL followed by colon (potential port number here)\n  const DomainDotTldColonPort = makeState(Url); // TLD followed by a port number\n  ta(DomainDotTldColon, groups.numeric, DomainDotTldColonPort);\n\n  // Long URL with optional port and maybe query string\n  const Url$1 = makeState(Url);\n\n  // URL with extra symbols at the end, followed by an opening bracket\n  const UrlNonaccept = makeState(); // URL followed by some symbols (will not be part of the final URL)\n\n  // Query strings\n  ta(Url$1, qsAccepting, Url$1);\n  ta(Url$1, qsNonAccepting, UrlNonaccept);\n  ta(UrlNonaccept, qsAccepting, Url$1);\n  ta(UrlNonaccept, qsNonAccepting, UrlNonaccept);\n\n  // Become real URLs after `SLASH` or `COLON NUM SLASH`\n  // Here works with or without scheme:// prefix\n  tt(DomainDotTld, SLASH, Url$1);\n  tt(DomainDotTldColonPort, SLASH, Url$1);\n\n  // A query string or fragment may also follow the domain (or port) directly,\n  // without a path slash (e.g. `example.com?q=1`, `example.com#frag`). Mirror\n  // how the `Url` state treats these tokens: `?` is non-accepting (a trailing\n  // `?` is trimmed), `#` is accepting.\n  tt(DomainDotTld, QUERY, UrlNonaccept);\n  tt(DomainDotTld, POUND, Url$1);\n  tt(DomainDotTldColonPort, QUERY, UrlNonaccept);\n  tt(DomainDotTldColonPort, POUND, Url$1);\n\n  // Note that domains that begin with schemes are treated slighly differently\n  const SchemeColon = tt(Scheme, COLON); // e.g., 'mailto:'\n  const SlashSchemeColon = tt(SlashScheme, COLON); // e.g., 'http:'\n  const SlashSchemeColonSlash = tt(SlashSchemeColon, SLASH); // e.g., 'http:/'\n\n  const UriPrefix = tt(SlashSchemeColonSlash, SLASH); // e.g., 'http://'\n\n  // Scheme states can transition to domain states\n  ta(Scheme, groups.domain, Domain);\n  tt(Scheme, DOT, DomainDot);\n  tt(Scheme, HYPHEN, DomainHyphen);\n  ta(SlashScheme, groups.domain, Domain);\n  tt(SlashScheme, DOT, DomainDot);\n  tt(SlashScheme, HYPHEN, DomainHyphen);\n\n  // Force URL with scheme prefix followed by anything sane\n  ta(SchemeColon, groups.domain, Url$1);\n  tt(SchemeColon, SLASH, Url$1);\n  tt(SchemeColon, QUERY, Url$1);\n  ta(UriPrefix, groups.domain, Url$1);\n  ta(UriPrefix, qsAccepting, Url$1);\n  tt(UriPrefix, SLASH, Url$1);\n  const bracketPairs = [[OPENBRACE, CLOSEBRACE],\n  // {}\n  [OPENBRACKET, CLOSEBRACKET],\n  // []\n  [OPENPAREN, CLOSEPAREN],\n  // ()\n  [OPENANGLEBRACKET, CLOSEANGLEBRACKET],\n  // <>\n  [FULLWIDTHLEFTPAREN, FULLWIDTHRIGHTPAREN],\n  // \uFF08\uFF09\n  [LEFTCORNERBRACKET, RIGHTCORNERBRACKET],\n  // \u300C\u300D\n  [LEFTWHITECORNERBRACKET, RIGHTWHITECORNERBRACKET],\n  // \u300E\u300F\n  [FULLWIDTHLESSTHAN, FULLWIDTHGREATERTHAN] // \uFF1C\uFF1E\n  ];\n  for (let i = 0; i < bracketPairs.length; i++) {\n    const [OPEN, CLOSE] = bracketPairs[i];\n    const UrlOpen = tt(Url$1, OPEN); // URL followed by open bracket\n\n    // Continue not accepting for open brackets\n    tt(UrlNonaccept, OPEN, UrlOpen);\n\n    // URL that begins with an opening bracket, followed by a symbols.\n    // Note that the final state can still be `UrlOpen` (if the URL has a\n    // single opening bracket for some reason).\n    const UrlOpenQ = makeState(Url);\n    ta(UrlOpen, qsAccepting, UrlOpenQ);\n    const UrlOpenSyms = makeState(); // UrlOpen followed by some symbols it cannot end it\n    ta(UrlOpen, qsNonAccepting, UrlOpenSyms);\n\n    // Closing bracket component. This character WILL be included in the URL.\n    // Must come after qsNonAccepting (which includes all close-bracket tokens)\n    // so that CLOSE -> Url wins over CLOSE -> UrlOpenSyms.\n    tt(UrlOpen, CLOSE, Url$1);\n\n    // URL that begins with an opening bracket, followed by some symbols\n    ta(UrlOpenQ, qsAccepting, UrlOpenQ);\n    ta(UrlOpenQ, qsNonAccepting, UrlOpenSyms);\n    ta(UrlOpenSyms, qsAccepting, UrlOpenQ);\n    ta(UrlOpenSyms, qsNonAccepting, UrlOpenSyms);\n\n    // Close brace/bracket to become regular URL\n    tt(UrlOpenQ, CLOSE, Url$1);\n    tt(UrlOpenSyms, CLOSE, Url$1);\n  }\n  tt(Start, LOCALHOST, DomainDotTld); // localhost is a valid URL state\n  tt(Start, NL, Nl); // single new line\n\n  return {\n    start: Start,\n    tokens: tk\n  };\n}\n\n/**\n * Run the parser state machine on a list of scanned string-based tokens to\n * create a list of multi tokens, each of which represents a URL, email address,\n * plain text, etc.\n *\n * @param {State<MultiToken>} start parser start state\n * @param {string} input the original input used to generate the given tokens\n * @param {Token[]} tokens list of scanned tokens\n * @returns {MultiToken[]}\n */\nfunction run(start, input, tokens) {\n  let len = tokens.length;\n  let cursor = 0;\n  let multis = [];\n  let textTokens = [];\n\n  // Memo of parser states that are known not to lead to any accepting state\n  // when reached at a given cursor position. dead[i] is a Set of states that,\n  // once reached right before tokens[i], can never reach another accepting\n  // state. Because the parser is deterministic, a run that reaches one of\n  // these (state, cursor) pairs can stop there with the same result as\n  // continuing. Without this, inputs where every token can extend a\n  // potential link that never completes (e.g., 'a.a.a.a.\u2026') make each\n  // failed attempt rescan to the end of the input, which is quadratic.\n  // See https://github.com/Hypercontext/linkifyjs/issues/568\n  /** @type {Array<Set<State<MultiToken>> | undefined>} */\n  const dead = [];\n  while (cursor < len) {\n    let state = start;\n    let secondState = null;\n    let nextState = null;\n    let multiLength = 0;\n    let latestAccepting = null;\n    let sinceAccepts = -1;\n    // States reached since the latest accepting state (or since the start\n    // of this attempt), in order. visited[k] is the state reached right\n    // before tokens[cursor - visited.length + k + 1]\n    let visited = [];\n    while (cursor < len && !(secondState = state.go(tokens[cursor].t))) {\n      // Starting tokens with nowhere to jump to.\n      // Consider these to be just plain text\n      textTokens.push(tokens[cursor++]);\n    }\n    while (cursor < len && (nextState = secondState || state.go(tokens[cursor].t))) {\n      // Get the next state\n      secondState = null;\n      state = nextState;\n      cursor++;\n      multiLength++;\n\n      // Keep track of the latest accepting state\n      if (state.accepts()) {\n        sinceAccepts = 0;\n        latestAccepting = state;\n        visited = [];\n      } else {\n        if (sinceAccepts >= 0) {\n          sinceAccepts++;\n        }\n        visited.push(state);\n        if (dead[cursor] && dead[cursor].has(state)) {\n          // Already known that no accepting state is reachable from here\n          break;\n        }\n      }\n    }\n\n    // None of the states visited since the latest accepting state lead to\n    // another accepting state; remember them so later attempts that reach\n    // the same state at the same position can stop early.\n    for (let k = 0, pos = cursor - visited.length + 1; k < visited.length; k++, pos++) {\n      (dead[pos] || (dead[pos] = new Set())).add(visited[k]);\n    }\n    if (sinceAccepts < 0) {\n      // No accepting state was found, part of a regular text token add\n      // the first text token to the text tokens array and try again from\n      // the next\n      cursor -= multiLength;\n      if (cursor < len) {\n        textTokens.push(tokens[cursor]);\n        cursor++;\n      }\n    } else {\n      // Accepting state!\n      // First close off the textTokens (if available)\n      if (textTokens.length > 0) {\n        multis.push(initMultiToken(Text, input, textTokens));\n        textTokens = [];\n      }\n\n      // Roll back to the latest accepting state\n      cursor -= sinceAccepts;\n      multiLength -= sinceAccepts;\n\n      // Create a new multitoken\n      const Multi = latestAccepting.t;\n      const subtokens = tokens.slice(cursor - multiLength, cursor);\n      multis.push(initMultiToken(Multi, input, subtokens));\n    }\n  }\n\n  // Finally close off the textTokens (if available)\n  if (textTokens.length > 0) {\n    multis.push(initMultiToken(Text, input, textTokens));\n  }\n  return multis;\n}\n\n/**\n * Utility function for instantiating a new multitoken with all the relevant\n * fields during parsing.\n * @param {new (value: string, tokens: Token[]) => MultiToken} Multi class to instantiate\n * @param {string} input original input string\n * @param {Token[]} tokens consecutive tokens scanned from input string\n * @returns {MultiToken}\n */\nfunction initMultiToken(Multi, input, tokens) {\n  const startIdx = tokens[0].s;\n  const endIdx = tokens[tokens.length - 1].e;\n  const value = input.slice(startIdx, endIdx);\n  return new Multi(value, tokens);\n}\n\nconst warn = typeof console !== 'undefined' && console && console.warn || (() => {});\nconst warnAdvice = 'until manual call of linkify.init(). Register all schemes and plugins before invoking linkify the first time.';\n\n// Side-effect initialization state\nconst INIT = {\n  scanner: null,\n  parser: null,\n  tokenQueue: [],\n  pluginQueue: [],\n  customSchemes: [],\n  initialized: false\n};\n\n/**\n * @typedef {{\n * \tstart: State<string>,\n * \ttokens: { groups: Collections<string> } & typeof tk\n * }} ScannerInit\n */\n\n/**\n * @typedef {{\n * \tstart: State<MultiToken>,\n * \ttokens: typeof multi\n * }} ParserInit\n */\n\n/**\n * @typedef {(arg: { scanner: ScannerInit }) => void} TokenPlugin\n */\n\n/**\n * @typedef {(arg: { scanner: ScannerInit, parser: ParserInit }) => void} Plugin\n */\n\n/**\n * De-register all plugins and reset the internal state-machine. Used for\n * testing; not required in practice.\n * @private\n */\nfunction reset() {\n  State.groups = {};\n  INIT.scanner = null;\n  INIT.parser = null;\n  INIT.tokenQueue = [];\n  INIT.pluginQueue = [];\n  INIT.customSchemes = [];\n  INIT.initialized = false;\n  return INIT;\n}\n\n/**\n * Register a token plugin to allow the scanner to recognize additional token\n * types before the parser state machine is constructed from the results.\n * @param {string} name of plugin to register\n * @param {TokenPlugin} plugin function that accepts the scanner state machine\n * and available scanner tokens and collections and extends the state machine to\n * recognize additional tokens or groups.\n */\nfunction registerTokenPlugin(name, plugin) {\n  if (typeof plugin !== 'function') {\n    throw new Error(`linkifyjs: Invalid token plugin ${plugin} (expects function)`);\n  }\n  for (let i = 0; i < INIT.tokenQueue.length; i++) {\n    if (name === INIT.tokenQueue[i][0]) {\n      warn(`linkifyjs: token plugin \"${name}\" already registered - will be overwritten`);\n      INIT.tokenQueue[i] = [name, plugin];\n      return;\n    }\n  }\n  INIT.tokenQueue.push([name, plugin]);\n  if (INIT.initialized) {\n    warn(`linkifyjs: already initialized - will not register token plugin \"${name}\" ${warnAdvice}`);\n  }\n}\n\n/**\n * Register a linkify plugin\n * @param {string} name of plugin to register\n * @param {Plugin} plugin function that accepts the parser state machine and\n * extends the parser to recognize additional link types\n */\nfunction registerPlugin(name, plugin) {\n  if (typeof plugin !== 'function') {\n    throw new Error(`linkifyjs: Invalid plugin ${plugin} (expects function)`);\n  }\n  for (let i = 0; i < INIT.pluginQueue.length; i++) {\n    if (name === INIT.pluginQueue[i][0]) {\n      warn(`linkifyjs: plugin \"${name}\" already registered - will be overwritten`);\n      INIT.pluginQueue[i] = [name, plugin];\n      return;\n    }\n  }\n  INIT.pluginQueue.push([name, plugin]);\n  if (INIT.initialized) {\n    warn(`linkifyjs: already initialized - will not register plugin \"${name}\" ${warnAdvice}`);\n  }\n}\n\n/**\n * Detect URLs with the following additional protocol. Anything with format\n * \"protocol://...\" will be considered a link. If `optionalSlashSlash` is set to\n * `true`, anything with format \"protocol:...\" will be considered a link.\n * @param {string} scheme\n * @param {boolean} [optionalSlashSlash]\n */\nfunction registerCustomProtocol(scheme, optionalSlashSlash = false) {\n  if (INIT.initialized) {\n    warn(`linkifyjs: already initialized - will not register custom scheme \"${scheme}\" ${warnAdvice}`);\n  }\n  if (!/^[0-9a-z]+(-[0-9a-z]+)*$/.test(scheme)) {\n    throw new Error(`linkifyjs: incorrect scheme format.\n1. Must only contain digits, lowercase ASCII letters or \"-\"\n2. Cannot start or end with \"-\"\n3. \"-\" cannot repeat`);\n  }\n  INIT.customSchemes.push([scheme, optionalSlashSlash]);\n}\n\n/**\n * Initialize the linkify state machine. Called automatically the first time\n * linkify is called on a string, but may be called manually as well.\n */\nfunction init() {\n  // Initialize scanner state machine and plugins\n  INIT.scanner = init$2(INIT.customSchemes);\n  for (let i = 0; i < INIT.tokenQueue.length; i++) {\n    INIT.tokenQueue[i][1]({\n      scanner: INIT.scanner\n    });\n  }\n\n  // Initialize parser state machine and plugins\n  INIT.parser = init$1(INIT.scanner.tokens);\n  for (let i = 0; i < INIT.pluginQueue.length; i++) {\n    INIT.pluginQueue[i][1]({\n      scanner: INIT.scanner,\n      parser: INIT.parser\n    });\n  }\n  INIT.initialized = true;\n  return INIT;\n}\n\n/**\n * Parse a string into tokens that represent linkable and non-linkable sub-components\n * @param {string} str\n * @return {MultiToken[]} tokens\n */\nfunction tokenize(str) {\n  if (!INIT.initialized) {\n    init();\n  }\n  return run(INIT.parser.start, str, run$1(INIT.scanner.start, str));\n}\ntokenize.scan = run$1; // for testing\n\n/**\n * Find a list of linkable items in the given string.\n * @param {string} str string to find links in\n * @param {string | Opts} [type] either formatting options or specific type of\n * links to find, e.g., 'url' or 'email'\n * @param {Opts} [opts] formatting options for final output. Cannot be specified\n * if opts already provided in `type` argument\n */\nfunction find(str, type = null, opts = null) {\n  if (type && typeof type === 'object') {\n    if (opts) {\n      throw Error(`linkifyjs: Invalid link type ${type}; must be a string`);\n    }\n    opts = type;\n    type = null;\n  }\n  const options = new Options(opts);\n  const tokens = tokenize(str);\n  const filtered = [];\n  for (let i = 0; i < tokens.length; i++) {\n    const token = tokens[i];\n    if (token.isLink && (!type || token.t === type) && options.check(token)) {\n      filtered.push(token.toFormattedObject(options));\n    }\n  }\n  return filtered;\n}\n\n/**\n * Is the given string valid linkable text of some sort. Note that this does not\n * trim the text for you.\n *\n * Optionally pass in a second `type` param, which is the type of link to test\n * for.\n *\n * For example,\n *\n *     linkify.test(str, 'email');\n *\n * Returns `true` if str is a valid email.\n * @param {string} str string to test for links\n * @param {string} [type] optional specific link type to look for\n * @returns boolean true/false\n */\nfunction test(str, type = null) {\n  const tokens = tokenize(str);\n  return tokens.length === 1 && tokens[0].isLink && (!type || tokens[0].t === type);\n}\n\nexport { MultiToken, Options, State, createTokenClass, find, init, multi, options, regexp, registerCustomProtocol, registerPlugin, registerTokenPlugin, reset, stringToArray, test, tk as text, tokenize };\n", "// From DOMPurify\n// https://github.com/cure53/DOMPurify/blob/main/src/regexp.ts\nconst UNICODE_WHITESPACE_PATTERN = '[\\u0000-\\u0020\\u00A0\\u1680\\u180E\\u2000-\\u2029\\u205F\\u3000]'\n\nexport const UNICODE_WHITESPACE_REGEX = new RegExp(UNICODE_WHITESPACE_PATTERN)\nexport const UNICODE_WHITESPACE_REGEX_END = new RegExp(`${UNICODE_WHITESPACE_PATTERN}$`)\nexport const UNICODE_WHITESPACE_REGEX_TRAILING = new RegExp(`${UNICODE_WHITESPACE_PATTERN}+$`)\nexport const UNICODE_WHITESPACE_REGEX_GLOBAL = new RegExp(UNICODE_WHITESPACE_PATTERN, 'g')\n", "import type { Range } from '@tiptap/core'\nimport { getMarksBetween } from '@tiptap/core'\nimport type { MarkType } from '@tiptap/pm/model'\nimport type { Transaction } from '@tiptap/pm/state'\n\nimport { UNICODE_WHITESPACE_REGEX_TRAILING } from './whitespace.js'\n\nexport function unlinkTrailingWhitespace(tr: Transaction, range: Range, type: MarkType) {\n  const rangeEnd = tr.doc.resolve(range.to)\n\n  if (!rangeEnd.nodeBefore?.isText) {\n    return\n  }\n\n  // Keep inline atoms from being mistaken for whitespace.\n  const insertedText = tr.doc.textBetween(range.from, range.to, '\\uFFFC', '\\uFFFC')\n  const trailingWhitespace = insertedText.match(UNICODE_WHITESPACE_REGEX_TRAILING)?.[0]\n\n  if (!trailingWhitespace) {\n    return\n  }\n\n  const whitespaceFrom = range.to - trailingWhitespace.length\n  const linkMarks = getMarksBetween(whitespaceFrom, range.to, tr.doc).filter(\n    item => item.mark.type === type,\n  )\n\n  if (!linkMarks.length) {\n    return\n  }\n\n  const { nodeAfter } = rangeEnd\n  const linkContinues = !!nodeAfter && linkMarks.some(item => item.mark.isInSet(nodeAfter.marks))\n\n  if (linkContinues) {\n    return\n  }\n\n  const storedMarks = tr.storedMarks\n  tr.removeMark(whitespaceFrom, range.to, type)\n  tr.setStoredMarks(storedMarks)\n\n  if (tr.selection.empty && tr.selection.from === range.to) {\n    tr.removeStoredMark(type)\n  }\n}\n", "import type { NodeWithPos, Range } from '@tiptap/core'\nimport {\n  combineTransactionSteps,\n  findChildrenInRange,\n  getChangedRanges,\n  getMarksBetween,\n} from '@tiptap/core'\nimport { isHistoryTransaction } from '@tiptap/pm/history'\nimport type { MarkType } from '@tiptap/pm/model'\nimport { Plugin, PluginKey } from '@tiptap/pm/state'\nimport { ReplaceStep } from '@tiptap/pm/transform'\nimport type { MultiToken } from 'linkifyjs'\nimport { tokenize } from 'linkifyjs'\n\nimport { unlinkTrailingWhitespace } from './unlinkTrailingWhitespace.js'\nimport { UNICODE_WHITESPACE_REGEX, UNICODE_WHITESPACE_REGEX_END } from './whitespace.js'\n\n/**\n * Check if the provided tokens form a valid link structure, which can either be a single link token\n * or a link token surrounded by parentheses or square brackets.\n *\n * This ensures that only complete and valid text is hyperlinked, preventing cases where a valid\n * top-level domain (TLD) is immediately followed by an invalid character, like a number. For\n * example, with the `find` method from Linkify, entering `example.com1` would result in\n * `example.com` being linked and the trailing `1` left as plain text. By using the `tokenize`\n * method, we can perform more comprehensive validation on the input text.\n */\nfunction isValidLinkStructure(tokens: Array<ReturnType<MultiToken['toObject']>>) {\n  if (tokens.length === 1) {\n    return tokens[0].isLink\n  }\n\n  if (tokens.length === 3 && tokens[1].isLink) {\n    return ['()', '[]'].includes(tokens[0].value + tokens[2].value)\n  }\n\n  return false\n}\n\ntype AutolinkOptions = {\n  type: MarkType\n  defaultProtocol: string\n  validate: (url: string) => boolean\n  shouldAutoLink: (url: string) => boolean\n}\n\n/**\n * This plugin allows you to automatically add links to your editor.\n * @param options The plugin options\n * @returns The plugin instance\n */\nexport function autolink(options: AutolinkOptions): Plugin {\n  return new Plugin({\n    key: new PluginKey('autolink'),\n    appendTransaction: (transactions, oldState, newState) => {\n      /**\n       * Does the transaction change the document?\n       */\n      const docChanges =\n        transactions.some(transaction => transaction.docChanged) && !oldState.doc.eq(newState.doc)\n\n      /**\n       * Prevent autolink if the transaction is not a document change or if the transaction has the meta `preventAutolink`.\n       */\n      const preventAutolink = transactions.some(transaction =>\n        transaction.getMeta('preventAutolink'),\n      )\n\n      /**\n       * Prevent autolink if the transaction is not a document change\n       * or if the transaction has the meta `preventAutolink`.\n       */\n      if (!docChanges || preventAutolink) {\n        return\n      }\n\n      const { tr } = newState\n      const transform = combineTransactionSteps(oldState.doc, [...transactions])\n      if (!transactions.some(isHistoryTransaction)) {\n        const insertedRanges: Range[] = []\n\n        transform.steps.forEach((step, index) => {\n          if (!(step instanceof ReplaceStep) || !step.slice.size) {\n            return\n          }\n\n          const mapping = transform.mapping.slice(index + 1)\n          const from = mapping.map(step.from, 1)\n          const to = mapping.map(step.from + step.slice.size, -1)\n\n          if (from < to) {\n            insertedRanges.push({ from, to })\n          }\n        })\n\n        // Unlink later spaces before checking whether earlier spaces end a link.\n        insertedRanges.sort((left, right) => right.to - left.to)\n        insertedRanges.forEach(range => unlinkTrailingWhitespace(tr, range, options.type))\n      }\n\n      const changes = getChangedRanges(transform)\n\n      changes.forEach(({ newRange }) => {\n        // Now let’s see if we can add new links.\n        const nodesInChangedRanges = findChildrenInRange(\n          newState.doc,\n          newRange,\n          node => node.isTextblock,\n        )\n\n        let textBlock: NodeWithPos | undefined\n        let textBeforeWhitespace: string | undefined\n\n        if (nodesInChangedRanges.length > 1) {\n          // Grab the first node within the changed ranges (ex. the first of two paragraphs when hitting enter).\n          textBlock = nodesInChangedRanges[0]\n          textBeforeWhitespace = newState.doc.textBetween(\n            textBlock.pos,\n            textBlock.pos + textBlock.node.nodeSize,\n            undefined,\n            ' ',\n          )\n        } else if (nodesInChangedRanges.length) {\n          const endText = newState.doc.textBetween(newRange.from, newRange.to, ' ', ' ')\n          if (!UNICODE_WHITESPACE_REGEX_END.test(endText)) {\n            return\n          }\n\n          textBlock = nodesInChangedRanges[0]\n          textBeforeWhitespace = newState.doc.textBetween(\n            textBlock.pos,\n            newRange.to,\n            undefined,\n            ' ',\n          )\n        }\n\n        if (textBlock && textBeforeWhitespace) {\n          const wordsBeforeWhitespace = textBeforeWhitespace\n            .split(UNICODE_WHITESPACE_REGEX)\n            .filter(Boolean)\n\n          if (wordsBeforeWhitespace.length <= 0) {\n            return false\n          }\n\n          const lastWordBeforeSpace = wordsBeforeWhitespace[wordsBeforeWhitespace.length - 1]\n          const lastWordAndBlockOffset =\n            textBlock.pos + textBeforeWhitespace.lastIndexOf(lastWordBeforeSpace)\n\n          if (!lastWordBeforeSpace) {\n            return false\n          }\n\n          const linksBeforeSpace = tokenize(lastWordBeforeSpace).map(t =>\n            t.toObject(options.defaultProtocol),\n          )\n\n          if (!isValidLinkStructure(linksBeforeSpace)) {\n            return false\n          }\n\n          linksBeforeSpace\n            .filter(link => link.isLink)\n            // Calculate link position.\n            .map(link => ({\n              ...link,\n              from: lastWordAndBlockOffset + link.start + 1,\n              to: lastWordAndBlockOffset + link.end + 1,\n            }))\n            // ignore link inside code mark\n            .filter(link => {\n              if (!newState.schema.marks.code) {\n                return true\n              }\n\n              return !newState.doc.rangeHasMark(link.from, link.to, newState.schema.marks.code)\n            })\n            // validate link\n            .filter(link => options.validate(link.value))\n            // check whether should autolink\n            .filter(link => options.shouldAutoLink(link.value))\n            // Add link mark.\n            .forEach(link => {\n              if (\n                getMarksBetween(link.from, link.to, newState.doc).some(\n                  item => item.mark.type === options.type,\n                )\n              ) {\n                return\n              }\n\n              tr.addMark(\n                link.from,\n                link.to,\n                options.type.create({\n                  href: link.href,\n                }),\n              )\n            })\n        }\n      })\n\n      if (!tr.steps.length) {\n        return\n      }\n\n      return tr\n    },\n  })\n}\n", "import type { Editor } from '@tiptap/core'\nimport { getAttributes } from '@tiptap/core'\nimport type { MarkType } from '@tiptap/pm/model'\nimport { Plugin, PluginKey } from '@tiptap/pm/state'\n\ntype ClickHandlerOptions = {\n  type: MarkType\n  editor: Editor\n  openOnClick?: boolean\n  enableClickSelection?: boolean\n}\n\nexport function clickHandler(options: ClickHandlerOptions): Plugin {\n  return new Plugin({\n    key: new PluginKey('handleClickLink'),\n    props: {\n      handleClick: (view, pos, event) => {\n        if (event.button !== 0) {\n          return false\n        }\n\n        if (!view.editable) {\n          return false\n        }\n\n        let link: HTMLAnchorElement | null = null\n\n        if (event.target instanceof HTMLAnchorElement) {\n          link = event.target\n        } else {\n          const target = event.target as HTMLElement | null\n          if (!target) {\n            return false\n          }\n\n          const root = options.editor.view.dom\n\n          // Tntentionally limit the lookup to the editor root.\n          // Using tag names like DIV as boundaries breaks with custom NodeViews,\n          link = target.closest<HTMLAnchorElement>('a')\n\n          if (link && !root.contains(link)) {\n            link = null\n          }\n        }\n\n        if (!link) {\n          return false\n        }\n\n        let handled = false\n\n        if (options.enableClickSelection) {\n          const commandResult = options.editor.commands.extendMarkRange(options.type.name)\n          handled = commandResult\n        }\n\n        if (options.openOnClick) {\n          const attrs = getAttributes(view.state, options.type.name)\n          const href = link.href ?? attrs.href\n          const target = link.target ?? attrs.target\n\n          if (href) {\n            window.open(href, target)\n            handled = true\n          }\n        }\n\n        return handled\n      },\n    },\n  })\n}\n", "import type { InputRuleMatch, PasteRuleMatch } from '@tiptap/core'\nimport { InputRule, markInputRule, markPasteRule, PasteRule } from '@tiptap/core'\nimport type { MarkType } from '@tiptap/pm/model'\n\n/**\n * Matches a Markdown link with an optional quoted title.\n * for ex: [Tiptap](https://tiptap.dev) or [Tiptap](https://tiptap.dev \"some title\")\n * the URL may also contain one level of balanced parentheses, as in CommonMark\n * (titles accept curly quotes too, the Typography extension swaps them in while typing)\n * the title delimiters must come in matching pairs\n */\nconst MARKDOWN_LINK_INPUT_REGEX =\n  /\\[([^[\\]]+)\\]\\(((?:[^\\s()]|\\([^\\s()]*\\))+)(?:\\s+(?:([\"'])(.*?)\\3|“(.*?)”|‘(.*?)’))?\\)$/\n\n/**\n * Same as the input regex but global, to find every Markdown link in pasted text.\n */\nconst MARKDOWN_LINK_PASTE_REGEX =\n  /\\[([^[\\]]+)\\]\\(((?:[^\\s()]|\\([^\\s()]*\\))+)(?:\\s+(?:([\"'])(.*?)\\3|“(.*?)”|‘(.*?)’))?\\)/g\n\nexport interface MarkdownLinkRuleConfig {\n  type: MarkType\n\n  /**\n   * Return `false` to leave the Markdown syntax untouched.\n   */\n  isAllowedHref: (href: string) => boolean\n}\n\nexport interface MarkdownLinkPasteRuleConfig extends MarkdownLinkRuleConfig {\n  /**\n   * Finds plain URLs to link in the same pass. Matches overlapping a\n   * converted Markdown link are dropped so its href is kept.\n   */\n  findPlainUrls?: (text: string) => PasteRuleMatch[]\n}\n\nfunction isEscaped(text: string, index: number): boolean {\n  let backslashes = 0\n\n  for (let position = index - 1; position >= 0 && text[position] === '\\\\'; position -= 1) {\n    backslashes += 1\n  }\n\n  return backslashes % 2 === 1\n}\n\n/**\n * Pairs the backtick runs before the match by length, as CommonMark does.\n * A run left open means the match sits in an unfinished code span.\n */\nfunction isInsideCodeSpan(text: string, matchIndex: number): boolean {\n  let openRunLength = 0\n  let index = 0\n\n  while (index < matchIndex) {\n    if (text[index] !== '`') {\n      index += 1\n      continue\n    }\n\n    // escapes only apply outside code spans\n    if (openRunLength === 0 && isEscaped(text, index)) {\n      index += 1\n      continue\n    }\n\n    let runLength = 0\n\n    while (index < matchIndex && text[index] === '`') {\n      runLength += 1\n      index += 1\n    }\n\n    if (openRunLength === 0) {\n      openRunLength = runLength\n    } else if (runLength === openRunLength) {\n      openRunLength = 0\n    }\n  }\n\n  return openRunLength > 0\n}\n\nfunction isConvertibleLink(\n  text: string,\n  match: RegExpMatchArray,\n  isAllowedHref: MarkdownLinkRuleConfig['isAllowedHref'],\n): boolean {\n  const [, linkText, href] = match\n  const characterBefore = match.index ? text[match.index - 1] : undefined\n\n  // `!` is the Markdown image syntax, `\\` may escape the opening bracket\n  if (characterBefore === '!' || isEscaped(text, match.index ?? 0)) {\n    return false\n  }\n\n  if (isInsideCodeSpan(text, match.index ?? 0)) {\n    return false\n  }\n\n  return !!linkText.trim() && isAllowedHref(href)\n}\n\nfunction toRuleMatch(match: RegExpMatchArray): InputRuleMatch & PasteRuleMatch {\n  const [linkSyntax, linkText, href, , straightQuotedTitle, curlyDoubleTitle, curlySingleTitle] =\n    match\n  const title = straightQuotedTitle ?? curlyDoubleTitle ?? curlySingleTitle\n\n  return {\n    index: match.index ?? 0,\n    text: linkSyntax,\n    replaceWith: linkText,\n    data: {\n      href,\n      // an empty title (\"\") counts as no title, as in CommonMark\n      title: title || null,\n      markdown: true,\n    },\n  }\n}\n\nfunction matchesOverlap(a: PasteRuleMatch, b: PasteRuleMatch): boolean {\n  return a.index < b.index + b.text.length && b.index < a.index + a.text.length\n}\n\nfunction getMarkdownLinkAttributes(match: { data?: Record<string, any> }) {\n  return {\n    href: match.data?.href,\n    title: match.data?.title ?? null,\n  }\n}\n\n/**\n * Turns typed Markdown link syntax into a link mark as soon as the closing `)` comes in.\n * The transaction gets flagged so autolink doesn't touch the converted text again.\n */\nexport function markdownLinkInputRule(config: MarkdownLinkRuleConfig): InputRule {\n  const rule = markInputRule({\n    find: text => {\n      const match = MARKDOWN_LINK_INPUT_REGEX.exec(text)\n\n      if (!match || !isConvertibleLink(text, match, config.isAllowedHref)) {\n        return null\n      }\n\n      return toRuleMatch(match)\n    },\n    type: config.type,\n    getAttributes: getMarkdownLinkAttributes,\n  })\n\n  return new InputRule({\n    find: rule.find,\n    handler: props => {\n      const result = rule.handler(props)\n\n      if (result !== null && props.state.tr.steps.length) {\n        props.state.tr.setMeta('preventAutolink', true)\n      }\n\n      return result\n    },\n  })\n}\n\n/**\n * Same for pasting, converts every Markdown link found in the pasted text\n * and links the plain URLs from `findPlainUrls`.\n */\nexport function markdownLinkPasteRule(config: MarkdownLinkPasteRuleConfig): PasteRule {\n  const rule = markPasteRule({\n    find: text => {\n      const markdownMatches: PasteRuleMatch[] = []\n\n      for (const match of text.matchAll(MARKDOWN_LINK_PASTE_REGEX)) {\n        if (isConvertibleLink(text, match, config.isAllowedHref)) {\n          markdownMatches.push(toRuleMatch(match))\n        }\n      }\n\n      const plainUrlMatches = (config.findPlainUrls?.(text) ?? []).filter(\n        urlMatch => !markdownMatches.some(markdownMatch => matchesOverlap(markdownMatch, urlMatch)),\n      )\n\n      return [...markdownMatches, ...plainUrlMatches]\n    },\n    type: config.type,\n    getAttributes: getMarkdownLinkAttributes,\n  })\n\n  return new PasteRule({\n    find: rule.find,\n    handler: props => {\n      const result = rule.handler(props)\n\n      // only Markdown conversions suppress autolink\n      if (result !== null && props.state.tr.steps.length && props.match.data?.markdown) {\n        props.state.tr.setMeta('preventAutolink', true)\n      }\n\n      return result\n    },\n  })\n}\n", "import type { Editor } from '@tiptap/core'\nimport type { MarkType } from '@tiptap/pm/model'\nimport { Plugin, PluginKey } from '@tiptap/pm/state'\nimport { find } from 'linkifyjs'\n\nimport type { LinkOptions } from '../link.js'\n\ntype PasteHandlerOptions = {\n  editor: Editor\n  defaultProtocol: string\n  type: MarkType\n  shouldAutoLink?: LinkOptions['shouldAutoLink']\n}\n\nexport function pasteHandler(options: PasteHandlerOptions): Plugin {\n  return new Plugin({\n    key: new PluginKey('handlePasteLink'),\n    props: {\n      handlePaste: (view, _event, slice) => {\n        const { shouldAutoLink } = options\n        const { state } = view\n        const { selection } = state\n        const { empty } = selection\n\n        if (empty) {\n          return false\n        }\n\n        let textContent = ''\n\n        slice.content.forEach(node => {\n          textContent += node.textContent\n        })\n\n        const link = find(textContent, { defaultProtocol: options.defaultProtocol }).find(\n          item => item.isLink && item.value === textContent,\n        )\n\n        if (\n          !textContent ||\n          !link ||\n          (shouldAutoLink !== undefined && !shouldAutoLink(link.value))\n        ) {\n          return false\n        }\n\n        return options.editor.commands.setMark(options.type, {\n          href: link.href,\n        })\n      },\n    },\n  })\n}\n", "import type { PasteRuleMatch } from '@tiptap/core'\nimport { Mark, markPasteRule, mergeAttributes } from '@tiptap/core'\nimport type { Plugin } from '@tiptap/pm/state'\nimport { find, registerCustomProtocol, reset } from 'linkifyjs'\n\nimport { autolink } from './helpers/autolink.js'\nimport { clickHandler } from './helpers/clickHandler.js'\nimport { markdownLinkInputRule, markdownLinkPasteRule } from './helpers/markdownLink.js'\nimport { pasteHandler } from './helpers/pasteHandler.js'\nimport { UNICODE_WHITESPACE_REGEX_GLOBAL } from './helpers/whitespace.js'\n\nexport interface LinkProtocolOptions {\n  /**\n   * The protocol scheme to be registered.\n   * @default '''\n   * @example 'ftp'\n   * @example 'git'\n   */\n  scheme: string\n\n  /**\n   * If enabled, it allows optional slashes after the protocol.\n   * @default false\n   * @example true\n   */\n  optionalSlashes?: boolean\n}\n\nexport const pasteRegex =\n  /https?:\\/\\/(?:www\\.)?[-a-zA-Z0-9@:%._+~#=]{1,256}\\.[a-zA-Z]{2,}\\b(?:[-a-zA-Z0-9@:%._+~#=?!&/]*)(?:[-a-zA-Z0-9@:%._+~#=?!&/]*)/gi\n\n/**\n * @deprecated The default behavior is now to open links when the editor is not editable.\n */\ntype DeprecatedOpenWhenNotEditable = 'whenNotEditable'\n\nexport interface LinkOptions {\n  /**\n   * If enabled, the extension will automatically add links as you type.\n   * @default true\n   * @example false\n   */\n  autolink: boolean\n\n  /**\n   * An array of custom protocols to be registered with linkifyjs.\n   * @default []\n   * @example ['ftp', 'git']\n   */\n  protocols: Array<LinkProtocolOptions | string>\n\n  /**\n   * Default protocol to use when no protocol is specified.\n   * @default 'http'\n   */\n  defaultProtocol: string\n  /**\n   * If enabled, links will be opened on click.\n   * @default true\n   * @example false\n   */\n  openOnClick: boolean | DeprecatedOpenWhenNotEditable\n  /**\n   * If enabled, the link will be selected when clicked.\n   * @default false\n   * @example true\n   */\n  enableClickSelection: boolean\n  /**\n   * Adds a link to the current selection if the pasted content only contains an url.\n   * @default true\n   * @example false\n   */\n  linkOnPaste: boolean\n\n  /**\n   * If enabled, typing or pasting the Markdown link syntax, e.g. `[Tiptap](https://tiptap.dev)`\n   * or `[Tiptap](https://tiptap.dev \"Rich text editor\")`, converts it into a link.\n   * @default false\n   * @example true\n   */\n  markdownLinks: boolean\n\n  /**\n   * HTML attributes to add to the link element.\n   * @default {}\n   * @example { class: 'foo' }\n   */\n  HTMLAttributes: Record<string, any>\n\n  /**\n   * @deprecated Use the `shouldAutoLink` option instead.\n   * A validation function that modifies link verification for the auto linker.\n   * @param url - The url to be validated.\n   * @returns - True if the url is valid, false otherwise.\n   */\n  validate: (url: string) => boolean\n\n  /**\n   * A validation function which is used for configuring link verification for preventing XSS attacks.\n   * Only modify this if you know what you're doing.\n   *\n   * @returns {boolean} `true` if the URL is valid, `false` otherwise.\n   *\n   * @example\n   * isAllowedUri: (url, { defaultValidate, protocols, defaultProtocol }) => {\n   * return url.startsWith('./') || defaultValidate(url)\n   * }\n   */\n  isAllowedUri: (\n    /**\n     * The URL to be validated.\n     */\n    url: string,\n    ctx: {\n      /**\n       * The default validation function.\n       */\n      defaultValidate: (url: string) => boolean\n      /**\n       * An array of allowed protocols for the URL (e.g., \"http\", \"https\"). As defined in the `protocols` option.\n       */\n      protocols: Array<LinkProtocolOptions | string>\n      /**\n       * A string that represents the default protocol (e.g., 'http'). As defined in the `defaultProtocol` option.\n       */\n      defaultProtocol: string\n    },\n  ) => boolean\n\n  /**\n   * Determines whether a valid link should be automatically linked in the content.\n   *\n   * @param {string} url - The URL that has already been validated.\n   * @returns {boolean} - True if the link should be auto-linked; false if it should not be auto-linked.\n   */\n  shouldAutoLink: (url: string) => boolean\n}\n\ndeclare module '@tiptap/core' {\n  interface Commands<ReturnType> {\n    link: {\n      /**\n       * Set a link mark\n       * @param attributes The link attributes\n       * @example editor.commands.setLink({ href: 'https://tiptap.dev' })\n       */\n      setLink: (attributes: {\n        href: string\n        target?: string | null\n        rel?: string | null\n        class?: string | null\n        title?: string | null\n      }) => ReturnType\n      /**\n       * Toggle a link mark\n       * @param attributes The link attributes\n       * @example editor.commands.toggleLink({ href: 'https://tiptap.dev' })\n       */\n      toggleLink: (attributes?: {\n        href: string\n        target?: string | null\n        rel?: string | null\n        class?: string | null\n        title?: string | null\n      }) => ReturnType\n      /**\n       * Unset a link mark\n       * @example editor.commands.unsetLink()\n       */\n      unsetLink: () => ReturnType\n    }\n  }\n}\n\nexport function isAllowedUri(uri: string | undefined, protocols?: LinkOptions['protocols']) {\n  const allowedProtocols: string[] = [\n    'http',\n    'https',\n    'ftp',\n    'ftps',\n    'mailto',\n    'tel',\n    'callto',\n    'sms',\n    'cid',\n    'xmpp',\n  ]\n\n  if (protocols) {\n    protocols.forEach(protocol => {\n      const nextProtocol = typeof protocol === 'string' ? protocol : protocol.scheme\n\n      if (nextProtocol) {\n        allowedProtocols.push(nextProtocol)\n      }\n    })\n  }\n\n  return (\n    !uri ||\n    uri\n      .replace(UNICODE_WHITESPACE_REGEX_GLOBAL, '')\n      .match(\n        new RegExp(\n          `^(?:(?:${allowedProtocols\n            .map(protocol => protocol.replace(/[-/\\\\^$*+?.()|[\\]{}]/g, '\\\\$&'))\n            .join('|')}):|[^a-z]|[a-z0-9+.\\\\-]+(?:[^a-z+.\\\\-:]|$))`,\n          'i',\n        ),\n      )\n  )\n}\n\n/**\n * This extension allows you to create links.\n * @see https://www.tiptap.dev/api/marks/link\n */\nexport const Link = Mark.create<LinkOptions>({\n  name: 'link',\n\n  priority: 1000,\n\n  keepOnSplit: false,\n\n  exitable: true,\n\n  onCreate() {\n    // TODO: v4 - remove validate option\n    if (this.options.validate && !this.options.shouldAutoLink) {\n      // Copy the validate function to the shouldAutoLink option\n      this.options.shouldAutoLink = this.options.validate\n      console.warn(\n        'The `validate` option is deprecated. Rename to the `shouldAutoLink` option instead.',\n      )\n    }\n    this.options.protocols.forEach(protocol => {\n      if (typeof protocol === 'string') {\n        registerCustomProtocol(protocol)\n        return\n      }\n      registerCustomProtocol(protocol.scheme, protocol.optionalSlashes)\n    })\n  },\n\n  onDestroy() {\n    reset()\n  },\n\n  inclusive() {\n    return this.options.autolink\n  },\n\n  addOptions() {\n    return {\n      openOnClick: true,\n      enableClickSelection: false,\n      linkOnPaste: true,\n      markdownLinks: false, // TODO (major) - default to true on next major version\n      autolink: true,\n      protocols: [],\n      defaultProtocol: 'http',\n      HTMLAttributes: {\n        target: '_blank',\n        rel: 'noopener noreferrer nofollow',\n        class: null,\n      },\n      isAllowedUri: (url, ctx) => !!isAllowedUri(url, ctx.protocols),\n      validate: url => !!url,\n      shouldAutoLink: url => {\n        // URLs with explicit protocols (e.g., https://) should be auto-linked\n        // But not if @ appears before :// (that would be userinfo like user:pass@host)\n        const hasProtocol = /^[a-z][a-z0-9+.-]*:\\/\\//i.test(url)\n        const hasMaybeProtocol = /^[a-z][a-z0-9+.-]*:/i.test(url)\n\n        if (hasProtocol || (hasMaybeProtocol && !url.includes('@'))) {\n          return true\n        }\n        // Strip userinfo (user:pass@) if present, then extract hostname\n        const urlWithoutUserinfo = url.includes('@') ? url.split('@').pop()! : url\n        const hostname = urlWithoutUserinfo.split(/[/?#:]/)[0]\n\n        // Don't auto-link IP addresses without protocol\n        if (/^\\d{1,3}(\\.\\d{1,3}){3}$/.test(hostname)) {\n          return false\n        }\n        // Don't auto-link single-word hostnames without TLD (e.g., \"localhost\")\n        if (!/\\./.test(hostname)) {\n          return false\n        }\n        return true\n      },\n    }\n  },\n\n  addAttributes() {\n    return {\n      href: {\n        default: null,\n        parseHTML(element) {\n          return element.getAttribute('href')\n        },\n      },\n      target: {\n        // Coerce `undefined` to `null` because `undefined` is an invalid attribute value\n        default: this.options.HTMLAttributes.target ?? null,\n      },\n      rel: {\n        // Coerce `undefined` to `null` because `undefined` is an invalid attribute value\n        default: this.options.HTMLAttributes.rel ?? null,\n      },\n      class: {\n        // Coerce `undefined` to `null` because `undefined` is an invalid attribute value\n        default: this.options.HTMLAttributes.class ?? null,\n      },\n      title: {\n        default: null,\n      },\n    }\n  },\n\n  parseHTML() {\n    return [\n      {\n        tag: 'a[href]',\n        getAttrs: dom => {\n          const href = (dom as HTMLElement).getAttribute('href')\n\n          // prevent XSS attacks\n          if (\n            !href ||\n            !this.options.isAllowedUri(href, {\n              defaultValidate: url => !!isAllowedUri(url, this.options.protocols),\n              protocols: this.options.protocols,\n              defaultProtocol: this.options.defaultProtocol,\n            })\n          ) {\n            return false\n          }\n          return null\n        },\n      },\n    ]\n  },\n\n  renderHTML({ HTMLAttributes }) {\n    // prevent XSS attacks\n    if (\n      !this.options.isAllowedUri(HTMLAttributes.href, {\n        defaultValidate: href => !!isAllowedUri(href, this.options.protocols),\n        protocols: this.options.protocols,\n        defaultProtocol: this.options.defaultProtocol,\n      })\n    ) {\n      // strip out the href\n      return ['a', mergeAttributes(this.options.HTMLAttributes, { ...HTMLAttributes, href: '' }), 0]\n    }\n\n    return ['a', mergeAttributes(this.options.HTMLAttributes, HTMLAttributes), 0]\n  },\n\n  markdownTokenName: 'link',\n\n  parseMarkdown: (token, helpers) => {\n    return helpers.applyMark('link', helpers.parseInline(token.tokens || []), {\n      href: token.href,\n      title: token.title || null,\n    })\n  },\n\n  renderMarkdown: (node, h) => {\n    const href = node.attrs?.href ?? ''\n    const title = node.attrs?.title ?? ''\n    const text = h.renderChildren(node)\n\n    return title ? `[${text}](${href} \"${title}\")` : `[${text}](${href})`\n  },\n\n  addCommands() {\n    return {\n      setLink:\n        attributes =>\n        ({ chain }) => {\n          const { href } = attributes\n\n          if (\n            !this.options.isAllowedUri(href, {\n              defaultValidate: url => !!isAllowedUri(url, this.options.protocols),\n              protocols: this.options.protocols,\n              defaultProtocol: this.options.defaultProtocol,\n            })\n          ) {\n            return false\n          }\n\n          return chain().setMark(this.name, attributes).setMeta('preventAutolink', true).run()\n        },\n\n      toggleLink:\n        attributes =>\n        ({ chain }) => {\n          const { href } = attributes || {}\n\n          if (\n            href &&\n            !this.options.isAllowedUri(href, {\n              defaultValidate: url => !!isAllowedUri(url, this.options.protocols),\n              protocols: this.options.protocols,\n              defaultProtocol: this.options.defaultProtocol,\n            })\n          ) {\n            return false\n          }\n\n          return chain()\n            .toggleMark(this.name, attributes, { extendEmptyMarkRange: true })\n            .setMeta('preventAutolink', true)\n            .run()\n        },\n\n      unsetLink:\n        () =>\n        ({ chain }) => {\n          return chain()\n            .unsetMark(this.name, { extendEmptyMarkRange: true })\n            .setMeta('preventAutolink', true)\n            .run()\n        },\n    }\n  },\n\n  addInputRules() {\n    if (!this.options.markdownLinks) {\n      return []\n    }\n\n    return [\n      markdownLinkInputRule({\n        type: this.type,\n        isAllowedHref: href =>\n          this.options.isAllowedUri(href, {\n            defaultValidate: url => !!isAllowedUri(url, this.options.protocols),\n            protocols: this.options.protocols,\n            defaultProtocol: this.options.defaultProtocol,\n          }),\n      }),\n    ]\n  },\n\n  addPasteRules() {\n    const findPlainUrls = (text: string): PasteRuleMatch[] => {\n      const foundLinks: PasteRuleMatch[] = []\n\n      if (text) {\n        const { protocols, defaultProtocol } = this.options\n        const links = find(text, { defaultProtocol }).filter(\n          item =>\n            item.isLink &&\n            this.options.isAllowedUri(item.value, {\n              defaultValidate: href => !!isAllowedUri(href, protocols),\n              protocols,\n              defaultProtocol,\n            }),\n        )\n\n        links.forEach(link => {\n          if (!this.options.shouldAutoLink(link.value)) {\n            return\n          }\n\n          foundLinks.push({\n            text: link.value,\n            data: {\n              href: link.href,\n            },\n            index: link.start,\n          })\n        })\n      }\n\n      return foundLinks\n    }\n\n    if (this.options.markdownLinks) {\n      return [\n        markdownLinkPasteRule({\n          type: this.type,\n          isAllowedHref: href =>\n            this.options.isAllowedUri(href, {\n              defaultValidate: url => !!isAllowedUri(url, this.options.protocols),\n              protocols: this.options.protocols,\n              defaultProtocol: this.options.defaultProtocol,\n            }),\n          findPlainUrls,\n        }),\n      ]\n    }\n\n    return [\n      markPasteRule({\n        find: findPlainUrls,\n        type: this.type,\n        getAttributes: match => {\n          return {\n            href: match.data?.href,\n          }\n        },\n      }),\n    ]\n  },\n\n  addProseMirrorPlugins() {\n    const plugins: Plugin[] = []\n    const { protocols, defaultProtocol } = this.options\n\n    if (this.options.autolink) {\n      plugins.push(\n        autolink({\n          type: this.type,\n          defaultProtocol: this.options.defaultProtocol,\n          validate: url =>\n            this.options.isAllowedUri(url, {\n              defaultValidate: href => !!isAllowedUri(href, protocols),\n              protocols,\n              defaultProtocol,\n            }),\n          shouldAutoLink: this.options.shouldAutoLink,\n        }),\n      )\n    }\n\n    plugins.push(\n      clickHandler({\n        type: this.type,\n        editor: this.editor,\n        openOnClick:\n          this.options.openOnClick === 'whenNotEditable' ? true : this.options.openOnClick,\n        enableClickSelection: this.options.enableClickSelection,\n      }),\n    )\n\n    if (this.options.linkOnPaste) {\n      plugins.push(\n        pasteHandler({\n          editor: this.editor,\n          defaultProtocol: this.options.defaultProtocol,\n          type: this.type,\n          shouldAutoLink: this.options.shouldAutoLink,\n        }),\n      )\n    }\n\n    return plugins\n  },\n})\n", "import { Link } from './link.js'\n\nexport * from './link.js'\n\nexport default Link\n", "import { mergeAttributes, Node, wrappingInputRule } from '@tiptap/core'\n\nconst ListItemName = 'listItem'\nconst TextStyleName = 'textStyle'\n\nexport interface BulletListOptions {\n  /**\n   * The node name for the list items\n   * @default 'listItem'\n   * @example 'paragraph'\n   */\n  itemTypeName: string\n\n  /**\n   * HTML attributes to add to the bullet list element\n   * @default {}\n   * @example { class: 'foo' }\n   */\n  HTMLAttributes: Record<string, any>\n\n  /**\n   * Keep the marks when splitting the list\n   * @default false\n   * @example true\n   */\n  keepMarks: boolean\n\n  /**\n   * Keep the attributes when splitting the list\n   * @default false\n   * @example true\n   */\n  keepAttributes: boolean\n}\n\ndeclare module '@tiptap/core' {\n  interface Commands<ReturnType> {\n    bulletList: {\n      /**\n       * Toggle a bullet list\n       */\n      toggleBulletList: () => ReturnType\n    }\n  }\n}\n\n/**\n * Matches a bullet list to a dash or asterisk.\n */\nexport const bulletListInputRegex = /^\\s*([-+*])\\s$/\n\n/**\n * This extension allows you to create bullet lists.\n * This requires the ListItem extension\n * @see https://tiptap.dev/api/nodes/bullet-list\n * @see https://tiptap.dev/api/nodes/list-item.\n */\nexport const BulletList = Node.create<BulletListOptions>({\n  name: 'bulletList',\n\n  addOptions() {\n    return {\n      itemTypeName: 'listItem',\n      HTMLAttributes: {},\n      keepMarks: false,\n      keepAttributes: false,\n    }\n  },\n\n  group: 'block list',\n\n  content() {\n    return `${this.options.itemTypeName}+`\n  },\n\n  parseHTML() {\n    return [{ tag: 'ul' }]\n  },\n\n  renderHTML({ HTMLAttributes }) {\n    return ['ul', mergeAttributes(this.options.HTMLAttributes, HTMLAttributes), 0]\n  },\n\n  markdownTokenName: 'list',\n\n  parseMarkdown: (token, helpers) => {\n    if (token.type !== 'list' || (token as any).ordered) {\n      return []\n    }\n\n    return {\n      type: 'bulletList',\n      content: token.items ? helpers.parseChildren(token.items) : [],\n    }\n  },\n\n  renderMarkdown: (node, h) => {\n    if (!node.content) {\n      return ''\n    }\n\n    return h.renderChildren(node.content, '\\n')\n  },\n\n  markdownOptions: {\n    indentsContent: true,\n  },\n\n  addCommands() {\n    return {\n      toggleBulletList:\n        () =>\n        ({ commands, chain }) => {\n          if (this.options.keepAttributes) {\n            return chain()\n              .toggleList(this.name, this.options.itemTypeName, this.options.keepMarks)\n              .updateAttributes(ListItemName, this.editor.getAttributes(TextStyleName))\n              .run()\n          }\n          return commands.toggleList(this.name, this.options.itemTypeName, this.options.keepMarks)\n        },\n    }\n  },\n\n  addKeyboardShortcuts() {\n    return {\n      'Mod-Shift-8': () => this.editor.commands.toggleBulletList(),\n    }\n  },\n\n  addInputRules() {\n    let inputRule = wrappingInputRule({\n      find: bulletListInputRegex,\n      type: this.type,\n    })\n\n    if (this.options.keepMarks || this.options.keepAttributes) {\n      inputRule = wrappingInputRule({\n        find: bulletListInputRegex,\n        type: this.type,\n        keepMarks: this.options.keepMarks,\n        keepAttributes: this.options.keepAttributes,\n        getAttributes: () => {\n          return this.editor.getAttributes(TextStyleName)\n        },\n        editor: this.editor,\n      })\n    }\n    return [inputRule]\n  },\n})\n", "import type { Node } from '@tiptap/pm/model'\nimport type { EditorState } from '@tiptap/pm/state'\n\nexport type BranchingNestedListAtCursor = {\n  listItemDepth: number\n  nestedList: Node\n  nestedListPos: number\n  insertPos: number\n  items: Node[]\n}\n\n/**\n * Resolves a branching nested list immediately after the cursor when the selection is\n * collapsed at the end of a textblock inside a list item.\n *\n * @param state - The editor state to inspect.\n * @param itemName - The list item node name (for example `listItem` or `taskItem`).\n * @param wrapperNames - List wrapper node names (for example `bulletList` and `orderedList`).\n * @returns Resolved positions and nodes for hoisting, or `null` when not applicable.\n *\n * @example\n * ```ts\n * const context = getBranchingNestedListAtCursor(editor.state, 'listItem', [\n *   'bulletList',\n *   'orderedList',\n * ])\n *\n * if (context) {\n *   // cursor is at the end of Item 1 before a branching nested sublist\n * }\n * ```\n */\nexport const getBranchingNestedListAtCursor = (\n  state: EditorState,\n  itemName: string,\n  wrapperNames: string[],\n): BranchingNestedListAtCursor | null => {\n  const { selection } = state\n\n  if (!selection.empty) {\n    return null\n  }\n\n  const { $from } = selection\n\n  if (!$from.parent.isTextblock) {\n    return null\n  }\n\n  if ($from.parentOffset !== $from.parent.content.size) {\n    return null\n  }\n\n  let listItemDepth = -1\n\n  for (let depth = $from.depth; depth > 0; depth -= 1) {\n    if ($from.node(depth).type.name === itemName) {\n      listItemDepth = depth\n      break\n    }\n  }\n\n  if (listItemDepth < 0) {\n    return null\n  }\n\n  const listItem = $from.node(listItemDepth)\n  const indexInListItem = $from.index(listItemDepth)\n\n  if (indexInListItem + 1 >= listItem.childCount) {\n    return null\n  }\n\n  const nextChild = listItem.child(indexInListItem + 1)\n\n  if (!wrapperNames.includes(nextChild.type.name)) {\n    return null\n  }\n\n  const itemType = state.schema.nodes[itemName]\n  let hasBranching = false\n\n  nextChild.forEach(child => {\n    if (child.type === itemType && child.childCount > 1) {\n      hasBranching = true\n    }\n  })\n\n  if (!hasBranching) {\n    return null\n  }\n\n  const nodeAfter = state.doc.resolve($from.after()).nodeAfter\n\n  if (!nodeAfter || !wrapperNames.includes(nodeAfter.type.name)) {\n    return null\n  }\n\n  const items: Node[] = []\n\n  nodeAfter.forEach(child => {\n    items.push(child)\n  })\n\n  if (items.length === 0) {\n    return null\n  }\n\n  return {\n    listItemDepth,\n    nestedList: nodeAfter,\n    nestedListPos: $from.after(),\n    insertPos: $from.after(listItemDepth),\n    items,\n  }\n}\n", "import { Fragment } from '@tiptap/pm/model'\nimport type { EditorState, Transaction } from '@tiptap/pm/state'\n\nimport { getBranchingNestedListAtCursor } from './getBranchingNestedListAtCursor.js'\n\n/**\n * Hoists all list items from a branching nested list after the cursor into the parent list.\n *\n * Use this when `joinForward` cannot restructure a nested list that contains list items\n * with sublists (see issue #6906).\n *\n * @param state - The editor state to transform.\n * @param dispatch - Optional dispatch function for the transaction.\n * @param itemName - The list item node name (for example `listItem` or `taskItem`).\n * @param wrapperNames - List wrapper node names (for example `bulletList` and `orderedList`).\n * @returns `true` when the nested list was hoisted, otherwise `false`.\n *\n * @example\n * ```ts\n * // Cursor at the end of \"Item 1\" before a nested list with branching items.\n * hoistBranchingNestedList(editor.state, editor.view.dispatch, 'listItem', [\n *   'bulletList',\n *   'orderedList',\n * ])\n * ```\n */\nexport const hoistBranchingNestedList = (\n  state: EditorState,\n  dispatch: ((tr: Transaction) => void) | undefined,\n  itemName: string,\n  wrapperNames: string[],\n) => {\n  const context = getBranchingNestedListAtCursor(state, itemName, wrapperNames)\n\n  if (!context) {\n    return false\n  }\n\n  const { selection } = state\n  const { nestedList, nestedListPos, insertPos, items } = context\n  const tr = state.tr\n\n  tr.delete(nestedListPos, nestedListPos + nestedList.nodeSize)\n\n  const mappedInsertPos = tr.mapping.map(insertPos)\n\n  tr.insert(mappedInsertPos, Fragment.from(items))\n\n  tr.setSelection(selection.map(tr.doc, tr.mapping))\n\n  if (dispatch) {\n    dispatch(tr)\n  }\n\n  return true\n}\n", "import type { Editor } from '@tiptap/core'\n\nimport { hoistBranchingNestedList } from './hoistBranchingNestedList.js'\n\n/**\n * Handles Delete for a list item when a branching nested sublist follows the cursor.\n *\n * @param editor - The editor instance whose state should be updated.\n * @param itemName - The list item node name (for example `listItem` or `taskItem`).\n * @param wrapperNames - List wrapper node names (for example `bulletList` and `orderedList`).\n * @returns `true` when the nested list was hoisted, otherwise `false`.\n *\n * @example\n * ```ts\n * Delete: () =>\n *   handleDeleteBranchingNestedList(editor, 'listItem', ['bulletList', 'orderedList']),\n * ```\n */\nexport const handleDeleteBranchingNestedList = (\n  editor: Editor,\n  itemName: string,\n  wrapperNames: string[],\n) => {\n  return hoistBranchingNestedList(editor.state, editor.view.dispatch, itemName, wrapperNames)\n}\n", "import { Extension } from '@tiptap/core'\n\nimport { handleDeleteBranchingNestedList } from './handleDeleteBranchingNestedList.js'\n\n/**\n * Creates a high-priority keymap extension that handles Delete for branching nested lists.\n * Kept separate from the list item node so Enter/Tab shortcuts keep their default priority.\n */\nexport const createBranchingListDeleteKeymap = (itemName: string, wrapperNames: string[]) => {\n  return Extension.create({\n    name: `${itemName}BranchingDeleteKeymap`,\n    priority: 101,\n\n    addKeyboardShortcuts() {\n      const handleDelete = () =>\n        handleDeleteBranchingNestedList(this.editor, itemName, wrapperNames)\n\n      return {\n        Delete: handleDelete,\n        'Mod-Delete': handleDelete,\n      }\n    },\n  })\n}\n", "const ROMAN_NUMERALS: [number, string][] = [\n  [1000, 'm'],\n  [900, 'cm'],\n  [500, 'd'],\n  [400, 'cd'],\n  [100, 'c'],\n  [90, 'xc'],\n  [50, 'l'],\n  [40, 'xl'],\n  [10, 'x'],\n  [9, 'ix'],\n  [5, 'v'],\n  [4, 'iv'],\n  [1, 'i'],\n]\n\nconst ALPHA_NUMERALS = 'abcdefghijklmnopqrstuvwxyz'\n\n/** Alpha list markers support at most 2 letters (a–z, aa–zz), matching {@link fromAlpha}. */\nexport const ORDERED_LIST_ALPHA_MARKER_PATTERN = '[a-zA-Z]{1,2}'\n\n/**\n * Marker segment for ordered list lines: numeric, roman, or 1–2 letter alpha.\n * Roman is matched before alpha so \"iii\" is roman; invalid romans like \"aa\" fall through to alpha.\n */\nexport const ORDERED_LIST_MARKER_PATTERN = String.raw`\\d+|[ivxlcdmIVXLCDM]+|${ORDERED_LIST_ALPHA_MARKER_PATTERN}`\n\n/**\n * Convert a number to lowercase roman numerals.\n * @example toRoman(1) // 'i'\n * @example toRoman(4) // 'iv'\n */\nexport function toRoman(num: number): string {\n  let remaining = num\n  let result = ''\n\n  for (const [value, numeral] of ROMAN_NUMERALS) {\n    while (remaining >= value) {\n      result += numeral\n      remaining -= value\n    }\n  }\n\n  return result\n}\n\n/**\n * Convert a number to uppercase roman numerals.\n * @example toRomanUpper(1) // 'I'\n * @example toRomanUpper(4) // 'IV'\n */\nexport function toRomanUpper(num: number): string {\n  return toRoman(num).toUpperCase()\n}\n\nfunction fromRoman(roman: string): number {\n  const lower = roman.toLowerCase()\n  let index = 0\n  let result = 0\n\n  while (index < lower.length) {\n    let matched = false\n\n    for (const [value, numeral] of ROMAN_NUMERALS) {\n      if (lower.startsWith(numeral, index)) {\n        result += value\n        index += numeral.length\n        matched = true\n        break\n      }\n    }\n\n    if (!matched) {\n      return 0\n    }\n  }\n\n  return result\n}\n\nfunction isValidRoman(marker: string): boolean {\n  if (!/^[ivxlcdmIVXLCDM]+$/.test(marker)) {\n    return false\n  }\n\n  const value = fromRoman(marker)\n\n  if (value <= 0) {\n    return false\n  }\n\n  const expected = marker === marker.toLowerCase() ? toRoman(value) : toRomanUpper(value)\n\n  return expected === marker\n}\n\nfunction fromAlpha(marker: string): number {\n  const lower = marker.toLowerCase()\n\n  if (lower.length === 1) {\n    return lower.charCodeAt(0) - 'a'.charCodeAt(0) + 1\n  }\n\n  if (lower.length === 2) {\n    const first = lower.charCodeAt(0) - 'a'.charCodeAt(0)\n    const second = lower.charCodeAt(1) - 'a'.charCodeAt(0)\n\n    return (first + 1) * 26 + second + 1\n  }\n\n  return 0\n}\n\nfunction toRomanAlpha(num: number): string {\n  if (num <= 26) {\n    return ALPHA_NUMERALS[num - 1]\n  }\n\n  const first = Math.floor((num - 1) / 26) - 1\n  const second = (num - 1) % 26\n\n  if (first < 0) {\n    return ALPHA_NUMERALS[second]\n  }\n\n  return ALPHA_NUMERALS[first] + ALPHA_NUMERALS[second]\n}\n\n/**\n * Extract the list marker type from a marker string.\n * Supports \"1\", \"a\", \"A\", \"i\", \"I\" marker styles.\n *\n * @param marker The text content of the list marker (e.g. \"a\", \"1\", \"iii\", \"b\")\n * @returns The normalized type string, or undefined for default numeric type\n */\nexport function detectMarkerType(marker: string): string | undefined {\n  if (!marker || /^\\d+$/.test(marker)) {\n    return undefined\n  }\n\n  if (isValidRoman(marker)) {\n    return marker === marker.toLowerCase() ? 'i' : 'I'\n  }\n\n  if (/^[a-z]{1,2}$/.test(marker)) {\n    return 'a'\n  }\n\n  if (/^[A-Z]{1,2}$/.test(marker)) {\n    return 'A'\n  }\n\n  return undefined\n}\n\n/**\n * Convert a list marker string to its numeric start position.\n *\n * @param marker The text content of the list marker (e.g. \"3\", \"b\", \"II\")\n * @returns The 1-based start value for the ordered list\n */\nexport function markerToStart(marker: string): number {\n  if (/^\\d+$/.test(marker)) {\n    return parseInt(marker, 10)\n  }\n\n  const type = detectMarkerType(marker)\n\n  if (type === 'i' || type === 'I') {\n    return fromRoman(marker)\n  }\n\n  if (type === 'a' || type === 'A') {\n    const start = fromAlpha(marker)\n\n    return start > 0 ? start : 1\n  }\n\n  const parsed = parseInt(marker, 10)\n\n  return Number.isNaN(parsed) ? 1 : parsed\n}\n\nfunction startToMarker(type: string, start: number): string {\n  if (type === 'numeric') {\n    return String(start)\n  }\n\n  switch (type) {\n    case 'a':\n      return toRomanAlpha(start)\n    case 'A':\n      return toRomanAlpha(start).toUpperCase()\n    case 'i':\n      return toRoman(start)\n    case 'I':\n      return toRomanUpper(start)\n    default:\n      return String(start)\n  }\n}\n\n/**\n * Returns true when all markers share the same style and increment by 1.\n * Style is inferred from the first marker so ambiguous letters (e.g. \"c\", \"i\")\n * are not re-classified differently on later lines.\n */\nexport function areOrderedListMarkersSequential(markers: string[]): boolean {\n  if (markers.length === 0) {\n    return false\n  }\n\n  const firstType = detectMarkerType(markers[0]) ?? 'numeric'\n  const firstStart = markerToStart(markers[0])\n\n  if (firstStart < 1) {\n    return false\n  }\n\n  for (let i = 0; i < markers.length; i++) {\n    const expected = startToMarker(firstType, firstStart + i)\n\n    if (markers[i] !== expected) {\n      return false\n    }\n  }\n\n  return true\n}\n\nexport interface ParsedListMarker {\n  type?: string\n  start: number\n}\n\n/**\n * Parse a list marker into HTML ordered-list attrs (type + start).\n */\nexport function parseListMarker(marker: string): ParsedListMarker {\n  return {\n    type: detectMarkerType(marker),\n    start: markerToStart(marker),\n  }\n}\n\n/**\n * Build orderedList node attrs from the first list item marker.\n */\nexport function buildOrderedListAttrsFromMarker(marker: string): Record<string, string | number> {\n  const { type, start } = parseListMarker(marker)\n  const attrs: Record<string, string | number> = {}\n\n  if (type) {\n    attrs.type = type\n  }\n\n  if (start !== 1) {\n    attrs.start = start\n  }\n\n  return attrs\n}\n\n/**\n * Returns the list marker prefix for a given item at a given index.\n *\n * @param type The list type attribute (e.g. \"a\", \"A\", \"i\", \"I\", null/undefined for default)\n * @param index The zero-based index of the list item\n * @param separator The separator to use (default: \". \")\n * @returns The marker string (e.g. \"a. \", \"I. \", \"1. \")\n */\nexport function getListMarker(\n  type: string | null | undefined,\n  index: number,\n  separator = '. ',\n): string {\n  const position = index + 1\n\n  if (!type || type === '1') {\n    return `${position}${separator}`\n  }\n\n  switch (type) {\n    case 'a':\n      return `${toRomanAlpha(position)}${separator}`\n    case 'A':\n      return `${toRomanAlpha(position).toUpperCase()}${separator}`\n    case 'i':\n      return `${toRoman(position)}${separator}`\n    case 'I':\n      return `${toRomanUpper(position)}${separator}`\n    default:\n      return `${position}${separator}`\n  }\n}\n", "import type { JSONContent } from '@tiptap/core'\n\nexport function ensureLeadingParagraph(content: JSONContent[]): JSONContent[] {\n  if (!content[0] || content[0].type === 'paragraph') {\n    return content\n  }\n\n  // List items must start with a paragraph\n  return [{ type: 'paragraph', content: [] }, ...content]\n}\n", "import type { JSONContent } from '@tiptap/core'\n\nexport function hasEmptyLeadingParagraph(node: JSONContent): boolean {\n  const first = node.content?.[0]\n\n  return first?.type === 'paragraph' && !first.content?.length\n}\n", "import type { JSONContent, MarkdownParseHelpers, MarkdownToken } from '@tiptap/core'\nimport { mergeAttributes, Node, renderNestedMarkdownContent } from '@tiptap/core'\n\nimport { createBranchingListDeleteKeymap } from '../helpers/createBranchingListDeleteKeymap.js'\n\nimport { getListMarker } from '../ordered-list/roman.js'\nimport { ensureLeadingParagraph } from './ensureLeadingParagraph.js'\nimport { hasEmptyLeadingParagraph } from './hasEmptyLeadingParagraph.js'\n\nconst EMPTY_ITEM_TEXT = '&nbsp;'\nconst TOP_LEVEL = 1\n\nconst isNested = (ctx: any) => (ctx?.level ?? TOP_LEVEL) > TOP_LEVEL\n\nexport interface ListItemOptions {\n  /**\n   * The HTML attributes for a list item node.\n   * @default {}\n   * @example { class: 'foo' }\n   */\n  HTMLAttributes: Record<string, any>\n\n  /**\n   * The node type for bulletList nodes\n   * @default 'bulletList'\n   * @example 'myCustomBulletList'\n   */\n  bulletListTypeName: string\n\n  /**\n   * The node type for orderedList nodes\n   * @default 'orderedList'\n   * @example 'myCustomOrderedList'\n   */\n  orderedListTypeName: string\n}\n\nfunction isSameLineOrderedListToken(token: MarkdownToken): boolean {\n  const nestedToken = token.tokens?.[0]\n\n  return Boolean(\n    token.text &&\n    token.tokens?.length === 1 &&\n    nestedToken?.type === 'list' &&\n    nestedToken.ordered &&\n    nestedToken.raw === token.text,\n  )\n}\n\nfunction parseSameLineOrderedListText(text: string, helpers: MarkdownParseHelpers): JSONContent[] {\n  if (helpers.tokenizeInline) {\n    return helpers.parseInline(helpers.tokenizeInline(text))\n  }\n\n  return helpers.parseInline([\n    {\n      type: 'text',\n      raw: text,\n      text,\n    },\n  ])\n}\n\n/**\n * This extension allows you to create list items.\n * @see https://www.tiptap.dev/api/nodes/list-item\n */\nexport const ListItem = Node.create<ListItemOptions>({\n  name: 'listItem',\n\n  addOptions() {\n    return {\n      HTMLAttributes: {},\n      bulletListTypeName: 'bulletList',\n      orderedListTypeName: 'orderedList',\n    }\n  },\n\n  content: 'paragraph block*',\n\n  defining: true,\n\n  parseHTML() {\n    return [\n      {\n        tag: 'li',\n      },\n    ]\n  },\n\n  renderHTML({ HTMLAttributes }) {\n    return ['li', mergeAttributes(this.options.HTMLAttributes, HTMLAttributes), 0]\n  },\n\n  markdownTokenName: 'list_item',\n\n  parseMarkdown: (token, helpers) => {\n    if (token.type !== 'list_item') {\n      return []\n    }\n\n    const parseBlockChildren = helpers.parseBlockChildren ?? helpers.parseChildren\n    let content: any[] = []\n\n    if (token.tokens && token.tokens.length > 0) {\n      if (isSameLineOrderedListToken(token)) {\n        return {\n          type: 'listItem',\n          content: [\n            {\n              type: 'paragraph',\n              content: parseSameLineOrderedListText(token.text || '', helpers),\n            },\n          ],\n        }\n      }\n\n      const [firstToken, ...remainingTokens] = token.tokens\n\n      // A setext underline or \"# \" makes marked emit a heading, but the item text is a paragraph\n      if (firstToken.type === 'heading') {\n        return {\n          type: 'listItem',\n          content: [\n            { type: 'paragraph', content: helpers.parseInline(firstToken.tokens ?? []) },\n            ...(remainingTokens.length > 0 ? parseBlockChildren(remainingTokens) : []),\n          ],\n        }\n      }\n\n      // Check if we have paragraph tokens (complex list items)\n      const hasParagraphTokens = token.tokens.some(t => t.type === 'paragraph')\n\n      if (hasParagraphTokens) {\n        // If we have paragraph tokens, parse them as block elements\n        content = parseBlockChildren(token.tokens)\n      } else {\n        // Check if the first token is a text token with nested inline tokens\n        if (firstToken.type === 'text' && firstToken.tokens && firstToken.tokens.length > 0) {\n          // Parse the inline content from the text token\n          const inlineContent = helpers.parseInline(firstToken.tokens)\n\n          // Start with the paragraph containing the inline content\n          content = [\n            {\n              type: 'paragraph',\n              content: inlineContent,\n            },\n          ]\n\n          // If there are additional tokens after the first text token (like nested lists),\n          // parse them as block elements and add them\n          if (token.tokens.length > 1) {\n            const remainingTokens = token.tokens.slice(1)\n            const additionalContent = parseBlockChildren(remainingTokens)\n            content.push(...additionalContent)\n          }\n        } else {\n          // Fallback: parse all tokens as block elements\n          content = parseBlockChildren(token.tokens)\n        }\n      }\n    }\n\n    // Ensure we always have at least an empty paragraph\n    if (content.length === 0) {\n      content = [\n        {\n          type: 'paragraph',\n          content: [],\n        },\n      ]\n    }\n\n    return {\n      type: 'listItem',\n      content: ensureLeadingParagraph(content),\n    }\n  },\n\n  renderMarkdown: (node, h, ctx) => {\n    const getPrefix = (context: any) => {\n      if (context.parentType === 'bulletList') {\n        return '- '\n      }\n      if (context.parentType === 'orderedList') {\n        const start = context.meta?.parentAttrs?.start || 1\n        const type = context.meta?.parentAttrs?.type as string | undefined\n        const index = start - 1 + (context.index || 0)\n        return getListMarker(type, index, '. ')\n      }\n      // Fallback to bullet list for unknown parent types\n      return '- '\n    }\n\n    const output = renderNestedMarkdownContent(node, h, getPrefix, ctx, {\n      alignNestedToPrefix: ctx?.parentType === 'orderedList',\n    })\n\n    if (!hasEmptyLeadingParagraph(node) || !isNested(ctx)) {\n      return output\n    }\n\n    // A bare nested marker is read as a heading underline\n    const prefix = getPrefix(ctx)\n\n    return `${prefix}${EMPTY_ITEM_TEXT}${output.slice(prefix.length)}`\n  },\n\n  addExtensions() {\n    return [\n      createBranchingListDeleteKeymap(this.name, [\n        this.options.bulletListTypeName,\n        this.options.orderedListTypeName,\n      ]),\n    ]\n  },\n\n  addKeyboardShortcuts() {\n    return {\n      Enter: () => this.editor.commands.splitListItem(this.name),\n      Tab: () => this.editor.commands.sinkListItem(this.name),\n      'Shift-Tab': () => this.editor.commands.liftListItem(this.name),\n    }\n  },\n})\n", "import { getNodeType } from '@tiptap/core'\nimport type { NodeType } from '@tiptap/pm/model'\nimport type { EditorState } from '@tiptap/pm/state'\n\nexport const findListItemPos = (typeOrName: string | NodeType, state: EditorState) => {\n  const { $from } = state.selection\n  const nodeType = getNodeType(typeOrName, state.schema)\n\n  let currentNode = null\n  let currentDepth = $from.depth\n  let currentPos = $from.pos\n  let targetDepth: number | null = null\n\n  while (currentDepth > 0 && targetDepth === null) {\n    currentNode = $from.node(currentDepth)\n\n    if (currentNode.type === nodeType) {\n      targetDepth = currentDepth\n    } else {\n      currentDepth -= 1\n      currentPos -= 1\n    }\n  }\n\n  if (targetDepth === null) {\n    return null\n  }\n\n  return { $pos: state.doc.resolve(currentPos), depth: targetDepth }\n}\n", "import { getNodeAtPosition } from '@tiptap/core'\nimport type { EditorState } from '@tiptap/pm/state'\n\nimport { findListItemPos } from './findListItemPos.js'\n\nexport const getNextListDepth = (typeOrName: string, state: EditorState) => {\n  const listItemPos = findListItemPos(typeOrName, state)\n\n  if (!listItemPos) {\n    return false\n  }\n\n  const [, depth] = getNodeAtPosition(state, typeOrName, listItemPos.$pos.pos + 4)\n\n  return depth\n}\n", "import type { EditorState } from '@tiptap/pm/state'\n\nexport const hasListBefore = (\n  editorState: EditorState,\n  name: string,\n  parentListTypes: string[],\n) => {\n  const { $anchor } = editorState.selection\n\n  const previousNodePos = Math.max(0, $anchor.pos - 2)\n\n  const previousNode = editorState.doc.resolve(previousNodePos).node()\n\n  if (!previousNode || !parentListTypes.includes(previousNode.type.name)) {\n    return false\n  }\n\n  return true\n}\n", "import type { Editor } from '@tiptap/core'\nimport { isAtStartOfNode, isNodeActive } from '@tiptap/core'\nimport { joinTextblockBackward } from '@tiptap/pm/commands'\nimport type { Node } from '@tiptap/pm/model'\nimport { TextSelection } from '@tiptap/pm/state'\n\nimport { hasListBefore } from './hasListBefore.js'\n\nexport const handleBackspace = (editor: Editor, name: string, parentListTypes: string[]) => {\n  // this is required to still handle the undo handling\n  if (editor.commands.undoInputRule()) {\n    return true\n  }\n\n  // if the selection is not collapsed\n  // we can rely on the default backspace behavior\n  if (editor.state.selection.from !== editor.state.selection.to) {\n    return false\n  }\n\n  // if the current item is NOT inside a list item &\n  // the previous item is a list (orderedList or bulletList)\n  // move the cursor into the list and delete the current item\n  if (!isNodeActive(editor.state, name) && hasListBefore(editor.state, name, parentListTypes)) {\n    const { $anchor } = editor.state.selection\n\n    const $listPos = editor.state.doc.resolve($anchor.before() - 1)\n\n    const listDescendants: Array<{ node: Node; pos: number }> = []\n\n    $listPos.node().descendants((node, pos) => {\n      if (node.type.name === name) {\n        listDescendants.push({ node, pos })\n      }\n    })\n\n    const lastItem = listDescendants.at(-1)\n\n    if (!lastItem) {\n      return false\n    }\n\n    const $lastItemPos = editor.state.doc.resolve($listPos.start() + lastItem.pos + 1)\n\n    return editor\n      .chain()\n      .command(({ tr }) => {\n        const target = $lastItemPos.end()\n\n        tr.delete($anchor.before(), $anchor.after()).insert(target, $anchor.parent)\n        tr.setSelection(TextSelection.create(tr.doc, target + 1))\n\n        return true\n      })\n      .command(({ state, dispatch }) => {\n        joinTextblockBackward(state, dispatch)\n\n        return true\n      })\n      .run()\n  }\n\n  // if the cursor is not inside the current node type\n  // do nothing and proceed\n  if (!isNodeActive(editor.state, name)) {\n    return false\n  }\n\n  // if the cursor is not at the start of a node\n  // do nothing and proceed\n  if (!isAtStartOfNode(editor.state)) {\n    return false\n  }\n\n  // only intercept at the start of the list item's first child\n  const { $from } = editor.state.selection\n  const itemDepth = $from.depth - 1\n  if ($from.node(itemDepth).type !== editor.schema.nodes[name] || $from.index(itemDepth) !== 0) {\n    return false\n  }\n\n  return editor.chain().liftListItem(name).run()\n}\n", "import type { EditorState } from '@tiptap/pm/state'\n\nimport { findListItemPos } from './findListItemPos.js'\nimport { getNextListDepth } from './getNextListDepth.js'\n\nexport const nextListIsDeeper = (typeOrName: string, state: EditorState) => {\n  const listDepth = getNextListDepth(typeOrName, state)\n  const listItemPos = findListItemPos(typeOrName, state)\n\n  if (!listItemPos || !listDepth) {\n    return false\n  }\n\n  if (listDepth > listItemPos.depth) {\n    return true\n  }\n\n  return false\n}\n", "import type { EditorState } from '@tiptap/pm/state'\n\nimport { findListItemPos } from './findListItemPos.js'\nimport { getNextListDepth } from './getNextListDepth.js'\n\nexport const nextListIsHigher = (typeOrName: string, state: EditorState) => {\n  const listDepth = getNextListDepth(typeOrName, state)\n  const listItemPos = findListItemPos(typeOrName, state)\n\n  if (!listItemPos || !listDepth) {\n    return false\n  }\n\n  if (listDepth < listItemPos.depth) {\n    return true\n  }\n\n  return false\n}\n", "import type { Editor } from '@tiptap/core'\nimport { isAtEndOfNode, isNodeActive } from '@tiptap/core'\nimport { joinTextblockForward } from '@tiptap/pm/commands'\n\nimport { nextListIsDeeper } from './nextListIsDeeper.js'\nimport { nextListIsHigher } from './nextListIsHigher.js'\n\nexport const handleDelete = (editor: Editor, name: string) => {\n  // if the cursor is not inside the current node type\n  // do nothing and proceed\n  if (!isNodeActive(editor.state, name)) {\n    return false\n  }\n\n  // if the cursor is not at the end of a node\n  // do nothing and proceed\n  if (!isAtEndOfNode(editor.state, name)) {\n    return false\n  }\n\n  // if the selection is not collapsed\n  // we can rely on the default delete behavior\n  if (!editor.state.selection.empty) {\n    return false\n  }\n\n  // check if the next node is a list with a deeper depth\n  if (nextListIsDeeper(name, editor.state)) {\n    return editor\n      .chain()\n      .focus(editor.state.selection.from + 4)\n      .lift(name)\n      .joinBackward()\n      .run()\n  }\n\n  if (nextListIsHigher(name, editor.state)) {\n    return editor.commands.command(({ state, dispatch }) => joinTextblockForward(state, dispatch))\n  }\n\n  return editor.commands.joinItemForward()\n}\n", "import type { Editor } from '@tiptap/core'\nimport { getPreviousBlockSibling, isNodeActive } from '@tiptap/core'\nimport { Fragment } from '@tiptap/pm/model'\nimport { TextSelection } from '@tiptap/pm/state'\n\nexport const handleTab = (editor: Editor, name: string, parentListTypes: string[]) => {\n  const { state } = editor\n  const { selection } = state\n  if (!selection.empty) return false\n\n  const { $from } = selection\n  if ($from.parentOffset !== 0) return false\n\n  // gap cursors satisfy both checks above but resolve outside a textblock\n  if (!$from.parent.isTextblock) return false\n\n  // Tab inside a list item belongs to sinkListItem\n  if (isNodeActive(state, name)) return false\n\n  const previous = getPreviousBlockSibling($from)\n  if (!previous || !parentListTypes.includes(previous.type.name)) return false\n\n  const lastItem = previous.lastChild\n  if (!lastItem || lastItem.type.name !== name) return false\n\n  const block = $from.parent\n\n  if (!lastItem.canReplace(lastItem.childCount, lastItem.childCount, Fragment.from(block))) {\n    return false\n  }\n\n  const blockStart = $from.before()\n  const blockEnd = $from.after()\n\n  // step back over the closing tokens of the list and its last item\n  const insideLastItemEnd = blockStart - 2\n\n  return editor.commands.command(({ tr, dispatch }) => {\n    if (dispatch) {\n      tr.delete(blockStart, blockEnd).insert(insideLastItemEnd, Fragment.from(block))\n      // place the cursor at the start of the inserted block\n      tr.setSelection(TextSelection.create(tr.doc, insideLastItemEnd + 1))\n      tr.scrollIntoView()\n    }\n\n    return true\n  })\n}\n", "import type { EditorState } from '@tiptap/pm/state'\n\nexport const hasListItemAfter = (typeOrName: string, state: EditorState): boolean => {\n  const { $anchor } = state.selection\n\n  const $targetPos = state.doc.resolve($anchor.pos - $anchor.parentOffset - 2)\n\n  if ($targetPos.index() === $targetPos.parent.childCount - 1) {\n    return false\n  }\n\n  if ($targetPos.nodeAfter?.type.name !== typeOrName) {\n    return false\n  }\n\n  return true\n}\n", "import type { EditorState } from '@tiptap/pm/state'\n\nexport const hasListItemBefore = (typeOrName: string, state: EditorState): boolean => {\n  const { $anchor } = state.selection\n\n  const $targetPos = state.doc.resolve($anchor.pos - 2)\n\n  if ($targetPos.index() === 0) {\n    return false\n  }\n\n  if ($targetPos.nodeBefore?.type.name !== typeOrName) {\n    return false\n  }\n\n  return true\n}\n", "import { getNodeType } from '@tiptap/core'\nimport type { Node } from '@tiptap/pm/model'\nimport type { EditorState } from '@tiptap/pm/state'\n\nexport const listItemHasSubList = (typeOrName: string, state: EditorState, node?: Node) => {\n  if (!node) {\n    return false\n  }\n\n  const nodeType = getNodeType(typeOrName, state.schema)\n\n  let hasSubList = false\n\n  node.descendants(child => {\n    if (child.type === nodeType) {\n      hasSubList = true\n    }\n  })\n\n  return hasSubList\n}\n", "export * from './findListItemPos.js'\nexport * from './getNextListDepth.js'\nexport * from './handleBackspace.js'\nexport * from './handleDelete.js'\nexport * from './handleTab.js'\nexport * from './hasListBefore.js'\nexport * from './hasListItemAfter.js'\nexport * from './hasListItemBefore.js'\nexport * from './listItemHasSubList.js'\nexport * from './nextListIsDeeper.js'\nexport * from './nextListIsHigher.js'\n", "import { Extension } from '@tiptap/core'\n\nimport { handleBackspace, handleDelete, handleTab } from './listHelpers/index.js'\n\nexport type ListKeymapOptions = {\n  /**\n   * An array of list types. This is used for item and wrapper list matching.\n   * @default []\n   * @example [{ itemName: 'listItem', wrapperNames: ['bulletList', 'orderedList'] }]\n   */\n  listTypes: Array<{\n    itemName: string\n    wrapperNames: string[]\n  }>\n}\n\n/**\n * This extension registers custom keymaps to change the behaviour of the backspace and delete keys.\n * By default Prosemirror keyhandling will always lift or sink items so paragraphs are joined into\n * the adjacent or previous list item. This extension will prevent this behaviour and instead will\n * try to join paragraphs from two list items into a single list item.\n * @see https://www.tiptap.dev/api/extensions/list-keymap\n */\nexport const ListKeymap = Extension.create<ListKeymapOptions>({\n  name: 'listKeymap',\n\n  addOptions() {\n    return {\n      listTypes: [\n        {\n          itemName: 'listItem',\n          wrapperNames: ['bulletList', 'orderedList'],\n        },\n        {\n          itemName: 'taskItem',\n          wrapperNames: ['taskList'],\n        },\n      ],\n    }\n  },\n\n  addKeyboardShortcuts() {\n    return {\n      Delete: ({ editor }) => {\n        let handled = false\n\n        this.options.listTypes.forEach(({ itemName }) => {\n          if (editor.state.schema.nodes[itemName] === undefined) {\n            return\n          }\n\n          if (handleDelete(editor, itemName)) {\n            handled = true\n          }\n        })\n\n        return handled\n      },\n      'Mod-Delete': ({ editor }) => {\n        let handled = false\n\n        this.options.listTypes.forEach(({ itemName }) => {\n          if (editor.state.schema.nodes[itemName] === undefined) {\n            return\n          }\n\n          if (handleDelete(editor, itemName)) {\n            handled = true\n          }\n        })\n\n        return handled\n      },\n      Backspace: ({ editor }) => {\n        let handled = false\n\n        this.options.listTypes.forEach(({ itemName, wrapperNames }) => {\n          if (editor.state.schema.nodes[itemName] === undefined) {\n            return\n          }\n\n          if (handleBackspace(editor, itemName, wrapperNames)) {\n            handled = true\n          }\n        })\n\n        return handled\n      },\n      'Mod-Backspace': ({ editor }) => {\n        let handled = false\n\n        this.options.listTypes.forEach(({ itemName, wrapperNames }) => {\n          if (editor.state.schema.nodes[itemName] === undefined) {\n            return\n          }\n\n          if (handleBackspace(editor, itemName, wrapperNames)) {\n            handled = true\n          }\n        })\n\n        return handled\n      },\n      Tab: ({ editor }) => {\n        // stop at the first handled list type so a single Tab cannot sink the block twice\n        for (const { itemName, wrapperNames } of this.options.listTypes) {\n          if (editor.state.schema.nodes[itemName] === undefined) {\n            continue\n          }\n\n          if (handleTab(editor, itemName, wrapperNames)) {\n            return true\n          }\n        }\n\n        return false\n      },\n    }\n  },\n})\n", "import type {\n  JSONContent,\n  MarkdownLexerConfiguration,\n  MarkdownParseHelpers,\n  MarkdownToken,\n} from '@tiptap/core'\n\nimport {\n  areOrderedListMarkersSequential,\n  buildOrderedListAttrsFromMarker,\n  detectMarkerType,\n  markerToStart,\n  ORDERED_LIST_MARKER_PATTERN,\n} from './roman.js'\n\nexport { ORDERED_LIST_MARKER_PATTERN }\n\n/**\n * Matches an ordered list item line with optional leading whitespace.\n * Captures: (1) indentation spaces, (2) item marker (number, letter, or roman numeral),\n * (3) separator (. or )), (4) content after marker\n *\n * Examples: \"1. Item\", \"  a) Nested item\", \"    I. Roman item\", \"iii. Another\", \"aa. Item 27\"\n */\nexport const ORDERED_LIST_ITEM_REGEX = new RegExp(\n  `^(\\\\s*)(${ORDERED_LIST_MARKER_PATTERN})([.)])\\\\s+(.*)$`,\n)\n\n// Mixed-case titles match the pattern but are not list markers.\nexport function matchOrderedListItemLine(line: string): RegExpMatchArray | undefined {\n  const match = line.match(ORDERED_LIST_ITEM_REGEX)\n\n  if (!match) {\n    return undefined\n  }\n\n  const [, , marker] = match\n\n  if (/^\\d+$/.test(marker) || detectMarkerType(marker)) {\n    return match\n  }\n\n  return undefined\n}\n\n/**\n * Matches any line that starts with whitespace (indented content).\n * Used to identify continuation content that belongs to a list item.\n */\nconst INDENTED_LINE_REGEX = /^\\s/\n\n/**\n * This are blocks that can interrupt a paragraph, so a line starting with one of\n * them can never be lazy continuation text of a list item\n */\nconst PARAGRAPH_INTERRUPTERS = {\n  heading: /^#{1,6}(?:\\s|$)/,\n  bulletItem: /^[-+*]\\s+/,\n  codeFence: /^(?:```|~~~)/,\n  blockMath: /^\\$\\$/,\n  thematicBreak: /^(?:(?:-[ \\t]*){3,}|(?:_[ \\t]*){3,}|(?:\\*[ \\t]*){3,})$/,\n}\n\n/**\n * Represents a parsed ordered list item with indentation information\n */\nexport interface OrderedListItem {\n  indent: number\n  number: number\n  type?: string\n  content: string\n  contentLines: string[]\n  raw: string\n}\n\nfunction isOrderedListMarkerLine(line: string): boolean {\n  return matchOrderedListItemLine(line.trimStart()) !== undefined\n}\n\nfunction isBlockContentLine(line: string): boolean {\n  const trimmedLine = line.trimStart()\n\n  return (\n    PARAGRAPH_INTERRUPTERS.bulletItem.test(trimmedLine) ||\n    isOrderedListMarkerLine(trimmedLine) ||\n    PARAGRAPH_INTERRUPTERS.heading.test(trimmedLine) ||\n    // dash breaks are excluded: \"---\" directly below paragraph text is a\n    // setext heading underline, not a thematic break\n    (PARAGRAPH_INTERRUPTERS.thematicBreak.test(trimmedLine) && !trimmedLine.startsWith('-')) ||\n    // oxlint-disable-next-line prefer-string-starts-ends-with\n    /^>\\s?/.test(trimmedLine) ||\n    PARAGRAPH_INTERRUPTERS.codeFence.test(trimmedLine) ||\n    PARAGRAPH_INTERRUPTERS.blockMath.test(trimmedLine)\n  )\n}\n\nfunction interruptsLazyContinuation(line: string): boolean {\n  return Object.values(PARAGRAPH_INTERRUPTERS).some(pattern => pattern.test(line))\n}\n\nfunction splitItemContent(contentLines: string[]): {\n  paragraphLines: string[]\n  blockLines: string[]\n} {\n  const paragraphLines: string[] = []\n  const blockLines: string[] = []\n  let reachedBlockBoundary = false\n\n  contentLines.forEach(line => {\n    if (reachedBlockBoundary) {\n      blockLines.push(line)\n      return\n    }\n\n    if (line.trim() === '') {\n      reachedBlockBoundary = true\n      blockLines.push(line)\n      return\n    }\n\n    if (paragraphLines.length > 0 && isBlockContentLine(line)) {\n      reachedBlockBoundary = true\n      blockLines.push(line)\n      return\n    }\n\n    paragraphLines.push(line)\n  })\n\n  return {\n    paragraphLines,\n    blockLines,\n  }\n}\n\n/**\n * Collects all ordered list items from lines, parsing them into a flat array\n * with indentation information. Stops collecting continuation content when\n * encountering nested list items, allowing them to be processed separately.\n *\n * @param lines - Array of source lines to parse\n * @returns Tuple of [listItems array, number of lines consumed]\n */\nexport function collectOrderedListItems(lines: string[]): [OrderedListItem[], number] {\n  const listItems: OrderedListItem[] = []\n  let currentLineIndex = 0\n  let consumed = 0\n\n  while (currentLineIndex < lines.length) {\n    const line = lines[currentLineIndex]\n    const match = matchOrderedListItemLine(line)\n\n    if (!match) {\n      break\n    }\n\n    const [, indent, marker, _separator, content] = match\n    const indentLevel = indent.length\n    const number = parseInt(marker, 10)\n\n    const markerType = isNaN(number) ? detectMarkerType(marker) : undefined\n    const itemNumber = isNaN(number) ? markerToStart(marker) : number\n\n    const itemContentLines = [content]\n    let nextLineIndex = currentLineIndex + 1\n    const itemLines = [line]\n    let sawBlankLine = false\n\n    // Collect continuation lines for this item (but NOT nested list items)\n    while (nextLineIndex < lines.length) {\n      const nextLine = lines[nextLineIndex]\n\n      // If it's another list item (nested or not), stop collecting\n      if (matchOrderedListItemLine(nextLine)) {\n        break\n      }\n\n      // Check for continuation content (non-list content)\n      if (nextLine.trim() === '') {\n        // Empty line\n        itemLines.push(nextLine)\n        itemContentLines.push('')\n        sawBlankLine = true\n        nextLineIndex += 1\n      } else if (nextLine.match(INDENTED_LINE_REGEX)) {\n        // Indented content - part of this item (but not a list item).\n        // Strip the indentation only up to the whitespace that is actually present,\n        // so an under-indented line (e.g. a single leading space) keeps its first character.\n        const leadingWhitespace = nextLine.length - nextLine.trimStart().length\n        const contentIndent = indentLevel + marker.length + 1\n        itemLines.push(nextLine)\n        itemContentLines.push(nextLine.slice(Math.min(leadingWhitespace, contentIndent)))\n        nextLineIndex += 1\n      } else {\n        if (sawBlankLine || interruptsLazyContinuation(nextLine)) {\n          break\n        }\n\n        itemLines.push(nextLine)\n        itemContentLines.push(nextLine)\n        nextLineIndex += 1\n      }\n    }\n\n    listItems.push({\n      indent: indentLevel,\n      number: itemNumber,\n      type: markerType,\n      content: itemContentLines.join('\\n').trim(),\n      contentLines: itemContentLines,\n      raw: itemLines.join('\\n'),\n    })\n\n    consumed = nextLineIndex\n    currentLineIndex = nextLineIndex\n  }\n\n  return [listItems, consumed]\n}\n\nconst PLAIN_TEXT_ORDERED_LIST_LINE_REGEX = new RegExp(\n  `^(${ORDERED_LIST_MARKER_PATTERN})([.)])\\\\s+(.+)$`,\n)\n\n/**\n * Parse plain-text pasted ordered list lines into JSONContent, or null if not a typed list.\n */\nexport function parsePlainTextOrderedListPaste(text: string): JSONContent | null {\n  const lines = text.split('\\n').filter(l => l.trim().length > 0)\n\n  if (lines.length === 0) {\n    return null\n  }\n\n  const parsedItems: Array<{ marker: string; content: string }> = []\n\n  for (const line of lines) {\n    const match = line.trim().match(PLAIN_TEXT_ORDERED_LIST_LINE_REGEX)\n\n    if (!match) {\n      return null\n    }\n\n    parsedItems.push({\n      marker: match[1],\n      content: match[3],\n    })\n  }\n\n  const markers = parsedItems.map(item => item.marker)\n\n  if (!areOrderedListMarkersSequential(markers)) {\n    return null\n  }\n\n  const attrs = buildOrderedListAttrsFromMarker(parsedItems[0].marker)\n\n  return {\n    type: 'orderedList',\n    attrs,\n    content: parsedItems.map(item => ({\n      type: 'listItem',\n      content: [\n        {\n          type: 'paragraph',\n          content: [{ type: 'text', text: item.content }],\n        },\n      ],\n    })),\n  }\n}\n\n/**\n * Recursively builds a nested structure from a flat array of list items\n * based on their indentation levels. Creates proper markdown tokens with\n * nested lists where appropriate.\n *\n * @param items - Flat array of list items with indentation info\n * @param baseIndent - The indentation level to process at this recursion level\n * @param lexer - Markdown lexer for parsing inline and block content\n * @returns Array of list_item tokens with proper nesting\n */\nexport function buildNestedStructure(\n  items: OrderedListItem[],\n  baseIndent: number,\n  lexer: MarkdownLexerConfiguration,\n): unknown[] {\n  const result: unknown[] = []\n  let currentIndex = 0\n\n  while (currentIndex < items.length) {\n    const item = items[currentIndex]\n\n    if (item.indent === baseIndent) {\n      // This item belongs at the current level\n      const { paragraphLines, blockLines } = splitItemContent(item.contentLines)\n      const mainText = paragraphLines.join('\\n').trim()\n\n      const tokens = []\n\n      // Always wrap the main text in a paragraph token\n      if (mainText) {\n        tokens.push({\n          type: 'paragraph',\n          raw: mainText,\n          tokens: lexer.inlineTokens(mainText),\n        })\n      }\n\n      const additionalContent = blockLines.join('\\n').trim()\n      if (additionalContent) {\n        const blockTokens = lexer.blockTokens(additionalContent)\n        tokens.push(...blockTokens)\n      }\n\n      // Look ahead to find nested items at deeper indent levels\n      let lookAheadIndex = currentIndex + 1\n      const nestedItems = []\n\n      while (lookAheadIndex < items.length && items[lookAheadIndex].indent > baseIndent) {\n        nestedItems.push(items[lookAheadIndex])\n        lookAheadIndex += 1\n      }\n\n      // If we have nested items, recursively build their structure\n      if (nestedItems.length > 0) {\n        // Find the next indent level (immediate children)\n        const nextIndent = Math.min(...nestedItems.map(nestedItem => nestedItem.indent))\n\n        // Build the nested list recursively with all nested items\n        // The recursive call will handle further nesting\n        const nestedListItems = buildNestedStructure(nestedItems, nextIndent, lexer)\n\n        // Create a nested list token\n        tokens.push({\n          type: 'list',\n          ordered: true,\n          start: nestedItems[0].number,\n          typeMarker: nestedItems[0].type,\n          items: nestedListItems,\n          raw: nestedItems.map(nestedItem => nestedItem.raw).join('\\n'),\n        })\n      }\n\n      result.push({\n        type: 'list_item',\n        raw: item.raw,\n        tokens,\n      })\n\n      // Skip the nested items we just processed\n      currentIndex = lookAheadIndex\n    } else {\n      // This item has deeper indent than we're currently processing\n      // It should be handled by a recursive call\n      currentIndex += 1\n    }\n  }\n\n  return result\n}\n\n/**\n * Parses markdown list item tokens into Tiptap JSONContent structure,\n * ensuring text content is properly wrapped in paragraph nodes.\n *\n * @param items - Array of markdown tokens representing list items\n * @param helpers - Markdown parse helpers for recursive parsing\n * @returns Array of listItem JSONContent nodes\n */\nexport function parseListItems(\n  items: MarkdownToken[],\n  helpers: MarkdownParseHelpers,\n): JSONContent[] {\n  return items.map(item => {\n    if (item.type !== 'list_item') {\n      return helpers.parseChildren([item])[0]\n    }\n\n    // Parse the tokens within the list item\n    const content: JSONContent[] = []\n\n    if (item.tokens && item.tokens.length > 0) {\n      item.tokens.forEach(itemToken => {\n        // If it's already a proper block node (paragraph, list, etc.), parse it directly\n        if (\n          itemToken.type === 'paragraph' ||\n          itemToken.type === 'list' ||\n          itemToken.type === 'blockquote' ||\n          itemToken.type === 'code'\n        ) {\n          content.push(...helpers.parseChildren([itemToken]))\n        } else if (itemToken.type === 'text' && itemToken.tokens) {\n          // If it's inline text tokens, wrap them in a paragraph\n          const inlineContent = helpers.parseChildren([itemToken])\n          content.push({\n            type: 'paragraph',\n            content: inlineContent,\n          })\n        } else {\n          // For any other content, try to parse it\n          const parsed = helpers.parseChildren([itemToken])\n          if (parsed.length > 0) {\n            content.push(...parsed)\n          }\n        }\n      })\n    }\n\n    return {\n      type: 'listItem',\n      content,\n    }\n  })\n}\n", "import type { OrderedListItem } from './utils.js'\nimport { collectOrderedListItems, matchOrderedListItemLine } from './utils.js'\n\nconst ORDERED_LIST_SCAN_WINDOW = 64\n\n// Fewer than `max` lines means `source` ended.\nfunction takeLines(source: string, max: number): string[] {\n  const lines: string[] = []\n  let start = 0\n\n  while (lines.length < max) {\n    const lineEnd = source.indexOf('\\n', start)\n\n    if (lineEnd === -1) {\n      lines.push(source.slice(start))\n      return lines\n    }\n\n    lines.push(source.slice(start, lineEnd))\n    start = lineEnd + 1\n  }\n\n  return lines\n}\n\n/**\n * Collect ordered list items from the start of `source`, reading only the lines the list needs.\n *\n * @param source Markdown beginning at a block boundary.\n * @returns The items, how many lines they consumed, and the lines that were read.\n * @example\n *   collectOrderedListItemsFromSource('1. one\\n2. two\\n\\nAfter')\n *   // → [[item, item], 3, ['1. one', '2. two', '', 'After']]\n */\nexport function collectOrderedListItemsFromSource(\n  source: string,\n): [OrderedListItem[], number, string[]] {\n  const firstLineEnd = source.indexOf('\\n')\n  const firstLine = firstLineEnd === -1 ? source : source.slice(0, firstLineEnd)\n\n  // Every block start is offered here, so reject non-lists before reading further.\n  if (!matchOrderedListItemLine(firstLine)) {\n    return [[], 0, []]\n  }\n\n  let windowSize = ORDERED_LIST_SCAN_WINDOW\n  let lines = takeLines(source, windowSize)\n  let collected = collectOrderedListItems(lines)\n\n  // Consuming the whole window means the list may continue past it.\n  while (collected[1] === lines.length && lines.length === windowSize) {\n    windowSize *= 2\n    lines = takeLines(source, windowSize)\n    collected = collectOrderedListItems(lines)\n  }\n\n  return [collected[0], collected[1], lines]\n}\n", "import type { Node as ProseMirrorNode } from '@tiptap/pm/model'\nimport { Plugin } from '@tiptap/pm/state'\n\nimport { mergeAttributes, Node, wrappingInputRule } from '@tiptap/core'\n\nimport { collectOrderedListItemsFromSource } from './collectOrderedListItemsFromSource.js'\nimport { buildNestedStructure, parseListItems, parsePlainTextOrderedListPaste } from './utils.js'\n\nconst ListItemName = 'listItem'\nconst TextStyleName = 'textStyle'\n\nexport interface OrderedListOptions {\n  /**\n   * The node type name for list items.\n   * @default 'listItem'\n   * @example 'myListItem'\n   */\n  itemTypeName: string\n\n  /**\n   * The HTML attributes for an ordered list node.\n   * @default {}\n   * @example { class: 'foo' }\n   */\n  HTMLAttributes: Record<string, any>\n\n  /**\n   * Keep the marks when splitting a list item.\n   * @default false\n   * @example true\n   */\n  keepMarks: boolean\n\n  /**\n   * Keep the attributes when splitting a list item.\n   * @default false\n   * @example true\n   */\n  keepAttributes: boolean\n}\n\ndeclare module '@tiptap/core' {\n  interface Commands<ReturnType> {\n    orderedList: {\n      /**\n       * Toggle an ordered list\n       * @example editor.commands.toggleOrderedList()\n       */\n      toggleOrderedList: () => ReturnType\n    }\n  }\n}\n\n/**\n * Matches an ordered list to a 1. on input (or any number followed by a dot).\n */\nexport const orderedListInputRegex = /^(\\d+)\\.\\s$/\n\n/**\n * Maps CSS list-style-type values to HTML type attribute values.\n * Google Docs and Word often use CSS instead of the HTML type attribute.\n */\nfunction cssListStyleTypeToHtmlType(style: string): string | null {\n  const match = style.match(/list-style-type\\s*:\\s*([^;]+)/i)\n  if (!match) {\n    return null\n  }\n\n  const cssValue = match[1].trim().toLowerCase()\n\n  switch (cssValue) {\n    case 'upper-roman':\n      return 'I'\n    case 'lower-roman':\n      return 'i'\n    case 'upper-alpha':\n    case 'upper-latin':\n      return 'A'\n    case 'lower-alpha':\n    case 'lower-latin':\n      return 'a'\n    default:\n      return null\n  }\n}\n\n/**\n * This extension allows you to create ordered lists.\n * This requires the ListItem extension\n * @see https://www.tiptap.dev/api/nodes/ordered-list\n * @see https://www.tiptap.dev/api/nodes/list-item\n */\nexport const OrderedList = Node.create<OrderedListOptions>({\n  name: 'orderedList',\n\n  addOptions() {\n    return {\n      itemTypeName: 'listItem',\n      HTMLAttributes: {},\n      keepMarks: false,\n      keepAttributes: false,\n    }\n  },\n\n  group: 'block list',\n\n  content() {\n    return `${this.options.itemTypeName}+`\n  },\n\n  addAttributes() {\n    return {\n      start: {\n        default: 1,\n        parseHTML: element => {\n          return element.hasAttribute('start')\n            ? parseInt(element.getAttribute('start') || '', 10)\n            : 1\n        },\n      },\n      type: {\n        default: null,\n        parseHTML: element => {\n          // 1. Check the HTML type attribute on <ol>\n          const htmlType = element.getAttribute('type')\n          if (htmlType) {\n            return htmlType\n          }\n\n          // 2. Check CSS list-style-type on the <ol> element's style attribute\n          const style = element.getAttribute('style')\n          if (style) {\n            const mappedFromOl = cssListStyleTypeToHtmlType(style)\n            if (mappedFromOl) {\n              return mappedFromOl\n            }\n          }\n\n          // 3. Check the first <li> child for list-style-type (Google Docs pattern)\n          const firstLi = element.querySelector('li')\n          if (firstLi) {\n            const liStyle = firstLi.getAttribute('style')\n            if (liStyle) {\n              const mappedFromLi = cssListStyleTypeToHtmlType(liStyle)\n              if (mappedFromLi) {\n                return mappedFromLi\n              }\n            }\n          }\n\n          return null\n        },\n      },\n    }\n  },\n\n  parseHTML() {\n    return [\n      {\n        tag: 'ol',\n      },\n    ]\n  },\n\n  renderHTML({ HTMLAttributes }) {\n    const { start, type, ...attributesWithoutType } = HTMLAttributes\n\n    const attrs = mergeAttributes(this.options.HTMLAttributes, attributesWithoutType)\n\n    if (start !== 1) {\n      attrs.start = start\n    }\n\n    if (type && type !== '1') {\n      attrs.type = type\n    }\n\n    return ['ol', attrs, 0]\n  },\n\n  markdownTokenName: 'list',\n\n  parseMarkdown: (token, helpers) => {\n    if (token.type !== 'list' || !token.ordered) {\n      return []\n    }\n\n    const startValue = token.start || 1\n    const typeValue = token.typeMarker as string | undefined\n    const content = token.items ? parseListItems(token.items, helpers) : []\n\n    // Build attrs only when they differ from defaults\n    const attrs: Record<string, unknown> = {}\n\n    if (startValue !== 1) {\n      attrs.start = startValue\n    }\n\n    if (typeValue) {\n      attrs.type = typeValue\n    }\n\n    if (Object.keys(attrs).length > 0) {\n      return {\n        type: 'orderedList',\n        attrs,\n        content,\n      }\n    }\n\n    return {\n      type: 'orderedList',\n      content,\n    }\n  },\n\n  renderMarkdown: (node, h) => {\n    if (!node.content) {\n      return ''\n    }\n\n    return h.renderChildren(node.content, '\\n')\n  },\n\n  markdownTokenizer: {\n    name: 'orderedList',\n    level: 'block',\n    // marked already breaks paragraphs before a start-of-line list marker. It\n    // probes this with `src.slice(1)`, so any marker it surfaces here is\n    // mid-line (like the \"216)\" in \"(216) 555-1234\") and must not start a list.\n    // We still define the callback so marked does not fall back to probing\n    // `tokenize`, which would re-introduce the mid-line split.\n    start: () => -1,\n    tokenize: (src: string, _tokens, lexer) => {\n      const [listItems, consumed, lines] = collectOrderedListItemsFromSource(src)\n\n      if (listItems.length === 0) {\n        return undefined\n      }\n\n      // buildNestedStructure() only includes an item when item.indent matches\n      // the base indent it's given, so the base must be this list's own\n      // indentation level (that of its first collected item, e.g. 1 for a\n      // line with a single leading space) rather than always 0 — a nested\n      // list is not necessarily flush with the start of the line.\n      const items = buildNestedStructure(listItems, listItems[0].indent, lexer)\n\n      if (items.length === 0) {\n        return undefined\n      }\n\n      const startValue = listItems[0]?.number || 1\n      const typeMarker = listItems[0]?.type\n\n      return {\n        type: 'list',\n        ordered: true,\n        start: startValue,\n        typeMarker,\n        items,\n        raw: lines.slice(0, consumed).join('\\n'),\n      } as unknown as object\n    },\n  },\n\n  markdownOptions: {\n    indentsContent: true,\n  },\n\n  addCommands() {\n    return {\n      toggleOrderedList:\n        () =>\n        ({ commands, chain }) => {\n          if (this.options.keepAttributes) {\n            return chain()\n              .toggleList(this.name, this.options.itemTypeName, this.options.keepMarks)\n              .updateAttributes(ListItemName, this.editor.getAttributes(TextStyleName))\n              .run()\n          }\n          return commands.toggleList(this.name, this.options.itemTypeName, this.options.keepMarks)\n        },\n    }\n  },\n\n  addKeyboardShortcuts() {\n    return {\n      'Mod-Shift-7': () => this.editor.commands.toggleOrderedList(),\n    }\n  },\n\n  addProseMirrorPlugins() {\n    return [\n      new Plugin({\n        props: {\n          handlePaste: (view, event) => {\n            const html = event.clipboardData?.getData('text/html')\n\n            if (html?.trim()) {\n              return false\n            }\n\n            const text = event.clipboardData?.getData('text/plain')\n\n            if (!text) {\n              return false\n            }\n\n            const orderedListContent = parsePlainTextOrderedListPaste(text)\n\n            if (!orderedListContent) {\n              return false\n            }\n\n            try {\n              const orderedListNode = view.state.schema.nodeFromJSON(orderedListContent)\n              const tr = view.state.tr.replaceSelectionWith(orderedListNode)\n\n              view.dispatch(tr)\n\n              return true\n            } catch {\n              return false\n            }\n          },\n        },\n      }),\n    ]\n  },\n\n  addInputRules() {\n    const joinPredicate = (match: RegExpMatchArray, node: ProseMirrorNode) => {\n      // Only join if the existing list has a default type\n      // (not a typed list like \"a\" or \"i\" which should stay separate)\n      const hasDefaultType = !node.attrs.type || node.attrs.type === '1'\n\n      return hasDefaultType && node.childCount + node.attrs.start === +match[1]\n    }\n\n    let inputRule = wrappingInputRule({\n      find: orderedListInputRegex,\n      type: this.type,\n      getAttributes: match => ({ start: +match[1] }),\n      joinPredicate,\n    })\n\n    if (this.options.keepMarks || this.options.keepAttributes) {\n      inputRule = wrappingInputRule({\n        find: orderedListInputRegex,\n        type: this.type,\n        keepMarks: this.options.keepMarks,\n        keepAttributes: this.options.keepAttributes,\n        getAttributes: match => ({ start: +match[1], ...this.editor.getAttributes(TextStyleName) }),\n        joinPredicate,\n        editor: this.editor,\n      })\n    }\n    return [inputRule]\n  },\n})\n", "import type { KeyboardShortcutCommand } from '@tiptap/core'\nimport {\n  getRenderedAttributes,\n  mergeAttributes,\n  Node,\n  renderNestedMarkdownContent,\n  wrappingInputRule,\n} from '@tiptap/core'\nimport type { Node as ProseMirrorNode } from '@tiptap/pm/model'\n\nimport { createBranchingListDeleteKeymap } from '../helpers/createBranchingListDeleteKeymap.js'\n\nexport interface TaskItemOptions {\n  /**\n   * A callback function that is called when the checkbox is clicked while the editor is in readonly mode.\n   * @param node The prosemirror node of the task item\n   * @param checked The new checked state\n   * @returns boolean\n   */\n  onReadOnlyChecked?: (node: ProseMirrorNode, checked: boolean) => boolean\n\n  /**\n   * Controls whether the task items can be nested or not.\n   * @default false\n   * @example true\n   */\n  nested: boolean\n\n  /**\n   * HTML attributes to add to the task item element.\n   * @default {}\n   * @example { class: 'foo' }\n   */\n  HTMLAttributes: Record<string, any>\n\n  /**\n   * The node type for taskList nodes\n   * @default 'taskList'\n   * @example 'myCustomTaskList'\n   */\n  taskListTypeName: string\n\n  /**\n   * Accessibility options for the task item.\n   * @default {}\n   * @example\n   * ```js\n   * {\n   *   checkboxLabel: (node) => `Task item: ${node.textContent || 'empty task item'}`\n   * }\n   */\n  a11y?: {\n    /**\n     * The accessible label for the checkbox. Used as the aria-label on the input and as the\n     * (visually hidden) text of the wrapping label element.\n     * @param node The prosemirror node of the task item\n     * @param checked The new checked state\n     * @returns The accessible label for the checkbox\n     * @example\n     * ```js\n     * TaskItem.configure({\n     *   a11y: {\n     *     checkboxLabel: node => `Task item: ${node.textContent || 'empty task item'}`,\n     *   },\n     * })\n     * ```\n     */\n    checkboxLabel?: (node: ProseMirrorNode, checked: boolean) => string\n  }\n}\n\n/**\n * Matches a task item to a - [ ] on input.\n */\nexport const inputRegex = /^\\s*(\\[([( |x])?\\])\\s$/\n\n/**\n * Hides the checkbox label visually while keeping it in the accessibility tree.\n */\nconst visuallyHiddenStyle =\n  'position:absolute;width:1px;height:1px;padding:0;margin:-1px;overflow:hidden;clip:rect(0,0,0,0);white-space:nowrap;border:0'\n\nconst getCheckboxLabel = (node: ProseMirrorNode, checked: boolean, a11y: TaskItemOptions['a11y']) =>\n  a11y?.checkboxLabel?.(node, checked) ||\n  `Task item checkbox for ${node.textContent || 'empty task item'}`\n\n/**\n * This extension allows you to create task items.\n * @see https://www.tiptap.dev/api/nodes/task-item\n */\nexport const TaskItem = Node.create<TaskItemOptions>({\n  name: 'taskItem',\n\n  addOptions() {\n    return {\n      nested: false,\n      HTMLAttributes: {},\n      taskListTypeName: 'taskList',\n      a11y: undefined,\n    }\n  },\n\n  content() {\n    return this.options.nested ? 'paragraph block*' : 'paragraph+'\n  },\n\n  defining: true,\n\n  addAttributes() {\n    return {\n      checked: {\n        default: false,\n        keepOnSplit: false,\n        parseHTML: element => {\n          const dataChecked = element.getAttribute('data-checked')\n\n          return dataChecked === '' || dataChecked === 'true'\n        },\n        renderHTML: attributes => ({\n          'data-checked': attributes.checked,\n        }),\n      },\n    }\n  },\n\n  parseHTML() {\n    return [\n      {\n        tag: `li[data-type=\"${this.name}\"]`,\n        priority: 51,\n        contentElement: element => element.querySelector('div') ?? element,\n      },\n    ]\n  },\n\n  renderHTML({ node, HTMLAttributes }) {\n    return [\n      'li',\n      mergeAttributes(this.options.HTMLAttributes, HTMLAttributes, {\n        'data-type': this.name,\n      }),\n      [\n        'label',\n        [\n          'input',\n          {\n            type: 'checkbox',\n            checked: node.attrs.checked ? 'checked' : null,\n          },\n        ],\n        ['span'],\n      ],\n      ['div', 0],\n    ]\n  },\n\n  parseMarkdown: (token, h) => {\n    // Parse the task item's text content into paragraph content\n    const content = []\n\n    // First, add the main paragraph content\n    if (token.tokens && token.tokens.length > 0) {\n      // If we have tokens, create a paragraph with the inline content\n      content.push(h.createNode('paragraph', {}, h.parseInline(token.tokens)))\n    } else if (token.text) {\n      // If we have raw text, create a paragraph with text node\n      content.push(h.createNode('paragraph', {}, [h.createNode('text', { text: token.text })]))\n    } else {\n      // Fallback: empty paragraph\n      content.push(h.createNode('paragraph', {}, []))\n    }\n\n    // Then, add any nested content (like nested task lists)\n    if (token.nestedTokens && token.nestedTokens.length > 0) {\n      const nestedContent = h.parseChildren(token.nestedTokens)\n      content.push(...nestedContent)\n    }\n\n    return h.createNode('taskItem', { checked: token.checked || false }, content)\n  },\n\n  renderMarkdown: (node, h) => {\n    const checkedChar = node.attrs?.checked ? 'x' : ' '\n    const prefix = `- [${checkedChar}] `\n\n    return renderNestedMarkdownContent(node, h, prefix, undefined, { indentMainContent: true })\n  },\n\n  addExtensions() {\n    if (!this.options.nested) {\n      return []\n    }\n\n    return [createBranchingListDeleteKeymap(this.name, [this.options.taskListTypeName])]\n  },\n\n  addKeyboardShortcuts() {\n    const shortcuts: {\n      [key: string]: KeyboardShortcutCommand\n    } = {\n      Enter: () => this.editor.commands.splitListItem(this.name),\n      'Shift-Tab': () => this.editor.commands.liftListItem(this.name),\n    }\n\n    if (!this.options.nested) {\n      return shortcuts\n    }\n\n    return {\n      ...shortcuts,\n      Tab: () => this.editor.commands.sinkListItem(this.name),\n    }\n  },\n\n  addNodeView() {\n    return ({ node, HTMLAttributes, getPos, editor }) => {\n      const listItem = document.createElement('li')\n      const checkboxWrapper = document.createElement('label')\n      const checkboxStyler = document.createElement('span')\n      const checkbox = document.createElement('input')\n      const content = document.createElement('div')\n\n      checkboxStyler.style.cssText = visuallyHiddenStyle\n\n      const updateA11Y = (currentNode: ProseMirrorNode) => {\n        const label = getCheckboxLabel(currentNode, currentNode.attrs.checked, this.options.a11y)\n\n        checkbox.setAttribute('aria-label', label)\n        checkboxStyler.textContent = label\n      }\n\n      updateA11Y(node)\n\n      checkboxWrapper.contentEditable = 'false'\n      checkbox.type = 'checkbox'\n      checkbox.addEventListener('mousedown', event => event.preventDefault())\n      checkbox.addEventListener('change', event => {\n        // if the editor isn’t editable and we don't have a handler for\n        // readonly checks we have to undo the latest change\n        if (!editor.isEditable && !this.options.onReadOnlyChecked) {\n          checkbox.checked = !checkbox.checked\n\n          return\n        }\n\n        const { checked } = event.target as any\n\n        if (editor.isEditable && typeof getPos === 'function') {\n          editor\n            .chain()\n            .focus(undefined, { scrollIntoView: false })\n            .command(({ tr }) => {\n              const position = getPos()\n\n              if (typeof position !== 'number') {\n                return false\n              }\n              const currentNode = tr.doc.nodeAt(position)\n\n              tr.setNodeMarkup(position, undefined, {\n                ...currentNode?.attrs,\n                checked,\n              })\n\n              return true\n            })\n            .run()\n        }\n        if (!editor.isEditable && this.options.onReadOnlyChecked) {\n          // Reset state if onReadOnlyChecked returns false\n          if (!this.options.onReadOnlyChecked(node, checked)) {\n            checkbox.checked = !checkbox.checked\n          }\n        }\n      })\n\n      Object.entries(this.options.HTMLAttributes).forEach(([key, value]) => {\n        listItem.setAttribute(key, value)\n      })\n\n      listItem.dataset.checked = node.attrs.checked\n      checkbox.checked = node.attrs.checked\n\n      checkboxWrapper.append(checkbox, checkboxStyler)\n      listItem.append(checkboxWrapper, content)\n\n      Object.entries(HTMLAttributes).forEach(([key, value]) => {\n        listItem.setAttribute(key, value)\n      })\n\n      // Track the keys of previously rendered HTML attributes for proper removal\n      let prevRenderedAttributeKeys = new Set(Object.keys(HTMLAttributes))\n\n      return {\n        dom: listItem,\n        contentDOM: content,\n        update: updatedNode => {\n          if (updatedNode.type !== this.type) {\n            return false\n          }\n\n          listItem.dataset.checked = updatedNode.attrs.checked\n          checkbox.checked = updatedNode.attrs.checked\n          updateA11Y(updatedNode)\n\n          // Sync all HTML attributes from the updated node\n          const extensionAttributes = editor.extensionManager.attributes\n          const newHTMLAttributes = getRenderedAttributes(updatedNode, extensionAttributes)\n          const newKeys = new Set(Object.keys(newHTMLAttributes))\n\n          // Remove attributes that were previously rendered but are no longer present\n          // If the attribute exists in static options, restore it instead of removing\n          const staticAttrs = this.options.HTMLAttributes\n\n          prevRenderedAttributeKeys.forEach(key => {\n            if (!newKeys.has(key)) {\n              if (key in staticAttrs) {\n                listItem.setAttribute(key, staticAttrs[key])\n              } else {\n                listItem.removeAttribute(key)\n              }\n            }\n          })\n\n          // Update or add new attributes\n          Object.entries(newHTMLAttributes).forEach(([key, value]) => {\n            if (value === null || value === undefined) {\n              // If the attribute exists in static options, restore it instead of removing\n              if (key in staticAttrs) {\n                listItem.setAttribute(key, staticAttrs[key])\n              } else {\n                listItem.removeAttribute(key)\n              }\n            } else {\n              listItem.setAttribute(key, value)\n            }\n          })\n\n          // Update the tracked keys for next update\n          prevRenderedAttributeKeys = newKeys\n\n          return true\n        },\n      }\n    }\n  },\n\n  addInputRules() {\n    return [\n      wrappingInputRule({\n        find: inputRegex,\n        type: this.type,\n        getAttributes: match => ({\n          checked: match[match.length - 1] === 'x',\n        }),\n      }),\n    ]\n  },\n})\n", "import { mergeAttributes, Node, parseIndentedBlocks } from '@tiptap/core'\n\nexport interface TaskListOptions {\n  /**\n   * The node type name for a task item.\n   * @default 'taskItem'\n   * @example 'myCustomTaskItem'\n   */\n  itemTypeName: string\n\n  /**\n   * The HTML attributes for a task list node.\n   * @default {}\n   * @example { class: 'foo' }\n   */\n  HTMLAttributes: Record<string, any>\n}\n\ndeclare module '@tiptap/core' {\n  interface Commands<ReturnType> {\n    taskList: {\n      /**\n       * Toggle a task list\n       * @example editor.commands.toggleTaskList()\n       */\n      toggleTaskList: () => ReturnType\n    }\n  }\n}\n\n/**\n * This extension allows you to create task lists.\n * @see https://www.tiptap.dev/api/nodes/task-list\n */\nexport const TaskList = Node.create<TaskListOptions>({\n  name: 'taskList',\n\n  addOptions() {\n    return {\n      itemTypeName: 'taskItem',\n      HTMLAttributes: {},\n    }\n  },\n\n  group: 'block list',\n\n  content() {\n    return `${this.options.itemTypeName}+`\n  },\n\n  parseHTML() {\n    return [\n      {\n        tag: `ul[data-type=\"${this.name}\"]`,\n        priority: 51,\n      },\n    ]\n  },\n\n  renderHTML({ HTMLAttributes }) {\n    return [\n      'ul',\n      mergeAttributes(this.options.HTMLAttributes, HTMLAttributes, { 'data-type': this.name }),\n      0,\n    ]\n  },\n\n  parseMarkdown: (token, h) => {\n    return h.createNode('taskList', {}, h.parseChildren(token.items || []))\n  },\n\n  renderMarkdown: (node, h) => {\n    if (!node.content) {\n      return ''\n    }\n\n    return h.renderChildren(node.content, '\\n')\n  },\n\n  markdownTokenizer: {\n    name: 'taskList',\n    level: 'block',\n    start(src) {\n      // Look for the start of a task list item\n      const index = src.match(/^\\s*[-+*]\\s+\\[([ xX])\\]\\s+/)?.index\n      return index !== undefined ? index : -1\n    },\n    tokenize(src, tokens, lexer) {\n      // Helper function to recursively parse task lists\n      const parseTaskListContent = (content: string): any[] | undefined => {\n        const nestedResult = parseIndentedBlocks(\n          content,\n          {\n            itemPattern: /^(\\s*)([-+*])\\s+\\[([ xX])\\]\\s+(.*)$/,\n            extractItemData: match => ({\n              indentLevel: match[1].length,\n              mainContent: match[4],\n              checked: match[3].toLowerCase() === 'x',\n            }),\n            createToken: (data, nestedTokens) => ({\n              type: 'taskItem',\n              raw: '',\n              mainContent: data.mainContent,\n              indentLevel: data.indentLevel,\n              checked: data.checked,\n              text: data.mainContent,\n              tokens: lexer.inlineTokens(data.mainContent),\n              nestedTokens,\n            }),\n            // Allow recursive nesting\n            customNestedParser: parseTaskListContent,\n          },\n          lexer,\n        )\n\n        if (nestedResult) {\n          const taskListToken = {\n            type: 'taskList',\n            raw: nestedResult.raw,\n            items: nestedResult.items,\n          }\n\n          // parseIndentedBlocks only consumes checkbox items.\n          // Parse any remaining indented content, such as plain bullets,\n          // and keep it as sibling tokens.\n          const remainder = content.slice(nestedResult.raw.length)\n          if (remainder.trim()) {\n            return [taskListToken, ...lexer.blockTokens(remainder)]\n          }\n\n          return [taskListToken]\n        }\n\n        // Fall back to regular markdown parsing if not a task list\n        return lexer.blockTokens(content)\n      }\n\n      const result = parseIndentedBlocks(\n        src,\n        {\n          itemPattern: /^(\\s*)([-+*])\\s+\\[([ xX])\\]\\s+(.*)$/,\n          extractItemData: match => ({\n            indentLevel: match[1].length,\n            mainContent: match[4],\n            checked: match[3].toLowerCase() === 'x',\n          }),\n          createToken: (data, nestedTokens) => ({\n            type: 'taskItem',\n            raw: '',\n            mainContent: data.mainContent,\n            indentLevel: data.indentLevel,\n            checked: data.checked,\n            text: data.mainContent,\n            tokens: lexer.inlineTokens(data.mainContent),\n            nestedTokens,\n          }),\n          // Use the recursive parser for nested content\n          customNestedParser: parseTaskListContent,\n        },\n        lexer,\n      )\n\n      if (!result) {\n        return undefined\n      }\n\n      return {\n        type: 'taskList',\n        raw: result.raw,\n        items: result.items,\n      }\n    },\n  },\n\n  markdownOptions: {\n    indentsContent: true,\n  },\n\n  addCommands() {\n    return {\n      toggleTaskList:\n        () =>\n        ({ commands }) => {\n          return commands.toggleList(this.name, this.options.itemTypeName)\n        },\n    }\n  },\n\n  addKeyboardShortcuts() {\n    return {\n      'Mod-Shift-9': () => this.editor.commands.toggleTaskList(),\n    }\n  },\n})\n", "import { Extension } from '@tiptap/core'\n\nimport type { BulletListOptions } from '../bullet-list/index.js'\nimport { BulletList } from '../bullet-list/index.js'\nimport type { ListItemOptions } from '../item/index.js'\nimport { ListItem } from '../item/index.js'\nimport type { ListKeymapOptions } from '../keymap/index.js'\nimport { ListKeymap } from '../keymap/index.js'\nimport type { OrderedListOptions } from '../ordered-list/index.js'\nimport { OrderedList } from '../ordered-list/index.js'\nimport type { TaskItemOptions } from '../task-item/index.js'\nimport { TaskItem } from '../task-item/index.js'\nimport type { TaskListOptions } from '../task-list/index.js'\nimport { TaskList } from '../task-list/index.js'\n\nexport interface ListKitOptions {\n  /**\n   * If set to false, the bulletList extension will not be registered\n   * @example table: false\n   */\n  bulletList: Partial<BulletListOptions> | false\n  /**\n   * If set to false, the listItem extension will not be registered\n   */\n  listItem: Partial<ListItemOptions> | false\n  /**\n   * If set to false, the listKeymap extension will not be registered\n   */\n  listKeymap: Partial<ListKeymapOptions> | false\n  /**\n   * If set to false, the orderedList extension will not be registered\n   */\n  orderedList: Partial<OrderedListOptions> | false\n  /**\n   * If set to false, the taskItem extension will not be registered\n   */\n  taskItem: Partial<TaskItemOptions> | false\n  /**\n   * If set to false, the taskList extension will not be registered\n   */\n  taskList: Partial<TaskListOptions> | false\n}\n\n/**\n * The table kit is a collection of table editor extensions.\n *\n * It’s a good starting point for building your own table in Tiptap.\n */\nexport const ListKit = Extension.create<ListKitOptions>({\n  name: 'listKit',\n\n  addExtensions() {\n    const extensions = []\n\n    if (this.options.bulletList !== false) {\n      extensions.push(BulletList.configure(this.options.bulletList))\n    }\n\n    if (this.options.listItem !== false) {\n      extensions.push(ListItem.configure(this.options.listItem))\n    }\n\n    if (this.options.listKeymap !== false) {\n      extensions.push(ListKeymap.configure(this.options.listKeymap))\n    }\n\n    if (this.options.orderedList !== false) {\n      extensions.push(OrderedList.configure(this.options.orderedList))\n    }\n\n    if (this.options.taskItem !== false) {\n      extensions.push(TaskItem.configure(this.options.taskItem))\n    }\n\n    if (this.options.taskList !== false) {\n      extensions.push(TaskList.configure(this.options.taskList))\n    }\n\n    return extensions\n  },\n})\n", "import { mergeAttributes, Node } from '@tiptap/core'\n\nexport interface ParagraphOptions {\n  /**\n   * The HTML attributes for a paragraph node.\n   * @default {}\n   * @example { class: 'foo' }\n   */\n  HTMLAttributes: Record<string, any>\n}\n\ndeclare module '@tiptap/core' {\n  interface Commands<ReturnType> {\n    paragraph: {\n      /**\n       * Toggle a paragraph\n       * @example editor.commands.toggleParagraph()\n       */\n      setParagraph: () => ReturnType\n    }\n  }\n}\n\n/**\n * Markdown marker for empty paragraphs to preserve blank lines.\n * Using &nbsp; (non-breaking space HTML entity) ensures the paragraph\n * is not collapsed by markdown parsers while remaining human-readable.\n */\nconst EMPTY_PARAGRAPH_MARKDOWN = '&nbsp;'\n\n/**\n * Unicode character for non-breaking space (U+00A0).\n * Some markdown parsers may convert &nbsp; entities to this literal character.\n */\nconst NBSP_CHAR = '\\u00A0'\n\n/**\n * This extension allows you to create paragraphs.\n * @see https://www.tiptap.dev/api/nodes/paragraph\n */\nexport const Paragraph = Node.create<ParagraphOptions>({\n  name: 'paragraph',\n\n  priority: 1000,\n\n  addOptions() {\n    return {\n      HTMLAttributes: {},\n    }\n  },\n\n  group: 'block',\n\n  content: 'inline*',\n\n  parseHTML() {\n    return [{ tag: 'p' }]\n  },\n\n  renderHTML({ HTMLAttributes }) {\n    return ['p', mergeAttributes(this.options.HTMLAttributes, HTMLAttributes), 0]\n  },\n\n  parseMarkdown: (token, helpers) => {\n    const tokens = token.tokens || []\n\n    // Special case: if paragraph contains only a single image token,\n    // unwrap it to avoid nesting block elements incorrectly\n    if (tokens.length === 1 && tokens[0].type === 'image') {\n      // Parse the image token directly as a block element\n      return helpers.parseChildren([tokens[0]])\n    }\n\n    // Parse the inline tokens\n    const content = helpers.parseInline(tokens)\n\n    // Special case: if paragraph contains only &nbsp; (non-breaking space),\n    // treat it as an empty paragraph to preserve blank lines\n    const hasExplicitEmptyParagraphMarker =\n      tokens.length === 1 &&\n      tokens[0].type === 'text' &&\n      (tokens[0].raw === EMPTY_PARAGRAPH_MARKDOWN ||\n        tokens[0].text === EMPTY_PARAGRAPH_MARKDOWN ||\n        tokens[0].raw === NBSP_CHAR ||\n        tokens[0].text === NBSP_CHAR)\n\n    if (\n      hasExplicitEmptyParagraphMarker &&\n      content.length === 1 &&\n      content[0].type === 'text' &&\n      (content[0].text === EMPTY_PARAGRAPH_MARKDOWN || content[0].text === NBSP_CHAR)\n    ) {\n      return helpers.createNode('paragraph', undefined, [])\n    }\n\n    // Convert 'paragraph' token to paragraph node\n    return helpers.createNode('paragraph', undefined, content)\n  },\n\n  renderMarkdown: (node, h, ctx) => {\n    if (!node) {\n      return ''\n    }\n\n    // Normalize content: treat undefined/null as empty array\n    const content = Array.isArray(node.content) ? node.content : []\n\n    if (content.length === 0) {\n      // Emit &nbsp; for the second and later empty paragraphs in a consecutive\n      // run at the current nesting level. The first empty paragraph stays empty\n      // so markdown spacing is preserved naturally.\n      const previousContent = Array.isArray(ctx?.previousNode?.content)\n        ? ctx.previousNode.content\n        : []\n      const previousNodeIsEmptyParagraph =\n        ctx?.previousNode?.type === 'paragraph' && previousContent.length === 0\n\n      return previousNodeIsEmptyParagraph ? EMPTY_PARAGRAPH_MARKDOWN : ''\n    }\n\n    return h.renderChildren(content)\n  },\n\n  addCommands() {\n    return {\n      setParagraph:\n        () =>\n        ({ commands }) => {\n          return commands.setNode(this.name)\n        },\n    }\n  },\n\n  addKeyboardShortcuts() {\n    return {\n      'Mod-Alt-0': () => this.editor.commands.setParagraph(),\n    }\n  },\n})\n", "import { Paragraph } from './paragraph.js'\n\nexport * from './paragraph.js'\n\nexport default Paragraph\n", "import { Mark, markInputRule, markPasteRule, mergeAttributes } from '@tiptap/core'\n\nexport interface StrikeOptions {\n  /**\n   * HTML attributes to add to the strike element.\n   * @default {}\n   * @example { class: 'foo' }\n   */\n  HTMLAttributes: Record<string, any>\n}\n\ndeclare module '@tiptap/core' {\n  interface Commands<ReturnType> {\n    strike: {\n      /**\n       * Set a strike mark\n       * @example editor.commands.setStrike()\n       */\n      setStrike: () => ReturnType\n      /**\n       * Toggle a strike mark\n       * @example editor.commands.toggleStrike()\n       */\n      toggleStrike: () => ReturnType\n      /**\n       * Unset a strike mark\n       * @example editor.commands.unsetStrike()\n       */\n      unsetStrike: () => ReturnType\n    }\n  }\n}\n\n/**\n * Matches a strike to a ~~strike~~ on input.\n */\nexport const inputRegex = /(?:^|\\s)(~~(?!\\s+~~)((?:[^~]+))~~(?!\\s+~~))$/\n\n/**\n * Matches a strike to a ~~strike~~ on paste.\n */\nexport const pasteRegex = /(?:^|\\s)(~~(?!\\s+~~)((?:[^~]+))~~(?!\\s+~~))/g\n\n/**\n * This extension allows you to create strike text.\n * @see https://www.tiptap.dev/api/marks/strike\n */\nexport const Strike = Mark.create<StrikeOptions>({\n  name: 'strike',\n\n  addOptions() {\n    return {\n      HTMLAttributes: {},\n    }\n  },\n\n  parseHTML() {\n    return [\n      {\n        tag: 's',\n      },\n      {\n        tag: 'del',\n      },\n      {\n        tag: 'strike',\n      },\n      {\n        style: 'text-decoration',\n        consuming: false,\n        getAttrs: style => ((style as string).includes('line-through') ? {} : false),\n      },\n    ]\n  },\n\n  renderHTML({ HTMLAttributes }) {\n    return ['s', mergeAttributes(this.options.HTMLAttributes, HTMLAttributes), 0]\n  },\n\n  markdownTokenName: 'del',\n\n  parseMarkdown: (token, helpers) => {\n    // Convert 'del' token to strike mark\n    return helpers.applyMark('strike', helpers.parseInline(token.tokens || []))\n  },\n\n  renderMarkdown: (node, h) => {\n    return `~~${h.renderChildren(node)}~~`\n  },\n\n  addCommands() {\n    return {\n      setStrike:\n        () =>\n        ({ commands }) => {\n          return commands.setMark(this.name)\n        },\n      toggleStrike:\n        () =>\n        ({ commands }) => {\n          return commands.toggleMark(this.name)\n        },\n      unsetStrike:\n        () =>\n        ({ commands }) => {\n          return commands.unsetMark(this.name)\n        },\n    }\n  },\n\n  addKeyboardShortcuts() {\n    return {\n      'Mod-Shift-s': () => this.editor.commands.toggleStrike(),\n    }\n  },\n\n  addInputRules() {\n    return [\n      markInputRule({\n        find: inputRegex,\n        type: this.type,\n      }),\n    ]\n  },\n\n  addPasteRules() {\n    return [\n      markPasteRule({\n        find: pasteRegex,\n        type: this.type,\n      }),\n    ]\n  },\n})\n", "import { Strike } from './strike.js'\n\nexport * from './strike.js'\n\nexport default Strike\n", "import { Node } from '@tiptap/core'\n\n/**\n * This extension allows you to create text nodes.\n * @see https://www.tiptap.dev/api/nodes/text\n */\nexport const Text = Node.create({\n  name: 'text',\n  group: 'inline',\n\n  parseMarkdown: token => {\n    // Convert 'text' token to text node - text nodes are special as they store text directly\n    return {\n      type: 'text',\n      text: token.text || '',\n    }\n  },\n\n  renderMarkdown: node => node.text || '',\n})\n", "import { Text } from './text.js'\n\nexport * from './text.js'\n\nexport default Text\n", "import { Mark, mergeAttributes } from '@tiptap/core'\n\nexport interface UnderlineOptions {\n  /**\n   * HTML attributes to add to the underline element.\n   * @default {}\n   * @example { class: 'foo' }\n   */\n  HTMLAttributes: Record<string, any>\n}\n\ndeclare module '@tiptap/core' {\n  interface Commands<ReturnType> {\n    underline: {\n      /**\n       * Set an underline mark\n       * @example editor.commands.setUnderline()\n       */\n      setUnderline: () => ReturnType\n      /**\n       * Toggle an underline mark\n       * @example editor.commands.toggleUnderline()\n       */\n      toggleUnderline: () => ReturnType\n      /**\n       * Unset an underline mark\n       * @example editor.commands.unsetUnderline()\n       */\n      unsetUnderline: () => ReturnType\n    }\n  }\n}\n\n/**\n * This extension allows you to create underline text.\n * @see https://www.tiptap.dev/api/marks/underline\n */\nexport const Underline = Mark.create<UnderlineOptions>({\n  name: 'underline',\n\n  addOptions() {\n    return {\n      HTMLAttributes: {},\n    }\n  },\n\n  parseHTML() {\n    return [\n      {\n        tag: 'u',\n      },\n      {\n        style: 'text-decoration',\n        consuming: false,\n        getAttrs: style => ((style as string).includes('underline') ? {} : false),\n      },\n    ]\n  },\n\n  renderHTML({ HTMLAttributes }) {\n    return ['u', mergeAttributes(this.options.HTMLAttributes, HTMLAttributes), 0]\n  },\n\n  parseMarkdown(token, helpers) {\n    return helpers.applyMark(this.name || 'underline', helpers.parseInline(token.tokens || []))\n  },\n\n  renderMarkdown(node, helpers) {\n    return `<u>${helpers.renderChildren(node)}</u>`\n  },\n\n  markdownTokenizer: {\n    name: 'underline',\n    level: 'inline',\n    start(src) {\n      return src.toLowerCase().indexOf('<u>')\n    },\n    tokenize(src, _tokens, lexer) {\n      if (!/^<u>/i.test(src)) {\n        return undefined\n      }\n\n      const delimiters = /\\\\[\\s\\S]|`+|<\\/u>/gi\n      delimiters.lastIndex = 3\n\n      let match = delimiters.exec(src)\n\n      while (match) {\n        if (match[0].startsWith('`')) {\n          const codeSpan = /^(`+)([^`]|[^`][\\s\\S]*?[^`])\\1(?!`)/.exec(src.slice(match.index))\n\n          if (codeSpan) {\n            delimiters.lastIndex = match.index + codeSpan[0].length\n          }\n        } else if (!match[0].startsWith('\\\\')) {\n          const text = src.slice(3, match.index)\n\n          if (!text) {\n            return undefined\n          }\n\n          return {\n            type: 'underline',\n            raw: src.slice(0, delimiters.lastIndex),\n            text,\n            tokens: lexer.inlineTokens(text),\n          }\n        }\n\n        match = delimiters.exec(src)\n      }\n\n      return undefined\n    },\n  },\n\n  addCommands() {\n    return {\n      setUnderline:\n        () =>\n        ({ commands }) => {\n          return commands.setMark(this.name)\n        },\n      toggleUnderline:\n        () =>\n        ({ commands }) => {\n          return commands.toggleMark(this.name)\n        },\n      unsetUnderline:\n        () =>\n        ({ commands }) => {\n          return commands.unsetMark(this.name)\n        },\n    }\n  },\n\n  addKeyboardShortcuts() {\n    return {\n      'Mod-u': () => this.editor.commands.toggleUnderline(),\n      'Mod-U': () => this.editor.commands.toggleUnderline(),\n    }\n  },\n})\n", "import { Underline } from './underline.js'\n\nexport * from './underline.js'\n\nexport default Underline\n", "import { Plugin } from 'prosemirror-state';\nimport { dropPoint } from 'prosemirror-transform';\n\n/**\nCreate a plugin that, when added to a ProseMirror instance,\ncauses a decoration to show up at the drop position when something\nis dragged over the editor.\n\nNodes may add a `disableDropCursor` property to their spec to\ncontrol the showing of a drop cursor inside them. This may be a\nboolean or a function, which will be called with a view and a\nposition, and should return a boolean.\n*/\nfunction dropCursor(options = {}) {\n    return new Plugin({\n        view(editorView) { return new DropCursorView(editorView, options); }\n    });\n}\nclass DropCursorView {\n    constructor(editorView, options) {\n        var _a;\n        this.editorView = editorView;\n        this.cursorPos = null;\n        this.element = null;\n        this.timeout = -1;\n        this.lastDragEvent = null;\n        this.width = (_a = options.width) !== null && _a !== void 0 ? _a : 1;\n        this.color = options.color === false ? undefined : (options.color || \"black\");\n        this.class = options.class;\n        this.handlers = [\"dragover\", \"dragend\", \"drop\", \"dragleave\"].map(name => {\n            let handler = (e) => { this[name](e); };\n            editorView.dom.addEventListener(name, handler);\n            return { name, handler };\n        });\n    }\n    destroy() {\n        this.setCursor(null);\n        this.handlers.forEach(({ name, handler }) => this.editorView.dom.removeEventListener(name, handler));\n    }\n    update(editorView, prevState) {\n        if (this.cursorPos != null && prevState.doc != editorView.state.doc) {\n            // if we currently have an on-going drag event\n            // we need to update the cursor position again and update the overlay\n            if (this.lastDragEvent) {\n                let target = this.computeTarget(this.lastDragEvent);\n                if (target == this.cursorPos)\n                    this.updateOverlay();\n                else\n                    this.setCursor(target);\n            }\n            else {\n                this.updateOverlay();\n            }\n        }\n    }\n    setCursor(pos) {\n        if (pos == this.cursorPos)\n            return;\n        this.cursorPos = pos;\n        if (pos == null) {\n            this.element.parentNode.removeChild(this.element);\n            this.element = null;\n        }\n        else {\n            this.updateOverlay();\n        }\n    }\n    updateOverlay() {\n        let $pos = this.editorView.state.doc.resolve(this.cursorPos);\n        let isBlock = !$pos.parent.inlineContent, rect;\n        let editorDOM = this.editorView.dom, editorRect = editorDOM.getBoundingClientRect();\n        let scaleX = editorRect.width / editorDOM.offsetWidth, scaleY = editorRect.height / editorDOM.offsetHeight;\n        if (isBlock) {\n            let before = $pos.nodeBefore, after = $pos.nodeAfter;\n            if (before || after) {\n                let node = this.editorView.nodeDOM(this.cursorPos - (before ? before.nodeSize : 0));\n                if (node) {\n                    let nodeRect = node.getBoundingClientRect();\n                    let top = before ? nodeRect.bottom : nodeRect.top;\n                    if (before && after)\n                        top = (top + this.editorView.nodeDOM(this.cursorPos).getBoundingClientRect().top) / 2;\n                    let halfWidth = (this.width / 2) * scaleY;\n                    rect = { left: nodeRect.left, right: nodeRect.right, top: top - halfWidth, bottom: top + halfWidth };\n                }\n            }\n        }\n        if (!rect) {\n            let coords = this.editorView.coordsAtPos(this.cursorPos);\n            let halfWidth = (this.width / 2) * scaleX;\n            rect = { left: coords.left - halfWidth, right: coords.left + halfWidth, top: coords.top, bottom: coords.bottom };\n        }\n        let parent = this.editorView.dom.offsetParent;\n        if (!this.element) {\n            this.element = parent.appendChild(document.createElement(\"div\"));\n            if (this.class)\n                this.element.className = this.class;\n            this.element.style.cssText = \"position: absolute; z-index: 50; pointer-events: none;\";\n            if (this.color) {\n                this.element.style.backgroundColor = this.color;\n            }\n        }\n        this.element.classList.toggle(\"prosemirror-dropcursor-block\", isBlock);\n        this.element.classList.toggle(\"prosemirror-dropcursor-inline\", !isBlock);\n        let parentLeft, parentTop;\n        if (!parent || parent == document.body && getComputedStyle(parent).position == \"static\") {\n            parentLeft = -pageXOffset;\n            parentTop = -pageYOffset;\n        }\n        else {\n            let rect = parent.getBoundingClientRect();\n            let parentScaleX = rect.width / parent.offsetWidth, parentScaleY = rect.height / parent.offsetHeight;\n            parentLeft = rect.left - parent.scrollLeft * parentScaleX;\n            parentTop = rect.top - parent.scrollTop * parentScaleY;\n        }\n        this.element.style.left = (rect.left - parentLeft) / scaleX + \"px\";\n        this.element.style.top = (rect.top - parentTop) / scaleY + \"px\";\n        this.element.style.width = (rect.right - rect.left) / scaleX + \"px\";\n        this.element.style.height = (rect.bottom - rect.top) / scaleY + \"px\";\n    }\n    scheduleRemoval(timeout) {\n        clearTimeout(this.timeout);\n        this.timeout = setTimeout(() => this.setCursor(null), timeout);\n    }\n    computeTarget(event) {\n        let pos = this.editorView.posAtCoords({ left: event.clientX, top: event.clientY });\n        let node = pos && pos.inside >= 0 && this.editorView.state.doc.nodeAt(pos.inside);\n        let disableDropCursor = node && node.type.spec.disableDropCursor;\n        let disabled = typeof disableDropCursor == \"function\"\n            ? disableDropCursor(this.editorView, pos, event)\n            : disableDropCursor;\n        if (!pos || disabled)\n            return null;\n        let target = pos.pos;\n        if (this.editorView.dragging && this.editorView.dragging.slice) {\n            let point = dropPoint(this.editorView.state.doc, target, this.editorView.dragging.slice);\n            if (point != null)\n                target = point;\n        }\n        return target;\n    }\n    dragover(event) {\n        if (!this.editorView.editable)\n            return;\n        this.lastDragEvent = event;\n        let target = this.computeTarget(event);\n        if (target != null) {\n            this.setCursor(target);\n            this.scheduleRemoval(5000);\n        }\n    }\n    dragend() {\n        this.scheduleRemoval(20);\n    }\n    drop() {\n        this.scheduleRemoval(20);\n    }\n    dragleave(event) {\n        if (!this.editorView.dom.contains(event.relatedTarget))\n            this.setCursor(null);\n    }\n}\n\nexport { dropCursor };\n", "import { keydownHandler } from 'prosemirror-keymap';\nimport { Selection, NodeSelection, TextSelection, Plugin } from 'prosemirror-state';\nimport { Slice, Fragment } from 'prosemirror-model';\nimport { DecorationSet, Decoration } from 'prosemirror-view';\n\n/**\nGap cursor selections are represented using this class. Its\n`$anchor` and `$head` properties both point at the cursor position.\n*/\nclass GapCursor extends Selection {\n    /**\n    Create a gap cursor.\n    */\n    constructor($pos) {\n        super($pos, $pos);\n    }\n    map(doc, mapping) {\n        let $pos = doc.resolve(mapping.map(this.head));\n        return GapCursor.valid($pos) ? new GapCursor($pos) : Selection.near($pos);\n    }\n    content() { return Slice.empty; }\n    eq(other) {\n        return other instanceof GapCursor && other.head == this.head;\n    }\n    toJSON() {\n        return { type: \"gapcursor\", pos: this.head };\n    }\n    /**\n    @internal\n    */\n    static fromJSON(doc, json) {\n        if (typeof json.pos != \"number\")\n            throw new RangeError(\"Invalid input for GapCursor.fromJSON\");\n        return new GapCursor(doc.resolve(json.pos));\n    }\n    /**\n    @internal\n    */\n    getBookmark() { return new GapBookmark(this.anchor); }\n    /**\n    @internal\n    */\n    static valid($pos) {\n        let parent = $pos.parent;\n        if (parent.inlineContent || !closedBefore($pos) || !closedAfter($pos))\n            return false;\n        let override = parent.type.spec.allowGapCursor;\n        if (override != null)\n            return override;\n        let deflt = parent.contentMatchAt($pos.index()).defaultType;\n        return deflt && deflt.isTextblock;\n    }\n    /**\n    @internal\n    */\n    static findGapCursorFrom($pos, dir, mustMove = false) {\n        search: for (;;) {\n            if (!mustMove && GapCursor.valid($pos))\n                return $pos;\n            let pos = $pos.pos, next = null;\n            // Scan up from this position\n            for (let d = $pos.depth;; d--) {\n                let parent = $pos.node(d);\n                if (dir > 0 ? $pos.indexAfter(d) < parent.childCount : $pos.index(d) > 0) {\n                    next = parent.child(dir > 0 ? $pos.indexAfter(d) : $pos.index(d) - 1);\n                    break;\n                }\n                else if (d == 0) {\n                    return null;\n                }\n                pos += dir;\n                let $cur = $pos.doc.resolve(pos);\n                if (GapCursor.valid($cur))\n                    return $cur;\n            }\n            // And then down into the next node\n            for (;;) {\n                let inside = dir > 0 ? next.firstChild : next.lastChild;\n                if (!inside) {\n                    if (next.isAtom && !next.isText && !NodeSelection.isSelectable(next)) {\n                        $pos = $pos.doc.resolve(pos + next.nodeSize * dir);\n                        mustMove = false;\n                        continue search;\n                    }\n                    break;\n                }\n                next = inside;\n                pos += dir;\n                let $cur = $pos.doc.resolve(pos);\n                if (GapCursor.valid($cur))\n                    return $cur;\n            }\n            return null;\n        }\n    }\n}\nGapCursor.prototype.visible = false;\nGapCursor.findFrom = GapCursor.findGapCursorFrom;\nSelection.jsonID(\"gapcursor\", GapCursor);\nclass GapBookmark {\n    constructor(pos) {\n        this.pos = pos;\n    }\n    map(mapping) {\n        return new GapBookmark(mapping.map(this.pos));\n    }\n    resolve(doc) {\n        let $pos = doc.resolve(this.pos);\n        return GapCursor.valid($pos) ? new GapCursor($pos) : Selection.near($pos);\n    }\n}\nfunction needsGap(type) {\n    return type.isAtom || type.spec.isolating || type.spec.createGapCursor;\n}\nfunction closedBefore($pos) {\n    for (let d = $pos.depth; d >= 0; d--) {\n        let index = $pos.index(d), parent = $pos.node(d);\n        // At the start of this parent, look at next one\n        if (index == 0) {\n            if (parent.type.spec.isolating)\n                return true;\n            continue;\n        }\n        // See if the node before (or its first ancestor) is closed\n        for (let before = parent.child(index - 1);; before = before.lastChild) {\n            if ((before.childCount == 0 && !before.inlineContent) || needsGap(before.type))\n                return true;\n            if (before.inlineContent)\n                return false;\n        }\n    }\n    // Hit start of document\n    return true;\n}\nfunction closedAfter($pos) {\n    for (let d = $pos.depth; d >= 0; d--) {\n        let index = $pos.indexAfter(d), parent = $pos.node(d);\n        if (index == parent.childCount) {\n            if (parent.type.spec.isolating)\n                return true;\n            continue;\n        }\n        for (let after = parent.child(index);; after = after.firstChild) {\n            if ((after.childCount == 0 && !after.inlineContent) || needsGap(after.type))\n                return true;\n            if (after.inlineContent)\n                return false;\n        }\n    }\n    return true;\n}\n\n/**\nCreate a gap cursor plugin. When enabled, this will capture clicks\nnear and arrow-key-motion past places that don't have a normally\nselectable position nearby, and create a gap cursor selection for\nthem. The cursor is drawn as an element with class\n`ProseMirror-gapcursor`. You can either include\n`style/gapcursor.css` from the package's directory or add your own\nstyles to make it visible.\n*/\nfunction gapCursor() {\n    return new Plugin({\n        props: {\n            decorations: drawGapCursor,\n            createSelectionBetween(_view, $anchor, $head) {\n                return $anchor.pos == $head.pos && GapCursor.valid($head) ? new GapCursor($head) : null;\n            },\n            handleClick,\n            handleKeyDown,\n            handleDOMEvents: { beforeinput: beforeinput }\n        }\n    });\n}\nconst handleKeyDown = keydownHandler({\n    \"ArrowLeft\": arrow(\"horiz\", -1),\n    \"ArrowRight\": arrow(\"horiz\", 1),\n    \"ArrowUp\": arrow(\"vert\", -1),\n    \"ArrowDown\": arrow(\"vert\", 1)\n});\nfunction arrow(axis, dir) {\n    const dirStr = axis == \"vert\" ? (dir > 0 ? \"down\" : \"up\") : (dir > 0 ? \"right\" : \"left\");\n    return function (state, dispatch, view) {\n        let sel = state.selection;\n        let $start = dir > 0 ? sel.$to : sel.$from, mustMove = sel.empty;\n        if (sel instanceof TextSelection) {\n            if (!view.endOfTextblock(dirStr) || $start.depth == 0)\n                return false;\n            mustMove = false;\n            $start = state.doc.resolve(dir > 0 ? $start.after() : $start.before());\n        }\n        let $found = GapCursor.findGapCursorFrom($start, dir, mustMove);\n        if (!$found)\n            return false;\n        if (dispatch)\n            dispatch(state.tr.setSelection(new GapCursor($found)));\n        return true;\n    };\n}\nfunction handleClick(view, pos, event) {\n    if (!view || !view.editable)\n        return false;\n    let $pos = view.state.doc.resolve(pos);\n    if (!GapCursor.valid($pos))\n        return false;\n    let clickPos = view.posAtCoords({ left: event.clientX, top: event.clientY });\n    if (clickPos && clickPos.inside > -1 && NodeSelection.isSelectable(view.state.doc.nodeAt(clickPos.inside)))\n        return false;\n    view.dispatch(view.state.tr.setSelection(new GapCursor($pos)));\n    return true;\n}\n// This is a hack that, when a composition starts while a gap cursor\n// is active, quickly creates an inline context for the composition to\n// happen in, to avoid it being aborted by the DOM selection being\n// moved into a valid position.\nfunction beforeinput(view, event) {\n    if (event.inputType != \"insertCompositionText\" || !(view.state.selection instanceof GapCursor))\n        return false;\n    let { $from } = view.state.selection;\n    let insert = $from.parent.contentMatchAt($from.index()).findWrapping(view.state.schema.nodes.text);\n    if (!insert)\n        return false;\n    let frag = Fragment.empty;\n    for (let i = insert.length - 1; i >= 0; i--)\n        frag = Fragment.from(insert[i].createAndFill(null, frag));\n    let tr = view.state.tr.replace($from.pos, $from.pos, new Slice(frag, 0, 0));\n    tr.setSelection(TextSelection.near(tr.doc.resolve($from.pos + 1)));\n    view.dispatch(tr);\n    return false;\n}\nfunction drawGapCursor(state) {\n    if (!(state.selection instanceof GapCursor))\n        return null;\n    let node = document.createElement(\"div\");\n    node.className = \"ProseMirror-gapcursor\";\n    return DecorationSet.create(state.doc, [Decoration.widget(state.selection.head, node, { key: \"gapcursor\" })]);\n}\n\nexport { GapCursor, gapCursor };\n", "import { Extension } from '@tiptap/core'\nimport type { Node as ProseMirrorNode } from '@tiptap/pm/model'\nimport { Plugin, PluginKey } from '@tiptap/pm/state'\n\nexport interface CharacterCountOptions {\n  /**\n   * The maximum number of characters that should be allowed. Defaults to `0`.\n   * @default null\n   * @example 180\n   */\n  limit: number | null | undefined\n  /**\n   * The mode by which the size is calculated. If set to `textSize`, the textContent of the document is used.\n   * If set to `nodeSize`, the nodeSize of the document is used.\n   * @default 'textSize'\n   * @example 'textSize'\n   */\n  mode: 'textSize' | 'nodeSize'\n  /**\n   * Sets whether the content will be automatically trimmed when programatically setting content over the limit.\n   * If set to false, the user will be able to trim the text manually.\n   * @default true\n   * @example false\n   */\n  autoTrim?: boolean\n  /**\n   * The text counter function to use. Defaults to a simple character count.\n   * @default (text) => text.length\n   * @example (text) => [...new Intl.Segmenter().segment(text)].length\n   */\n  textCounter: (text: string) => number\n  /**\n   * The word counter function to use. Defaults to a simple word count.\n   * @default (text) => text.split(' ').filter(word => word !== '').length\n   * @example (text) => text.split(/\\s+/).filter(word => word !== '').length\n   */\n  wordCounter: (text: string) => number\n}\n\nexport interface CharacterCountStorage {\n  /**\n   * Get the number of characters for the current document.\n   * @param options The options for the character count. (optional)\n   * @param options.node The node to get the characters from. Defaults to the current document.\n   * @param options.mode The mode by which the size is calculated. If set to `textSize`, the textContent of the document is used.\n   */\n  characters: (options?: { node?: ProseMirrorNode; mode?: 'textSize' | 'nodeSize' }) => number\n\n  /**\n   * Get the number of words for the current document.\n   * @param options The options for the character count. (optional)\n   * @param options.node The node to get the words from. Defaults to the current document.\n   */\n  words: (options?: { node?: ProseMirrorNode }) => number\n}\n\ndeclare module '@tiptap/core' {\n  interface Storage {\n    characterCount: CharacterCountStorage\n  }\n}\n\n/**\n * This extension allows you to count the characters and words of your document.\n * @see https://tiptap.dev/api/extensions/character-count\n */\nexport const CharacterCount = Extension.create<CharacterCountOptions, CharacterCountStorage>({\n  name: 'characterCount',\n\n  addOptions() {\n    return {\n      limit: null,\n      autoTrim: true,\n      mode: 'textSize',\n      textCounter: text => text.length,\n      wordCounter: text => text.split(' ').filter(word => word !== '').length,\n    }\n  },\n\n  addStorage() {\n    return {\n      characters: () => 0,\n      words: () => 0,\n    }\n  },\n\n  onBeforeCreate() {\n    this.storage.characters = options => {\n      const node = options?.node || this.editor.state.doc\n      const mode = options?.mode || this.options.mode\n\n      if (mode === 'textSize') {\n        const text = node.textBetween(0, node.content.size, undefined, ' ')\n\n        return this.options.textCounter(text)\n      }\n\n      return node.nodeSize\n    }\n\n    this.storage.words = options => {\n      const node = options?.node || this.editor.state.doc\n      const text = node.textBetween(0, node.content.size, ' ', ' ')\n\n      return this.options.wordCounter(text)\n    }\n  },\n\n  addProseMirrorPlugins() {\n    let initialEvaluationDone = false\n\n    return [\n      new Plugin({\n        key: new PluginKey('characterCount'),\n        appendTransaction: (transactions, oldState, newState) => {\n          if (initialEvaluationDone) {\n            return\n          }\n\n          const limit = this.options.limit\n          const autoTrim = this.options.autoTrim\n\n          if (limit === null || limit === undefined || limit === 0 || autoTrim === false) {\n            initialEvaluationDone = true\n            return\n          }\n\n          const initialContentSize = this.storage.characters({ node: newState.doc })\n\n          if (initialContentSize > limit) {\n            const over = initialContentSize - limit\n            const from = 0\n            const to = over\n\n            console.warn(\n              `[CharacterCount] Initial content exceeded limit of ${limit} characters. Content was automatically trimmed.`,\n            )\n            const tr = newState.tr.deleteRange(from, to)\n            initialEvaluationDone = true\n            return tr\n          }\n\n          initialEvaluationDone = true\n        },\n        filterTransaction: (transaction, state) => {\n          const limit = this.options.limit\n\n          // Nothing has changed or no limit is defined. Ignore it.\n          if (!transaction.docChanged || limit === 0 || limit === null || limit === undefined) {\n            return true\n          }\n\n          const oldSize = this.storage.characters({ node: state.doc })\n          const newSize = this.storage.characters({ node: transaction.doc })\n\n          // Everything is in the limit. Good.\n          if (newSize <= limit) {\n            return true\n          }\n\n          // The limit has already been exceeded but will be reduced.\n          if (oldSize > limit && newSize > limit && newSize <= oldSize) {\n            return true\n          }\n\n          // The limit has already been exceeded and will be increased further.\n          if (oldSize > limit && newSize > limit && newSize > oldSize) {\n            return false\n          }\n\n          const isPaste = transaction.getMeta('paste')\n\n          // Block all exceeding transactions that were not pasted.\n          if (!isPaste) {\n            return false\n          }\n\n          // For pasted content, we try to remove the exceeding content.\n          const pos = transaction.selection.$head.pos\n          const over = newSize - limit\n          const from = pos - over\n          const to = pos\n\n          // It’s probably a bad idea to mutate transactions within `filterTransaction`\n          // but for now this is working fine.\n          transaction.deleteRange(from, to)\n\n          // In some situations, the limit will continue to be exceeded after trimming.\n          // This happens e.g. when truncating within a complex node (e.g. table)\n          // and ProseMirror has to close this node again.\n          // If this is the case, we prevent the transaction completely.\n          const updatedSize = this.storage.characters({ node: transaction.doc })\n\n          if (updatedSize > limit) {\n            return false\n          }\n\n          return true\n        },\n      }),\n    ]\n  },\n})\n", "import { Extension } from '@tiptap/core'\nimport { dropCursor } from '@tiptap/pm/dropcursor'\n\nexport interface DropcursorOptions {\n  /**\n   * The color of the drop cursor. Use `false` to apply no color and rely only on class.\n   * @default 'currentColor'\n   * @example 'red'\n   */\n  color?: string | false\n\n  /**\n   * The width of the drop cursor\n   * @default 1\n   * @example 2\n   */\n  width: number | undefined\n\n  /**\n   * The class of the drop cursor\n   * @default undefined\n   * @example 'drop-cursor'\n   */\n  class: string | undefined\n}\n\n/**\n * This extension allows you to add a drop cursor to your editor.\n * A drop cursor is a line that appears when you drag and drop content\n * in-between nodes.\n * @see https://tiptap.dev/api/extensions/dropcursor\n */\nexport const Dropcursor = Extension.create<DropcursorOptions>({\n  name: 'dropCursor',\n\n  addOptions() {\n    return {\n      color: 'currentColor',\n      width: 1,\n      class: undefined,\n    }\n  },\n\n  addProseMirrorPlugins() {\n    return [dropCursor(this.options)]\n  },\n})\n", "import { Extension } from '@tiptap/core'\nimport { Plugin, PluginKey } from '@tiptap/pm/state'\nimport { Decoration, DecorationSet } from '@tiptap/pm/view'\n\nexport interface FocusOptions {\n  /**\n   * The class name that should be added to the focused node.\n   * @default 'has-focus'\n   * @example 'is-focused'\n   */\n  className: string\n\n  /**\n   * The mode by which the focused node is determined.\n   * - All: All nodes are marked as focused.\n   * - Deepest: Only the deepest node is marked as focused.\n   * - Shallowest: Only the shallowest node is marked as focused.\n   *\n   * @default 'all'\n   * @example 'deepest'\n   * @example 'shallowest'\n   */\n  mode: 'all' | 'deepest' | 'shallowest'\n}\n\n/**\n * This extension allows you to add a class to the focused node.\n * @see https://www.tiptap.dev/api/extensions/focus\n */\nexport const Focus = Extension.create<FocusOptions>({\n  name: 'focus',\n\n  addOptions() {\n    return {\n      className: 'has-focus',\n      mode: 'all',\n    }\n  },\n\n  addProseMirrorPlugins() {\n    return [\n      new Plugin({\n        key: new PluginKey('focus'),\n        props: {\n          decorations: ({ doc, selection }) => {\n            const { isEditable, isFocused } = this.editor\n            const { anchor } = selection\n            const decorations: Decoration[] = []\n\n            if (!isEditable || !isFocused) {\n              return DecorationSet.create(doc, [])\n            }\n\n            // Maximum Levels\n            let maxLevels = 0\n\n            if (this.options.mode === 'deepest') {\n              doc.descendants((node, pos) => {\n                if (node.isText) {\n                  return\n                }\n\n                const isCurrent = anchor >= pos && anchor <= pos + node.nodeSize - 1\n\n                if (!isCurrent) {\n                  return false\n                }\n\n                maxLevels += 1\n              })\n            }\n\n            // Loop through current\n            let currentLevel = 0\n\n            doc.descendants((node, pos) => {\n              if (node.isText) {\n                return false\n              }\n\n              const isCurrent = anchor >= pos && anchor <= pos + node.nodeSize - 1\n\n              if (!isCurrent) {\n                return false\n              }\n\n              currentLevel += 1\n\n              const outOfScope =\n                (this.options.mode === 'deepest' && maxLevels - currentLevel > 0) ||\n                (this.options.mode === 'shallowest' && currentLevel > 1)\n\n              if (outOfScope) {\n                return this.options.mode === 'deepest'\n              }\n\n              decorations.push(\n                Decoration.node(pos, pos + node.nodeSize, {\n                  class: this.options.className,\n                }),\n              )\n            })\n\n            return DecorationSet.create(doc, decorations)\n          },\n        },\n      }),\n    ]\n  },\n})\n", "import type { ParentConfig } from '@tiptap/core'\nimport { callOrReturn, Extension, getExtensionField } from '@tiptap/core'\nimport { gapCursor } from '@tiptap/pm/gapcursor'\n\ndeclare module '@tiptap/core' {\n  interface NodeConfig<Options, Storage> {\n    /**\n     * A function to determine whether the gap cursor is allowed at the current position. Must return `true` or `false`.\n     * @default null\n     */\n    allowGapCursor?:\n      | boolean\n      | null\n      | ((this: {\n          name: string\n          options: Options\n          storage: Storage\n          parent: ParentConfig<NodeConfig<Options>>['allowGapCursor']\n        }) => boolean | null)\n  }\n}\n\n/**\n * This extension allows you to add a gap cursor to your editor.\n * A gap cursor is a cursor that appears when you click on a place\n * where no content is present, for example inbetween nodes.\n * @see https://tiptap.dev/api/extensions/gapcursor\n */\nexport const Gapcursor = Extension.create({\n  name: 'gapCursor',\n\n  addProseMirrorPlugins() {\n    return [gapCursor()]\n  },\n\n  extendNodeSchema(extension) {\n    const context = {\n      name: extension.name,\n      options: extension.options,\n      storage: extension.storage,\n    }\n\n    return {\n      allowGapCursor: callOrReturn(getExtensionField(extension, 'allowGapCursor', context)) ?? null,\n    }\n  },\n})\n", "import { PluginKey } from '@tiptap/pm/state'\nimport type { DecorationSet } from '@tiptap/pm/view'\n\n/** The default data attribute label */\nexport const DEFAULT_DATA_ATTRIBUTE = 'placeholder'\n\n/** The plugin key used to store and read the placeholder decoration set */\nexport const PLUGIN_KEY = new PluginKey<DecorationSet>('tiptap__placeholder')\n", "import type { Editor } from '@tiptap/core'\nimport type { Node } from '@tiptap/pm/model'\nimport { Decoration } from '@tiptap/pm/view'\n\nimport type { PlaceholderOptions } from '../types.js'\n\n/**\n * Creates a ProseMirror node decoration that applies a placeholder\n * CSS class and data attribute to an empty node.\n * @param options.editor - The editor instance\n * @param options.pos - The position of the node in the document\n * @param options.node - The ProseMirror node\n * @param options.isEmptyDoc - Whether the entire document is empty\n * @param options.hasAnchor - Whether the selection anchor is within the node\n * @param options.dataAttribute - The data attribute name (e.g. `data-placeholder`)\n * @param options.classes - CSS classes for empty nodes and the empty editor\n * @param options.placeholder - The placeholder text or a function that returns it\n * @returns A ProseMirror node decoration with placeholder classes and data attribute\n */\nexport function createPlaceholderDecoration(options: {\n  editor: Editor\n  pos: number\n  node: Node\n  isEmptyDoc: boolean\n  hasAnchor: boolean\n  dataAttribute: string\n  classes: {\n    emptyEditor: PlaceholderOptions['emptyEditorClass']\n    emptyNode: string\n  }\n  placeholder: PlaceholderOptions['placeholder']\n}) {\n  const {\n    editor,\n    placeholder,\n    dataAttribute,\n    pos,\n    node,\n    isEmptyDoc,\n    hasAnchor,\n    classes: { emptyNode, emptyEditor },\n  } = options\n  const classes = [emptyNode]\n\n  if (isEmptyDoc) {\n    classes.push(emptyEditor)\n  }\n\n  return Decoration.node(pos, pos + node.nodeSize, {\n    class: classes.join(' '),\n    [dataAttribute]:\n      typeof placeholder === 'function'\n        ? placeholder({\n            editor,\n            node,\n            pos,\n            hasAnchor,\n          })\n        : placeholder,\n  })\n}\n", "import type { Editor } from '@tiptap/core'\nimport { isNodeEmpty } from '@tiptap/core'\nimport type { Node } from '@tiptap/pm/model'\nimport type { Selection } from '@tiptap/pm/state'\nimport type { Decoration } from '@tiptap/pm/view'\nimport { DecorationSet } from '@tiptap/pm/view'\n\nimport type { PlaceholderOptions } from '../types.js'\nimport { createPlaceholderDecoration } from './createPlaceholderDecoration.js'\n\nfunction resolveEmptyNodeClass(\n  emptyNodeClass: PlaceholderOptions['emptyNodeClass'],\n  props: { editor: Editor; node: Node; pos: number; hasAnchor: boolean },\n): string {\n  return typeof emptyNodeClass === 'function' ? emptyNodeClass(props) : emptyNodeClass\n}\n\n/**\n * Scans a document range for empty textblocks that should receive placeholder\n * decorations. Used by the slow path and incremental state updates.\n */\nexport function scanRangeForDecorations({\n  editor,\n  options,\n  dataAttribute,\n  doc,\n  selection,\n  from,\n  to,\n}: {\n  editor: Editor\n  options: PlaceholderOptions\n  dataAttribute: string\n  doc: Node\n  selection: Selection\n  from: number\n  to: number\n}): Decoration[] {\n  const { anchor } = selection\n  const decorations: Decoration[] = []\n  const isEmptyDoc = editor.isEmpty\n\n  doc.nodesBetween(from, to, (node, pos) => {\n    const hasAnchor = anchor >= pos && anchor <= pos + node.nodeSize\n    const isEmpty = !node.isLeaf && isNodeEmpty(node)\n\n    if (!node.type.isTextblock) {\n      return options.includeChildren\n    }\n\n    if ((hasAnchor || !options.showOnlyCurrent) && isEmpty) {\n      decorations.push(\n        createPlaceholderDecoration({\n          editor,\n          isEmptyDoc,\n          dataAttribute,\n          hasAnchor,\n          placeholder: options.placeholder,\n          classes: {\n            emptyEditor: options.emptyEditorClass,\n            emptyNode: resolveEmptyNodeClass(options.emptyNodeClass, {\n              editor,\n              node,\n              pos,\n              hasAnchor,\n            }),\n          },\n          node,\n          pos,\n        }),\n      )\n    }\n\n    return options.includeChildren\n  })\n\n  return decorations\n}\n\n/**\n * Builds the placeholder decorations for the current document state.\n * @param options.editor - The editor instance.\n * @param options.options - The resolved placeholder options.\n * @param options.dataAttribute - The prepared `data-*` attribute name.\n * @param options.doc - The current document node.\n * @param options.selection - The current selection.\n * @returns A decoration set, or `null` when no placeholders should be shown.\n */\nexport function buildPlaceholderDecorations({\n  editor,\n  options,\n  dataAttribute,\n  doc,\n  selection,\n}: {\n  editor: Editor\n  options: PlaceholderOptions\n  dataAttribute: string\n  doc: Node\n  selection: Selection\n}): DecorationSet | null {\n  const active = editor.isEditable || !options.showOnlyWhenEditable\n\n  if (!active) {\n    return null\n  }\n\n  const { anchor } = selection\n  const decorations: Decoration[] = []\n  const isEmptyDoc = editor.isEmpty\n\n  const useResolvedPath = options.showOnlyCurrent && !options.includeChildren\n\n  if (useResolvedPath) {\n    const resolved = doc.resolve(anchor)\n\n    // When the selection spans the whole document (e.g. an `AllSelection`\n    // after Cmd+A), the anchor resolves to the document level (depth 0). In\n    // that case the relevant textblock is the node directly after the\n    // position rather than an ancestor. otherwise the placeholder would\n    // disappear after selecting all and deleting.\n    const node = resolved.depth > 0 ? resolved.node(1) : resolved.nodeAfter\n    const nodeStart = resolved.depth > 0 ? resolved.before(1) : anchor\n\n    if (node && node.type.isTextblock && isNodeEmpty(node)) {\n      const hasAnchor = anchor >= nodeStart && anchor <= nodeStart + node.nodeSize\n\n      decorations.push(\n        createPlaceholderDecoration({\n          editor,\n          isEmptyDoc,\n          dataAttribute,\n          hasAnchor,\n          placeholder: options.placeholder,\n          classes: {\n            emptyEditor: options.emptyEditorClass,\n            emptyNode: resolveEmptyNodeClass(options.emptyNodeClass, {\n              editor,\n              node,\n              pos: nodeStart,\n              hasAnchor,\n            }),\n          },\n          node,\n          pos: nodeStart,\n        }),\n      )\n    }\n  } else {\n    decorations.push(\n      ...scanRangeForDecorations({\n        editor,\n        options,\n        dataAttribute,\n        doc,\n        selection,\n        from: 0,\n        to: doc.content.size,\n      }),\n    )\n  }\n\n  return DecorationSet.create(doc, decorations)\n}\n", "import type { Node } from '@tiptap/pm/model'\n\n/**\n * Resolves a document position to the `[from, to)` range of its containing\n * top-level block node in absolute document positions.\n */\nexport function resolveTopLevelRange(doc: Node, pos: number): { from: number; to: number } {\n  const resolved = doc.resolve(pos)\n\n  if (resolved.depth === 0) {\n    const node = resolved.nodeAfter ?? resolved.nodeBefore\n\n    if (!node) {\n      return { from: pos, to: pos }\n    }\n\n    const nodePos = resolved.nodeAfter ? pos : pos - node.nodeSize\n\n    return { from: nodePos, to: nodePos + node.nodeSize }\n  }\n\n  const topLevelPos = resolved.before(1)\n  const node = resolved.node(1)\n\n  return { from: topLevelPos, to: topLevelPos + node.nodeSize }\n}\n\n/**\n * Clamps a top-level block range from `resolveTopLevelRange` to the document\n * content, giving the positions used by `Node#nodesBetween` and `Node#forEach`\n * offsets.\n *\n * A top-level node at `Node#forEach` offset `n` already sits at document\n * position `n`, so the range must not be shifted: a node decoration spans\n * exactly `[n, n + nodeSize]` and has to stay inside the range to be replaced.\n */\nexport function toContentRelativeRange(\n  doc: Node,\n  range: { from: number; to: number },\n): { from: number; to: number } {\n  return {\n    from: Math.max(0, range.from),\n    to: Math.min(doc.content.size, range.to),\n  }\n}\n\n/**\n * Returns the top-level block ranges that intersect a document change range.\n * Input `from`/`to` are absolute positions (e.g. from `getChangedRanges`).\n * Returned ranges are content-relative, matching `Node#forEach` offsets.\n */\nexport function getTopLevelBlocksInRange(\n  doc: Node,\n  from: number,\n  to: number,\n): Array<{ from: number; to: number }> {\n  const ranges: Array<{ from: number; to: number }> = []\n\n  doc.forEach((node, offset) => {\n    const nodeStart = offset\n    const nodeEnd = nodeStart + node.nodeSize\n    const absNodeStart = nodeStart + 1\n    const absNodeEnd = nodeEnd + 1\n\n    if (absNodeStart < to && absNodeEnd > from) {\n      ranges.push({ from: nodeStart, to: nodeEnd })\n    }\n  })\n\n  return ranges\n}\n\n/**\n * Sorts ranges by start position and merges overlapping or adjacent ranges.\n */\nexport function mergeRanges(\n  ranges: Array<{ from: number; to: number }>,\n): Array<{ from: number; to: number }> {\n  if (ranges.length === 0) {\n    return []\n  }\n\n  const sorted = [...ranges].sort((a, b) => a.from - b.from)\n  const merged: Array<{ from: number; to: number }> = [{ ...sorted[0] }]\n\n  for (let i = 1; i < sorted.length; i += 1) {\n    const last = merged[merged.length - 1]\n    const current = sorted[i]\n\n    if (current.from <= last.to) {\n      last.to = Math.max(last.to, current.to)\n    } else {\n      merged.push({ ...current })\n    }\n  }\n\n  return merged\n}\n", "import type { Editor } from '@tiptap/core'\nimport { getChangedRanges } from '@tiptap/core'\nimport type { Node } from '@tiptap/pm/model'\nimport type { EditorState, StateField, Transaction } from '@tiptap/pm/state'\nimport type { Selection } from '@tiptap/pm/state'\nimport { DecorationSet } from '@tiptap/pm/view'\n\nimport type { PlaceholderOptions } from '../types.js'\nimport {\n  buildPlaceholderDecorations,\n  scanRangeForDecorations,\n} from './buildPlaceholderDecorations.js'\nimport {\n  getTopLevelBlocksInRange,\n  mergeRanges,\n  resolveTopLevelRange,\n  toContentRelativeRange,\n} from './resolveTopLevelRange.js'\n\n/** Options passed to {@link createPlaceholderStateField}. */\nexport type CreatePlaceholderStateFieldOptions = {\n  editor: Editor\n  options: PlaceholderOptions\n  dataAttribute: string\n}\n\n/**\n * Expands a single changed range to the top-level blocks it touches.\n * Also resolves blocks at range boundaries so split/merge edits update\n * adjacent empty nodes (e.g. a new paragraph after Enter).\n */\nfunction collectBlocksForChange(\n  doc: Node,\n  change: { from: number; to: number },\n): Array<{ from: number; to: number }> {\n  const ranges = getTopLevelBlocksInRange(doc, change.from, change.to)\n\n  ranges.push(toContentRelativeRange(doc, resolveTopLevelRange(doc, change.from)))\n\n  if (change.to > change.from) {\n    ranges.push(\n      toContentRelativeRange(\n        doc,\n        resolveTopLevelRange(doc, Math.min(change.to, doc.content.size + 1) - 1),\n      ),\n    )\n  } else if (change.from < doc.content.size + 1) {\n    ranges.push(\n      toContentRelativeRange(\n        doc,\n        resolveTopLevelRange(doc, Math.min(change.from + 1, doc.content.size)),\n      ),\n    )\n  }\n\n  return ranges\n}\n\n/**\n * Collects content-relative top-level block ranges that need placeholder\n * decorations recomputed after a transaction.\n */\nfunction collectRescanRanges(\n  tr: Transaction,\n  oldState: EditorState,\n  newState: EditorState,\n): Array<{ from: number; to: number }> {\n  const ranges: Array<{ from: number; to: number }> = []\n\n  if (tr.docChanged) {\n    const changes = getChangedRanges(tr)\n\n    for (const change of changes) {\n      ranges.push(...collectBlocksForChange(newState.doc, change.newRange))\n    }\n  }\n\n  if (tr.selectionSet) {\n    ranges.push(\n      toContentRelativeRange(\n        newState.doc,\n        resolveTopLevelRange(newState.doc, tr.mapping.map(oldState.selection.anchor)),\n      ),\n    )\n    ranges.push(\n      toContentRelativeRange(\n        newState.doc,\n        resolveTopLevelRange(newState.doc, newState.selection.anchor),\n      ),\n    )\n  }\n\n  return mergeRanges(ranges)\n}\n\n/** Clamps a content-relative range to `[0, doc.content.size]`. */\nfunction clampRange(from: number, to: number, doc: Node): { from: number; to: number } {\n  const clampedFrom = Math.max(0, Math.min(from, doc.content.size))\n  const clampedTo = Math.max(clampedFrom, Math.min(to, doc.content.size))\n\n  return { from: clampedFrom, to: clampedTo }\n}\n\n/**\n * Removes and rebuilds placeholder decorations within the given ranges.\n * Only drops decorations fully contained in a range so mapped decorations\n * on neighbouring blocks (e.g. at a block boundary) are kept intact.\n */\nfunction updateDecorationsInRanges({\n  decorations,\n  ranges,\n  editor,\n  options,\n  dataAttribute,\n  doc,\n  selection,\n}: {\n  decorations: DecorationSet\n  ranges: Array<{ from: number; to: number }>\n  editor: Editor\n  options: PlaceholderOptions\n  dataAttribute: string\n  doc: Node\n  selection: Selection\n}): DecorationSet {\n  let next = decorations\n\n  for (const range of ranges) {\n    const { from, to } = clampRange(range.from, range.to, doc)\n    const existing = next\n      .find(from, to)\n      .filter(decoration => decoration.from >= from && decoration.to <= to)\n\n    if (existing.length) {\n      next = next.remove(existing)\n    }\n\n    const newDecos = scanRangeForDecorations({\n      editor,\n      options,\n      dataAttribute,\n      doc,\n      selection,\n      from,\n      to,\n    })\n\n    if (newDecos.length) {\n      next = next.add(doc, newDecos)\n    }\n  }\n\n  return next\n}\n\n/**\n * Creates the incremental `StateField<DecorationSet>` used by the slow path\n * (`showOnlyCurrent: false` or `includeChildren: true`).\n *\n * Decorations are mapped through each transaction and only recomputed for\n * top-level blocks touched by document or selection changes.\n * @param options.editor - The editor instance.\n * @param options.options - The resolved placeholder options.\n * @param options.dataAttribute - The prepared `data-*` attribute name.\n * @returns A ProseMirror state field storing the placeholder decoration set.\n */\nexport function createPlaceholderStateField({\n  editor,\n  options,\n  dataAttribute,\n}: CreatePlaceholderStateFieldOptions): StateField<DecorationSet> {\n  return {\n    init(_config, state: EditorState) {\n      const decorations = buildPlaceholderDecorations({\n        editor,\n        options,\n        dataAttribute,\n        doc: state.doc,\n        selection: state.selection,\n      })\n\n      return decorations ?? DecorationSet.empty\n    },\n\n    apply(tr: Transaction, prev: DecorationSet, oldState: EditorState, newState: EditorState) {\n      if (!tr.docChanged && !tr.selectionSet) {\n        return prev\n      }\n\n      const mapped = prev.map(tr.mapping, tr.doc)\n      const ranges = collectRescanRanges(tr, oldState, newState)\n\n      return updateDecorationsInRanges({\n        decorations: mapped,\n        ranges,\n        editor,\n        options,\n        dataAttribute,\n        doc: newState.doc,\n        selection: newState.selection,\n      })\n    },\n  }\n}\n", "/**\n * Prepares the placeholder attribute by ensuring it is properly formatted.\n * @param attr - The placeholder attribute string.\n * @returns The prepared placeholder attribute string.\n */\nexport function preparePlaceholderAttribute(attr: string): string {\n  return (\n    attr\n      // replace whitespace with dashes\n      .replace(/\\s+/g, '-')\n      // replace non-alphanumeric  characters\n      // or special chars like $, %, &, etc.\n      // but not dashes\n      .replace(/[^a-zA-Z0-9-]/g, '')\n      // and replace any numeric character at the start\n      .replace(/^[0-9-]+/, '')\n      // and finally replace any stray, leading dashes\n      .replace(/^-+/, '')\n      .toLowerCase()\n  )\n}\n", "import type { Editor } from '@tiptap/core'\nimport { Plugin } from '@tiptap/pm/state'\nimport { DecorationSet } from '@tiptap/pm/view'\n\nimport { DEFAULT_DATA_ATTRIBUTE, PLUGIN_KEY } from '../constants.js'\nimport type { PlaceholderOptions } from '../types.js'\nimport { buildPlaceholderDecorations } from '../utils/buildPlaceholderDecorations.js'\nimport { createPlaceholderStateField } from '../utils/placeholderStateField.js'\nimport { preparePlaceholderAttribute } from '../utils/preparePlaceholderAttribute.js'\n\nexport type CreatePluginOptions = {\n  editor: Editor\n  options: PlaceholderOptions\n}\n\n/**\n * Creates the ProseMirror plugin that renders placeholder decorations.\n * @param options.editor - The editor instance.\n * @param options.options - The resolved placeholder options.\n * @returns The configured placeholder plugin.\n */\nexport function createPlaceholderPlugin({ editor, options }: CreatePluginOptions) {\n  const dataAttribute = options.dataAttribute\n    ? `data-${preparePlaceholderAttribute(options.dataAttribute)}`\n    : `data-${DEFAULT_DATA_ATTRIBUTE}`\n\n  const useResolvedPath = options.showOnlyCurrent && !options.includeChildren\n\n  return new Plugin({\n    key: PLUGIN_KEY,\n    ...(useResolvedPath\n      ? {}\n      : {\n          state: createPlaceholderStateField({ editor, options, dataAttribute }),\n        }),\n    props: {\n      decorations: useResolvedPath\n        ? ({ doc, selection }) =>\n            buildPlaceholderDecorations({ editor, options, dataAttribute, doc, selection })\n        : state => {\n            if (options.showOnlyWhenEditable && !editor.isEditable) {\n              return DecorationSet.empty\n            }\n\n            return PLUGIN_KEY.getState(state) ?? DecorationSet.empty\n          },\n    },\n  })\n}\n", "import { Extension } from '@tiptap/core'\n\nimport { DEFAULT_DATA_ATTRIBUTE } from './constants.js'\nimport { createPlaceholderPlugin } from './plugins/PlaceholderPlugin.js'\nimport type { PlaceholderOptions } from './types.js'\n\n/**\n * This extension allows you to add a placeholder to your editor.\n * A placeholder is a text that appears when the editor or a node is empty.\n * @see https://www.tiptap.dev/api/extensions/placeholder\n */\nexport const Placeholder = Extension.create<PlaceholderOptions>({\n  name: 'placeholder',\n\n  addOptions() {\n    return {\n      emptyEditorClass: 'is-editor-empty',\n      emptyNodeClass: 'is-empty',\n      dataAttribute: DEFAULT_DATA_ATTRIBUTE,\n      placeholder: 'Write something …',\n      showOnlyWhenEditable: true,\n      showOnlyCurrent: true,\n      includeChildren: false,\n    }\n  },\n\n  addProseMirrorPlugins() {\n    return [createPlaceholderPlugin({ editor: this.editor, options: this.options })]\n  },\n})\n", "import { Extension, isNodeSelection, type Editor } from '@tiptap/core'\nimport { Plugin, PluginKey, type EditorState } from '@tiptap/pm/state'\nimport type { EditorView } from '@tiptap/pm/view'\nimport { Decoration, DecorationSet } from '@tiptap/pm/view'\n\nexport type SelectionOptions = {\n  /**\n   * The class name that should be added to the selected text.\n   * @default 'selection'\n   * @example 'is-selected'\n   */\n  className: string\n}\n\n/**\n * Whether the native browser selection should be cleared on blur and restored on focus.\n * Only applies to non-empty text selections in an editable editor.\n */\nfunction shouldSyncDomSelection(state: EditorState, editor: Editor): boolean {\n  return !state.selection.empty && !isNodeSelection(state.selection) && editor.isEditable\n}\n\n/**\n * Whether the selection decoration should be rendered to keep the selection\n * visible while the editor is blurred (and not dragging).\n */\nfunction shouldPreserveSelection(state: EditorState, editor: Editor): boolean {\n  return shouldSyncDomSelection(state, editor) && !editor.isFocused && !editor.view.dragging\n}\n\nfunction clearDomSelection() {\n  window.getSelection()?.removeAllRanges()\n}\n\n/**\n * Sync the native selection from the editor state.\n * @see https://prosemirror.net/docs/ref/#view.EditorView.focus\n */\nfunction restoreDomSelection(view: EditorView) {\n  view.focus()\n}\n\n/**\n * This extension allows you to add a class to the selected text when the editor is blurred.\n * It clears the native browser selection on blur (so `::selection` styles do not overlap the\n * decoration) and restores it when the editor is focused again.\n * @see https://www.tiptap.dev/api/extensions/selection\n */\nexport const Selection = Extension.create<SelectionOptions>({\n  name: 'selection',\n\n  addOptions() {\n    return {\n      className: 'selection',\n    }\n  },\n\n  addProseMirrorPlugins() {\n    const { editor, options } = this\n\n    return [\n      new Plugin({\n        key: new PluginKey('selection'),\n        props: {\n          decorations(state) {\n            if (!shouldPreserveSelection(state, editor)) {\n              return null\n            }\n\n            return DecorationSet.create(state.doc, [\n              Decoration.inline(state.selection.from, state.selection.to, {\n                class: options.className,\n              }),\n            ])\n          },\n          handleDOMEvents: {\n            blur(view) {\n              if (!shouldSyncDomSelection(view.state, editor)) {\n                return false\n              }\n\n              clearDomSelection()\n\n              return false\n            },\n            focus(view) {\n              if (!shouldSyncDomSelection(view.state, editor)) {\n                return false\n              }\n\n              requestAnimationFrame(() => {\n                if (!editor.isDestroyed && view.hasFocus()) {\n                  restoreDomSelection(view)\n                }\n              })\n\n              return false\n            },\n          },\n        },\n      }),\n    ]\n  },\n})\n\nexport default Selection\n", "import { Extension } from '@tiptap/core'\nimport type { Node, NodeType } from '@tiptap/pm/model'\nimport { Plugin, PluginKey } from '@tiptap/pm/state'\n\nexport const skipTrailingNodeMeta = 'skipTrailingNode'\n\nfunction nodeEqualsType({\n  types,\n  node,\n}: {\n  types: NodeType | NodeType[]\n  node: Node | null | undefined\n}) {\n  return (node && Array.isArray(types) && types.includes(node.type)) || node?.type === types\n}\n\n/**\n * Extension based on:\n * - https://github.com/ueberdosis/tiptap/blob/v1/packages/tiptap-extensions/src/extensions/TrailingNode.js\n * - https://github.com/remirror/remirror/blob/e0f1bec4a1e8073ce8f5500d62193e52321155b9/packages/prosemirror-trailing-node/src/trailing-node-plugin.ts\n */\n\nexport interface TrailingNodeOptions {\n  /**\n   * The node type that should be inserted at the end of the document.\n   * @note the node will always be added to the `notAfter` lists to\n   * prevent an infinite loop.\n   * @default undefined\n   */\n  node?: string\n  /**\n   * The node types after which the trailing node should not be inserted.\n   * @default ['paragraph']\n   */\n  notAfter?: string | string[]\n}\n\n/**\n * This extension allows you to add an extra node at the end of the document.\n * @see https://www.tiptap.dev/api/extensions/trailing-node\n */\nexport const TrailingNode = Extension.create<TrailingNodeOptions>({\n  name: 'trailingNode',\n\n  addOptions() {\n    return {\n      node: undefined,\n      notAfter: [],\n    }\n  },\n\n  addProseMirrorPlugins() {\n    const plugin = new PluginKey(this.name)\n    const defaultNode =\n      this.options.node ||\n      this.editor.schema.topNodeType.contentMatch.defaultType?.name ||\n      'paragraph'\n\n    const disabledNodes = Object.entries(this.editor.schema.nodes)\n      .map(([, value]) => value)\n      .filter(node => (this.options.notAfter || []).concat(defaultNode).includes(node.name))\n\n    return [\n      new Plugin({\n        key: plugin,\n        appendTransaction: (transactions, __, state) => {\n          const { doc, tr, schema } = state\n          const shouldInsertNodeAtEnd = plugin.getState(state)\n          const endPosition = doc.content.size\n          const type = schema.nodes[defaultNode]\n\n          if (transactions.some(transaction => transaction.getMeta(skipTrailingNodeMeta))) {\n            return\n          }\n\n          if (!shouldInsertNodeAtEnd) {\n            return\n          }\n\n          return tr.insert(endPosition, type.create())\n        },\n        state: {\n          init: (_, state) => {\n            const lastNode = state.tr.doc.lastChild\n\n            return !nodeEqualsType({ node: lastNode, types: disabledNodes })\n          },\n          apply: (tr, value) => {\n            if (!tr.docChanged) {\n              return value\n            }\n\n            // Ignore transactions from UniqueID extension to prevent infinite loops\n            // when UniqueID adds IDs to newly inserted trailing nodes\n            if (tr.getMeta('__uniqueIDTransaction')) {\n              return value\n            }\n\n            const lastNode = tr.doc.lastChild\n\n            return !nodeEqualsType({ node: lastNode, types: disabledNodes })\n          },\n        },\n      }),\n    ]\n  },\n})\n", "import { Extension } from '@tiptap/core'\nimport { history, redo, undo } from '@tiptap/pm/history'\n\nexport interface UndoRedoOptions {\n  /**\n   * The amount of history events that are collected before the oldest events are discarded.\n   * @default 100\n   * @example 50\n   */\n  depth: number\n\n  /**\n   * The delay (in milliseconds) between changes after which a new group should be started.\n   * @default 500\n   * @example 1000\n   */\n  newGroupDelay: number\n}\n\ndeclare module '@tiptap/core' {\n  interface Commands<ReturnType> {\n    undoRedo: {\n      /**\n       * Undo recent changes\n       * @example editor.commands.undo()\n       */\n      undo: () => ReturnType\n      /**\n       * Reapply reverted changes\n       * @example editor.commands.redo()\n       */\n      redo: () => ReturnType\n    }\n  }\n}\n\n/**\n * This extension allows you to undo and redo recent changes.\n * @see https://www.tiptap.dev/api/extensions/undo-redo\n *\n * **Important**: If the `@tiptap/extension-collaboration` package is used, make sure to remove\n * the `undo-redo` extension, as it is not compatible with the `collaboration` extension.\n *\n * `@tiptap/extension-collaboration` uses its own history implementation.\n */\nexport const UndoRedo = Extension.create<UndoRedoOptions>({\n  name: 'undoRedo',\n\n  addOptions() {\n    return {\n      depth: 100,\n      newGroupDelay: 500,\n    }\n  },\n\n  addCommands() {\n    return {\n      undo:\n        () =>\n        ({ state, dispatch }) => {\n          return undo(state, dispatch)\n        },\n      redo:\n        () =>\n        ({ state, dispatch }) => {\n          return redo(state, dispatch)\n        },\n    }\n  },\n\n  addProseMirrorPlugins() {\n    return [history(this.options)]\n  },\n\n  addKeyboardShortcuts() {\n    return {\n      'Mod-z': () => this.editor.commands.undo(),\n      'Shift-Mod-z': () => this.editor.commands.redo(),\n      'Mod-y': () => this.editor.commands.redo(),\n\n      // Russian keyboard layouts\n      'Mod-я': () => this.editor.commands.undo(),\n      'Shift-Mod-я': () => this.editor.commands.redo(),\n    }\n  },\n})\n", "import { Extension } from '@tiptap/core'\nimport type { BlockquoteOptions } from '@tiptap/extension-blockquote'\nimport { Blockquote } from '@tiptap/extension-blockquote'\nimport type { BoldOptions } from '@tiptap/extension-bold'\nimport { Bold } from '@tiptap/extension-bold'\nimport type { CodeOptions } from '@tiptap/extension-code'\nimport { Code } from '@tiptap/extension-code'\nimport type { CodeBlockOptions } from '@tiptap/extension-code-block'\nimport { CodeBlock } from '@tiptap/extension-code-block'\nimport { Document } from '@tiptap/extension-document'\nimport type { HardBreakOptions } from '@tiptap/extension-hard-break'\nimport { HardBreak } from '@tiptap/extension-hard-break'\nimport type { HeadingOptions } from '@tiptap/extension-heading'\nimport { Heading } from '@tiptap/extension-heading'\nimport type { HorizontalRuleOptions } from '@tiptap/extension-horizontal-rule'\nimport { HorizontalRule } from '@tiptap/extension-horizontal-rule'\nimport type { ItalicOptions } from '@tiptap/extension-italic'\nimport { Italic } from '@tiptap/extension-italic'\nimport type { LinkOptions } from '@tiptap/extension-link'\nimport { Link } from '@tiptap/extension-link'\nimport type {\n  BulletListOptions,\n  ListItemOptions,\n  ListKeymapOptions,\n  OrderedListOptions,\n} from '@tiptap/extension-list'\nimport { BulletList, ListItem, ListKeymap, OrderedList } from '@tiptap/extension-list'\nimport type { ParagraphOptions } from '@tiptap/extension-paragraph'\nimport { Paragraph } from '@tiptap/extension-paragraph'\nimport type { StrikeOptions } from '@tiptap/extension-strike'\nimport { Strike } from '@tiptap/extension-strike'\nimport { Text } from '@tiptap/extension-text'\nimport type { UnderlineOptions } from '@tiptap/extension-underline'\nimport { Underline } from '@tiptap/extension-underline'\nimport type { DropcursorOptions, TrailingNodeOptions, UndoRedoOptions } from '@tiptap/extensions'\nimport { Dropcursor, Gapcursor, TrailingNode, UndoRedo } from '@tiptap/extensions'\n\nexport interface StarterKitOptions {\n  /**\n   * If set to false, the blockquote extension will not be registered\n   * @example blockquote: false\n   */\n  blockquote: Partial<BlockquoteOptions> | false\n\n  /**\n   * If set to false, the bold extension will not be registered\n   * @example bold: false\n   */\n  bold: Partial<BoldOptions> | false\n\n  /**\n   * If set to false, the bulletList extension will not be registered\n   * @example bulletList: false\n   */\n  bulletList: Partial<BulletListOptions> | false\n\n  /**\n   * If set to false, the code extension will not be registered\n   * @example code: false\n   */\n  code: Partial<CodeOptions> | false\n\n  /**\n   * If set to false, the codeBlock extension will not be registered\n   * @example codeBlock: false\n   */\n  codeBlock: Partial<CodeBlockOptions> | false\n\n  /**\n   * If set to false, the document extension will not be registered\n   * @example document: false\n   */\n  document: false\n\n  /**\n   * If set to false, the dropcursor extension will not be registered\n   * @example dropcursor: false\n   */\n  dropcursor: Partial<DropcursorOptions> | false\n\n  /**\n   * If set to false, the gapcursor extension will not be registered\n   * @example gapcursor: false\n   */\n  gapcursor: false\n\n  /**\n   * If set to false, the hardBreak extension will not be registered\n   * @example hardBreak: false\n   */\n  hardBreak: Partial<HardBreakOptions> | false\n\n  /**\n   * If set to false, the heading extension will not be registered\n   * @example heading: false\n   */\n  heading: Partial<HeadingOptions> | false\n\n  /**\n   * If set to false, the undo-redo extension will not be registered\n   * @example undoRedo: false\n   */\n  undoRedo: Partial<UndoRedoOptions> | false\n\n  /**\n   * If set to false, the horizontalRule extension will not be registered\n   * @example horizontalRule: false\n   */\n  horizontalRule: Partial<HorizontalRuleOptions> | false\n\n  /**\n   * If set to false, the italic extension will not be registered\n   * @example italic: false\n   */\n  italic: Partial<ItalicOptions> | false\n\n  /**\n   * If set to false, the listItem extension will not be registered\n   * @example listItem: false\n   */\n  listItem: Partial<ListItemOptions> | false\n\n  /**\n   * If set to false, the listItemKeymap extension will not be registered\n   * @example listKeymap: false\n   */\n  listKeymap: Partial<ListKeymapOptions> | false\n\n  /**\n   * If set to false, the link extension will not be registered\n   * @example link: false\n   */\n  link: Partial<LinkOptions> | false\n\n  /**\n   * If set to false, the orderedList extension will not be registered\n   * @example orderedList: false\n   */\n  orderedList: Partial<OrderedListOptions> | false\n\n  /**\n   * If set to false, the paragraph extension will not be registered\n   * @example paragraph: false\n   */\n  paragraph: Partial<ParagraphOptions> | false\n\n  /**\n   * If set to false, the strike extension will not be registered\n   * @example strike: false\n   */\n  strike: Partial<StrikeOptions> | false\n\n  /**\n   * If set to false, the text extension will not be registered\n   * @example text: false\n   */\n  text: false\n\n  /**\n   * If set to false, the underline extension will not be registered\n   * @example underline: false\n   */\n  underline: Partial<UnderlineOptions> | false\n\n  /**\n   * If set to false, the trailingNode extension will not be registered\n   * @example trailingNode: false\n   */\n  trailingNode: Partial<TrailingNodeOptions> | false\n}\n\n/**\n * The starter kit is a collection of essential editor extensions.\n *\n * It’s a good starting point for building your own editor.\n */\nexport const StarterKit = Extension.create<StarterKitOptions>({\n  name: 'starterKit',\n\n  addExtensions() {\n    const extensions = []\n\n    if (this.options.bold !== false) {\n      extensions.push(Bold.configure(this.options.bold))\n    }\n\n    if (this.options.blockquote !== false) {\n      extensions.push(Blockquote.configure(this.options.blockquote))\n    }\n\n    if (this.options.bulletList !== false) {\n      extensions.push(BulletList.configure(this.options.bulletList))\n    }\n\n    if (this.options.code !== false) {\n      extensions.push(Code.configure(this.options.code))\n    }\n\n    if (this.options.codeBlock !== false) {\n      extensions.push(CodeBlock.configure(this.options.codeBlock))\n    }\n\n    if (this.options.document !== false) {\n      extensions.push(Document.configure(this.options.document))\n    }\n\n    if (this.options.dropcursor !== false) {\n      extensions.push(Dropcursor.configure(this.options.dropcursor))\n    }\n\n    if (this.options.gapcursor !== false) {\n      extensions.push(Gapcursor.configure(this.options.gapcursor))\n    }\n\n    if (this.options.hardBreak !== false) {\n      extensions.push(HardBreak.configure(this.options.hardBreak))\n    }\n\n    if (this.options.heading !== false) {\n      extensions.push(Heading.configure(this.options.heading))\n    }\n\n    if (this.options.undoRedo !== false) {\n      extensions.push(UndoRedo.configure(this.options.undoRedo))\n    }\n\n    if (this.options.horizontalRule !== false) {\n      extensions.push(HorizontalRule.configure(this.options.horizontalRule))\n    }\n\n    if (this.options.italic !== false) {\n      extensions.push(Italic.configure(this.options.italic))\n    }\n\n    if (this.options.listItem !== false) {\n      extensions.push(ListItem.configure(this.options.listItem))\n    }\n\n    if (this.options.listKeymap !== false) {\n      extensions.push(ListKeymap.configure(this.options?.listKeymap))\n    }\n\n    if (this.options.link !== false) {\n      extensions.push(Link.configure(this.options?.link))\n    }\n\n    if (this.options.orderedList !== false) {\n      extensions.push(OrderedList.configure(this.options.orderedList))\n    }\n\n    if (this.options.paragraph !== false) {\n      extensions.push(Paragraph.configure(this.options.paragraph))\n    }\n\n    if (this.options.strike !== false) {\n      extensions.push(Strike.configure(this.options.strike))\n    }\n\n    if (this.options.text !== false) {\n      extensions.push(Text.configure(this.options.text))\n    }\n\n    if (this.options.underline !== false) {\n      extensions.push(Underline.configure(this.options?.underline))\n    }\n\n    if (this.options.trailingNode !== false) {\n      extensions.push(TrailingNode.configure(this.options?.trailingNode))\n    }\n\n    return extensions\n  },\n})\n", "import { StarterKit } from './starter-kit.js'\n\nexport type { StarterKitOptions } from './starter-kit.js'\nexport * from './starter-kit.js'\n\nexport default StarterKit\n", "import type { ResizableNodeViewDirection, ResizableNodeViewOptions } from '@tiptap/core'\nimport {\n  getRenderedAttributes,\n  mergeAttributes,\n  Node,\n  nodeInputRule,\n  ResizableNodeView,\n} from '@tiptap/core'\n\nexport interface ImageOptions {\n  /**\n   * Controls if the image node should be inline or not.\n   * @default false\n   * @example true\n   */\n  inline: boolean\n\n  /**\n   * Controls if base64 images are allowed. Enable this if you want to allow\n   * base64 image urls in the `src` attribute.\n   * @default false\n   * @example true\n   */\n  allowBase64: boolean\n\n  /**\n   * HTML attributes to add to the image element.\n   * @default {}\n   * @example { class: 'foo' }\n   */\n  HTMLAttributes: Record<string, any>\n\n  /**\n   * Controls if the image should be resizable and how the resize is configured.\n   * @default false\n   * @example { directions: { top: true, right: true, bottom: true, left: true, topLeft: true, topRight: true, bottomLeft: true, bottomRight: true }, minWidth: 100, minHeight: 100 }\n   */\n  resize:\n    | {\n        enabled: boolean\n        directions?: ResizableNodeViewDirection[]\n        minWidth?: number\n        minHeight?: number\n        alwaysPreserveAspectRatio?: boolean\n      }\n    | false\n}\n\nexport interface SetImageOptions {\n  src: string\n  alt?: string\n  title?: string\n  width?: number\n  height?: number\n}\n\ndeclare module '@tiptap/core' {\n  interface Commands<ReturnType> {\n    image: {\n      /**\n       * Add an image\n       * @param options The image attributes\n       * @example\n       * editor\n       *   .commands\n       *   .setImage({ src: 'https://tiptap.dev/logo.png', alt: 'tiptap', title: 'tiptap logo' })\n       */\n      setImage: (options: SetImageOptions) => ReturnType\n    }\n  }\n}\n\n/**\n * Matches an image to a ![image](src \"title\") on input.\n */\nexport const inputRegex = /(?:^|\\s)(!\\[(.+|:?)]\\((\\S+)(?:(?:\\s+)[\"'](\\S+)[\"'])?\\))$/\n\n/**\n * This extension allows you to insert images.\n * @see https://www.tiptap.dev/api/nodes/image\n */\nexport const Image = Node.create<ImageOptions>({\n  name: 'image',\n\n  addOptions() {\n    return {\n      inline: false,\n      allowBase64: false,\n      HTMLAttributes: {},\n      resize: false,\n    }\n  },\n\n  inline() {\n    return this.options.inline\n  },\n\n  group() {\n    return this.options.inline ? 'inline' : 'block'\n  },\n\n  draggable: true,\n\n  addAttributes() {\n    return {\n      src: {\n        default: null,\n      },\n      alt: {\n        default: null,\n      },\n      title: {\n        default: null,\n      },\n      width: {\n        default: null,\n      },\n      height: {\n        default: null,\n      },\n    }\n  },\n\n  parseHTML() {\n    return [\n      {\n        tag: this.options.allowBase64 ? 'img[src]' : 'img[src]:not([src^=\"data:\"])',\n      },\n    ]\n  },\n\n  renderHTML({ HTMLAttributes }) {\n    return ['img', mergeAttributes(this.options.HTMLAttributes, HTMLAttributes)]\n  },\n\n  parseMarkdown: (token, helpers) => {\n    return helpers.createNode('image', {\n      src: token.href,\n      title: token.title,\n      alt: token.text,\n    })\n  },\n\n  renderMarkdown: node => {\n    const src = node.attrs?.src ?? ''\n    const alt = node.attrs?.alt ?? ''\n    const title = node.attrs?.title ?? ''\n\n    return title ? `![${alt}](${src} \"${title}\")` : `![${alt}](${src})`\n  },\n\n  addNodeView() {\n    if (!this.options.resize || !this.options.resize.enabled || typeof document === 'undefined') {\n      return null\n    }\n\n    const { directions, minWidth, minHeight, alwaysPreserveAspectRatio } = this.options.resize\n    const resizeManagedAttributes = new Set(['src', 'width', 'height'])\n\n    return ({ node, getPos, HTMLAttributes, editor }) => {\n      const el = document.createElement('img')\n      el.draggable = false\n\n      const mergedAttributes = mergeAttributes(this.options.HTMLAttributes, HTMLAttributes)\n\n      Object.entries(mergedAttributes).forEach(([key, value]) => {\n        if (value != null) {\n          switch (key) {\n            case 'src':\n            case 'width':\n            case 'height':\n              break\n            default:\n              el.setAttribute(key, value)\n              break\n          }\n        }\n      })\n\n      if (mergedAttributes.src !== null) {\n        el.src = mergedAttributes.src\n      }\n\n      let previousHTMLAttributes = { ...HTMLAttributes }\n      const syncImageSource = (src: unknown) => {\n        if (typeof src === 'string' && src !== '') {\n          if (el.getAttribute('src') !== src) {\n            el.src = src\n          }\n\n          return\n        }\n\n        if (el.hasAttribute('src')) {\n          el.removeAttribute('src')\n        }\n\n        if (el.src !== '') {\n          el.src = ''\n        }\n      }\n\n      syncImageSource(HTMLAttributes.src)\n\n      const onUpdate: ResizableNodeViewOptions['onUpdate'] = (\n        updatedNode: Parameters<typeof getRenderedAttributes>[0],\n      ) => {\n        if (updatedNode.type !== node.type) {\n          return false\n        }\n\n        const extensionAttributes = editor.extensionManager.attributes.filter(\n          attribute => attribute.type === updatedNode.type.name,\n        )\n        const newHTMLAttributes = getRenderedAttributes(updatedNode, extensionAttributes)\n\n        // Remove attributes that were previously rendered but are no longer present\n        Object.keys(previousHTMLAttributes).forEach(key => {\n          if (!resizeManagedAttributes.has(key) && !(key in newHTMLAttributes)) {\n            el.removeAttribute(key)\n          }\n        })\n\n        Object.entries(newHTMLAttributes).forEach(([key, value]) => {\n          if (resizeManagedAttributes.has(key)) {\n            return\n          }\n\n          if (value != null) {\n            el.setAttribute(key, value)\n          } else {\n            el.removeAttribute(key)\n          }\n        })\n\n        syncImageSource(newHTMLAttributes.src)\n\n        previousHTMLAttributes = newHTMLAttributes\n\n        return true\n      }\n\n      const nodeView = new ResizableNodeView({\n        element: el,\n        editor,\n        node,\n        getPos,\n        onResize: (width, height) => {\n          el.style.width = `${width}px`\n          el.style.height = `${height}px`\n        },\n        onCommit: (width, height) => {\n          const pos = getPos()\n          if (pos === undefined) {\n            return\n          }\n\n          this.editor\n            .chain()\n            .setNodeSelection(pos)\n            .updateAttributes(this.name, {\n              width,\n              height,\n            })\n            .run()\n        },\n        onUpdate,\n        options: {\n          directions,\n          min: {\n            width: minWidth,\n            height: minHeight,\n          },\n          preserveAspectRatio: alwaysPreserveAspectRatio === true,\n        },\n      })\n\n      const dom = nodeView.dom as HTMLElement\n\n      // when image is loaded, show the node view to get the correct dimensions\n      const showNodeView = () => {\n        dom.style.visibility = ''\n        dom.style.pointerEvents = ''\n      }\n\n      dom.style.visibility = 'hidden'\n      dom.style.pointerEvents = 'none'\n\n      if (el.complete && el.naturalWidth > 0) {\n        // A cached image is already complete before this node view mounts, so\n        // `load` never fires again and the image would stay hidden forever.\n        showNodeView()\n      } else {\n        el.onload = showNodeView\n        // Reveal on error too, so a broken src renders as an inspectable broken\n        // image instead of an invisible node.\n        el.onerror = showNodeView\n      }\n\n      return nodeView\n    }\n  },\n\n  addCommands() {\n    return {\n      setImage:\n        options =>\n        ({ commands }) => {\n          return commands.insertContent({\n            type: this.name,\n            attrs: options,\n          })\n        },\n    }\n  },\n\n  addInputRules() {\n    return [\n      nodeInputRule({\n        find: inputRegex,\n        type: this.type,\n        getAttributes: match => {\n          const [, , alt, src, title] = match\n\n          return { src, alt, title }\n        },\n      }),\n    ]\n  },\n})\n", "import { Image } from './image.js'\n\nexport * from './image.js'\n\nexport default Image\n", "// Because working with row and column-spanning cells is not quite\n// trivial, this code builds up a descriptive structure for a given\n// table node. The structures are cached with the (persistent) table\n// nodes as key, so that they only have to be recomputed when the\n// content of the table changes.\n//\n// This does mean that they have to store table-relative, not\n// document-relative positions. So code that uses them will typically\n// compute the start position of the table and offset positions passed\n// to or gotten from this structure by that amount.\nimport type { Attrs, Node } from 'prosemirror-model';\n\nimport type { CellAttrs } from './util';\n\n/**\n * @public\n */\nexport type ColWidths = number[];\n\n/**\n * @public\n */\nexport type Problem =\n  | {\n      type: 'colwidth mismatch';\n      pos: number;\n      colwidth: ColWidths;\n    }\n  | {\n      type: 'collision';\n      pos: number;\n      row: number;\n      n: number;\n    }\n  | {\n      type: 'missing';\n      row: number;\n      n: number;\n    }\n  | {\n      type: 'overlong_rowspan';\n      pos: number;\n      n: number;\n    }\n  | {\n      type: 'zero_sized';\n    };\n\nlet readFromCache: (key: Node) => TableMap | undefined;\nlet addToCache: (key: Node, value: TableMap) => TableMap;\n\n// Prefer using a weak map to cache table maps. Fall back on a\n// fixed-size cache if that's not supported.\nif (typeof WeakMap != 'undefined') {\n  let cache = new WeakMap<Node, TableMap>();\n  readFromCache = (key) => cache.get(key);\n  addToCache = (key, value) => {\n    cache.set(key, value);\n    return value;\n  };\n} else {\n  const cache: (Node | TableMap)[] = [];\n  const cacheSize = 10;\n  let cachePos = 0;\n  readFromCache = (key) => {\n    for (let i = 0; i < cache.length; i += 2)\n      if (cache[i] == key) return cache[i + 1] as TableMap;\n  };\n  addToCache = (key, value) => {\n    if (cachePos == cacheSize) cachePos = 0;\n    cache[cachePos++] = key;\n    return (cache[cachePos++] = value);\n  };\n}\n\n/**\n * @public\n */\nexport interface Rect {\n  left: number;\n  top: number;\n  right: number;\n  bottom: number;\n}\n\n/**\n * A table map describes the structure of a given table. To avoid\n * recomputing them all the time, they are cached per table node. To\n * be able to do that, positions saved in the map are relative to the\n * start of the table, rather than the start of the document.\n *\n * @public\n */\nexport class TableMap {\n  constructor(\n    /**\n     * The number of columns\n     */\n    public width: number,\n    /**\n     * The number of rows\n     */\n    public height: number,\n    /**\n     * A width * height array with the start position of\n     * the cell covering that part of the table in each slot\n     */\n    public map: number[],\n    /**\n     * An optional array of problems (cell overlap or non-rectangular\n     * shape) for the table, used by the table normalizer.\n     */\n    public problems: Problem[] | null,\n  ) {}\n\n  // Find the dimensions of the cell at the given position.\n  findCell(pos: number): Rect {\n    for (let i = 0; i < this.map.length; i++) {\n      const curPos = this.map[i];\n      if (curPos != pos) continue;\n\n      const left = i % this.width;\n      const top = (i / this.width) | 0;\n      let right = left + 1;\n      let bottom = top + 1;\n\n      for (let j = 1; right < this.width && this.map[i + j] == curPos; j++) {\n        right++;\n      }\n      for (\n        let j = 1;\n        bottom < this.height && this.map[i + this.width * j] == curPos;\n        j++\n      ) {\n        bottom++;\n      }\n\n      return { left, top, right, bottom };\n    }\n    throw new RangeError(`No cell with offset ${pos} found`);\n  }\n\n  // Find the left side of the cell at the given position.\n  colCount(pos: number): number {\n    for (let i = 0; i < this.map.length; i++) {\n      if (this.map[i] == pos) {\n        return i % this.width;\n      }\n    }\n    throw new RangeError(`No cell with offset ${pos} found`);\n  }\n\n  // Find the next cell in the given direction, starting from the cell\n  // at `pos`, if any.\n  nextCell(pos: number, axis: 'horiz' | 'vert', dir: number): null | number {\n    const { left, right, top, bottom } = this.findCell(pos);\n    if (axis == 'horiz') {\n      if (dir < 0 ? left == 0 : right == this.width) return null;\n      return this.map[top * this.width + (dir < 0 ? left - 1 : right)];\n    } else {\n      if (dir < 0 ? top == 0 : bottom == this.height) return null;\n      return this.map[left + this.width * (dir < 0 ? top - 1 : bottom)];\n    }\n  }\n\n  // Get the rectangle spanning the two given cells.\n  rectBetween(a: number, b: number): Rect {\n    const {\n      left: leftA,\n      right: rightA,\n      top: topA,\n      bottom: bottomA,\n    } = this.findCell(a);\n    const {\n      left: leftB,\n      right: rightB,\n      top: topB,\n      bottom: bottomB,\n    } = this.findCell(b);\n    return {\n      left: Math.min(leftA, leftB),\n      top: Math.min(topA, topB),\n      right: Math.max(rightA, rightB),\n      bottom: Math.max(bottomA, bottomB),\n    };\n  }\n\n  // Return the position of all cells that have the top left corner in\n  // the given rectangle.\n  cellsInRect(rect: Rect): number[] {\n    const result: number[] = [];\n    const seen: Record<number, boolean> = {};\n    for (let row = rect.top; row < rect.bottom; row++) {\n      for (let col = rect.left; col < rect.right; col++) {\n        const index = row * this.width + col;\n        const pos = this.map[index];\n\n        if (seen[pos]) continue;\n        seen[pos] = true;\n\n        if (\n          (col == rect.left && col && this.map[index - 1] == pos) ||\n          (row == rect.top && row && this.map[index - this.width] == pos)\n        ) {\n          continue;\n        }\n        result.push(pos);\n      }\n    }\n    return result;\n  }\n\n  // Return the position at which the cell at the given row and column\n  // starts, or would start, if a cell started there.\n  positionAt(row: number, col: number, table: Node): number {\n    for (let i = 0, rowStart = 0; ; i++) {\n      const rowEnd = rowStart + table.child(i).nodeSize;\n      if (i == row) {\n        let index = col + row * this.width;\n        const rowEndIndex = (row + 1) * this.width;\n        // Skip past cells from previous rows (via rowspan)\n        while (index < rowEndIndex && this.map[index] < rowStart) index++;\n        return index == rowEndIndex ? rowEnd - 1 : this.map[index];\n      }\n      rowStart = rowEnd;\n    }\n  }\n\n  // Find the table map for the given table node.\n  static get(table: Node): TableMap {\n    return readFromCache(table) || addToCache(table, computeMap(table));\n  }\n}\n\n// Compute a table map.\nfunction computeMap(table: Node): TableMap {\n  if (table.type.spec.tableRole != 'table')\n    throw new RangeError('Not a table node: ' + table.type.name);\n  const width = findWidth(table),\n    height = table.childCount;\n  const map = [];\n  let mapPos = 0;\n  let problems: Problem[] | null = null;\n  const colWidths: ColWidths = [];\n  for (let i = 0, e = width * height; i < e; i++) map[i] = 0;\n\n  for (let row = 0, pos = 0; row < height; row++) {\n    const rowNode = table.child(row);\n    pos++;\n    for (let i = 0; ; i++) {\n      while (mapPos < map.length && map[mapPos] != 0) mapPos++;\n      if (i == rowNode.childCount) break;\n      const cellNode = rowNode.child(i);\n      const { colspan, rowspan, colwidth } = cellNode.attrs;\n      for (let h = 0; h < rowspan; h++) {\n        if (h + row >= height) {\n          (problems || (problems = [])).push({\n            type: 'overlong_rowspan',\n            pos,\n            n: rowspan - h,\n          });\n          break;\n        }\n        const start = mapPos + h * width;\n        for (let w = 0; w < colspan; w++) {\n          if (map[start + w] == 0) map[start + w] = pos;\n          else\n            (problems || (problems = [])).push({\n              type: 'collision',\n              row,\n              pos,\n              n: colspan - w,\n            });\n          const colW = colwidth && colwidth[w];\n          if (colW) {\n            const widthIndex = ((start + w) % width) * 2,\n              prev = colWidths[widthIndex];\n            if (\n              prev == null ||\n              (prev != colW && colWidths[widthIndex + 1] == 1)\n            ) {\n              colWidths[widthIndex] = colW;\n              colWidths[widthIndex + 1] = 1;\n            } else if (prev == colW) {\n              colWidths[widthIndex + 1]++;\n            }\n          }\n        }\n      }\n      mapPos += colspan;\n      pos += cellNode.nodeSize;\n    }\n    const expectedPos = (row + 1) * width;\n    let missing = 0;\n    while (mapPos < expectedPos) if (map[mapPos++] == 0) missing++;\n    if (missing)\n      (problems || (problems = [])).push({ type: 'missing', row, n: missing });\n    pos++;\n  }\n\n  if (width === 0 || height === 0)\n    (problems || (problems = [])).push({ type: 'zero_sized' });\n\n  const tableMap = new TableMap(width, height, map, problems);\n  let badWidths = false;\n\n  // For columns that have defined widths, but whose widths disagree\n  // between rows, fix up the cells whose width doesn't match the\n  // computed one.\n  for (let i = 0; !badWidths && i < colWidths.length; i += 2)\n    if (colWidths[i] != null && colWidths[i + 1] < height) badWidths = true;\n  if (badWidths) findBadColWidths(tableMap, colWidths, table);\n\n  return tableMap;\n}\n\nfunction findWidth(table: Node): number {\n  let width = -1;\n  let hasRowSpan = false;\n  for (let row = 0; row < table.childCount; row++) {\n    const rowNode = table.child(row);\n    let rowWidth = 0;\n    if (hasRowSpan)\n      for (let j = 0; j < row; j++) {\n        const prevRow = table.child(j);\n        for (let i = 0; i < prevRow.childCount; i++) {\n          const cell = prevRow.child(i);\n          if (j + cell.attrs.rowspan > row) rowWidth += cell.attrs.colspan;\n        }\n      }\n    for (let i = 0; i < rowNode.childCount; i++) {\n      const cell = rowNode.child(i);\n      rowWidth += cell.attrs.colspan;\n      if (cell.attrs.rowspan > 1) hasRowSpan = true;\n    }\n    if (width == -1) width = rowWidth;\n    else if (width != rowWidth) width = Math.max(width, rowWidth);\n  }\n  return width;\n}\n\nfunction findBadColWidths(\n  map: TableMap,\n  colWidths: ColWidths,\n  table: Node,\n): void {\n  if (!map.problems) map.problems = [];\n  const seen: Record<number, boolean> = {};\n  for (let i = 0; i < map.map.length; i++) {\n    const pos = map.map[i];\n    if (seen[pos]) continue;\n    seen[pos] = true;\n    const node = table.nodeAt(pos);\n    if (!node) {\n      throw new RangeError(`No cell with offset ${pos} found`);\n    }\n\n    let updated = null;\n    const attrs = node.attrs as CellAttrs;\n    for (let j = 0; j < attrs.colspan; j++) {\n      const col = (i + j) % map.width;\n      const colWidth = colWidths[col * 2];\n      if (\n        colWidth != null &&\n        (!attrs.colwidth || attrs.colwidth[j] != colWidth)\n      )\n        (updated || (updated = freshColWidth(attrs)))[j] = colWidth;\n    }\n    if (updated)\n      map.problems.unshift({\n        type: 'colwidth mismatch',\n        pos,\n        colwidth: updated,\n      });\n  }\n}\n\nfunction freshColWidth(attrs: Attrs): ColWidths {\n  if (attrs.colwidth) return attrs.colwidth.slice();\n  const result: ColWidths = [];\n  for (let i = 0; i < attrs.colspan; i++) result.push(0);\n  return result;\n}\n", "// Helper for creating a schema that supports tables.\n\nimport type {\n  AttributeSpec,\n  Attrs,\n  Node,\n  NodeSpec,\n  NodeType,\n  Schema,\n} from 'prosemirror-model';\n\nimport type { CellAttrs, MutableAttrs } from './util';\n\nfunction getCellAttrs(dom: HTMLElement | string, extraAttrs: Attrs): Attrs {\n  if (typeof dom === 'string') {\n    return {};\n  }\n\n  const widthAttr = dom.getAttribute('data-colwidth');\n  const widths =\n    widthAttr && /^\\d+(,\\d+)*$/.test(widthAttr)\n      ? widthAttr.split(',').map((s) => Number(s))\n      : null;\n  const colspan = Number(dom.getAttribute('colspan') || 1);\n  const result: MutableAttrs = {\n    colspan,\n    rowspan: Number(dom.getAttribute('rowspan') || 1),\n    colwidth: widths && widths.length == colspan ? widths : null,\n  } satisfies CellAttrs;\n  for (const prop in extraAttrs) {\n    const getter = extraAttrs[prop].getFromDOM;\n    const value = getter && getter(dom);\n    if (value != null) {\n      result[prop] = value;\n    }\n  }\n  return result;\n}\n\nfunction setCellAttrs(node: Node, extraAttrs: Attrs): Attrs {\n  const attrs: MutableAttrs = {};\n  if (node.attrs.colspan != 1) attrs.colspan = node.attrs.colspan;\n  if (node.attrs.rowspan != 1) attrs.rowspan = node.attrs.rowspan;\n  if (node.attrs.colwidth)\n    attrs['data-colwidth'] = node.attrs.colwidth.join(',');\n  for (const prop in extraAttrs) {\n    const setter = extraAttrs[prop].setDOMAttr;\n    if (setter) setter(node.attrs[prop], attrs);\n  }\n  return attrs;\n}\n\n/**\n * @public\n */\nexport type getFromDOM = (dom: HTMLElement) => unknown;\n\n/**\n * @public\n */\nexport type setDOMAttr = (value: unknown, attrs: MutableAttrs) => void;\n\n/**\n * @public\n */\nexport interface CellAttributes {\n  /**\n   * The attribute's default value.\n   */\n  default: unknown;\n\n  /**\n   * A function or type name used to validate values of this attribute.\n   *\n   * See [validate](https://prosemirror.net/docs/ref/#model.AttributeSpec.validate).\n   */\n  validate?: string | ((value: unknown) => void);\n\n  /**\n   * A function to read the attribute's value from a DOM node.\n   */\n  getFromDOM?: getFromDOM;\n\n  /**\n   * A function to add the attribute's value to an attribute\n   * object that's used to render the cell's DOM.\n   */\n  setDOMAttr?: setDOMAttr;\n}\n\n/**\n * @public\n */\nexport interface TableNodesOptions {\n  /**\n   * A group name (something like `\"block\"`) to add to the table\n   * node type.\n   */\n  tableGroup?: string;\n\n  /**\n   * The content expression for table cells.\n   */\n  cellContent: string;\n\n  /**\n   * Additional attributes to add to cells. Maps attribute names to\n   * objects with the following properties:\n   */\n  cellAttributes: { [key: string]: CellAttributes };\n}\n\n/**\n * @public\n */\nexport type TableNodes = Record<\n  'table' | 'table_row' | 'table_cell' | 'table_header',\n  NodeSpec\n>;\n\nfunction validateColwidth(value: unknown) {\n  if (value === null) {\n    return;\n  }\n  if (!Array.isArray(value)) {\n    throw new TypeError('colwidth must be null or an array');\n  }\n  for (const item of value) {\n    if (typeof item !== 'number') {\n      throw new TypeError('colwidth must be null or an array of numbers');\n    }\n  }\n}\n\n/**\n * This function creates a set of [node\n * specs](http://prosemirror.net/docs/ref/#model.SchemaSpec.nodes) for\n * `table`, `table_row`, and `table_cell` nodes types as used by this\n * module. The result can then be added to the set of nodes when\n * creating a schema.\n *\n * @public\n */\nexport function tableNodes(options: TableNodesOptions): TableNodes {\n  const extraAttrs = options.cellAttributes || {};\n  const cellAttrs: Record<string, AttributeSpec> = {\n    colspan: { default: 1, validate: 'number' },\n    rowspan: { default: 1, validate: 'number' },\n    colwidth: { default: null, validate: validateColwidth },\n  };\n  for (const prop in extraAttrs)\n    cellAttrs[prop] = {\n      default: extraAttrs[prop].default,\n      validate: extraAttrs[prop].validate,\n    };\n\n  return {\n    table: {\n      content: 'table_row+',\n      tableRole: 'table',\n      isolating: true,\n      group: options.tableGroup,\n      parseDOM: [{ tag: 'table' }],\n      toDOM() {\n        return ['table', ['tbody', 0]];\n      },\n    },\n    table_row: {\n      content: '(table_cell | table_header)*',\n      tableRole: 'row',\n      parseDOM: [{ tag: 'tr' }],\n      toDOM() {\n        return ['tr', 0];\n      },\n    },\n    table_cell: {\n      content: options.cellContent,\n      attrs: cellAttrs,\n      tableRole: 'cell',\n      isolating: true,\n      parseDOM: [\n        { tag: 'td', getAttrs: (dom) => getCellAttrs(dom, extraAttrs) },\n      ],\n      toDOM(node) {\n        return ['td', setCellAttrs(node, extraAttrs), 0];\n      },\n    },\n    table_header: {\n      content: options.cellContent,\n      attrs: cellAttrs,\n      tableRole: 'header_cell',\n      isolating: true,\n      parseDOM: [\n        { tag: 'th', getAttrs: (dom) => getCellAttrs(dom, extraAttrs) },\n      ],\n      toDOM(node) {\n        return ['th', setCellAttrs(node, extraAttrs), 0];\n      },\n    },\n  };\n}\n\n/**\n * @public\n */\nexport type TableRole = 'table' | 'row' | 'cell' | 'header_cell';\n\n/**\n * @public\n */\nexport function tableNodeTypes(schema: Schema): Record<TableRole, NodeType> {\n  let result = schema.cached.tableNodeTypes;\n  if (!result) {\n    result = schema.cached.tableNodeTypes = {};\n    for (const name in schema.nodes) {\n      const type = schema.nodes[name],\n        role = type.spec.tableRole;\n      if (role) result[role] = type;\n    }\n  }\n  return result;\n}\n", "// Various helper function for working with tables\n\nimport type { Attrs, Node, ResolvedPos } from 'prosemirror-model';\nimport type { EditorState, NodeSelection } from 'prosemirror-state';\nimport { PluginKey } from 'prosemirror-state';\n\nimport type { CellSelection } from './cellselection';\nimport { tableNodeTypes } from './schema';\nimport type { Rect } from './tablemap';\nimport { TableMap } from './tablemap';\n\n/**\n * @public\n */\nexport type MutableAttrs = Record<string, unknown>;\n\n/**\n * @public\n */\nexport interface CellAttrs {\n  colspan: number;\n  rowspan: number;\n  colwidth: number[] | null;\n}\n\n/**\n * @public\n */\nexport const tableEditingKey = new PluginKey<number>('selectingCells');\n\n/**\n * @public\n */\nexport function cellAround($pos: ResolvedPos): ResolvedPos | null {\n  for (let d = $pos.depth - 1; d > 0; d--)\n    if ($pos.node(d).type.spec.tableRole == 'row')\n      return $pos.node(0).resolve($pos.before(d + 1));\n  return null;\n}\n\nexport function cellWrapping($pos: ResolvedPos): null | Node {\n  for (let d = $pos.depth; d > 0; d--) {\n    // Sometimes the cell can be in the same depth.\n    const role = $pos.node(d).type.spec.tableRole;\n    if (role === 'cell' || role === 'header_cell') return $pos.node(d);\n  }\n  return null;\n}\n\n/**\n * @public\n */\nexport function isInTable(state: EditorState): boolean {\n  const $head = state.selection.$head;\n  for (let d = $head.depth; d > 0; d--)\n    if ($head.node(d).type.spec.tableRole == 'row') return true;\n  return false;\n}\n\n/**\n * @internal\n */\nexport function selectionCell(state: EditorState): ResolvedPos {\n  const sel = state.selection as CellSelection | NodeSelection;\n  if ('$anchorCell' in sel && sel.$anchorCell) {\n    return sel.$anchorCell.pos > sel.$headCell.pos\n      ? sel.$anchorCell\n      : sel.$headCell;\n  } else if (\n    'node' in sel &&\n    sel.node &&\n    sel.node.type.spec.tableRole == 'cell'\n  ) {\n    return sel.$anchor;\n  }\n  const $cell = cellAround(sel.$head) || cellNear(sel.$head);\n  if ($cell) {\n    return $cell;\n  }\n  throw new RangeError(`No cell found around position ${sel.head}`);\n}\n\n/**\n * @public\n */\nexport function cellNear($pos: ResolvedPos): ResolvedPos | undefined {\n  for (\n    let after = $pos.nodeAfter, pos = $pos.pos;\n    after;\n    after = after.firstChild, pos++\n  ) {\n    const role = after.type.spec.tableRole;\n    if (role == 'cell' || role == 'header_cell') return $pos.doc.resolve(pos);\n  }\n  for (\n    let before = $pos.nodeBefore, pos = $pos.pos;\n    before;\n    before = before.lastChild, pos--\n  ) {\n    const role = before.type.spec.tableRole;\n    if (role == 'cell' || role == 'header_cell')\n      return $pos.doc.resolve(pos - before.nodeSize);\n  }\n}\n\n/**\n * @public\n */\nexport function pointsAtCell($pos: ResolvedPos): boolean {\n  return $pos.parent.type.spec.tableRole == 'row' && !!$pos.nodeAfter;\n}\n\n/**\n * @public\n */\nexport function moveCellForward($pos: ResolvedPos): ResolvedPos {\n  return $pos.node(0).resolve($pos.pos + $pos.nodeAfter!.nodeSize);\n}\n\n/**\n * @internal\n */\nexport function inSameTable($cellA: ResolvedPos, $cellB: ResolvedPos): boolean {\n  return (\n    $cellA.depth == $cellB.depth &&\n    $cellA.pos >= $cellB.start(-1) &&\n    $cellA.pos <= $cellB.end(-1)\n  );\n}\n\n/**\n * @public\n */\nexport function findCell($pos: ResolvedPos): Rect {\n  return TableMap.get($pos.node(-1)).findCell($pos.pos - $pos.start(-1));\n}\n\n/**\n * @public\n */\nexport function colCount($pos: ResolvedPos): number {\n  return TableMap.get($pos.node(-1)).colCount($pos.pos - $pos.start(-1));\n}\n\n/**\n * @public\n */\nexport function nextCell(\n  $pos: ResolvedPos,\n  axis: 'horiz' | 'vert',\n  dir: number,\n): ResolvedPos | null {\n  const table = $pos.node(-1);\n  const map = TableMap.get(table);\n  const tableStart = $pos.start(-1);\n\n  const moved = map.nextCell($pos.pos - tableStart, axis, dir);\n  return moved == null ? null : $pos.node(0).resolve(tableStart + moved);\n}\n\n/**\n * @public\n */\nexport function removeColSpan(attrs: CellAttrs, pos: number, n = 1): CellAttrs {\n  const result: CellAttrs = { ...attrs, colspan: attrs.colspan - n };\n\n  if (result.colwidth) {\n    result.colwidth = result.colwidth.slice();\n    result.colwidth.splice(pos, n);\n    if (!result.colwidth.some((w) => w > 0)) result.colwidth = null;\n  }\n  return result;\n}\n\n/**\n * @public\n */\nexport function addColSpan(attrs: CellAttrs, pos: number, n = 1): Attrs {\n  const result = { ...attrs, colspan: attrs.colspan + n };\n  if (result.colwidth) {\n    result.colwidth = result.colwidth.slice();\n    for (let i = 0; i < n; i++) result.colwidth.splice(pos, 0, 0);\n  }\n  return result;\n}\n\n/**\n * @public\n */\nexport function columnIsHeader(\n  map: TableMap,\n  table: Node,\n  col: number,\n): boolean {\n  const headerCell = tableNodeTypes(table.type.schema).header_cell;\n  for (let row = 0; row < map.height; row++)\n    if (table.nodeAt(map.map[col + row * map.width])!.type != headerCell)\n      return false;\n  return true;\n}\n", "// This file defines a ProseMirror selection subclass that models\n// table cell selections. The table plugin needs to be active to wire\n// in the user interaction part of table selections (so that you\n// actually get such selections when you select across cells).\n\nimport type { Node, ResolvedPos } from 'prosemirror-model';\nimport { Fragment, Slice } from 'prosemirror-model';\nimport type { EditorState, Transaction } from 'prosemirror-state';\nimport {\n  NodeSelection,\n  Selection,\n  SelectionRange,\n  TextSelection,\n} from 'prosemirror-state';\nimport type { Mappable } from 'prosemirror-transform';\nimport type { DecorationSource } from 'prosemirror-view';\nimport { Decoration, DecorationSet } from 'prosemirror-view';\n\nimport { TableMap } from './tablemap';\nimport type { CellAttrs } from './util';\nimport { inSameTable, pointsAtCell, removeColSpan } from './util';\n\n/**\n * @public\n */\nexport interface CellSelectionJSON {\n  type: string;\n  anchor: number;\n  head: number;\n}\n\n/**\n * A [`Selection`](http://prosemirror.net/docs/ref/#state.Selection)\n * subclass that represents a cell selection spanning part of a table.\n * With the plugin enabled, these will be created when the user\n * selects across cells, and will be drawn by giving selected cells a\n * `selectedCell` CSS class.\n *\n * @public\n */\nexport class CellSelection extends Selection {\n  // A resolved position pointing _in front of_ the anchor cell (the one\n  // that doesn't move when extending the selection).\n  public $anchorCell: ResolvedPos;\n\n  // A resolved position pointing in front of the head cell (the one\n  // moves when extending the selection).\n  public $headCell: ResolvedPos;\n\n  // A table selection is identified by its anchor and head cells. The\n  // positions given to this constructor should point _before_ two\n  // cells in the same table. They may be the same, to select a single\n  // cell.\n  constructor($anchorCell: ResolvedPos, $headCell: ResolvedPos = $anchorCell) {\n    const table = $anchorCell.node(-1);\n    const map = TableMap.get(table);\n    const tableStart = $anchorCell.start(-1);\n    const rect = map.rectBetween(\n      $anchorCell.pos - tableStart,\n      $headCell.pos - tableStart,\n    );\n\n    const doc = $anchorCell.node(0);\n    const cells = map\n      .cellsInRect(rect)\n      .filter((p) => p != $headCell.pos - tableStart);\n    // Make the head cell the first range, so that it counts as the\n    // primary part of the selection\n    cells.unshift($headCell.pos - tableStart);\n    const ranges = cells.map((pos) => {\n      const cell = table.nodeAt(pos);\n      if (!cell) {\n        throw new RangeError(`No cell with offset ${pos} found`);\n      }\n      const from = tableStart + pos + 1;\n      return new SelectionRange(\n        doc.resolve(from),\n        doc.resolve(from + cell.content.size),\n      );\n    });\n    super(ranges[0].$from, ranges[0].$to, ranges);\n    this.$anchorCell = $anchorCell;\n    this.$headCell = $headCell;\n  }\n\n  public map(doc: Node, mapping: Mappable): CellSelection | Selection {\n    const $anchorCell = doc.resolve(mapping.map(this.$anchorCell.pos));\n    const $headCell = doc.resolve(mapping.map(this.$headCell.pos));\n    if (\n      pointsAtCell($anchorCell) &&\n      pointsAtCell($headCell) &&\n      inSameTable($anchorCell, $headCell)\n    ) {\n      const tableChanged = this.$anchorCell.node(-1) != $anchorCell.node(-1);\n      if (tableChanged && this.isRowSelection())\n        return CellSelection.rowSelection($anchorCell, $headCell);\n      else if (tableChanged && this.isColSelection())\n        return CellSelection.colSelection($anchorCell, $headCell);\n      else return new CellSelection($anchorCell, $headCell);\n    }\n    return TextSelection.between($anchorCell, $headCell);\n  }\n\n  // Returns a rectangular slice of table rows containing the selected\n  // cells.\n  public override content(): Slice {\n    const table = this.$anchorCell.node(-1);\n    const map = TableMap.get(table);\n    const tableStart = this.$anchorCell.start(-1);\n\n    const rect = map.rectBetween(\n      this.$anchorCell.pos - tableStart,\n      this.$headCell.pos - tableStart,\n    );\n    const seen: Record<number, boolean> = {};\n    const rows = [];\n    for (let row = rect.top; row < rect.bottom; row++) {\n      const rowContent = [];\n      for (\n        let index = row * map.width + rect.left, col = rect.left;\n        col < rect.right;\n        col++, index++\n      ) {\n        const pos = map.map[index];\n        if (seen[pos]) continue;\n        seen[pos] = true;\n\n        const cellRect = map.findCell(pos);\n        let cell = table.nodeAt(pos);\n        if (!cell) {\n          throw new RangeError(`No cell with offset ${pos} found`);\n        }\n\n        const extraLeft = rect.left - cellRect.left;\n        const extraRight = cellRect.right - rect.right;\n\n        if (extraLeft > 0 || extraRight > 0) {\n          let attrs = cell.attrs as CellAttrs;\n          if (extraLeft > 0) {\n            attrs = removeColSpan(attrs, 0, extraLeft);\n          }\n          if (extraRight > 0) {\n            attrs = removeColSpan(\n              attrs,\n              attrs.colspan - extraRight,\n              extraRight,\n            );\n          }\n          if (cellRect.left < rect.left) {\n            cell = cell.type.createAndFill(attrs);\n            if (!cell) {\n              throw new RangeError(\n                `Could not create cell with attrs ${JSON.stringify(attrs)}`,\n              );\n            }\n          } else {\n            cell = cell.type.create(attrs, cell.content);\n          }\n        }\n        if (cellRect.top < rect.top || cellRect.bottom > rect.bottom) {\n          const attrs = {\n            ...cell.attrs,\n            rowspan:\n              Math.min(cellRect.bottom, rect.bottom) -\n              Math.max(cellRect.top, rect.top),\n          };\n          if (cellRect.top < rect.top) {\n            cell = cell.type.createAndFill(attrs)!;\n          } else {\n            cell = cell.type.create(attrs, cell.content);\n          }\n        }\n        rowContent.push(cell);\n      }\n      rows.push(table.child(row).copy(Fragment.from(rowContent)));\n    }\n\n    const fragment =\n      this.isColSelection() && this.isRowSelection() ? table : rows;\n    return new Slice(Fragment.from(fragment), 1, 1);\n  }\n\n  public override replace(tr: Transaction, content: Slice = Slice.empty): void {\n    const mapFrom = tr.steps.length,\n      ranges = this.ranges;\n    for (let i = 0; i < ranges.length; i++) {\n      const { $from, $to } = ranges[i],\n        mapping = tr.mapping.slice(mapFrom);\n      tr.replace(\n        mapping.map($from.pos),\n        mapping.map($to.pos),\n        i ? Slice.empty : content,\n      );\n    }\n    const sel = Selection.findFrom(\n      tr.doc.resolve(tr.mapping.slice(mapFrom).map(this.to)),\n      -1,\n    );\n    if (sel) tr.setSelection(sel);\n  }\n\n  public override replaceWith(tr: Transaction, node: Node): void {\n    this.replace(tr, new Slice(Fragment.from(node), 0, 0));\n  }\n\n  public forEachCell(f: (node: Node, pos: number) => void): void {\n    const table = this.$anchorCell.node(-1);\n    const map = TableMap.get(table);\n    const tableStart = this.$anchorCell.start(-1);\n\n    const cells = map.cellsInRect(\n      map.rectBetween(\n        this.$anchorCell.pos - tableStart,\n        this.$headCell.pos - tableStart,\n      ),\n    );\n    for (let i = 0; i < cells.length; i++) {\n      f(table.nodeAt(cells[i])!, tableStart + cells[i]);\n    }\n  }\n\n  // True if this selection goes all the way from the top to the\n  // bottom of the table.\n  public isColSelection(): boolean {\n    const anchorTop = this.$anchorCell.index(-1);\n    const headTop = this.$headCell.index(-1);\n    if (Math.min(anchorTop, headTop) > 0) return false;\n\n    const anchorBottom = anchorTop + this.$anchorCell.nodeAfter!.attrs.rowspan;\n    const headBottom = headTop + this.$headCell.nodeAfter!.attrs.rowspan;\n\n    return (\n      Math.max(anchorBottom, headBottom) == this.$headCell.node(-1).childCount\n    );\n  }\n\n  // Returns the smallest column selection that covers the given anchor\n  // and head cell.\n  public static colSelection(\n    $anchorCell: ResolvedPos,\n    $headCell: ResolvedPos = $anchorCell,\n  ): CellSelection {\n    const table = $anchorCell.node(-1);\n    const map = TableMap.get(table);\n    const tableStart = $anchorCell.start(-1);\n\n    const anchorRect = map.findCell($anchorCell.pos - tableStart);\n    const headRect = map.findCell($headCell.pos - tableStart);\n    const doc = $anchorCell.node(0);\n\n    if (anchorRect.top <= headRect.top) {\n      if (anchorRect.top > 0)\n        $anchorCell = doc.resolve(tableStart + map.map[anchorRect.left]);\n      if (headRect.bottom < map.height)\n        $headCell = doc.resolve(\n          tableStart +\n            map.map[map.width * (map.height - 1) + headRect.right - 1],\n        );\n    } else {\n      if (headRect.top > 0)\n        $headCell = doc.resolve(tableStart + map.map[headRect.left]);\n      if (anchorRect.bottom < map.height)\n        $anchorCell = doc.resolve(\n          tableStart +\n            map.map[map.width * (map.height - 1) + anchorRect.right - 1],\n        );\n    }\n    return new CellSelection($anchorCell, $headCell);\n  }\n\n  // True if this selection goes all the way from the left to the\n  // right of the table.\n  public isRowSelection(): boolean {\n    const table = this.$anchorCell.node(-1);\n    const map = TableMap.get(table);\n    const tableStart = this.$anchorCell.start(-1);\n\n    const anchorLeft = map.colCount(this.$anchorCell.pos - tableStart);\n    const headLeft = map.colCount(this.$headCell.pos - tableStart);\n    if (Math.min(anchorLeft, headLeft) > 0) return false;\n\n    const anchorRight = anchorLeft + this.$anchorCell.nodeAfter!.attrs.colspan;\n    const headRight = headLeft + this.$headCell.nodeAfter!.attrs.colspan;\n    return Math.max(anchorRight, headRight) == map.width;\n  }\n\n  public eq(other: unknown): boolean {\n    return (\n      other instanceof CellSelection &&\n      other.$anchorCell.pos == this.$anchorCell.pos &&\n      other.$headCell.pos == this.$headCell.pos\n    );\n  }\n\n  // Returns the smallest row selection that covers the given anchor\n  // and head cell.\n  public static rowSelection(\n    $anchorCell: ResolvedPos,\n    $headCell: ResolvedPos = $anchorCell,\n  ): CellSelection {\n    const table = $anchorCell.node(-1);\n    const map = TableMap.get(table);\n    const tableStart = $anchorCell.start(-1);\n\n    const anchorRect = map.findCell($anchorCell.pos - tableStart);\n    const headRect = map.findCell($headCell.pos - tableStart);\n    const doc = $anchorCell.node(0);\n\n    if (anchorRect.left <= headRect.left) {\n      if (anchorRect.left > 0)\n        $anchorCell = doc.resolve(\n          tableStart + map.map[anchorRect.top * map.width],\n        );\n      if (headRect.right < map.width)\n        $headCell = doc.resolve(\n          tableStart + map.map[map.width * (headRect.top + 1) - 1],\n        );\n    } else {\n      if (headRect.left > 0)\n        $headCell = doc.resolve(tableStart + map.map[headRect.top * map.width]);\n      if (anchorRect.right < map.width)\n        $anchorCell = doc.resolve(\n          tableStart + map.map[map.width * (anchorRect.top + 1) - 1],\n        );\n    }\n    return new CellSelection($anchorCell, $headCell);\n  }\n\n  public toJSON(): CellSelectionJSON {\n    return {\n      type: 'cell',\n      anchor: this.$anchorCell.pos,\n      head: this.$headCell.pos,\n    };\n  }\n\n  public static override fromJSON(\n    doc: Node,\n    json: CellSelectionJSON,\n  ): CellSelection {\n    return new CellSelection(doc.resolve(json.anchor), doc.resolve(json.head));\n  }\n\n  static create(\n    doc: Node,\n    anchorCell: number,\n    headCell: number = anchorCell,\n  ): CellSelection {\n    return new CellSelection(doc.resolve(anchorCell), doc.resolve(headCell));\n  }\n\n  public override getBookmark(): CellBookmark {\n    return new CellBookmark(this.$anchorCell.pos, this.$headCell.pos);\n  }\n}\n\nCellSelection.prototype.visible = false;\n\nSelection.jsonID('cell', CellSelection);\n\n/**\n * @public\n */\nexport class CellBookmark {\n  constructor(\n    public anchor: number,\n    public head: number,\n  ) {}\n\n  map(mapping: Mappable): CellBookmark {\n    return new CellBookmark(mapping.map(this.anchor), mapping.map(this.head));\n  }\n\n  resolve(doc: Node): CellSelection | Selection {\n    const $anchorCell = doc.resolve(this.anchor),\n      $headCell = doc.resolve(this.head);\n    if (\n      $anchorCell.parent.type.spec.tableRole == 'row' &&\n      $headCell.parent.type.spec.tableRole == 'row' &&\n      $anchorCell.index() < $anchorCell.parent.childCount &&\n      $headCell.index() < $headCell.parent.childCount &&\n      inSameTable($anchorCell, $headCell)\n    )\n      return new CellSelection($anchorCell, $headCell);\n    else return Selection.near($headCell, 1);\n  }\n}\n\nexport function drawCellSelection(state: EditorState): DecorationSource | null {\n  if (!(state.selection instanceof CellSelection)) return null;\n  const cells: Decoration[] = [];\n  state.selection.forEachCell((node, pos) => {\n    cells.push(\n      Decoration.node(pos, pos + node.nodeSize, { class: 'selectedCell' }),\n    );\n  });\n  return DecorationSet.create(state.doc, cells);\n}\n\nfunction isCellBoundarySelection({ $from, $to }: TextSelection) {\n  if ($from.pos == $to.pos || $from.pos < $to.pos - 6) return false; // Cheap elimination\n  let afterFrom = $from.pos;\n  let beforeTo = $to.pos;\n  let depth = $from.depth;\n  for (; depth >= 0; depth--, afterFrom++)\n    if ($from.after(depth + 1) < $from.end(depth)) break;\n  for (let d = $to.depth; d >= 0; d--, beforeTo--)\n    if ($to.before(d + 1) > $to.start(d)) break;\n  return (\n    afterFrom == beforeTo &&\n    /row|table/.test($from.node(depth).type.spec.tableRole)\n  );\n}\n\nfunction isTextSelectionAcrossCells({ $from, $to }: TextSelection) {\n  let fromCellBoundaryNode: Node | undefined;\n  let toCellBoundaryNode: Node | undefined;\n\n  for (let i = $from.depth; i > 0; i--) {\n    const node = $from.node(i);\n    if (\n      node.type.spec.tableRole === 'cell' ||\n      node.type.spec.tableRole === 'header_cell'\n    ) {\n      fromCellBoundaryNode = node;\n      break;\n    }\n  }\n\n  for (let i = $to.depth; i > 0; i--) {\n    const node = $to.node(i);\n    if (\n      node.type.spec.tableRole === 'cell' ||\n      node.type.spec.tableRole === 'header_cell'\n    ) {\n      toCellBoundaryNode = node;\n      break;\n    }\n  }\n\n  return fromCellBoundaryNode !== toCellBoundaryNode && $to.parentOffset === 0;\n}\n\nexport function normalizeSelection(\n  state: EditorState,\n  tr: Transaction | undefined,\n  allowTableNodeSelection: boolean,\n): Transaction | undefined {\n  const sel = (tr || state).selection;\n  const doc = (tr || state).doc;\n  let normalize: Selection | undefined;\n  let role: string | undefined;\n  if (sel instanceof NodeSelection && (role = sel.node.type.spec.tableRole)) {\n    if (role == 'cell' || role == 'header_cell') {\n      normalize = CellSelection.create(doc, sel.from);\n    } else if (role == 'row') {\n      const $cell = doc.resolve(sel.from + 1);\n      normalize = CellSelection.rowSelection($cell, $cell);\n    } else if (!allowTableNodeSelection) {\n      const map = TableMap.get(sel.node);\n      const start = sel.from + 1;\n      const lastCell = start + map.map[map.width * map.height - 1];\n      normalize = CellSelection.create(doc, start + 1, lastCell);\n    }\n  } else if (sel instanceof TextSelection && isCellBoundarySelection(sel)) {\n    normalize = TextSelection.create(doc, sel.from);\n  } else if (sel instanceof TextSelection && isTextSelectionAcrossCells(sel)) {\n    normalize = TextSelection.create(doc, sel.$from.start(), sel.$from.end());\n  }\n  if (normalize) (tr || (tr = state.tr)).setSelection(normalize);\n  return tr;\n}\n", "// This file defines helpers for normalizing tables, making sure no\n// cells overlap (which can happen, if you have the wrong col- and\n// rowspans) and that each row has the same width. Uses the problems\n// reported by `TableMap`.\n\nimport type { Node } from 'prosemirror-model';\nimport type { EditorState, Transaction } from 'prosemirror-state';\nimport { PluginKey } from 'prosemirror-state';\n\nimport type { TableRole } from './schema';\nimport { tableNodeTypes } from './schema';\nimport { TableMap } from './tablemap';\nimport type { CellAttrs } from './util';\nimport { removeColSpan } from './util';\n\n/**\n * @public\n */\nexport const fixTablesKey = new PluginKey<{ fixTables: boolean }>('fix-tables');\n\n/**\n * Helper for iterating through the nodes in a document that changed\n * compared to the given previous document. Useful for avoiding\n * duplicate work on each transaction.\n *\n * @public\n */\nfunction changedDescendants(\n  old: Node,\n  cur: Node,\n  offset: number,\n  f: (node: Node, pos: number) => void,\n): void {\n  const oldSize = old.childCount,\n    curSize = cur.childCount;\n  outer: for (let i = 0, j = 0; i < curSize; i++) {\n    const child = cur.child(i);\n    for (let scan = j, e = Math.min(oldSize, i + 3); scan < e; scan++) {\n      if (old.child(scan) == child) {\n        j = scan + 1;\n        offset += child.nodeSize;\n        continue outer;\n      }\n    }\n    f(child, offset);\n    if (j < oldSize && old.child(j).sameMarkup(child))\n      changedDescendants(old.child(j), child, offset + 1, f);\n    else child.nodesBetween(0, child.content.size, f, offset + 1);\n    offset += child.nodeSize;\n  }\n}\n\n/**\n * Inspect all tables in the given state's document and return a\n * transaction that fixes them, if necessary. If `oldState` was\n * provided, that is assumed to hold a previous, known-good state,\n * which will be used to avoid re-scanning unchanged parts of the\n * document.\n *\n * @public\n */\nexport function fixTables(\n  state: EditorState,\n  oldState?: EditorState,\n): Transaction | undefined {\n  let tr: Transaction | undefined;\n  const check = (node: Node, pos: number) => {\n    if (node.type.spec.tableRole == 'table')\n      tr = fixTable(state, node, pos, tr);\n  };\n  if (!oldState) state.doc.descendants(check);\n  else if (oldState.doc != state.doc)\n    changedDescendants(oldState.doc, state.doc, 0, check);\n  return tr;\n}\n\n// Fix the given table, if necessary. Will append to the transaction\n// it was given, if non-null, or create a new one if necessary.\nexport function fixTable(\n  state: EditorState,\n  table: Node,\n  tablePos: number,\n  tr: Transaction | undefined,\n): Transaction | undefined {\n  const map = TableMap.get(table);\n  if (!map.problems) return tr;\n  if (!tr) tr = state.tr;\n\n  // Track which rows we must add cells to, so that we can adjust that\n  // when fixing collisions.\n  const mustAdd: number[] = [];\n  for (let i = 0; i < map.height; i++) mustAdd.push(0);\n  for (let i = 0; i < map.problems.length; i++) {\n    const prob = map.problems[i];\n    if (prob.type == 'collision') {\n      const cell = table.nodeAt(prob.pos);\n      if (!cell) continue;\n      const attrs = cell.attrs as CellAttrs;\n      for (let j = 0; j < attrs.rowspan; j++) mustAdd[prob.row + j] += prob.n;\n      tr.setNodeMarkup(\n        tr.mapping.map(tablePos + 1 + prob.pos),\n        null,\n        removeColSpan(attrs, attrs.colspan - prob.n, prob.n),\n      );\n    } else if (prob.type == 'missing') {\n      mustAdd[prob.row] += prob.n;\n    } else if (prob.type == 'overlong_rowspan') {\n      const cell = table.nodeAt(prob.pos);\n      if (!cell) continue;\n      tr.setNodeMarkup(tr.mapping.map(tablePos + 1 + prob.pos), null, {\n        ...cell.attrs,\n        rowspan: cell.attrs.rowspan - prob.n,\n      });\n    } else if (prob.type == 'colwidth mismatch') {\n      const cell = table.nodeAt(prob.pos);\n      if (!cell) continue;\n      tr.setNodeMarkup(tr.mapping.map(tablePos + 1 + prob.pos), null, {\n        ...cell.attrs,\n        colwidth: prob.colwidth,\n      });\n    } else if (prob.type == 'zero_sized') {\n      const pos = tr.mapping.map(tablePos);\n      tr.delete(pos, pos + table.nodeSize);\n    }\n  }\n  let first, last;\n  for (let i = 0; i < mustAdd.length; i++)\n    if (mustAdd[i]) {\n      if (first == null) first = i;\n      last = i;\n    }\n  // Add the necessary cells, using a heuristic for whether to add the\n  // cells at the start or end of the rows (if it looks like a 'bite'\n  // was taken out of the table, add cells at the start of the row\n  // after the bite. Otherwise add them at the end).\n  for (let i = 0, pos = tablePos + 1; i < map.height; i++) {\n    const row = table.child(i);\n    const end = pos + row.nodeSize;\n    const add = mustAdd[i];\n    if (add > 0) {\n      let role: TableRole = 'cell';\n      if (row.firstChild) {\n        role = row.firstChild.type.spec.tableRole;\n      }\n      const nodes: Node[] = [];\n      for (let j = 0; j < add; j++) {\n        const node = tableNodeTypes(state.schema)[role].createAndFill();\n\n        if (node) nodes.push(node);\n      }\n      const side = (i == 0 || first == i - 1) && last == i ? pos + 1 : end - 1;\n      tr.insert(tr.mapping.map(side), nodes);\n    }\n    pos = end;\n  }\n  return tr.setMeta(fixTablesKey, { fixTables: true });\n}\n", "import type { Node } from 'prosemirror-model';\n\nimport { TableMap } from '../tablemap';\n\n/**\n * This function will transform the table node into a matrix of rows and columns\n * respecting merged cells, for example this table:\n *\n * ```\n * ┌──────┬──────┬─────────────┐\n * │  A1  │  B1  │     C1      │\n * ├──────┼──────┴──────┬──────┤\n * │  A2  │     B2      │      │\n * ├──────┼─────────────┤  D1  │\n * │  A3  │  B3  │  C3  │      │\n * └──────┴──────┴──────┴──────┘\n * ```\n *\n * will be converted to the below:\n *\n * ```javascript\n * [\n *   [A1, B1, C1, null],\n *   [A2, B2, null, D1],\n *   [A3, B3, C3, null],\n * ]\n * ```\n * @internal\n */\nexport function convertTableNodeToArrayOfRows(\n  tableNode: Node,\n): (Node | null)[][] {\n  const map = TableMap.get(tableNode);\n  const rows: (Node | null)[][] = [];\n  const rowCount = map.height;\n  const colCount = map.width;\n  for (let rowIndex = 0; rowIndex < rowCount; rowIndex++) {\n    const row: (Node | null)[] = [];\n    for (let colIndex = 0; colIndex < colCount; colIndex++) {\n      const cellIndex = rowIndex * colCount + colIndex;\n      const cellPos = map.map[cellIndex];\n      if (rowIndex > 0) {\n        const topCellIndex = cellIndex - colCount;\n        const topCellPos = map.map[topCellIndex];\n        if (cellPos === topCellPos) {\n          row.push(null);\n          continue;\n        }\n      }\n      if (colIndex > 0) {\n        const leftCellIndex = cellIndex - 1;\n        const leftCellPos = map.map[leftCellIndex];\n        if (cellPos === leftCellPos) {\n          row.push(null);\n          continue;\n        }\n      }\n      row.push(tableNode.nodeAt(cellPos));\n    }\n    rows.push(row);\n  }\n\n  return rows;\n}\n\n/**\n * Convert an array of rows to a table node.\n *\n * @internal\n */\nexport function convertArrayOfRowsToTableNode(\n  tableNode: Node,\n  arrayOfNodes: (Node | null)[][],\n): Node {\n  const newRows: Node[] = [];\n  const map = TableMap.get(tableNode);\n  const rowCount = map.height;\n  const colCount = map.width;\n  for (let rowIndex = 0; rowIndex < rowCount; rowIndex++) {\n    const oldRow: Node = tableNode.child(rowIndex);\n    const newCells: Node[] = [];\n\n    for (let colIndex = 0; colIndex < colCount; colIndex++) {\n      const cell = arrayOfNodes[rowIndex][colIndex];\n      if (!cell) {\n        continue;\n      }\n\n      const cellPos = map.map[rowIndex * map.width + colIndex];\n      const oldCell = tableNode.nodeAt(cellPos);\n      if (!oldCell) {\n        continue;\n      }\n\n      const newCell = oldCell.type.createChecked(\n        cell.attrs,\n        cell.content,\n        cell.marks,\n      );\n      newCells.push(newCell);\n    }\n\n    const newRow = oldRow.type.createChecked(\n      oldRow.attrs,\n      newCells,\n      oldRow.marks,\n    );\n    newRows.push(newRow);\n  }\n\n  const newTable = tableNode.type.createChecked(\n    tableNode.attrs,\n    newRows,\n    tableNode.marks,\n  );\n  return newTable;\n}\n", "/**\n * Move a row in an array of rows.\n *\n * @internal\n */\nexport function moveRowInArrayOfRows<T>(\n  rows: T[],\n  indexesOrigin: number[],\n  indexesTarget: number[],\n  directionOverride: -1 | 1 | 0,\n): T[] {\n  const direction = indexesOrigin[0] > indexesTarget[0] ? -1 : 1;\n\n  const rowsExtracted = rows.splice(indexesOrigin[0], indexesOrigin.length);\n  const positionOffset = rowsExtracted.length % 2 === 0 ? 1 : 0;\n  let target: number;\n\n  if (directionOverride === -1 && direction === 1) {\n    target = indexesTarget[0] - 1;\n  } else if (directionOverride === 1 && direction === -1) {\n    target = indexesTarget[indexesTarget.length - 1] - positionOffset + 1;\n  } else {\n    target =\n      direction === -1\n        ? indexesTarget[0]\n        : indexesTarget[indexesTarget.length - 1] - positionOffset;\n  }\n\n  rows.splice(target, 0, ...rowsExtracted);\n  return rows;\n}\n", "import type { Node, ResolvedPos } from 'prosemirror-model';\nimport type { Selection } from 'prosemirror-state';\n\nimport { CellSelection } from '../cellselection';\nimport { cellAround, cellNear, inSameTable } from '../util';\n\n/**\n * Checks if the given object is a `CellSelection` instance.\n *\n * @internal\n */\nfunction isCellSelection(value: unknown): value is CellSelection {\n  return value instanceof CellSelection;\n}\n\n/**\n * Find the closest table node for a given position.\n *\n * @public\n */\nexport function findTable($pos: ResolvedPos): FindNodeResult | null {\n  return findParentNode((node) => node.type.spec.tableRole === 'table', $pos);\n}\n\n/**\n * Try to find the anchor and head cell in the same table by using the given\n * anchor and head as hit points, or fallback to the selection's anchor and\n * head.\n *\n * @public\n */\nexport function findCellRange(\n  selection: Selection,\n  anchorHit?: number,\n  headHit?: number,\n): [ResolvedPos, ResolvedPos] | null {\n  if (anchorHit == null && headHit == null && isCellSelection(selection)) {\n    return [selection.$anchorCell, selection.$headCell];\n  }\n\n  const anchor: number = anchorHit ?? headHit ?? selection.anchor;\n  const head: number = headHit ?? anchorHit ?? selection.head;\n\n  const doc = selection.$head.doc;\n\n  const $anchorCell = findCellPos(doc, anchor);\n  const $headCell = findCellPos(doc, head);\n\n  if ($anchorCell && $headCell && inSameTable($anchorCell, $headCell)) {\n    return [$anchorCell, $headCell];\n  }\n  return null;\n}\n\n/**\n * Try to find a resolved pos of a cell by using the given pos as a hit point.\n *\n * @public\n */\nexport function findCellPos(doc: Node, pos: number): ResolvedPos | undefined {\n  const $pos = doc.resolve(pos);\n  return cellAround($pos) || cellNear($pos);\n}\n\n/**\n * Result of finding a parent node.\n *\n * @public\n */\nexport interface FindNodeResult {\n  /**\n   * The closest parent node that satisfies the predicate.\n   */\n  node: Node;\n\n  /**\n   * The position directly before the node.\n   */\n  pos: number;\n\n  /**\n   * The position at the start of the node.\n   */\n  start: number;\n\n  /**\n   * The depth of the node.\n   */\n  depth: number;\n}\n\n/**\n * Find the closest parent node that satisfies the predicate.\n *\n * @internal\n */\nfunction findParentNode(\n  /**\n   * The predicate to test the parent node.\n   */\n  predicate: (node: Node) => boolean,\n  /**\n   * The position to start searching from.\n   */\n  $pos: ResolvedPos,\n): FindNodeResult | null {\n  for (let depth = $pos.depth; depth >= 0; depth -= 1) {\n    const node = $pos.node(depth);\n\n    if (predicate(node)) {\n      const pos = depth === 0 ? 0 : $pos.before(depth);\n      const start = $pos.start(depth);\n      return { node, pos, start, depth };\n    }\n  }\n\n  return null;\n}\n", "import type { Selection } from 'prosemirror-state';\n\nimport { TableMap } from '../tablemap';\n\nimport type { FindNodeResult } from './query';\nimport { findTable } from './query';\n\n/**\n * Returns an array of cells in a column at the specified column index.\n *\n * @internal\n */\nexport function getCellsInColumn(\n  columnIndex: number,\n  selection: Selection,\n): FindNodeResult[] | undefined {\n  const table = findTable(selection.$from);\n  if (!table) {\n    return;\n  }\n\n  const map = TableMap.get(table.node);\n\n  if (columnIndex < 0 || columnIndex > map.width - 1) {\n    return;\n  }\n\n  const cells = map.cellsInRect({\n    left: columnIndex,\n    right: columnIndex + 1,\n    top: 0,\n    bottom: map.height,\n  });\n\n  return cells.map((nodePos) => {\n    const node = table.node.nodeAt(nodePos)!;\n    const pos = nodePos + table.start;\n    return { pos, start: pos + 1, node, depth: table.depth + 2 };\n  });\n}\n\n/**\n * Returns an array of cells in a row at the specified row index.\n *\n * @internal\n */\nexport function getCellsInRow(\n  rowIndex: number,\n  selection: Selection,\n): FindNodeResult[] | undefined {\n  const table = findTable(selection.$from);\n  if (!table) {\n    return;\n  }\n\n  const map = TableMap.get(table.node);\n\n  if (rowIndex < 0 || rowIndex > map.height - 1) {\n    return;\n  }\n\n  const cells = map.cellsInRect({\n    left: 0,\n    right: map.width,\n    top: rowIndex,\n    bottom: rowIndex + 1,\n  });\n\n  return cells.map((nodePos) => {\n    const node = table.node.nodeAt(nodePos)!;\n    const pos = nodePos + table.start;\n    return { pos, start: pos + 1, node, depth: table.depth + 2 };\n  });\n}\n", "import type { ResolvedPos } from 'prosemirror-model';\nimport type { Transaction } from 'prosemirror-state';\n\nimport { getCellsInColumn, getCellsInRow } from './get-cells';\n\nexport type CellSelectionRange = {\n  $anchor: ResolvedPos;\n  $head: ResolvedPos;\n  // an array of column/row indexes\n  indexes: number[];\n};\n\n/**\n * Returns a range of rectangular selection spanning all merged cells around a\n * column at index `columnIndex`.\n *\n * Original implementation from Atlassian (Apache License 2.0)\n *\n * https://bitbucket.org/atlassian/atlassian-frontend-mirror/src/5f91cb871e8248bc3bae5ddc30bb9fd9200fadbb/editor/editor-tables/src/utils/get-selection-range-in-column.ts#editor/editor-tables/src/utils/get-selection-range-in-column.ts\n *\n * @internal\n */\nexport function getSelectionRangeInColumn(\n  tr: Transaction,\n  startColIndex: number,\n  endColIndex: number = startColIndex,\n): CellSelectionRange | undefined {\n  let startIndex = startColIndex;\n  let endIndex = endColIndex;\n\n  // looking for selection start column (startIndex)\n  for (let i = startColIndex; i >= 0; i--) {\n    const cells = getCellsInColumn(i, tr.selection);\n    if (cells) {\n      cells.forEach((cell) => {\n        const maybeEndIndex = cell.node.attrs.colspan + i - 1;\n        if (maybeEndIndex >= startIndex) {\n          startIndex = i;\n        }\n        if (maybeEndIndex > endIndex) {\n          endIndex = maybeEndIndex;\n        }\n      });\n    }\n  }\n  // looking for selection end column (endIndex)\n  for (let i = startColIndex; i <= endIndex; i++) {\n    const cells = getCellsInColumn(i, tr.selection);\n    if (cells) {\n      cells.forEach((cell) => {\n        const maybeEndIndex = cell.node.attrs.colspan + i - 1;\n        if (cell.node.attrs.colspan > 1 && maybeEndIndex > endIndex) {\n          endIndex = maybeEndIndex;\n        }\n      });\n    }\n  }\n\n  // filter out columns without cells (where all rows have colspan > 1 in the same column)\n  const indexes = [];\n  for (let i = startIndex; i <= endIndex; i++) {\n    const maybeCells = getCellsInColumn(i, tr.selection);\n    if (maybeCells && maybeCells.length > 0) {\n      indexes.push(i);\n    }\n  }\n  startIndex = indexes[0];\n  endIndex = indexes[indexes.length - 1];\n\n  const firstSelectedColumnCells = getCellsInColumn(startIndex, tr.selection);\n  const firstRowCells = getCellsInRow(0, tr.selection);\n  if (!firstSelectedColumnCells || !firstRowCells) {\n    return;\n  }\n\n  const $anchor = tr.doc.resolve(\n    firstSelectedColumnCells[firstSelectedColumnCells.length - 1].pos,\n  );\n\n  let headCell;\n  for (let i = endIndex; i >= startIndex; i--) {\n    const columnCells = getCellsInColumn(i, tr.selection);\n    if (columnCells && columnCells.length > 0) {\n      for (let j = firstRowCells.length - 1; j >= 0; j--) {\n        if (firstRowCells[j].pos === columnCells[0].pos) {\n          headCell = columnCells[0];\n          break;\n        }\n      }\n      if (headCell) {\n        break;\n      }\n    }\n  }\n  if (!headCell) {\n    return;\n  }\n\n  const $head = tr.doc.resolve(headCell.pos);\n  return { $anchor, $head, indexes };\n}\n\n/**\n * Returns a range of rectangular selection spanning all merged cells around a\n * row at index `rowIndex`.\n *\n * Original implementation from Atlassian (Apache License 2.0)\n *\n * https://bitbucket.org/atlassian/atlassian-frontend-mirror/src/5f91cb871e8248bc3bae5ddc30bb9fd9200fadbb/editor/editor-tables/src/utils/get-selection-range-in-row.ts#editor/editor-tables/src/utils/get-selection-range-in-row.ts\n *\n * @internal\n */\nexport function getSelectionRangeInRow(\n  tr: Transaction,\n  startRowIndex: number,\n  endRowIndex: number = startRowIndex,\n): CellSelectionRange | undefined {\n  let startIndex = startRowIndex;\n  let endIndex = endRowIndex;\n\n  // looking for selection start row (startIndex)\n  for (let i = startRowIndex; i >= 0; i--) {\n    const cells = getCellsInRow(i, tr.selection);\n    if (cells) {\n      cells.forEach((cell) => {\n        const maybeEndIndex = cell.node.attrs.rowspan + i - 1;\n        if (maybeEndIndex >= startIndex) {\n          startIndex = i;\n        }\n        if (maybeEndIndex > endIndex) {\n          endIndex = maybeEndIndex;\n        }\n      });\n    }\n  }\n  // looking for selection end row (endIndex)\n  for (let i = startRowIndex; i <= endIndex; i++) {\n    const cells = getCellsInRow(i, tr.selection);\n    if (cells) {\n      cells.forEach((cell) => {\n        const maybeEndIndex = cell.node.attrs.rowspan + i - 1;\n        if (cell.node.attrs.rowspan > 1 && maybeEndIndex > endIndex) {\n          endIndex = maybeEndIndex;\n        }\n      });\n    }\n  }\n\n  // filter out rows without cells (where all columns have rowspan > 1 in the same row)\n  const indexes = [];\n  for (let i = startIndex; i <= endIndex; i++) {\n    const maybeCells = getCellsInRow(i, tr.selection);\n    if (maybeCells && maybeCells.length > 0) {\n      indexes.push(i);\n    }\n  }\n  startIndex = indexes[0];\n  endIndex = indexes[indexes.length - 1];\n\n  const firstSelectedRowCells = getCellsInRow(startIndex, tr.selection);\n  const firstColumnCells = getCellsInColumn(0, tr.selection);\n  if (!firstSelectedRowCells || !firstColumnCells) {\n    return;\n  }\n\n  const $anchor = tr.doc.resolve(\n    firstSelectedRowCells[firstSelectedRowCells.length - 1].pos,\n  );\n\n  let headCell;\n  for (let i = endIndex; i >= startIndex; i--) {\n    const rowCells = getCellsInRow(i, tr.selection);\n    if (rowCells && rowCells.length > 0) {\n      for (let j = firstColumnCells.length - 1; j >= 0; j--) {\n        if (firstColumnCells[j].pos === rowCells[0].pos) {\n          headCell = rowCells[0];\n          break;\n        }\n      }\n      if (headCell) {\n        break;\n      }\n    }\n  }\n  if (!headCell) {\n    return;\n  }\n\n  const $head = tr.doc.resolve(headCell.pos);\n  return { $anchor, $head, indexes };\n}\n", "/**\n * Transposes a 2D array by flipping columns to rows.\n *\n * Transposition is a familiar algebra concept where the matrix is flipped\n * along its diagonal. For more details, see:\n * https://en.wikipedia.org/wiki/Transpose\n *\n * @example\n * ```javascript\n * const arr = [\n *   ['a1', 'a2', 'a3'],\n *   ['b1', 'b2', 'b3'],\n *   ['c1', 'c2', 'c3'],\n *   ['d1', 'd2', 'd3'],\n * ];\n *\n * const result = transpose(arr);\n * result === [\n *   ['a1', 'b1', 'c1', 'd1'],\n *   ['a2', 'b2', 'c2', 'd2'],\n *   ['a3', 'b3', 'c3', 'd3'],\n * ]\n * ```\n */\nexport function transpose<T>(array: T[][]): T[][] {\n  return array[0].map((_, i) => {\n    return array.map((column) => column[i]);\n  });\n}\n", "import type { Node } from 'prosemirror-model';\nimport type { Transaction } from 'prosemirror-state';\n\nimport { CellSelection } from '../cellselection';\nimport { TableMap } from '../tablemap';\n\nimport {\n  convertArrayOfRowsToTableNode,\n  convertTableNodeToArrayOfRows,\n} from './convert';\nimport { moveRowInArrayOfRows } from './move-row-in-array-of-rows';\nimport { findTable } from './query';\nimport { getSelectionRangeInColumn } from './selection-range';\nimport { transpose } from './transpose';\n\n/**\n * Parameters for moving a column in a table.\n *\n * @internal\n */\nexport interface MoveColumnParams {\n  tr: Transaction;\n  originIndex: number;\n  targetIndex: number;\n  select: boolean;\n  pos: number;\n}\n\n/**\n * Move a column from index `origin` to index `target`.\n *\n * @internal\n */\nexport function moveColumn(moveColParams: MoveColumnParams): boolean {\n  const { tr, originIndex, targetIndex, select, pos } = moveColParams;\n  const $pos = tr.doc.resolve(pos);\n  const table = findTable($pos);\n  if (!table) return false;\n\n  const indexesOriginColumn = getSelectionRangeInColumn(\n    tr,\n    originIndex,\n  )?.indexes;\n  const indexesTargetColumn = getSelectionRangeInColumn(\n    tr,\n    targetIndex,\n  )?.indexes;\n\n  if (!indexesOriginColumn || !indexesTargetColumn) return false;\n\n  if (indexesOriginColumn.includes(targetIndex)) return false;\n\n  const newTable = moveTableColumn(\n    table.node,\n    indexesOriginColumn,\n    indexesTargetColumn,\n    0,\n  );\n\n  tr.replaceWith(table.pos, table.pos + table.node.nodeSize, newTable);\n\n  if (!select) return true;\n\n  const map = TableMap.get(newTable);\n  const start = table.start;\n  const index = targetIndex;\n  const lastCell = map.positionAt(map.height - 1, index, newTable);\n  const $lastCell = tr.doc.resolve(start + lastCell);\n\n  const firstCell = map.positionAt(0, index, newTable);\n  const $firstCell = tr.doc.resolve(start + firstCell);\n\n  tr.setSelection(CellSelection.colSelection($lastCell, $firstCell));\n  return true;\n}\n\nfunction moveTableColumn(\n  table: Node,\n  indexesOrigin: number[],\n  indexesTarget: number[],\n  direction: -1 | 1 | 0,\n) {\n  let rows = transpose(convertTableNodeToArrayOfRows(table));\n\n  rows = moveRowInArrayOfRows(rows, indexesOrigin, indexesTarget, direction);\n  rows = transpose(rows);\n\n  return convertArrayOfRowsToTableNode(table, rows);\n}\n", "import type { Node } from 'prosemirror-model';\nimport type { Transaction } from 'prosemirror-state';\n\nimport { CellSelection } from '../cellselection';\nimport { TableMap } from '../tablemap';\n\nimport {\n  convertArrayOfRowsToTableNode,\n  convertTableNodeToArrayOfRows,\n} from './convert';\nimport { moveRowInArrayOfRows } from './move-row-in-array-of-rows';\nimport { findTable } from './query';\nimport { getSelectionRangeInRow } from './selection-range';\n\n/**\n * Parameters for moving a row in a table.\n *\n * @internal\n */\nexport interface MoveRowParams {\n  tr: Transaction;\n  originIndex: number;\n  targetIndex: number;\n  select: boolean;\n  pos: number;\n}\n\n/**\n * Move a row from index `origin` to index `target`.\n *\n * @internal\n */\nexport function moveRow(moveRowParams: MoveRowParams): boolean {\n  const { tr, originIndex, targetIndex, select, pos } = moveRowParams;\n  const $pos = tr.doc.resolve(pos);\n  const table = findTable($pos);\n  if (!table) return false;\n\n  const indexesOriginRow = getSelectionRangeInRow(tr, originIndex)?.indexes;\n  const indexesTargetRow = getSelectionRangeInRow(tr, targetIndex)?.indexes;\n\n  if (!indexesOriginRow || !indexesTargetRow) return false;\n\n  if (indexesOriginRow.includes(targetIndex)) return false;\n\n  const newTable = moveTableRow(\n    table.node,\n    indexesOriginRow,\n    indexesTargetRow,\n    0,\n  );\n\n  tr.replaceWith(table.pos, table.pos + table.node.nodeSize, newTable);\n\n  if (!select) return true;\n\n  const map = TableMap.get(newTable);\n  const start = table.start;\n  const index = targetIndex;\n  const lastCell = map.positionAt(index, map.width - 1, newTable);\n  const $lastCell = tr.doc.resolve(start + lastCell);\n\n  const firstCell = map.positionAt(index, 0, newTable);\n  const $firstCell = tr.doc.resolve(start + firstCell);\n\n  tr.setSelection(CellSelection.rowSelection($lastCell, $firstCell));\n  return true;\n}\n\nfunction moveTableRow(\n  table: Node,\n  indexesOrigin: number[],\n  indexesTarget: number[],\n  direction: -1 | 1 | 0,\n) {\n  let rows = convertTableNodeToArrayOfRows(table);\n\n  rows = moveRowInArrayOfRows(rows, indexesOrigin, indexesTarget, direction);\n\n  return convertArrayOfRowsToTableNode(table, rows);\n}\n", "// This file defines a number of table-related commands.\n\nimport type { Node, NodeType, ResolvedPos } from 'prosemirror-model';\nimport { Fragment, Slice } from 'prosemirror-model';\nimport type { Command, EditorState, Transaction } from 'prosemirror-state';\nimport { TextSelection } from 'prosemirror-state';\n\nimport { CellSelection } from './cellselection';\nimport type { Direction } from './input';\nimport type { TableRole } from './schema';\nimport { tableNodeTypes } from './schema';\nimport type { Rect } from './tablemap';\nimport { TableMap } from './tablemap';\nimport type { CellAttrs } from './util';\nimport {\n  addColSpan,\n  cellAround,\n  cellWrapping,\n  columnIsHeader,\n  isInTable,\n  moveCellForward,\n  removeColSpan,\n  selectionCell,\n} from './util';\nimport { moveColumn } from './utils/move-column';\nimport { moveRow } from './utils/move-row';\n\n/**\n * @public\n */\nexport type TableRect = Rect & {\n  tableStart: number;\n  map: TableMap;\n  table: Node;\n};\n\n/**\n * Helper to get the selected rectangle in a table, if any. Adds table\n * map, table node, and table start offset to the object for\n * convenience.\n *\n * @public\n */\nexport function selectedRect(state: EditorState): TableRect {\n  const sel = state.selection;\n  const $pos = selectionCell(state);\n  const table = $pos.node(-1);\n  const tableStart = $pos.start(-1);\n  const map = TableMap.get(table);\n  const rect =\n    sel instanceof CellSelection\n      ? map.rectBetween(\n          sel.$anchorCell.pos - tableStart,\n          sel.$headCell.pos - tableStart,\n        )\n      : map.findCell($pos.pos - tableStart);\n  return { ...rect, tableStart, map, table };\n}\n\n/**\n * Add a column at the given position in a table.\n *\n * @public\n */\nexport function addColumn(\n  tr: Transaction,\n  { map, tableStart, table }: TableRect,\n  col: number,\n): Transaction {\n  let refColumn: number | null = col > 0 ? -1 : 0;\n  if (columnIsHeader(map, table, col + refColumn)) {\n    refColumn = col == 0 || col == map.width ? null : 0;\n  }\n\n  for (let row = 0; row < map.height; row++) {\n    const index = row * map.width + col;\n    // If this position falls inside a col-spanning cell\n    if (col > 0 && col < map.width && map.map[index - 1] == map.map[index]) {\n      const pos = map.map[index];\n      const cell = table.nodeAt(pos)!;\n      tr.setNodeMarkup(\n        tr.mapping.map(tableStart + pos),\n        null,\n        addColSpan(cell.attrs as CellAttrs, col - map.colCount(pos)),\n      );\n      // Skip ahead if rowspan > 1\n      row += cell.attrs.rowspan - 1;\n    } else {\n      const type =\n        refColumn == null\n          ? tableNodeTypes(table.type.schema).cell\n          : table.nodeAt(map.map[index + refColumn])!.type;\n      const pos = map.positionAt(row, col, table);\n      tr.insert(tr.mapping.map(tableStart + pos), type.createAndFill()!);\n    }\n  }\n  return tr;\n}\n\n/**\n * Command to add a column before the column with the selection.\n *\n * @public\n */\nexport function addColumnBefore(\n  state: EditorState,\n  dispatch?: (tr: Transaction) => void,\n): boolean {\n  if (!isInTable(state)) return false;\n  if (dispatch) {\n    const rect = selectedRect(state);\n    dispatch(addColumn(state.tr, rect, rect.left));\n  }\n  return true;\n}\n\n/**\n * Command to add a column after the column with the selection.\n *\n * @public\n */\nexport function addColumnAfter(\n  state: EditorState,\n  dispatch?: (tr: Transaction) => void,\n): boolean {\n  if (!isInTable(state)) return false;\n  if (dispatch) {\n    const rect = selectedRect(state);\n    dispatch(addColumn(state.tr, rect, rect.right));\n  }\n  return true;\n}\n\n/**\n * @public\n */\nexport function removeColumn(\n  tr: Transaction,\n  { map, table, tableStart }: TableRect,\n  col: number,\n) {\n  const mapStart = tr.mapping.maps.length;\n  for (let row = 0; row < map.height; ) {\n    const index = row * map.width + col;\n    const pos = map.map[index];\n    const cell = table.nodeAt(pos)!;\n    const attrs = cell.attrs as CellAttrs;\n    // If this is part of a col-spanning cell\n    if (\n      (col > 0 && map.map[index - 1] == pos) ||\n      (col < map.width - 1 && map.map[index + 1] == pos)\n    ) {\n      tr.setNodeMarkup(\n        tr.mapping.slice(mapStart).map(tableStart + pos),\n        null,\n        removeColSpan(attrs, col - map.colCount(pos)),\n      );\n    } else {\n      const start = tr.mapping.slice(mapStart).map(tableStart + pos);\n      tr.delete(start, start + cell.nodeSize);\n    }\n    row += attrs.rowspan;\n  }\n}\n\n/**\n * Command function that removes the selected columns from a table.\n *\n * @public\n */\nexport function deleteColumn(\n  state: EditorState,\n  dispatch?: (tr: Transaction) => void,\n): boolean {\n  if (!isInTable(state)) return false;\n  if (dispatch) {\n    const rect = selectedRect(state);\n    const tr = state.tr;\n    if (rect.left == 0 && rect.right == rect.map.width) return false;\n    for (let i = rect.right - 1; ; i--) {\n      removeColumn(tr, rect, i);\n      if (i == rect.left) break;\n      const table = rect.tableStart\n        ? tr.doc.nodeAt(rect.tableStart - 1)\n        : tr.doc;\n      if (!table) {\n        throw new RangeError('No table found');\n      }\n      rect.table = table;\n      rect.map = TableMap.get(table);\n    }\n    dispatch(tr);\n  }\n  return true;\n}\n\n/**\n * @public\n */\nexport function rowIsHeader(map: TableMap, table: Node, row: number): boolean {\n  const headerCell = tableNodeTypes(table.type.schema).header_cell;\n  for (let col = 0; col < map.width; col++)\n    if (table.nodeAt(map.map[col + row * map.width])?.type != headerCell)\n      return false;\n  return true;\n}\n\n/**\n * @public\n */\nexport function addRow(\n  tr: Transaction,\n  { map, tableStart, table }: TableRect,\n  row: number,\n): Transaction {\n  let rowPos = tableStart;\n  for (let i = 0; i < row; i++) rowPos += table.child(i).nodeSize;\n  const cells = [];\n  let refRow: number | null = row > 0 ? -1 : 0;\n  if (rowIsHeader(map, table, row + refRow))\n    refRow = row == 0 || row == map.height ? null : 0;\n  for (let col = 0, index = map.width * row; col < map.width; col++, index++) {\n    // Covered by a rowspan cell\n    if (\n      row > 0 &&\n      row < map.height &&\n      map.map[index] == map.map[index - map.width]\n    ) {\n      const pos = map.map[index];\n      const attrs = table.nodeAt(pos)!.attrs;\n      tr.setNodeMarkup(tableStart + pos, null, {\n        ...attrs,\n        rowspan: attrs.rowspan + 1,\n      });\n      col += attrs.colspan - 1;\n    } else {\n      const type =\n        refRow == null\n          ? tableNodeTypes(table.type.schema).cell\n          : table.nodeAt(map.map[index + refRow * map.width])?.type;\n      const node = type?.createAndFill();\n      if (node) cells.push(node);\n    }\n  }\n  tr.insert(rowPos, tableNodeTypes(table.type.schema).row.create(null, cells));\n  return tr;\n}\n\n/**\n * Add a table row before the selection.\n *\n * @public\n */\nexport function addRowBefore(\n  state: EditorState,\n  dispatch?: (tr: Transaction) => void,\n): boolean {\n  if (!isInTable(state)) return false;\n  if (dispatch) {\n    const rect = selectedRect(state);\n    dispatch(addRow(state.tr, rect, rect.top));\n  }\n  return true;\n}\n\n/**\n * Add a table row after the selection.\n *\n * @public\n */\nexport function addRowAfter(\n  state: EditorState,\n  dispatch?: (tr: Transaction) => void,\n): boolean {\n  if (!isInTable(state)) return false;\n  if (dispatch) {\n    const rect = selectedRect(state);\n    dispatch(addRow(state.tr, rect, rect.bottom));\n  }\n  return true;\n}\n\n/**\n * @public\n */\nexport function removeRow(\n  tr: Transaction,\n  { map, table, tableStart }: TableRect,\n  row: number,\n): void {\n  let rowPos = 0;\n  for (let i = 0; i < row; i++) rowPos += table.child(i).nodeSize;\n  const nextRow = rowPos + table.child(row).nodeSize;\n\n  const mapFrom = tr.mapping.maps.length;\n  tr.delete(rowPos + tableStart, nextRow + tableStart);\n\n  const seen = new Set<number>();\n\n  for (let col = 0, index = row * map.width; col < map.width; col++, index++) {\n    const pos = map.map[index];\n\n    // Skip cells that are checked already\n    if (seen.has(pos)) continue;\n    seen.add(pos);\n\n    if (row > 0 && pos == map.map[index - map.width]) {\n      // If this cell starts in the row above, simply reduce its rowspan\n      const attrs = table.nodeAt(pos)!.attrs as CellAttrs;\n      tr.setNodeMarkup(tr.mapping.slice(mapFrom).map(pos + tableStart), null, {\n        ...attrs,\n        rowspan: attrs.rowspan - 1,\n      });\n      col += attrs.colspan - 1;\n    } else if (row < map.height && pos == map.map[index + map.width]) {\n      // Else, if it continues in the row below, it has to be moved down\n      const cell = table.nodeAt(pos)!;\n      const attrs = cell.attrs as CellAttrs;\n      const copy = cell.type.create(\n        { ...attrs, rowspan: cell.attrs.rowspan - 1 },\n        cell.content,\n      );\n      const newPos = map.positionAt(row + 1, col, table);\n      tr.insert(tr.mapping.slice(mapFrom).map(tableStart + newPos), copy);\n      col += attrs.colspan - 1;\n    }\n  }\n}\n\n/**\n * Remove the selected rows from a table.\n *\n * @public\n */\nexport function deleteRow(\n  state: EditorState,\n  dispatch?: (tr: Transaction) => void,\n): boolean {\n  if (!isInTable(state)) return false;\n  if (dispatch) {\n    const rect = selectedRect(state),\n      tr = state.tr;\n    if (rect.top == 0 && rect.bottom == rect.map.height) return false;\n    for (let i = rect.bottom - 1; ; i--) {\n      removeRow(tr, rect, i);\n      if (i == rect.top) break;\n      const table = rect.tableStart\n        ? tr.doc.nodeAt(rect.tableStart - 1)\n        : tr.doc;\n      if (!table) {\n        throw new RangeError('No table found');\n      }\n      rect.table = table;\n      rect.map = TableMap.get(rect.table);\n    }\n    dispatch(tr);\n  }\n  return true;\n}\n\nfunction isEmpty(cell: Node): boolean {\n  const c = cell.content;\n\n  return (\n    c.childCount == 1 && c.child(0).isTextblock && c.child(0).childCount == 0\n  );\n}\n\nfunction cellsOverlapRectangle({ width, height, map }: TableMap, rect: Rect) {\n  let indexTop = rect.top * width + rect.left,\n    indexLeft = indexTop;\n  let indexBottom = (rect.bottom - 1) * width + rect.left,\n    indexRight = indexTop + (rect.right - rect.left - 1);\n  for (let i = rect.top; i < rect.bottom; i++) {\n    if (\n      (rect.left > 0 && map[indexLeft] == map[indexLeft - 1]) ||\n      (rect.right < width && map[indexRight] == map[indexRight + 1])\n    )\n      return true;\n    indexLeft += width;\n    indexRight += width;\n  }\n  for (let i = rect.left; i < rect.right; i++) {\n    if (\n      (rect.top > 0 && map[indexTop] == map[indexTop - width]) ||\n      (rect.bottom < height && map[indexBottom] == map[indexBottom + width])\n    )\n      return true;\n    indexTop++;\n    indexBottom++;\n  }\n  return false;\n}\n\n/**\n * Merge the selected cells into a single cell. Only available when\n * the selected cells' outline forms a rectangle.\n *\n * @public\n */\nexport function mergeCells(\n  state: EditorState,\n  dispatch?: (tr: Transaction) => void,\n): boolean {\n  const sel = state.selection;\n  if (\n    !(sel instanceof CellSelection) ||\n    sel.$anchorCell.pos == sel.$headCell.pos\n  )\n    return false;\n  const rect = selectedRect(state),\n    { map } = rect;\n  if (cellsOverlapRectangle(map, rect)) return false;\n  if (dispatch) {\n    const tr = state.tr;\n    const seen: Record<number, boolean> = {};\n    let content = Fragment.empty;\n    let mergedPos: number | undefined;\n    let mergedCell: Node | undefined;\n    for (let row = rect.top; row < rect.bottom; row++) {\n      for (let col = rect.left; col < rect.right; col++) {\n        const cellPos = map.map[row * map.width + col];\n        const cell = rect.table.nodeAt(cellPos);\n        if (seen[cellPos] || !cell) continue;\n        seen[cellPos] = true;\n        if (mergedPos == null) {\n          mergedPos = cellPos;\n          mergedCell = cell;\n        } else {\n          if (!isEmpty(cell)) content = content.append(cell.content);\n          const mapped = tr.mapping.map(cellPos + rect.tableStart);\n          tr.delete(mapped, mapped + cell.nodeSize);\n        }\n      }\n    }\n    if (mergedPos == null || mergedCell == null) {\n      return true;\n    }\n\n    tr.setNodeMarkup(mergedPos + rect.tableStart, null, {\n      ...addColSpan(\n        mergedCell.attrs as CellAttrs,\n        mergedCell.attrs.colspan,\n        rect.right - rect.left - mergedCell.attrs.colspan,\n      ),\n      rowspan: rect.bottom - rect.top,\n    });\n    if (content.size > 0) {\n      const end = mergedPos + 1 + mergedCell.content.size;\n      const start = isEmpty(mergedCell) ? mergedPos + 1 : end;\n      tr.replaceWith(start + rect.tableStart, end + rect.tableStart, content);\n    }\n    tr.setSelection(\n      new CellSelection(tr.doc.resolve(mergedPos + rect.tableStart)),\n    );\n    dispatch(tr);\n  }\n  return true;\n}\n\n/**\n * Split a selected cell, whose rowpan or colspan is greater than one,\n * into smaller cells. Use the first cell type for the new cells.\n *\n * @public\n */\nexport function splitCell(\n  state: EditorState,\n  dispatch?: (tr: Transaction) => void,\n): boolean {\n  const nodeTypes = tableNodeTypes(state.schema);\n  return splitCellWithType(({ node }) => {\n    return nodeTypes[node.type.spec.tableRole as TableRole];\n  })(state, dispatch);\n}\n\n/**\n * @public\n */\nexport interface GetCellTypeOptions {\n  node: Node;\n  row: number;\n  col: number;\n}\n\n/**\n * Split a selected cell, whose rowpan or colspan is greater than one,\n * into smaller cells with the cell type (th, td) returned by getType function.\n *\n * @public\n */\nexport function splitCellWithType(\n  getCellType: (options: GetCellTypeOptions) => NodeType,\n): Command {\n  return (state, dispatch) => {\n    const sel = state.selection;\n    let cellNode: Node | null | undefined;\n    let cellPos: number | undefined;\n    if (!(sel instanceof CellSelection)) {\n      cellNode = cellWrapping(sel.$from);\n      if (!cellNode) return false;\n      cellPos = cellAround(sel.$from)?.pos;\n    } else {\n      if (sel.$anchorCell.pos != sel.$headCell.pos) return false;\n      cellNode = sel.$anchorCell.nodeAfter;\n      cellPos = sel.$anchorCell.pos;\n    }\n    if (cellNode == null || cellPos == null) {\n      return false;\n    }\n    if (cellNode.attrs.colspan == 1 && cellNode.attrs.rowspan == 1) {\n      return false;\n    }\n    if (dispatch) {\n      let baseAttrs = cellNode.attrs;\n      const attrs = [];\n      const colwidth = baseAttrs.colwidth;\n      if (baseAttrs.rowspan > 1) baseAttrs = { ...baseAttrs, rowspan: 1 };\n      if (baseAttrs.colspan > 1) baseAttrs = { ...baseAttrs, colspan: 1 };\n      const rect = selectedRect(state),\n        tr = state.tr;\n      for (let i = 0; i < rect.right - rect.left; i++)\n        attrs.push(\n          colwidth\n            ? {\n                ...baseAttrs,\n                colwidth: colwidth && colwidth[i] ? [colwidth[i]] : null,\n              }\n            : baseAttrs,\n        );\n      let lastCell;\n      for (let row = rect.top; row < rect.bottom; row++) {\n        let pos = rect.map.positionAt(row, rect.left, rect.table);\n        if (row == rect.top) pos += cellNode.nodeSize;\n        for (let col = rect.left, i = 0; col < rect.right; col++, i++) {\n          if (col == rect.left && row == rect.top) continue;\n          tr.insert(\n            (lastCell = tr.mapping.map(pos + rect.tableStart, 1)),\n            getCellType({ node: cellNode, row, col }).createAndFill(attrs[i])!,\n          );\n        }\n      }\n      tr.setNodeMarkup(\n        cellPos,\n        getCellType({ node: cellNode, row: rect.top, col: rect.left }),\n        attrs[0],\n      );\n      if (sel instanceof CellSelection)\n        tr.setSelection(\n          new CellSelection(\n            tr.doc.resolve(sel.$anchorCell.pos),\n            lastCell ? tr.doc.resolve(lastCell) : undefined,\n          ),\n        );\n      dispatch(tr);\n    }\n    return true;\n  };\n}\n\n/**\n * Returns a command that sets the given attribute to the given value,\n * and is only available when the currently selected cell doesn't\n * already have that attribute set to that value.\n *\n * @public\n */\nexport function setCellAttr(name: string, value: unknown): Command {\n  return function (state, dispatch) {\n    if (!isInTable(state)) return false;\n    const $cell = selectionCell(state);\n    if ($cell.nodeAfter!.attrs[name] === value) return false;\n    if (dispatch) {\n      const tr = state.tr;\n      if (state.selection instanceof CellSelection)\n        state.selection.forEachCell((node, pos) => {\n          if (node.attrs[name] !== value)\n            tr.setNodeMarkup(pos, null, {\n              ...node.attrs,\n              [name]: value,\n            });\n        });\n      else\n        tr.setNodeMarkup($cell.pos, null, {\n          ...$cell.nodeAfter!.attrs,\n          [name]: value,\n        });\n      dispatch(tr);\n    }\n    return true;\n  };\n}\n\nfunction deprecated_toggleHeader(type: ToggleHeaderType): Command {\n  return function (state, dispatch) {\n    if (!isInTable(state)) return false;\n    if (dispatch) {\n      const types = tableNodeTypes(state.schema);\n      const rect = selectedRect(state),\n        tr = state.tr;\n      const cells = rect.map.cellsInRect(\n        type == 'column'\n          ? {\n              left: rect.left,\n              top: 0,\n              right: rect.right,\n              bottom: rect.map.height,\n            }\n          : type == 'row'\n            ? {\n                left: 0,\n                top: rect.top,\n                right: rect.map.width,\n                bottom: rect.bottom,\n              }\n            : rect,\n      );\n      const nodes = cells.map((pos) => rect.table.nodeAt(pos)!);\n      for (\n        let i = 0;\n        i < cells.length;\n        i++ // Remove headers, if any\n      )\n        if (nodes[i].type == types.header_cell)\n          tr.setNodeMarkup(\n            rect.tableStart + cells[i],\n            types.cell,\n            nodes[i].attrs,\n          );\n      if (tr.steps.length === 0)\n        for (\n          let i = 0;\n          i < cells.length;\n          i++ // No headers removed, add instead\n        )\n          tr.setNodeMarkup(\n            rect.tableStart + cells[i],\n            types.header_cell,\n            nodes[i].attrs,\n          );\n      dispatch(tr);\n    }\n    return true;\n  };\n}\n\nfunction isHeaderEnabledByType(\n  type: 'row' | 'column',\n  rect: TableRect,\n  types: Record<string, NodeType>,\n): boolean {\n  // Get cell positions for first row or first column\n  const cellPositions = rect.map.cellsInRect({\n    left: 0,\n    top: 0,\n    right: type == 'row' ? rect.map.width : 1,\n    bottom: type == 'column' ? rect.map.height : 1,\n  });\n\n  for (let i = 0; i < cellPositions.length; i++) {\n    const cell = rect.table.nodeAt(cellPositions[i]);\n    if (cell && cell.type !== types.header_cell) {\n      return false;\n    }\n  }\n\n  return true;\n}\n\n/**\n * @public\n */\nexport type ToggleHeaderType = 'column' | 'row' | 'cell';\n\n/**\n * Toggles between row/column header and normal cells (Only applies to first row/column).\n * For deprecated behavior pass `useDeprecatedLogic` in options with true.\n *\n * @public\n */\nexport function toggleHeader(\n  type: ToggleHeaderType,\n  options?: { useDeprecatedLogic: boolean },\n): Command {\n  options = options || { useDeprecatedLogic: false };\n\n  if (options.useDeprecatedLogic) return deprecated_toggleHeader(type);\n\n  return function (state, dispatch) {\n    if (!isInTable(state)) return false;\n    if (dispatch) {\n      const types = tableNodeTypes(state.schema);\n      const rect = selectedRect(state),\n        tr = state.tr;\n\n      const isHeaderRowEnabled = isHeaderEnabledByType('row', rect, types);\n      const isHeaderColumnEnabled = isHeaderEnabledByType(\n        'column',\n        rect,\n        types,\n      );\n\n      const isHeaderEnabled =\n        type === 'column'\n          ? isHeaderRowEnabled\n          : type === 'row'\n            ? isHeaderColumnEnabled\n            : false;\n\n      const selectionStartsAt = isHeaderEnabled ? 1 : 0;\n\n      const cellsRect =\n        type == 'column'\n          ? {\n              left: 0,\n              top: selectionStartsAt,\n              right: 1,\n              bottom: rect.map.height,\n            }\n          : type == 'row'\n            ? {\n                left: selectionStartsAt,\n                top: 0,\n                right: rect.map.width,\n                bottom: 1,\n              }\n            : rect;\n\n      const newType =\n        type == 'column'\n          ? isHeaderColumnEnabled\n            ? types.cell\n            : types.header_cell\n          : type == 'row'\n            ? isHeaderRowEnabled\n              ? types.cell\n              : types.header_cell\n            : types.cell;\n\n      rect.map.cellsInRect(cellsRect).forEach((relativeCellPos) => {\n        const cellPos = relativeCellPos + rect.tableStart;\n        const cell = tr.doc.nodeAt(cellPos);\n\n        if (cell) {\n          tr.setNodeMarkup(cellPos, newType, cell.attrs);\n        }\n      });\n\n      dispatch(tr);\n    }\n    return true;\n  };\n}\n\n/**\n * Toggles whether the selected row contains header cells.\n *\n * @public\n */\nexport const toggleHeaderRow: Command = toggleHeader('row', {\n  useDeprecatedLogic: true,\n});\n\n/**\n * Toggles whether the selected column contains header cells.\n *\n * @public\n */\nexport const toggleHeaderColumn: Command = toggleHeader('column', {\n  useDeprecatedLogic: true,\n});\n\n/**\n * Toggles whether the selected cells are header cells.\n *\n * @public\n */\nexport const toggleHeaderCell: Command = toggleHeader('cell', {\n  useDeprecatedLogic: true,\n});\n\nfunction findNextCell($cell: ResolvedPos, dir: Direction): number | null {\n  if (dir < 0) {\n    const before = $cell.nodeBefore;\n    if (before) return $cell.pos - before.nodeSize;\n    for (\n      let row = $cell.index(-1) - 1, rowEnd = $cell.before();\n      row >= 0;\n      row--\n    ) {\n      const rowNode = $cell.node(-1).child(row);\n      const lastChild = rowNode.lastChild;\n      if (lastChild) {\n        return rowEnd - 1 - lastChild.nodeSize;\n      }\n      rowEnd -= rowNode.nodeSize;\n    }\n  } else {\n    if ($cell.index() < $cell.parent.childCount - 1) {\n      return $cell.pos + $cell.nodeAfter!.nodeSize;\n    }\n    const table = $cell.node(-1);\n    for (\n      let row = $cell.indexAfter(-1), rowStart = $cell.after();\n      row < table.childCount;\n      row++\n    ) {\n      const rowNode = table.child(row);\n      if (rowNode.childCount) return rowStart + 1;\n      rowStart += rowNode.nodeSize;\n    }\n  }\n  return null;\n}\n\n/**\n * Returns a command for selecting the next (direction=1) or previous\n * (direction=-1) cell in a table.\n *\n * @public\n */\nexport function goToNextCell(direction: Direction): Command {\n  return function (state, dispatch) {\n    if (!isInTable(state)) return false;\n    const cell = findNextCell(selectionCell(state), direction);\n    if (cell == null) return false;\n    if (dispatch) {\n      const $cell = state.doc.resolve(cell);\n      dispatch(\n        state.tr\n          .setSelection(TextSelection.between($cell, moveCellForward($cell)))\n          .scrollIntoView(),\n      );\n    }\n    return true;\n  };\n}\n\n/**\n * Deletes the table around the selection, if any.\n *\n * @public\n */\nexport function deleteTable(\n  state: EditorState,\n  dispatch?: (tr: Transaction) => void,\n): boolean {\n  const $pos = state.selection.$anchor;\n  for (let d = $pos.depth; d > 0; d--) {\n    const node = $pos.node(d);\n    if (node.type.spec.tableRole == 'table') {\n      if (dispatch)\n        dispatch(\n          state.tr.delete($pos.before(d), $pos.after(d)).scrollIntoView(),\n        );\n      return true;\n    }\n  }\n  return false;\n}\n\n/**\n * Deletes the content of the selected cells, if they are not empty.\n *\n * @public\n */\nexport function deleteCellSelection(\n  state: EditorState,\n  dispatch?: (tr: Transaction) => void,\n): boolean {\n  const sel = state.selection;\n  if (!(sel instanceof CellSelection)) return false;\n  if (dispatch) {\n    const tr = state.tr;\n    const baseContent = tableNodeTypes(state.schema).cell.createAndFill()!\n      .content;\n    sel.forEachCell((cell, pos) => {\n      if (!cell.content.eq(baseContent))\n        tr.replace(\n          tr.mapping.map(pos + 1),\n          tr.mapping.map(pos + cell.nodeSize - 1),\n          new Slice(baseContent, 0, 0),\n        );\n    });\n    if (tr.docChanged) dispatch(tr);\n  }\n  return true;\n}\n\n/**\n * Options for moveTableRow\n *\n * @public\n */\nexport interface MoveTableRowOptions {\n  /**\n   * The source row index to move from.\n   */\n  from: number;\n\n  /**\n   * The destination row index to move to.\n   */\n  to: number;\n\n  /**\n   * Whether to select the moved row after the operation.\n   *\n   * @default true\n   */\n  select?: boolean;\n\n  /**\n   * Optional position to resolve table from. If not provided, uses the current selection.\n   */\n  pos?: number;\n}\n\n/**\n * Move a table row from index `from` to index `to`.\n *\n * @public\n */\nexport function moveTableRow(options: MoveTableRowOptions): Command {\n  return (state, dispatch) => {\n    const {\n      from: originIndex,\n      to: targetIndex,\n      select = true,\n      pos = state.selection.from,\n    } = options;\n    const tr = state.tr;\n    if (moveRow({ tr, originIndex, targetIndex, select, pos })) {\n      dispatch?.(tr);\n      return true;\n    }\n    return false;\n  };\n}\n\n/**\n * Options for moveTableColumn\n *\n * @public\n */\nexport interface MoveTableColumnOptions {\n  /**\n   * The source column index to move from.\n   */\n  from: number;\n\n  /**\n   * The destination column index to move to.\n   */\n  to: number;\n\n  /**\n   * Whether to select the moved column after the operation.\n   *\n   * @default true\n   */\n  select?: boolean;\n\n  /**\n   * Optional position to resolve table from. If not provided, uses the current selection.\n   */\n  pos?: number;\n}\n\n/**\n * Move a table column from index `from` to index `to`.\n *\n * @public\n */\nexport function moveTableColumn(options: MoveTableColumnOptions): Command {\n  return (state, dispatch) => {\n    const {\n      from: originIndex,\n      to: targetIndex,\n      select = true,\n      pos = state.selection.from,\n    } = options;\n    const tr = state.tr;\n    if (moveColumn({ tr, originIndex, targetIndex, select, pos })) {\n      dispatch?.(tr);\n      return true;\n    }\n    return false;\n  };\n}\n", "// Utilities used for copy/paste handling.\n//\n// This module handles pasting cell content into tables, or pasting\n// anything into a cell selection, as replacing a block of cells with\n// the content of the selection. When pasting cells into a cell, that\n// involves placing the block of pasted content so that its top left\n// aligns with the selection cell, optionally extending the table to\n// the right or bottom to make sure it is large enough. Pasting into a\n// cell selection is different, here the cells in the selection are\n// clipped to the selection's rectangle, optionally repeating the\n// pasted cells when they are smaller than the selection.\n\nimport type { Node, NodeType, Schema } from 'prosemirror-model';\nimport { Fragment, Slice } from 'prosemirror-model';\nimport type { EditorState, Transaction } from 'prosemirror-state';\nimport { Transform } from 'prosemirror-transform';\n\nimport { CellSelection } from './cellselection';\nimport { tableNodeTypes } from './schema';\nimport type { ColWidths, Rect } from './tablemap';\nimport { TableMap } from './tablemap';\nimport type { CellAttrs } from './util';\nimport { removeColSpan } from './util';\n\n/**\n * @internal\n */\nexport type Area = { width: number; height: number; rows: Fragment[] };\n\n// Utilities to help with copying and pasting table cells\n\n/**\n * Get a rectangular area of cells from a slice, or null if the outer\n * nodes of the slice aren't table cells or rows.\n *\n * @internal\n */\nexport function pastedCells(slice: Slice): Area | null {\n  if (slice.size === 0) return null;\n  let { content, openStart, openEnd } = slice;\n  while (\n    content.childCount == 1 &&\n    ((openStart > 0 && openEnd > 0) ||\n      content.child(0).type.spec.tableRole == 'table')\n  ) {\n    openStart--;\n    openEnd--;\n    content = content.child(0).content;\n  }\n  const first = content.child(0);\n  const role = first.type.spec.tableRole;\n  const schema = first.type.schema,\n    rows = [];\n  if (role == 'row') {\n    for (let i = 0; i < content.childCount; i++) {\n      let cells = content.child(i).content;\n      const left = i ? 0 : Math.max(0, openStart - 1);\n      const right = i < content.childCount - 1 ? 0 : Math.max(0, openEnd - 1);\n      if (left || right)\n        cells = fitSlice(\n          tableNodeTypes(schema).row,\n          new Slice(cells, left, right),\n        ).content;\n      rows.push(cells);\n    }\n  } else if (role == 'cell' || role == 'header_cell') {\n    rows.push(\n      openStart || openEnd\n        ? fitSlice(\n            tableNodeTypes(schema).row,\n            new Slice(content, openStart, openEnd),\n          ).content\n        : content,\n    );\n  } else {\n    return null;\n  }\n  return ensureRectangular(schema, rows);\n}\n\n// Compute the width and height of a set of cells, and make sure each\n// row has the same number of cells.\nfunction ensureRectangular(schema: Schema, rows: Fragment[]): Area {\n  const widths: ColWidths = [];\n  for (let i = 0; i < rows.length; i++) {\n    const row = rows[i];\n    for (let j = row.childCount - 1; j >= 0; j--) {\n      const { rowspan, colspan } = row.child(j).attrs;\n      for (let r = i; r < i + rowspan; r++)\n        widths[r] = (widths[r] || 0) + colspan;\n    }\n  }\n  let width = 0;\n  for (let r = 0; r < widths.length; r++) width = Math.max(width, widths[r]);\n  for (let r = 0; r < widths.length; r++) {\n    if (r >= rows.length) rows.push(Fragment.empty);\n    if (widths[r] < width) {\n      const empty = tableNodeTypes(schema).cell.createAndFill()!;\n      const cells = [];\n      for (let i = widths[r]; i < width; i++) {\n        cells.push(empty);\n      }\n      rows[r] = rows[r].append(Fragment.from(cells));\n    }\n  }\n  return { height: rows.length, width, rows };\n}\n\nexport function fitSlice(nodeType: NodeType, slice: Slice): Node {\n  const node = nodeType.createAndFill()!;\n  const tr = new Transform(node).replace(0, node.content.size, slice);\n  return tr.doc;\n}\n\n/**\n * Clip or extend (repeat) the given set of cells to cover the given\n * width and height. Will clip rowspan/colspan cells at the edges when\n * they stick out.\n *\n * @internal\n */\nexport function clipCells(\n  { width, height, rows }: Area,\n  newWidth: number,\n  newHeight: number,\n): Area {\n  if (width != newWidth) {\n    const added: number[] = [];\n    const newRows: Fragment[] = [];\n    for (let row = 0; row < rows.length; row++) {\n      const frag = rows[row],\n        cells = [];\n      for (let col = added[row] || 0, i = 0; col < newWidth; i++) {\n        let cell = frag.child(i % frag.childCount);\n        if (col + cell.attrs.colspan > newWidth)\n          cell = cell.type.createChecked(\n            removeColSpan(\n              cell.attrs as CellAttrs,\n              cell.attrs.colspan,\n              col + cell.attrs.colspan - newWidth,\n            ),\n            cell.content,\n          );\n        cells.push(cell);\n        col += cell.attrs.colspan;\n        for (let j = 1; j < cell.attrs.rowspan; j++)\n          added[row + j] = (added[row + j] || 0) + cell.attrs.colspan;\n      }\n      newRows.push(Fragment.from(cells));\n    }\n    rows = newRows;\n    width = newWidth;\n  }\n\n  if (height != newHeight) {\n    const newRows = [];\n    for (let row = 0, i = 0; row < newHeight; row++, i++) {\n      const cells = [],\n        source = rows[i % height];\n      for (let j = 0; j < source.childCount; j++) {\n        let cell = source.child(j);\n        if (row + cell.attrs.rowspan > newHeight)\n          cell = cell.type.create(\n            {\n              ...cell.attrs,\n              rowspan: Math.max(1, newHeight - cell.attrs.rowspan),\n            },\n            cell.content,\n          );\n        cells.push(cell);\n      }\n      newRows.push(Fragment.from(cells));\n    }\n    rows = newRows;\n    height = newHeight;\n  }\n\n  return { width, height, rows };\n}\n\n// Make sure a table has at least the given width and height. Return\n// true if something was changed.\nfunction growTable(\n  tr: Transaction,\n  map: TableMap,\n  table: Node,\n  start: number,\n  width: number,\n  height: number,\n  mapFrom: number,\n): boolean {\n  const schema = tr.doc.type.schema;\n  const types = tableNodeTypes(schema);\n  let empty;\n  let emptyHead;\n  if (width > map.width) {\n    for (let row = 0, rowEnd = 0; row < map.height; row++) {\n      const rowNode = table.child(row);\n      rowEnd += rowNode.nodeSize;\n      const cells: Node[] = [];\n      let add: Node;\n      if (rowNode.lastChild == null || rowNode.lastChild.type == types.cell)\n        add = empty || (empty = types.cell.createAndFill()!);\n      else add = emptyHead || (emptyHead = types.header_cell.createAndFill()!);\n      for (let i = map.width; i < width; i++) cells.push(add);\n      tr.insert(tr.mapping.slice(mapFrom).map(rowEnd - 1 + start), cells);\n    }\n  }\n  if (height > map.height) {\n    const cells = [];\n    for (\n      let i = 0, start = (map.height - 1) * map.width;\n      i < Math.max(map.width, width);\n      i++\n    ) {\n      const header =\n        i >= map.width\n          ? false\n          : table.nodeAt(map.map[start + i])!.type == types.header_cell;\n      cells.push(\n        header\n          ? emptyHead || (emptyHead = types.header_cell.createAndFill()!)\n          : empty || (empty = types.cell.createAndFill()!),\n      );\n    }\n\n    const emptyRow = types.row.create(null, Fragment.from(cells)),\n      rows = [];\n    for (let i = map.height; i < height; i++) rows.push(emptyRow);\n    tr.insert(tr.mapping.slice(mapFrom).map(start + table.nodeSize - 2), rows);\n  }\n  return !!(empty || emptyHead);\n}\n\n// Make sure the given line (left, top) to (right, top) doesn't cross\n// any rowspan cells by splitting cells that cross it. Return true if\n// something changed.\nfunction isolateHorizontal(\n  tr: Transaction,\n  map: TableMap,\n  table: Node,\n  start: number,\n  left: number,\n  right: number,\n  top: number,\n  mapFrom: number,\n): boolean {\n  if (top == 0 || top == map.height) return false;\n  let found = false;\n  for (let col = left; col < right; col++) {\n    const index = top * map.width + col,\n      pos = map.map[index];\n    if (map.map[index - map.width] == pos) {\n      found = true;\n      const cell = table.nodeAt(pos)!;\n      const { top: cellTop, left: cellLeft } = map.findCell(pos);\n      tr.setNodeMarkup(tr.mapping.slice(mapFrom).map(pos + start), null, {\n        ...cell.attrs,\n        rowspan: top - cellTop,\n      });\n      tr.insert(\n        tr.mapping.slice(mapFrom).map(map.positionAt(top, cellLeft, table)),\n        cell.type.createAndFill({\n          ...cell.attrs,\n          rowspan: cellTop + cell.attrs.rowspan - top,\n        })!,\n      );\n      col += cell.attrs.colspan - 1;\n    }\n  }\n  return found;\n}\n\n// Make sure the given line (left, top) to (left, bottom) doesn't\n// cross any colspan cells by splitting cells that cross it. Return\n// true if something changed.\nfunction isolateVertical(\n  tr: Transaction,\n  map: TableMap,\n  table: Node,\n  start: number,\n  top: number,\n  bottom: number,\n  left: number,\n  mapFrom: number,\n): boolean {\n  if (left == 0 || left == map.width) return false;\n  let found = false;\n  for (let row = top; row < bottom; row++) {\n    const index = row * map.width + left,\n      pos = map.map[index];\n    if (map.map[index - 1] == pos) {\n      found = true;\n      const cell = table.nodeAt(pos)!;\n      const cellLeft = map.colCount(pos);\n      const updatePos = tr.mapping.slice(mapFrom).map(pos + start);\n      tr.setNodeMarkup(\n        updatePos,\n        null,\n        removeColSpan(\n          cell.attrs as CellAttrs,\n          left - cellLeft,\n          cell.attrs.colspan - (left - cellLeft),\n        ),\n      );\n      tr.insert(\n        updatePos + cell.nodeSize,\n        cell.type.createAndFill(\n          removeColSpan(cell.attrs as CellAttrs, 0, left - cellLeft),\n        )!,\n      );\n      row += cell.attrs.rowspan - 1;\n    }\n  }\n  return found;\n}\n\n/**\n * Insert the given set of cells (as returned by `pastedCells`) into a\n * table, at the position pointed at by rect.\n *\n * @internal\n */\nexport function insertCells(\n  state: EditorState,\n  dispatch: (tr: Transaction) => void,\n  tableStart: number,\n  rect: Rect,\n  cells: Area,\n): void {\n  let table = tableStart ? state.doc.nodeAt(tableStart - 1) : state.doc;\n  if (!table) {\n    throw new Error('No table found');\n  }\n  let map = TableMap.get(table);\n  const { top, left } = rect;\n  const right = left + cells.width,\n    bottom = top + cells.height;\n  const tr = state.tr;\n  let mapFrom = 0;\n\n  function recomp(): void {\n    table = tableStart ? tr.doc.nodeAt(tableStart - 1) : tr.doc;\n    if (!table) {\n      throw new Error('No table found');\n    }\n    map = TableMap.get(table);\n    mapFrom = tr.mapping.maps.length;\n  }\n\n  // Prepare the table to be large enough and not have any cells\n  // crossing the boundaries of the rectangle that we want to\n  // insert into. If anything about it changes, recompute the table\n  // map so that subsequent operations can see the current shape.\n  if (growTable(tr, map, table, tableStart, right, bottom, mapFrom)) recomp();\n  if (isolateHorizontal(tr, map, table, tableStart, left, right, top, mapFrom))\n    recomp();\n  if (\n    isolateHorizontal(tr, map, table, tableStart, left, right, bottom, mapFrom)\n  )\n    recomp();\n  if (isolateVertical(tr, map, table, tableStart, top, bottom, left, mapFrom))\n    recomp();\n  if (isolateVertical(tr, map, table, tableStart, top, bottom, right, mapFrom))\n    recomp();\n\n  for (let row = top; row < bottom; row++) {\n    const from = map.positionAt(row, left, table),\n      to = map.positionAt(row, right, table);\n    tr.replace(\n      tr.mapping.slice(mapFrom).map(from + tableStart),\n      tr.mapping.slice(mapFrom).map(to + tableStart),\n      new Slice(cells.rows[row - top], 0, 0),\n    );\n  }\n  recomp();\n  tr.setSelection(\n    new CellSelection(\n      tr.doc.resolve(tableStart + map.positionAt(top, left, table)),\n      tr.doc.resolve(tableStart + map.positionAt(bottom - 1, right - 1, table)),\n    ),\n  );\n  dispatch(tr);\n}\n", "// This file defines a number of helpers for wiring up user input to\n// table-related functionality.\n\nimport { keydownHandler } from 'prosemirror-keymap';\nimport type { ResolvedPos, Slice } from 'prosemirror-model';\nimport { Fragment } from 'prosemirror-model';\nimport type { Command, EditorState, Transaction } from 'prosemirror-state';\nimport { Selection, TextSelection } from 'prosemirror-state';\nimport type { EditorView } from 'prosemirror-view';\n\nimport { CellSelection } from './cellselection';\nimport { deleteCellSelection } from './commands';\nimport { clipCells, fitSlice, insertCells, pastedCells } from './copypaste';\nimport { tableNodeTypes } from './schema';\nimport { TableMap } from './tablemap';\nimport {\n  cellAround,\n  inSameTable,\n  isInTable,\n  nextCell,\n  selectionCell,\n  tableEditingKey,\n} from './util';\n\ntype Axis = 'horiz' | 'vert';\n\n/**\n * @public\n */\nexport type Direction = -1 | 1;\n\nexport const handleKeyDown = keydownHandler({\n  ArrowLeft: arrow('horiz', -1),\n  ArrowRight: arrow('horiz', 1),\n  ArrowUp: arrow('vert', -1),\n  ArrowDown: arrow('vert', 1),\n\n  'Shift-ArrowLeft': shiftArrow('horiz', -1),\n  'Shift-ArrowRight': shiftArrow('horiz', 1),\n  'Shift-ArrowUp': shiftArrow('vert', -1),\n  'Shift-ArrowDown': shiftArrow('vert', 1),\n\n  Backspace: deleteCellSelection,\n  'Mod-Backspace': deleteCellSelection,\n  Delete: deleteCellSelection,\n  'Mod-Delete': deleteCellSelection,\n});\n\nfunction maybeSetSelection(\n  state: EditorState,\n  dispatch: undefined | ((tr: Transaction) => void),\n  selection: Selection,\n): boolean {\n  if (selection.eq(state.selection)) return false;\n  if (dispatch) dispatch(state.tr.setSelection(selection).scrollIntoView());\n  return true;\n}\n\n/**\n * @internal\n */\nexport function arrow(axis: Axis, dir: Direction): Command {\n  return (state, dispatch, view) => {\n    if (!view) return false;\n    const sel = state.selection;\n    if (sel instanceof CellSelection) {\n      return maybeSetSelection(\n        state,\n        dispatch,\n        Selection.near(sel.$headCell, dir),\n      );\n    }\n    if (axis != 'horiz' && !sel.empty) return false;\n    const end = atEndOfCell(view, axis, dir);\n    if (end == null) return false;\n    if (axis == 'horiz') {\n      return maybeSetSelection(\n        state,\n        dispatch,\n        Selection.near(state.doc.resolve(sel.head + dir), dir),\n      );\n    } else {\n      const $cell = state.doc.resolve(end);\n      const $next = nextCell($cell, axis, dir);\n      let newSel;\n      if ($next) newSel = Selection.near($next, 1);\n      else if (dir < 0)\n        newSel = Selection.near(state.doc.resolve($cell.before(-1)), -1);\n      else newSel = Selection.near(state.doc.resolve($cell.after(-1)), 1);\n      return maybeSetSelection(state, dispatch, newSel);\n    }\n  };\n}\n\nfunction shiftArrow(axis: Axis, dir: Direction): Command {\n  return (state, dispatch, view) => {\n    if (!view) return false;\n    const sel = state.selection;\n    let cellSel: CellSelection;\n    if (sel instanceof CellSelection) {\n      cellSel = sel;\n    } else {\n      const end = atEndOfCell(view, axis, dir);\n      if (end == null) return false;\n      cellSel = new CellSelection(state.doc.resolve(end));\n    }\n\n    const $head = nextCell(cellSel.$headCell, axis, dir);\n    if (!$head) return false;\n    return maybeSetSelection(\n      state,\n      dispatch,\n      new CellSelection(cellSel.$anchorCell, $head),\n    );\n  };\n}\n\nexport function handleTripleClick(view: EditorView, pos: number): boolean {\n  const doc = view.state.doc,\n    $cell = cellAround(doc.resolve(pos));\n  if (!$cell) return false;\n  view.dispatch(view.state.tr.setSelection(new CellSelection($cell)));\n  return true;\n}\n\n/**\n * @public\n */\nexport function handlePaste(\n  view: EditorView,\n  _: ClipboardEvent,\n  slice: Slice,\n): boolean {\n  if (!isInTable(view.state)) return false;\n  let cells = pastedCells(slice);\n  const sel = view.state.selection;\n  if (sel instanceof CellSelection) {\n    if (!cells)\n      cells = {\n        width: 1,\n        height: 1,\n        rows: [\n          Fragment.from(\n            fitSlice(tableNodeTypes(view.state.schema).cell, slice),\n          ),\n        ],\n      };\n    const table = sel.$anchorCell.node(-1);\n    const start = sel.$anchorCell.start(-1);\n    const rect = TableMap.get(table).rectBetween(\n      sel.$anchorCell.pos - start,\n      sel.$headCell.pos - start,\n    );\n    cells = clipCells(cells, rect.right - rect.left, rect.bottom - rect.top);\n    insertCells(view.state, view.dispatch, start, rect, cells);\n    return true;\n  } else if (cells) {\n    const $cell = selectionCell(view.state);\n    const start = $cell.start(-1);\n    insertCells(\n      view.state,\n      view.dispatch,\n      start,\n      TableMap.get($cell.node(-1)).findCell($cell.pos - start),\n      cells,\n    );\n    return true;\n  } else {\n    return false;\n  }\n}\n\nexport function handleMouseDown(\n  view: EditorView,\n  startEvent: MouseEvent,\n): void {\n  // Only handle mouse down events for the main button (usually the left button).\n  // This ensures that the cell selection won't be triggered when trying to open\n  // the context menu.\n  if (startEvent.button != 0) return;\n\n  if (startEvent.ctrlKey || startEvent.metaKey) return;\n\n  const startDOMCell = domInCell(view, startEvent.target as Node);\n  let $anchor;\n  if (startEvent.shiftKey && view.state.selection instanceof CellSelection) {\n    // Adding to an existing cell selection\n    setCellSelection(view.state.selection.$anchorCell, startEvent);\n    startEvent.preventDefault();\n  } else if (\n    startEvent.shiftKey &&\n    startDOMCell &&\n    ($anchor = cellAround(view.state.selection.$anchor)) != null &&\n    cellUnderMouse(view, startEvent)?.pos != $anchor.pos\n  ) {\n    // Adding to a selection that starts in another cell (causing a\n    // cell selection to be created).\n    setCellSelection($anchor, startEvent);\n    startEvent.preventDefault();\n  } else if (!startDOMCell) {\n    // Not in a cell, let the default behavior happen.\n    return;\n  }\n\n  // Create and dispatch a cell selection between the given anchor and\n  // the position under the mouse.\n  function setCellSelection($anchor: ResolvedPos, event: MouseEvent): void {\n    let $head = cellUnderMouse(view, event);\n    const starting = tableEditingKey.getState(view.state) == null;\n    if (!$head || !inSameTable($anchor, $head)) {\n      if (starting) $head = $anchor;\n      else return;\n    }\n    const selection = new CellSelection($anchor, $head);\n    if (starting || !view.state.selection.eq(selection)) {\n      const tr = view.state.tr.setSelection(selection);\n      if (starting) tr.setMeta(tableEditingKey, $anchor.pos);\n      view.dispatch(tr);\n    }\n  }\n\n  // Stop listening to mouse motion events.\n  function stop(): void {\n    view.root.removeEventListener('mouseup', stop);\n    view.root.removeEventListener('dragstart', stop);\n    view.root.removeEventListener('mousemove', move);\n    if (tableEditingKey.getState(view.state) != null)\n      view.dispatch(view.state.tr.setMeta(tableEditingKey, -1));\n  }\n\n  function move(_event: Event): void {\n    const event = _event as MouseEvent;\n    const anchor = tableEditingKey.getState(view.state);\n    let $anchor;\n    if (anchor != null) {\n      // Continuing an existing cross-cell selection\n      $anchor = view.state.doc.resolve(anchor);\n    } else if (domInCell(view, event.target as Node) != startDOMCell) {\n      // Moving out of the initial cell -- start a new cell selection\n      $anchor = cellUnderMouse(view, startEvent);\n      if (!$anchor) return stop();\n    }\n    if ($anchor) setCellSelection($anchor, event);\n  }\n\n  view.root.addEventListener('mouseup', stop);\n  view.root.addEventListener('dragstart', stop);\n  view.root.addEventListener('mousemove', move);\n}\n\n// Check whether the cursor is at the end of a cell (so that further\n// motion would move out of the cell)\nfunction atEndOfCell(view: EditorView, axis: Axis, dir: number): null | number {\n  if (!(view.state.selection instanceof TextSelection)) return null;\n  const { $head } = view.state.selection;\n  for (let d = $head.depth - 1; d >= 0; d--) {\n    const parent = $head.node(d),\n      index = dir < 0 ? $head.index(d) : $head.indexAfter(d);\n    if (index != (dir < 0 ? 0 : parent.childCount)) return null;\n    if (\n      parent.type.spec.tableRole == 'cell' ||\n      parent.type.spec.tableRole == 'header_cell'\n    ) {\n      const cellPos = $head.before(d);\n      const dirStr: 'up' | 'down' | 'left' | 'right' =\n        axis == 'vert' ? (dir > 0 ? 'down' : 'up') : dir > 0 ? 'right' : 'left';\n      return view.endOfTextblock(dirStr) ? cellPos : null;\n    }\n  }\n  return null;\n}\n\nfunction domInCell(view: EditorView, dom: Node | null): Node | null {\n  for (; dom && dom != view.dom; dom = dom.parentNode) {\n    if (dom.nodeName == 'TD' || dom.nodeName == 'TH') {\n      return dom;\n    }\n  }\n  return null;\n}\n\nfunction cellUnderMouse(\n  view: EditorView,\n  event: MouseEvent,\n): ResolvedPos | null {\n  const mousePos = view.posAtCoords({\n    left: event.clientX,\n    top: event.clientY,\n  });\n  if (!mousePos) return null;\n  // Prefer `inside` position for better accuracy with merged cells (rowspan/colspan),\n  // but fall back to `pos` if `inside` doesn't resolve to a valid cell\n  let { inside, pos } = mousePos;\n  return (\n    (inside >= 0 && cellAround(view.state.doc.resolve(inside))) ||\n    cellAround(view.state.doc.resolve(pos))\n  );\n}\n", "import type { Node } from 'prosemirror-model';\nimport type { NodeView, ViewMutationRecord } from 'prosemirror-view';\n\nimport type { CellAttrs } from './util';\n\n/**\n * @public\n */\nexport class TableView implements NodeView {\n  public dom: HTMLDivElement;\n  public table: HTMLTableElement;\n  public colgroup: HTMLTableColElement;\n  public contentDOM: HTMLTableSectionElement;\n\n  constructor(\n    public node: Node,\n    public defaultCellMinWidth: number,\n  ) {\n    this.dom = document.createElement('div');\n    this.dom.className = 'tableWrapper';\n    this.table = this.dom.appendChild(document.createElement('table'));\n    this.table.style.setProperty(\n      '--default-cell-min-width',\n      `${defaultCellMinWidth}px`,\n    );\n    this.colgroup = this.table.appendChild(document.createElement('colgroup'));\n    updateColumnsOnResize(node, this.colgroup, this.table, defaultCellMinWidth);\n    this.contentDOM = this.table.appendChild(document.createElement('tbody'));\n  }\n\n  update(node: Node): boolean {\n    if (node.type != this.node.type) return false;\n    this.node = node;\n    updateColumnsOnResize(\n      node,\n      this.colgroup,\n      this.table,\n      this.defaultCellMinWidth,\n    );\n    return true;\n  }\n\n  ignoreMutation(record: ViewMutationRecord): boolean {\n    return (\n      record.type == 'attributes' &&\n      (record.target == this.table || this.colgroup.contains(record.target))\n    );\n  }\n}\n\n/**\n * @public\n */\nexport function updateColumnsOnResize(\n  node: Node,\n  colgroup: HTMLTableColElement,\n  table: HTMLTableElement,\n  defaultCellMinWidth: number,\n  overrideCol?: number,\n  overrideValue?: number,\n): void {\n  let totalWidth = 0;\n  let fixedWidth = true;\n  let nextDOM = colgroup.firstChild as HTMLElement;\n  const row = node.firstChild;\n  if (!row) return;\n\n  for (let i = 0, col = 0; i < row.childCount; i++) {\n    const { colspan, colwidth } = row.child(i).attrs as CellAttrs;\n    for (let j = 0; j < colspan; j++, col++) {\n      const hasWidth =\n        overrideCol == col ? overrideValue : colwidth && colwidth[j];\n      const cssWidth = hasWidth ? hasWidth + 'px' : '';\n      totalWidth += hasWidth || defaultCellMinWidth;\n      if (!hasWidth) fixedWidth = false;\n      if (!nextDOM) {\n        const col = document.createElement('col');\n        col.style.width = cssWidth;\n        colgroup.appendChild(col);\n      } else {\n        if (nextDOM.style.width != cssWidth) {\n          nextDOM.style.width = cssWidth;\n        }\n        nextDOM = nextDOM.nextSibling as HTMLElement;\n      }\n    }\n  }\n\n  while (nextDOM) {\n    const after = nextDOM.nextSibling;\n    nextDOM.parentNode?.removeChild(nextDOM);\n    nextDOM = after as HTMLElement;\n  }\n\n  if (fixedWidth) {\n    table.style.width = totalWidth + 'px';\n    table.style.minWidth = '';\n  } else {\n    table.style.width = '';\n    table.style.minWidth = totalWidth + 'px';\n  }\n}\n", "import type { Attrs, Node as ProsemirrorNode } from 'prosemirror-model';\nimport type { EditorState, Transaction } from 'prosemirror-state';\nimport { Plugin, PluginKey } from 'prosemirror-state';\nimport type { EditorView, NodeView } from 'prosemirror-view';\nimport { Decoration, DecorationSet } from 'prosemirror-view';\n\nimport { tableNodeTypes } from './schema';\nimport { TableMap } from './tablemap';\nimport { TableView, updateColumnsOnResize } from './tableview';\nimport type { CellAttrs } from './util';\nimport { cellAround, pointsAtCell } from './util';\n\n/**\n * @public\n */\nexport const columnResizingPluginKey = new PluginKey<ResizeState>(\n  'tableColumnResizing',\n);\n\n/**\n * @public\n */\nexport type ColumnResizingOptions = {\n  handleWidth?: number;\n  /**\n   * Minimum width of a cell /column. The column cannot be resized smaller than this.\n   */\n  cellMinWidth?: number;\n  /**\n   * The default minWidth of a cell / column when it doesn't have an explicit width (i.e.: it has not been resized manually)\n   */\n  defaultCellMinWidth?: number;\n  lastColumnResizable?: boolean;\n  /**\n   * A custom node view for the rendering table nodes. By default, the plugin\n   * uses the {@link TableView} class. You can explicitly set this to `null` to\n   * not use a custom node view.\n   */\n  View?:\n    | (new (\n        node: ProsemirrorNode,\n        cellMinWidth: number,\n        view: EditorView,\n      ) => NodeView)\n    | null;\n};\n\n/**\n * @public\n */\nexport type Dragging = { startX: number; startWidth: number };\n\n/**\n * @public\n */\nexport function columnResizing({\n  handleWidth = 5,\n  cellMinWidth = 25,\n  defaultCellMinWidth = 100,\n  View = TableView,\n  lastColumnResizable = true,\n}: ColumnResizingOptions = {}): Plugin {\n  const plugin = new Plugin<ResizeState>({\n    key: columnResizingPluginKey,\n    state: {\n      init(_, state) {\n        const nodeViews = plugin.spec?.props?.nodeViews;\n        const tableName = tableNodeTypes(state.schema).table.name;\n        if (View && nodeViews) {\n          nodeViews[tableName] = (node, view) => {\n            return new View(node, defaultCellMinWidth, view);\n          };\n        }\n        return new ResizeState(-1, false);\n      },\n      apply(tr, prev) {\n        return prev.apply(tr);\n      },\n    },\n    props: {\n      attributes: (state): Record<string, string> => {\n        const pluginState = columnResizingPluginKey.getState(state);\n        return pluginState && pluginState.activeHandle > -1\n          ? { class: 'resize-cursor' }\n          : {};\n      },\n\n      handleDOMEvents: {\n        mousemove: (view, event) => {\n          handleMouseMove(view, event, handleWidth, lastColumnResizable);\n        },\n        mouseleave: (view) => {\n          handleMouseLeave(view);\n        },\n        mousedown: (view, event) => {\n          handleMouseDown(view, event, cellMinWidth, defaultCellMinWidth);\n        },\n      },\n\n      decorations: (state) => {\n        const pluginState = columnResizingPluginKey.getState(state);\n        if (pluginState && pluginState.activeHandle > -1) {\n          return handleDecorations(state, pluginState.activeHandle);\n        }\n      },\n\n      nodeViews: {},\n    },\n  });\n  return plugin;\n}\n\n/**\n * @public\n */\nexport class ResizeState {\n  constructor(\n    public activeHandle: number,\n    public dragging: Dragging | false,\n  ) {}\n\n  apply(tr: Transaction): ResizeState {\n    // eslint-disable-next-line @typescript-eslint/no-this-alias\n    const state = this;\n    const action = tr.getMeta(columnResizingPluginKey);\n    if (action && action.setHandle != null)\n      return new ResizeState(action.setHandle, false);\n    if (action && action.setDragging !== undefined)\n      return new ResizeState(state.activeHandle, action.setDragging);\n    if (state.activeHandle > -1 && tr.docChanged) {\n      let handle = tr.mapping.map(state.activeHandle, -1);\n      if (!pointsAtCell(tr.doc.resolve(handle))) {\n        handle = -1;\n      }\n      return new ResizeState(handle, state.dragging);\n    }\n    return state;\n  }\n}\n\nfunction handleMouseMove(\n  view: EditorView,\n  event: MouseEvent,\n  handleWidth: number,\n  lastColumnResizable: boolean,\n): void {\n  if (!view.editable) return;\n\n  const pluginState = columnResizingPluginKey.getState(view.state);\n  if (!pluginState) return;\n\n  if (!pluginState.dragging) {\n    const target = domCellAround(event.target as HTMLElement);\n    let cell = -1;\n    if (target) {\n      const { left, right } = target.getBoundingClientRect();\n      if (event.clientX - left <= handleWidth)\n        cell = edgeCell(view, event, 'left', handleWidth);\n      else if (right - event.clientX <= handleWidth)\n        cell = edgeCell(view, event, 'right', handleWidth);\n    }\n\n    if (cell != pluginState.activeHandle) {\n      if (!lastColumnResizable && cell !== -1) {\n        const $cell = view.state.doc.resolve(cell);\n        const table = $cell.node(-1);\n        const map = TableMap.get(table);\n        const tableStart = $cell.start(-1);\n        const col =\n          map.colCount($cell.pos - tableStart) +\n          $cell.nodeAfter!.attrs.colspan -\n          1;\n\n        if (col == map.width - 1) {\n          return;\n        }\n      }\n\n      updateHandle(view, cell);\n    }\n  }\n}\n\nfunction handleMouseLeave(view: EditorView): void {\n  if (!view.editable) return;\n\n  const pluginState = columnResizingPluginKey.getState(view.state);\n  if (pluginState && pluginState.activeHandle > -1 && !pluginState.dragging)\n    updateHandle(view, -1);\n}\n\nfunction handleMouseDown(\n  view: EditorView,\n  event: MouseEvent,\n  cellMinWidth: number,\n  defaultCellMinWidth: number,\n): boolean {\n  if (!view.editable) return false;\n\n  const win = view.dom.ownerDocument.defaultView ?? window;\n\n  const pluginState = columnResizingPluginKey.getState(view.state);\n  if (!pluginState || pluginState.activeHandle == -1 || pluginState.dragging)\n    return false;\n\n  const cell = view.state.doc.nodeAt(pluginState.activeHandle)!;\n  const width = currentColWidth(view, pluginState.activeHandle, cell.attrs);\n  view.dispatch(\n    view.state.tr.setMeta(columnResizingPluginKey, {\n      setDragging: { startX: event.clientX, startWidth: width },\n    }),\n  );\n\n  function finish(event: MouseEvent) {\n    win.removeEventListener('mouseup', finish);\n    win.removeEventListener('mousemove', move);\n    const pluginState = columnResizingPluginKey.getState(view.state);\n    if (pluginState?.dragging) {\n      updateColumnWidth(\n        view,\n        pluginState.activeHandle,\n        draggedWidth(pluginState.dragging, event, cellMinWidth),\n      );\n      view.dispatch(\n        view.state.tr.setMeta(columnResizingPluginKey, { setDragging: null }),\n      );\n    }\n  }\n\n  function move(event: MouseEvent): void {\n    if (!event.which) return finish(event);\n    const pluginState = columnResizingPluginKey.getState(view.state);\n    if (!pluginState) return;\n    if (pluginState.dragging) {\n      const dragged = draggedWidth(pluginState.dragging, event, cellMinWidth);\n      displayColumnWidth(\n        view,\n        pluginState.activeHandle,\n        dragged,\n        defaultCellMinWidth,\n      );\n    }\n  }\n\n  displayColumnWidth(\n    view,\n    pluginState.activeHandle,\n    width,\n    defaultCellMinWidth,\n  );\n\n  win.addEventListener('mouseup', finish);\n  win.addEventListener('mousemove', move);\n  event.preventDefault();\n  return true;\n}\n\nfunction currentColWidth(\n  view: EditorView,\n  cellPos: number,\n  { colspan, colwidth }: Attrs,\n): number {\n  const width = colwidth && colwidth[colwidth.length - 1];\n  if (width) return width;\n  const dom = view.domAtPos(cellPos);\n  const node = dom.node.childNodes[dom.offset] as HTMLElement;\n  let domWidth = node.offsetWidth,\n    parts = colspan;\n  if (colwidth)\n    for (let i = 0; i < colspan; i++)\n      if (colwidth[i]) {\n        domWidth -= colwidth[i];\n        parts--;\n      }\n  return domWidth / parts;\n}\n\nfunction domCellAround(target: HTMLElement | null): HTMLElement | null {\n  while (target && target.nodeName != 'TD' && target.nodeName != 'TH')\n    target =\n      target.classList && target.classList.contains('ProseMirror')\n        ? null\n        : (target.parentNode as HTMLElement);\n  return target;\n}\n\nfunction edgeCell(\n  view: EditorView,\n  event: MouseEvent,\n  side: 'left' | 'right',\n  handleWidth: number,\n): number {\n  // posAtCoords returns inconsistent positions when cursor is moving\n  // across a collapsed table border. Use an offset to adjust the\n  // target viewport coordinates away from the table border.\n  const offset = side == 'right' ? -handleWidth : handleWidth;\n  const found = view.posAtCoords({\n    left: event.clientX + offset,\n    top: event.clientY,\n  });\n  if (!found) return -1;\n  const { pos } = found;\n  const $cell = cellAround(view.state.doc.resolve(pos));\n  if (!$cell) return -1;\n  if (side == 'right') return $cell.pos;\n  const map = TableMap.get($cell.node(-1)),\n    start = $cell.start(-1);\n  const index = map.map.indexOf($cell.pos - start);\n  return index % map.width == 0 ? -1 : start + map.map[index - 1];\n}\n\nfunction draggedWidth(\n  dragging: Dragging,\n  event: MouseEvent,\n  resizeMinWidth: number,\n): number {\n  const offset = event.clientX - dragging.startX;\n  return Math.max(resizeMinWidth, dragging.startWidth + offset);\n}\n\nfunction updateHandle(view: EditorView, value: number): void {\n  view.dispatch(\n    view.state.tr.setMeta(columnResizingPluginKey, { setHandle: value }),\n  );\n}\n\nfunction updateColumnWidth(\n  view: EditorView,\n  cell: number,\n  width: number,\n): void {\n  const $cell = view.state.doc.resolve(cell);\n  const table = $cell.node(-1),\n    map = TableMap.get(table),\n    start = $cell.start(-1);\n  const col =\n    map.colCount($cell.pos - start) + $cell.nodeAfter!.attrs.colspan - 1;\n  const tr = view.state.tr;\n  for (let row = 0; row < map.height; row++) {\n    const mapIndex = row * map.width + col;\n    // Rowspanning cell that has already been handled\n    if (row && map.map[mapIndex] == map.map[mapIndex - map.width]) continue;\n    const pos = map.map[mapIndex];\n    const attrs = table.nodeAt(pos)!.attrs as CellAttrs;\n    const index = attrs.colspan == 1 ? 0 : col - map.colCount(pos);\n    if (attrs.colwidth && attrs.colwidth[index] == width) continue;\n    const colwidth = attrs.colwidth\n      ? attrs.colwidth.slice()\n      : zeroes(attrs.colspan);\n    colwidth[index] = width;\n    tr.setNodeMarkup(start + pos, null, { ...attrs, colwidth: colwidth });\n  }\n  if (tr.docChanged) view.dispatch(tr);\n}\n\nfunction displayColumnWidth(\n  view: EditorView,\n  cell: number,\n  width: number,\n  defaultCellMinWidth: number,\n): void {\n  const $cell = view.state.doc.resolve(cell);\n  const table = $cell.node(-1),\n    start = $cell.start(-1);\n  const col =\n    TableMap.get(table).colCount($cell.pos - start) +\n    $cell.nodeAfter!.attrs.colspan -\n    1;\n  let dom: Node | null = view.domAtPos($cell.start(-1)).node;\n  while (dom && dom.nodeName != 'TABLE') {\n    dom = dom.parentNode;\n  }\n  if (!dom) return;\n  updateColumnsOnResize(\n    table,\n    dom.firstChild as HTMLTableColElement,\n    dom as HTMLTableElement,\n    defaultCellMinWidth,\n    col,\n    width,\n  );\n}\n\nfunction zeroes(n: number): 0[] {\n  return Array(n).fill(0);\n}\n\nexport function handleDecorations(\n  state: EditorState,\n  cell: number,\n): DecorationSet {\n  const decorations = [];\n  const $cell = state.doc.resolve(cell);\n  const table = $cell.node(-1);\n  if (!table) {\n    return DecorationSet.empty;\n  }\n  const map = TableMap.get(table);\n  const start = $cell.start(-1);\n  const col =\n    map.colCount($cell.pos - start) + $cell.nodeAfter!.attrs.colspan - 1;\n  for (let row = 0; row < map.height; row++) {\n    const index = col + row * map.width;\n    // For positions that have either a different cell or the end\n    // of the table to their right, and either the top of the table or\n    // a different cell above them, add a decoration\n    if (\n      (col == map.width - 1 || map.map[index] != map.map[index + 1]) &&\n      (row == 0 || map.map[index] != map.map[index - map.width])\n    ) {\n      const cellPos = map.map[index];\n      const pos = start + cellPos + table.nodeAt(cellPos)!.nodeSize - 1;\n      const dom = document.createElement('div');\n      dom.className = 'column-resize-handle';\n      if (columnResizingPluginKey.getState(state)?.dragging) {\n        decorations.push(\n          Decoration.node(\n            start + cellPos,\n            start + cellPos + table.nodeAt(cellPos)!.nodeSize,\n            {\n              class: 'column-resize-dragging',\n            },\n          ),\n        );\n      }\n\n      decorations.push(Decoration.widget(pos, dom));\n    }\n  }\n  return DecorationSet.create(state.doc, decorations);\n}\n", "// This file defines a plugin that handles the drawing of cell\n// selections and the basic user interactions for creating and working\n// with such selections. It also makes sure that, after each\n// transaction, the shapes of tables are normalized to be rectangular\n// and not contain overlapping cells.\n\nimport { Plugin } from 'prosemirror-state';\n\nimport { drawCellSelection, normalizeSelection } from './cellselection';\nimport { fixTables, fixTablesKey } from './fixtables';\nimport {\n  handleKeyDown,\n  handleMouseDown,\n  handlePaste,\n  handleTripleClick,\n} from './input';\nimport { tableEditingKey } from './util';\n\nexport { CellBookmark, CellSelection } from './cellselection';\nexport type { CellSelectionJSON } from './cellselection';\nexport {\n  columnResizing,\n  columnResizingPluginKey,\n  ResizeState,\n} from './columnresizing';\nexport type { ColumnResizingOptions, Dragging } from './columnresizing';\nexport * from './commands';\nexport {\n  clipCells as __clipCells,\n  insertCells as __insertCells,\n  pastedCells as __pastedCells,\n} from './copypaste';\nexport type { Area as __Area } from './copypaste';\nexport type { Direction } from './input';\nexport { tableNodes, tableNodeTypes } from './schema';\nexport type {\n  CellAttributes,\n  getFromDOM,\n  setDOMAttr,\n  TableNodes,\n  TableNodesOptions,\n  TableRole,\n} from './schema';\nexport { TableMap } from './tablemap';\nexport type { ColWidths, Problem, Rect } from './tablemap';\nexport { TableView, updateColumnsOnResize } from './tableview';\nexport {\n  addColSpan,\n  cellAround,\n  cellNear,\n  colCount,\n  columnIsHeader,\n  findCell,\n  inSameTable,\n  isInTable,\n  moveCellForward,\n  nextCell,\n  pointsAtCell,\n  removeColSpan,\n  selectionCell,\n} from './util';\nexport type { MutableAttrs } from './util';\nexport { findCellPos, findCellRange, findTable } from './utils/query';\nexport type { FindNodeResult } from './utils/query';\nexport { fixTables, fixTablesKey, handlePaste, tableEditingKey };\n\n/**\n * @public\n */\nexport type TableEditingOptions = {\n  /**\n   * Whether to allow table node selection.\n   *\n   * By default, any node selection wrapping a table will be converted into a\n   * CellSelection wrapping all cells in the table. You can pass `true` to allow\n   * the selection to remain a NodeSelection.\n   *\n   * @default false\n   */\n  allowTableNodeSelection?: boolean;\n};\n\n/**\n * Creates a [plugin](http://prosemirror.net/docs/ref/#state.Plugin)\n * that, when added to an editor, enables cell-selection, handles\n * cell-based copy/paste, and makes sure tables stay well-formed (each\n * row has the same width, and cells don't overlap).\n *\n * You should probably put this plugin near the end of your array of\n * plugins, since it handles mouse and arrow key events in tables\n * rather broadly, and other plugins, like the gap cursor or the\n * column-width dragging plugin, might want to get a turn first to\n * perform more specific behavior.\n *\n * @public\n */\nexport function tableEditing({\n  allowTableNodeSelection = false,\n}: TableEditingOptions = {}): Plugin {\n  return new Plugin({\n    key: tableEditingKey,\n\n    // This piece of state is used to remember when a mouse-drag\n    // cell-selection is happening, so that it can continue even as\n    // transactions (which might move its anchor cell) come in.\n    state: {\n      init() {\n        return null;\n      },\n      apply(tr, cur) {\n        const set = tr.getMeta(tableEditingKey);\n        if (set != null) return set == -1 ? null : set;\n        if (cur == null || !tr.docChanged) return cur;\n        const { deleted, pos } = tr.mapping.mapResult(cur);\n        return deleted ? null : pos;\n      },\n    },\n\n    props: {\n      decorations: drawCellSelection,\n\n      handleDOMEvents: {\n        mousedown: handleMouseDown,\n      },\n\n      createSelectionBetween(view) {\n        return tableEditingKey.getState(view.state) != null\n          ? view.state.selection\n          : null;\n      },\n\n      handleTripleClick,\n\n      handleKeyDown,\n\n      handlePaste,\n    },\n\n    appendTransaction(_, oldState, state) {\n      return normalizeSelection(\n        state,\n        fixTables(state, oldState),\n        allowTableNodeSelection,\n      );\n    },\n  });\n}\n", "import { type Attribute, isValidCSSStyleValue } from '@tiptap/core'\n\n/**\n * Supported table cell alignment values\n */\nexport enum TableCellAlign {\n  Left = 'left',\n  Right = 'right',\n  Center = 'center',\n}\n\n/**\n * Normalize unknown input into a supported table alignment\n *\n * @param value - A potential alignment value\n * @returns A valid TableCellAlign value or null\n */\nexport function normalizeTableCellAlign(value: unknown): TableCellAlign | null {\n  if (\n    value === TableCellAlign.Left ||\n    value === TableCellAlign.Right ||\n    value === TableCellAlign.Center\n  ) {\n    return value\n  }\n\n  return null\n}\n\n/**\n * Parse table cell alignment from an HTML element\n *\n * Prefers inline style (${\"`\"}text-align${\"`\"}) and falls back to the legacy\n * ${\"`\"}align${\"`\"} attribute.\n *\n * @param element - The table cell/header DOM element\n * @returns A valid TableCellAlign value or null\n */\nfunction parseAlign(element: HTMLElement): TableCellAlign | null {\n  const styleAlign = (element.style.textAlign || '').trim().toLowerCase()\n  const attrAlign = (element.getAttribute('align') || '').trim().toLowerCase()\n  const align = styleAlign || attrAlign\n\n  return normalizeTableCellAlign(align)\n}\n\n/**\n * Normalize alignment from a generic attrs object that may include an align field\n *\n * @param attributes - A node attrs-like object with an optional align field\n * @returns A valid TableCellAlign value or null.\n */\nexport function normalizeTableCellAlignFromAttributes(\n  attributes: { align?: TableCellAlign } | null | undefined,\n): TableCellAlign | null {\n  return normalizeTableCellAlign(attributes?.align)\n}\n\n/**\n * Create a reusable Tiptap attribute config for table alignment\n *\n * @returns A Tiptap Attribute definition that parses and renders table alignment\n */\nexport function createAlignAttribute(): Attribute {\n  return {\n    default: null,\n    parseHTML: (element: HTMLElement) => parseAlign(element),\n    renderHTML: (attributes: { align?: unknown }) => {\n      const align = normalizeTableCellAlign(attributes.align)\n\n      if (!isValidCSSStyleValue(align)) {\n        return {}\n      }\n\n      return {\n        style: `text-align: ${align}`,\n      }\n    },\n  }\n}\n", "/**\n * reads the width of the `<col>` element matching a cell's column from the table's `<colgroup>`\n *\n * @param element - The table cell/header DOM element\n * @returns - An array with the column width in pixels or null\n */\nfunction parseColgroupWidth(element: HTMLElement): number[] | null {\n  const row = element.parentElement\n  const table = element.closest('table')\n\n  if (!row || !table) {\n    return null\n  }\n\n  const cellIndex = Array.from(row.children).indexOf(element)\n  const width = table.querySelectorAll('colgroup > col')[cellIndex]?.getAttribute('width')\n\n  return width ? [parseInt(width, 10)] : null\n}\n\n/**\n * Parse the column width/s of a table cell/header from an HTML element.\n * it prefers the `colwidth` attribute and if not-provided falls back to the `width` attribute\n * of the matching `<col>` element in the table's `<colgroup>`.\n *\n * @param element - The table cell/header DOM element\n * @returns - An array of column widths in pixels or null\n */\nexport function parseColwidth(element: HTMLElement): number[] | null {\n  const colwidth = element.getAttribute('colwidth')\n\n  if (colwidth) {\n    return colwidth.split(',').map(width => parseInt(width, 10))\n  }\n\n  return parseColgroupWidth(element)\n}\n", "import type { NodeType } from '@tiptap/pm/model'\nimport { Fragment } from '@tiptap/pm/model'\n\n// ASCII whitespace only, so a non-breaking-space cell is not treated as empty.\nconst COLLAPSIBLE_WHITESPACE = /[ \\t\\r\\n\\f]+/g\n\n/** Whether a cell/header element has no child elements and only collapsible whitespace. */\nexport function isEmptyCellElement(element: HTMLElement): boolean {\n  if (element.children.length > 0) {\n    return false\n  }\n\n  return (element.textContent ?? '').replace(COLLAPSIBLE_WHITESPACE, '') === ''\n}\n\n/** Builds a cell/header's minimal `block+` content, derived from the node type. */\nexport function fillEmptyCellContent(cellType: NodeType): Fragment {\n  const filled = cellType.createAndFill()\n\n  if (!filled) {\n    throw new Error(`[tiptap error]: \"${cellType.name}\" has no default content to backfill.`)\n  }\n\n  return filled.content\n}\n", "export function omitDefaultSpanAttribute(\n  attributes: Record<string, unknown>,\n  renderedAttributes: Record<string, unknown>,\n  name: 'colspan' | 'rowspan',\n): void {\n  if (!(name in renderedAttributes)) {\n    return\n  }\n\n  const value = renderedAttributes[name]\n\n  if (value === 1 || value === '1' || value === null || value === undefined) {\n    delete attributes[name]\n  }\n}\n", "import '../types.js'\n\nimport { mergeAttributes, Node } from '@tiptap/core'\n\nimport { createAlignAttribute } from '../utils/parseAlign.js'\nimport { parseColwidth } from '../utils/parseColwidth.js'\nimport { fillEmptyCellContent, isEmptyCellElement } from '../utils/fillEmptyCellContent.js'\nimport { omitDefaultSpanAttribute } from '../utils/omitDefaultSpanAttribute.js'\n\nexport interface TableCellOptions {\n  /**\n   * The HTML attributes for a table cell node.\n   * @default {}\n   * @example { class: 'foo' }\n   */\n  HTMLAttributes: Record<string, any>\n}\n\n/**\n * This extension allows you to create table cells.\n * @see https://www.tiptap.dev/api/nodes/table-cell\n */\nexport const TableCell = Node.create<TableCellOptions>({\n  name: 'tableCell',\n\n  addOptions() {\n    return {\n      HTMLAttributes: {},\n    }\n  },\n\n  content: 'block+',\n\n  addAttributes() {\n    return {\n      colspan: {\n        default: 1,\n      },\n      rowspan: {\n        default: 1,\n      },\n      colwidth: {\n        default: null,\n        parseHTML: parseColwidth,\n      },\n      align: createAlignAttribute(),\n    }\n  },\n\n  tableRole: 'cell',\n\n  isolating: true,\n\n  parseHTML() {\n    return [\n      {\n        // Backfill empty cells; non-empty cells fall through to the rule below.\n        tag: 'td',\n        getAttrs: node => (isEmptyCellElement(node) ? {} : false),\n        getContent: (_node, schema) => fillEmptyCellContent(schema.nodes[this.name]),\n      },\n      { tag: 'td' },\n    ]\n  },\n\n  renderHTML({ HTMLAttributes }) {\n    const attributes = mergeAttributes(this.options.HTMLAttributes, HTMLAttributes)\n\n    omitDefaultSpanAttribute(attributes, HTMLAttributes, 'colspan')\n    omitDefaultSpanAttribute(attributes, HTMLAttributes, 'rowspan')\n\n    return ['td', attributes, 0]\n  },\n})\n", "import '../types.js'\n\nimport { mergeAttributes, Node } from '@tiptap/core'\n\nimport { createAlignAttribute } from '../utils/parseAlign.js'\nimport { parseColwidth } from '../utils/parseColwidth.js'\nimport { fillEmptyCellContent, isEmptyCellElement } from '../utils/fillEmptyCellContent.js'\nimport { omitDefaultSpanAttribute } from '../utils/omitDefaultSpanAttribute.js'\n\nexport interface TableHeaderOptions {\n  /**\n   * The HTML attributes for a table header node.\n   * @default {}\n   * @example { class: 'foo' }\n   */\n  HTMLAttributes: Record<string, any>\n}\n\n/**\n * This extension allows you to create table headers.\n * @see https://www.tiptap.dev/api/nodes/table-header\n */\nexport const TableHeader = Node.create<TableHeaderOptions>({\n  name: 'tableHeader',\n\n  addOptions() {\n    return {\n      HTMLAttributes: {},\n    }\n  },\n\n  content: 'block+',\n\n  addAttributes() {\n    return {\n      colspan: {\n        default: 1,\n      },\n      rowspan: {\n        default: 1,\n      },\n      colwidth: {\n        default: null,\n        parseHTML: parseColwidth,\n      },\n      align: createAlignAttribute(),\n    }\n  },\n\n  tableRole: 'header_cell',\n\n  isolating: true,\n\n  parseHTML() {\n    return [\n      {\n        // Backfill empty cells; non-empty cells fall through to the rule below.\n        tag: 'th',\n        getAttrs: node => (isEmptyCellElement(node) ? {} : false),\n        getContent: (_node, schema) => fillEmptyCellContent(schema.nodes[this.name]),\n      },\n      { tag: 'th' },\n    ]\n  },\n\n  renderHTML({ HTMLAttributes }) {\n    const attributes = mergeAttributes(this.options.HTMLAttributes, HTMLAttributes)\n\n    omitDefaultSpanAttribute(attributes, HTMLAttributes, 'colspan')\n    omitDefaultSpanAttribute(attributes, HTMLAttributes, 'rowspan')\n\n    return ['th', attributes, 0]\n  },\n})\n", "import '../types.js'\n\nimport { mergeAttributes, Node } from '@tiptap/core'\n\nexport interface TableRowOptions {\n  /**\n   * The HTML attributes for a table row node.\n   * @default {}\n   * @example { class: 'foo' }\n   */\n  HTMLAttributes: Record<string, any>\n}\n\n/**\n * This extension allows you to create table rows.\n * @see https://www.tiptap.dev/api/nodes/table-row\n */\nexport const TableRow = Node.create<TableRowOptions>({\n  name: 'tableRow',\n\n  addOptions() {\n    return {\n      HTMLAttributes: {},\n    }\n  },\n\n  content: '(tableCell | tableHeader)*',\n\n  tableRole: 'row',\n\n  parseHTML() {\n    return [{ tag: 'tr' }]\n  },\n\n  renderHTML({ HTMLAttributes }) {\n    return ['tr', mergeAttributes(this.options.HTMLAttributes, HTMLAttributes), 0]\n  },\n})\n", "export function getColStyleDeclaration(\n  minWidth: number,\n  width: number | undefined,\n): [string, string] {\n  if (width) {\n    // apply the stored width unless it is below the configured minimum cell width\n    return ['width', `${Math.max(width, minWidth)}px`]\n  }\n\n  // set the minimum with on the column if it has no stored width\n  return ['min-width', `${minWidth}px`]\n}\n", "import type { Node as ProseMirrorNode } from '@tiptap/pm/model'\nimport type { EditorView, NodeView, ViewMutationRecord } from '@tiptap/pm/view'\n\nimport { getColStyleDeclaration } from './utilities/colStyle.js'\n\nexport function updateColumns(\n  node: ProseMirrorNode,\n  colgroup: HTMLTableColElement, // <colgroup> has the same prototype as <col>\n  table: HTMLTableElement,\n  cellMinWidth: number,\n  overrideCol?: number,\n  overrideValue?: number,\n) {\n  let totalWidth = 0\n  let fixedWidth = true\n  let nextDOM = colgroup.firstChild\n  const row = node.firstChild\n\n  if (row !== null) {\n    for (let i = 0, col = 0; i < row.childCount; i += 1) {\n      const { colspan, colwidth } = row.child(i).attrs\n\n      for (let j = 0; j < colspan; j += 1, col += 1) {\n        const hasWidth =\n          overrideCol === col ? overrideValue : ((colwidth && colwidth[j]) as number | undefined)\n        const cssWidth = hasWidth ? `${hasWidth}px` : ''\n\n        totalWidth += hasWidth || cellMinWidth\n\n        if (!hasWidth) {\n          fixedWidth = false\n        }\n\n        if (!nextDOM) {\n          const colElement = document.createElement('col')\n\n          const [propertyKey, propertyValue] = getColStyleDeclaration(cellMinWidth, hasWidth)\n\n          colElement.style.setProperty(propertyKey, propertyValue)\n\n          colgroup.appendChild(colElement)\n        } else {\n          if ((nextDOM as HTMLTableColElement).style.width !== cssWidth) {\n            const [propertyKey, propertyValue] = getColStyleDeclaration(cellMinWidth, hasWidth)\n\n            ;(nextDOM as HTMLTableColElement).style.setProperty(propertyKey, propertyValue)\n          }\n\n          nextDOM = nextDOM.nextSibling\n        }\n      }\n    }\n  }\n\n  while (nextDOM) {\n    const after = nextDOM.nextSibling\n\n    nextDOM.parentNode?.removeChild(nextDOM)\n    nextDOM = after\n  }\n\n  // Check if user has set a width style on the table node\n  const hasUserWidth =\n    node.attrs.style &&\n    typeof node.attrs.style === 'string' &&\n    /\\bwidth\\s*:/i.test(node.attrs.style)\n\n  if (fixedWidth && !hasUserWidth) {\n    table.style.width = `${totalWidth}px`\n    table.style.minWidth = ''\n  } else {\n    table.style.width = ''\n    table.style.minWidth = `${totalWidth}px`\n  }\n}\n\nexport class TableView implements NodeView {\n  node: ProseMirrorNode\n\n  cellMinWidth: number\n\n  dom: HTMLDivElement\n\n  table: HTMLTableElement\n\n  colgroup: HTMLTableColElement\n\n  contentDOM: HTMLTableSectionElement\n\n  constructor(\n    node: ProseMirrorNode,\n    cellMinWidth: number,\n    _view?: EditorView,\n    HTMLAttributes: Record<string, any> = {},\n  ) {\n    this.node = node\n    this.cellMinWidth = cellMinWidth\n    this.dom = document.createElement('div')\n    this.dom.className = 'tableWrapper'\n    this.table = this.dom.appendChild(document.createElement('table'))\n\n    // Apply extension-configured HTMLAttributes to the table element\n    // (e.g. class, data-* set via Table.configure({ HTMLAttributes }))\n    for (const [key, value] of Object.entries(HTMLAttributes)) {\n      if (value !== undefined && value !== null) {\n        if (key === 'style') {\n          this.table.style.cssText = String(value)\n        } else {\n          this.table.setAttribute(key, String(value))\n        }\n      }\n    }\n\n    // Apply user styles from the ProseMirror document node.\n    // This may come from HTML parsing (e.g. <table style=\"...\">) and should\n    // override any style set via extension-configured HTMLAttributes above.\n    if (node.attrs.style) {\n      this.table.style.cssText = node.attrs.style\n    }\n\n    this.colgroup = this.table.appendChild(document.createElement('colgroup'))\n    updateColumns(node, this.colgroup, this.table, cellMinWidth)\n    this.contentDOM = this.table.appendChild(document.createElement('tbody'))\n  }\n\n  update(node: ProseMirrorNode) {\n    // Recreate the view to apply changed table attributes.\n    if (!node.sameMarkup(this.node)) {\n      return false\n    }\n\n    this.node = node\n    updateColumns(node, this.colgroup, this.table, this.cellMinWidth)\n\n    return true\n  }\n\n  ignoreMutation(mutation: ViewMutationRecord) {\n    const target = mutation.target as Node\n    const isInsideWrapper = this.dom.contains(target)\n    const isInsideContent = this.contentDOM.contains(target)\n\n    if (isInsideWrapper && !isInsideContent) {\n      if (\n        mutation.type === 'attributes' ||\n        mutation.type === 'childList' ||\n        mutation.type === 'characterData'\n      ) {\n        return true\n      }\n    }\n\n    return false\n  }\n}\n", "import type { DOMOutputSpec, Node as ProseMirrorNode } from '@tiptap/pm/model'\n\nimport { getColStyleDeclaration } from './colStyle.js'\n\nexport type ColGroup =\n  | {\n      colgroup: DOMOutputSpec\n      tableWidth: string\n      tableMinWidth: string\n    }\n  | Record<string, never>\n\n/**\n * Creates a colgroup element for a table node in ProseMirror.\n *\n * @param node - The ProseMirror node representing the table.\n * @param cellMinWidth - The minimum width of a cell in the table.\n * @param overrideCol - (Optional) The index of the column to override the width of.\n * @param overrideValue - (Optional) The width value to use for the overridden column.\n * @returns An object containing the colgroup element, the total width of the table, and the minimum width of the table.\n */\nexport function createColGroup(node: ProseMirrorNode, cellMinWidth: number): ColGroup\nexport function createColGroup(\n  node: ProseMirrorNode,\n  cellMinWidth: number,\n  overrideCol: number,\n  overrideValue: number,\n): ColGroup\nexport function createColGroup(\n  node: ProseMirrorNode,\n  cellMinWidth: number,\n  overrideCol?: number,\n  overrideValue?: number,\n): ColGroup {\n  let totalWidth = 0\n  let fixedWidth = true\n  const cols: DOMOutputSpec[] = []\n  const row = node.firstChild\n\n  if (!row) {\n    return {}\n  }\n\n  for (let i = 0, col = 0; i < row.childCount; i += 1) {\n    const { colspan, colwidth } = row.child(i).attrs\n\n    for (let j = 0; j < colspan; j += 1, col += 1) {\n      const hasWidth =\n        overrideCol === col ? overrideValue : colwidth && (colwidth[j] as number | undefined)\n\n      totalWidth += hasWidth || cellMinWidth\n\n      if (!hasWidth) {\n        fixedWidth = false\n      }\n\n      const [property, value] = getColStyleDeclaration(cellMinWidth, hasWidth)\n\n      cols.push(['col', { style: `${property}: ${value}` }])\n    }\n  }\n\n  const tableWidth = fixedWidth ? `${totalWidth}px` : ''\n  const tableMinWidth = fixedWidth ? '' : `${totalWidth}px`\n\n  const colgroup: DOMOutputSpec = ['colgroup', {}, ...cols]\n\n  return { colgroup, tableWidth, tableMinWidth }\n}\n", "import type { Fragment, Node as ProsemirrorNode, NodeType } from '@tiptap/pm/model'\n\nexport function createCell(\n  cellType: NodeType,\n  cellContent?: Fragment | ProsemirrorNode | Array<ProsemirrorNode>,\n): ProsemirrorNode | null | undefined {\n  if (cellContent) {\n    return cellType.createChecked(null, cellContent)\n  }\n\n  return cellType.createAndFill()\n}\n", "import type { NodeType, Schema } from '@tiptap/pm/model'\n\nexport function getTableNodeTypes(schema: Schema): { [key: string]: NodeType } {\n  if (schema.cached.tableNodeTypes) {\n    return schema.cached.tableNodeTypes\n  }\n\n  const roles: { [key: string]: NodeType } = {}\n\n  Object.keys(schema.nodes).forEach(type => {\n    const nodeType = schema.nodes[type]\n\n    if (nodeType.spec.tableRole) {\n      roles[nodeType.spec.tableRole] = nodeType\n    }\n  })\n\n  schema.cached.tableNodeTypes = roles\n\n  return roles\n}\n", "import type { Fragment, Node as ProsemirrorNode, Schema } from '@tiptap/pm/model'\n\nimport { createCell } from './createCell.js'\nimport { getTableNodeTypes } from './getTableNodeTypes.js'\n\nexport function createTable(\n  schema: Schema,\n  rowsCount: number,\n  colsCount: number,\n  withHeaderRow: boolean,\n  cellContent?: Fragment | ProsemirrorNode | Array<ProsemirrorNode>,\n): ProsemirrorNode {\n  const types = getTableNodeTypes(schema)\n  const headerCells: ProsemirrorNode[] = []\n  const cells: ProsemirrorNode[] = []\n\n  for (let index = 0; index < colsCount; index += 1) {\n    const cell = createCell(types.cell, cellContent)\n\n    if (cell) {\n      cells.push(cell)\n    }\n\n    if (withHeaderRow) {\n      const headerCell = createCell(types.header_cell, cellContent)\n\n      if (headerCell) {\n        headerCells.push(headerCell)\n      }\n    }\n  }\n\n  const rows: ProsemirrorNode[] = []\n\n  for (let index = 0; index < rowsCount; index += 1) {\n    rows.push(types.row.createChecked(null, withHeaderRow && index === 0 ? headerCells : cells))\n  }\n\n  return types.table.createChecked(null, rows)\n}\n", "import { CellSelection } from '@tiptap/pm/tables'\n\nexport function isCellSelection(value: unknown): value is CellSelection {\n  return value instanceof CellSelection\n}\n", "import type { KeyboardShortcutCommand } from '@tiptap/core'\nimport { findParentNodeClosestToPos } from '@tiptap/core'\n\nimport { isCellSelection } from './isCellSelection.js'\n\nexport const deleteTableWhenAllCellsSelected: KeyboardShortcutCommand = ({ editor }) => {\n  const { selection } = editor.state\n\n  if (!isCellSelection(selection)) {\n    return false\n  }\n\n  let cellCount = 0\n  const table = findParentNodeClosestToPos(selection.ranges[0].$from, node => {\n    return node.type.name === 'table'\n  })\n\n  table?.node.descendants(node => {\n    if (node.type.name === 'table') {\n      return false\n    }\n\n    if (['tableCell', 'tableHeader'].includes(node.type.name)) {\n      cellCount += 1\n    }\n  })\n\n  const allCellsSelected = cellCount === selection.ranges.length\n\n  if (!allCellsSelected) {\n    return false\n  }\n\n  editor.commands.deleteTable()\n\n  return true\n}\n", "import { findParentNodeClosestToPos } from '@tiptap/core'\nimport { TextSelection, type Transaction } from '@tiptap/pm/state'\n\n// prosemirror-tables does not move the selection after a deletion, so removing the\n// last row or column can push the cursor out of the table into the content below.\nexport function keepCursorInTable(tr: Transaction, tablePos: number) {\n  const mappedTablePos = tr.mapping.map(tablePos)\n\n  // The delete can push the cursor into a following table, so compare the\n  // mapped position to confirm it is still the table we edited.\n  const stillInTable = findParentNodeClosestToPos(\n    tr.selection.$from,\n    node => node.type.name === 'table',\n  )\n\n  if (stillInTable?.pos === mappedTablePos) {\n    return\n  }\n\n  const tableNode = tr.doc.nodeAt(mappedTablePos)\n\n  if (!tableNode) {\n    return\n  }\n\n  const endOfTable = mappedTablePos + tableNode.nodeSize - 1\n\n  tr.setSelection(TextSelection.near(tr.doc.resolve(endOfTable), -1))\n}\n", "import type { JSONContent, MarkdownRendererHelpers } from '@tiptap/core'\n\nimport {\n  type TableCellAlign as TableCellAlignType,\n  normalizeTableCellAlignFromAttributes,\n  TableCellAlign,\n} from '../../utils/parseAlign.js'\n\nexport const DEFAULT_CELL_LINE_SEPARATOR = '\\u001F'\n\n/**\n * Walk a single table-row line and escape any `|` characters that appear\n * inside backtick code spans so marked's cell splitter ignores them.\n * Backslash escape sequences outside code spans are passed through untouched.\n * If a backtick run has no matching closer on the same line it is emitted\n * as-is — no over-escaping for malformed input.\n */\nexport function escapeTableCellPipes(line: string): string {\n  let result = ''\n  let i = 0\n  while (i < line.length) {\n    if (line[i] === '\\\\' && i + 1 < line.length) {\n      result += line[i] + line[i + 1]\n      i += 2\n      continue\n    }\n    if (line[i] !== '`') {\n      result += line[i++]\n      continue\n    }\n    let runLen = 0\n    while (i + runLen < line.length && line[i + runLen] === '`') runLen += 1\n    let j = i + runLen\n    let found = false\n    while (j < line.length) {\n      if (line[j] !== '`') {\n        j += 1\n        continue\n      }\n      let closeLen = 0\n      while (j + closeLen < line.length && line[j + closeLen] === '`') closeLen += 1\n      if (closeLen === runLen) {\n        const spanContent = line.slice(i + runLen, j)\n        // Matches an already-escaped pipe (`\\|`, kept as-is) or a bare pipe\n        // (escaped). Deliberately avoids a negative lookbehind assertion:\n        // WebKit before Safari 16.4 cannot parse lookbehind, and a regex\n        // literal fails the whole chunk at parse time, not at call time.\n        result +=\n          line.slice(i, i + runLen) +\n          spanContent.replace(/\\\\\\||\\|/g, match => (match === '|' ? '\\\\|' : match)) +\n          line.slice(j, j + runLen)\n        i = j + runLen\n        found = true\n        break\n      }\n      j += closeLen\n    }\n    if (!found) {\n      result += line.slice(i, i + runLen)\n      i += runLen\n    }\n  }\n  return result\n}\n\n/**\n * Escape pipe characters inside backtick code spans on table-row lines.\n * marked's `splitCells` only recognises backslash-escaped pipes (`\\|`) and\n * splits on every other `|`, so \\`a || b\\` in a table cell would be treated\n * as multiple column delimiters. Escaping them here lets `splitCells` skip\n * them; it already converts `\\|` → `|` after splitting, so the cell content\n * is restored correctly.\n */\nexport function preprocessTablePipes(src: string): string {\n  return src\n    .split('\\n')\n    .map(line => {\n      if (!line.includes('|') || !line.includes('`')) return line\n      return escapeTableCellPipes(line)\n    })\n    .join('\\n')\n}\n\nfunction collapseWhitespace(s: string) {\n  return (s || '').replaceAll(DEFAULT_CELL_LINE_SEPARATOR, ' ').replace(/\\s+/g, ' ').trim()\n}\n\nfunction replaceCellLineSeparator(value: string, cellLineSeparator?: string) {\n  if (!cellLineSeparator) {\n    return value\n  }\n\n  return value.split(cellLineSeparator).join('\\n')\n}\n\nfunction escapePipesInCellText(text: string) {\n  // Keep already escaped pipes as they are\n  return text.replace(/\\\\.|\\|/g, match => (match === '|' ? '\\\\|' : match))\n}\n\nexport function renderTableToMarkdown(\n  node: JSONContent,\n  h: MarkdownRendererHelpers,\n  options: { cellLineSeparator?: string } = {},\n) {\n  if (!node || !node.content || node.content.length === 0) {\n    return ''\n  }\n\n  // Build rows: each cell is { text, isHeader, align }\n  const rows: { text: string; isHeader: boolean; align: TableCellAlignType | null }[][] = []\n\n  node.content.forEach(rowNode => {\n    const cells: { text: string; isHeader: boolean; align: TableCellAlignType | null }[] = []\n\n    if (rowNode.content) {\n      rowNode.content.forEach(cellNode => {\n        let raw = ''\n\n        if (cellNode.content && Array.isArray(cellNode.content) && cellNode.content.length > 1) {\n          const parts = cellNode.content.map(child =>\n            replaceCellLineSeparator(\n              h.renderChildren(child as unknown as JSONContent),\n              options.cellLineSeparator,\n            ),\n          )\n          raw = parts.join('\\n')\n        } else {\n          raw = replaceCellLineSeparator(\n            cellNode.content ? h.renderChildren(cellNode.content as unknown as JSONContent[]) : '',\n            options.cellLineSeparator,\n          )\n        }\n\n        // Cells have to stay on a single line, so line breaks become <br> tags.\n        // The parser already turns <br> back into hard breaks, so this round trips.\n        const singleLine = collapseWhitespace(raw.replace(/[ \\t]*\\r?\\n[ \\t]*/g, '<br>'))\n        const text = escapePipesInCellText(singleLine)\n        const isHeader = cellNode.type === 'tableHeader'\n        const align = normalizeTableCellAlignFromAttributes(cellNode.attrs)\n\n        cells.push({ text, isHeader, align })\n      })\n    }\n\n    rows.push(cells)\n  })\n\n  const columnCount = rows.reduce((max, r) => Math.max(max, r.length), 0)\n\n  if (columnCount === 0) {\n    return ''\n  }\n\n  // Compute max width for each column\n  const colWidths = Array.from<number>({ length: columnCount }).fill(0)\n\n  rows.forEach(r => {\n    for (let i = 0; i < columnCount; i += 1) {\n      const cell = r[i]?.text || ''\n      const len = cell.length\n      if (len > colWidths[i]) {\n        colWidths[i] = len\n      }\n\n      if (colWidths[i] < 3) {\n        colWidths[i] = 3\n      }\n    }\n  })\n\n  const pad = (s: string, width: number) => s + ' '.repeat(Math.max(0, width - s.length))\n\n  const headerRow = rows[0]\n  const hasHeader = headerRow.some(c => c.isHeader)\n  const colAlignments: Array<TableCellAlignType | null> = Array.from<TableCellAlignType | null>({\n    length: columnCount,\n  }).fill(null)\n\n  rows.forEach(r => {\n    for (let i = 0; i < columnCount; i += 1) {\n      if (!colAlignments[i] && r[i]?.align) {\n        colAlignments[i] = r[i].align\n      }\n    }\n  })\n\n  let out = '\\n'\n\n  // Render header: if the document has a header row (tableHeader cells) use it,\n  // otherwise emit an empty header row so most Markdown parsers will recognize\n  // the table (this makes roundtripping to Markdown -> JSON more reliable).\n  const headerTexts = Array.from<number>({ length: columnCount }).map((_, i) =>\n    hasHeader ? (headerRow[i] && headerRow[i].text) || '' : '',\n  )\n\n  out += `| ${headerTexts.map((t, i) => pad(t, colWidths[i])).join(' | ')} |\\n`\n\n  // Separator (use at least 3 dashes per column and include alignment markers)\n  out += `| ${colWidths\n    .map((w, index) => {\n      const dashCount = Math.max(3, w)\n      const alignment = colAlignments[index]\n\n      if (alignment === TableCellAlign.Left) {\n        return `:${'-'.repeat(dashCount)}`\n      }\n\n      if (alignment === TableCellAlign.Right) {\n        return `${'-'.repeat(dashCount)}:`\n      }\n\n      if (alignment === TableCellAlign.Center) {\n        return `:${'-'.repeat(dashCount)}:`\n      }\n\n      return '-'.repeat(dashCount)\n    })\n    .join(' | ')} |\\n`\n\n  // Body rows: if we had a header, skip the first row; otherwise render all rows\n  const body = hasHeader ? rows.slice(1) : rows\n  body.forEach(r => {\n    out += `| ${Array.from<number>({ length: columnCount })\n      .fill(0)\n      .map((_, i) => pad((r[i] && r[i].text) || '', colWidths[i]))\n      .join(' | ')} |\\n`\n  })\n\n  return out\n}\n\nexport default renderTableToMarkdown\n", "import { Plugin, PluginKey } from '@tiptap/pm/state'\nimport type { CellSelection } from '@tiptap/pm/tables'\nimport type { EditorView } from '@tiptap/pm/view'\n\nimport { isCellSelection } from './isCellSelection.js'\n\nconst preserveCellSelectionOnContextMenuPluginKey = new PluginKey(\n  'preserveCellSelectionOnContextMenu',\n)\n\nfunction resolveClickPos(view: EditorView, event: MouseEvent): number | null {\n  const coords = view.posAtCoords({ left: event.clientX, top: event.clientY })\n\n  if (coords) {\n    return coords.pos\n  }\n\n  if (!(event.target instanceof Node)) {\n    return null\n  }\n\n  try {\n    return view.posAtDOM(event.target, 0)\n  } catch {\n    return null\n  }\n}\n\nfunction isPosInsideCellSelection(selection: CellSelection, pos: number): boolean {\n  let inside = false\n\n  selection.forEachCell((cell, cellPos) => {\n    if (pos >= cellPos && pos < cellPos + cell.nodeSize) {\n      inside = true\n    }\n  })\n\n  return inside\n}\n\nexport function preserveCellSelectionOnContextMenu() {\n  return new Plugin({\n    key: preserveCellSelectionOnContextMenuPluginKey,\n    props: {\n      handleDOMEvents: {\n        mousedown(view, event) {\n          if (event.button !== 2) {\n            return false\n          }\n\n          const { selection } = view.state\n\n          if (!isCellSelection(selection) || selection.ranges.length < 2) {\n            return false\n          }\n\n          const clickPos = resolveClickPos(view, event)\n\n          if (clickPos == null || !isPosInsideCellSelection(selection, clickPos)) {\n            return false\n          }\n\n          event.preventDefault()\n          return true\n        },\n      },\n    },\n  })\n}\n", "import '../types.js'\n\nimport {\n  type JSONContent,\n  type MarkdownToken,\n  callOrReturn,\n  findParentNodeClosestToPos,\n  getExtensionField,\n  mergeAttributes,\n  Node,\n} from '@tiptap/core'\nimport type { DOMOutputSpec, Node as ProseMirrorNode } from '@tiptap/pm/model'\nimport { TextSelection } from '@tiptap/pm/state'\nimport {\n  addColumnAfter,\n  addColumnBefore,\n  addRowAfter,\n  addRowBefore,\n  CellSelection,\n  columnResizing,\n  deleteColumn,\n  deleteRow,\n  deleteTable,\n  fixTables,\n  goToNextCell,\n  mergeCells,\n  setCellAttr,\n  splitCell,\n  tableEditing,\n  toggleHeader,\n  toggleHeaderCell,\n} from '@tiptap/pm/tables'\nimport type { EditorView, NodeView } from '@tiptap/pm/view'\n\nimport { type TableCellAlign, normalizeTableCellAlign } from '../utils/parseAlign.js'\nimport { TableView } from './TableView.js'\nimport { createColGroup } from './utilities/createColGroup.js'\nimport { createTable } from './utilities/createTable.js'\nimport { deleteTableWhenAllCellsSelected } from './utilities/deleteTableWhenAllCellsSelected.js'\nimport { keepCursorInTable } from './utilities/keepCursorInTable.js'\nimport renderTableToMarkdown, { preprocessTablePipes } from './utilities/markdown.js'\nimport { preserveCellSelectionOnContextMenu } from './utilities/preserveCellSelectionOnContextMenu.js'\n\ntype MarkdownTableToken = {\n  align?: Array<TableCellAlign | null>\n  header?: { tokens: MarkdownToken[]; align?: TableCellAlign | null }[]\n  rows?: { tokens: MarkdownToken[]; align?: TableCellAlign | null }[][]\n} & MarkdownToken\n\nexport interface TableOptions {\n  /**\n   * HTML attributes for the table element.\n   * @default {}\n   * @example { class: 'foo' }\n   */\n  HTMLAttributes: Record<string, any>\n\n  /**\n   * Enables the resizing of tables.\n   * @default false\n   * @example true\n   */\n  resizable: boolean\n\n  /**\n   * Controls whether the table should be wrapped in a div with class \"tableWrapper\" when rendered.\n   * In editable mode with resizable tables, this wrapper is always present via TableView.\n   * @default false\n   * @example true\n   */\n  renderWrapper: boolean\n\n  /**\n   * The width of the resize handle.\n   * @default 5\n   * @example 10\n   */\n  handleWidth: number\n\n  /**\n   * The minimum width of a cell.\n   * @default 25\n   * @example 50\n   */\n  cellMinWidth: number\n\n  /**\n   * The node view to render the table.\n   * @default TableView\n   */\n  View:\n    | (new (\n        node: ProseMirrorNode,\n        cellMinWidth: number,\n        view: EditorView,\n        HTMLAttributes?: Record<string, any>,\n      ) => NodeView)\n    | null\n\n  /**\n   * Enables the resizing of the last column.\n   * @default true\n   * @example false\n   */\n  lastColumnResizable: boolean\n\n  /**\n   * Allow table node selection.\n   * @default false\n   * @example true\n   */\n  allowTableNodeSelection: boolean\n}\n\ndeclare module '@tiptap/core' {\n  interface Commands<ReturnType> {\n    table: {\n      /**\n       * Insert a table\n       * @param options The table attributes\n       * @returns True if the command was successful, otherwise false\n       * @example editor.commands.insertTable({ rows: 3, cols: 3, withHeaderRow: true })\n       */\n      insertTable: (options?: {\n        rows?: number\n        cols?: number\n        withHeaderRow?: boolean\n      }) => ReturnType\n\n      /**\n       * Add a column before the current column\n       * @returns True if the command was successful, otherwise false\n       * @example editor.commands.addColumnBefore()\n       */\n      addColumnBefore: () => ReturnType\n\n      /**\n       * Add a column after the current column\n       * @returns True if the command was successful, otherwise false\n       * @example editor.commands.addColumnAfter()\n       */\n      addColumnAfter: () => ReturnType\n\n      /**\n       * Delete the current column\n       * @returns True if the command was successful, otherwise false\n       * @example editor.commands.deleteColumn()\n       */\n      deleteColumn: () => ReturnType\n\n      /**\n       * Add a row before the current row\n       * @returns True if the command was successful, otherwise false\n       * @example editor.commands.addRowBefore()\n       */\n      addRowBefore: () => ReturnType\n\n      /**\n       * Add a row after the current row\n       * @returns True if the command was successful, otherwise false\n       * @example editor.commands.addRowAfter()\n       */\n      addRowAfter: () => ReturnType\n\n      /**\n       * Delete the current row\n       * @returns True if the command was successful, otherwise false\n       * @example editor.commands.deleteRow()\n       */\n      deleteRow: () => ReturnType\n\n      /**\n       * Delete the current table\n       * @returns True if the command was successful, otherwise false\n       * @example editor.commands.deleteTable()\n       */\n      deleteTable: () => ReturnType\n\n      /**\n       * Merge the currently selected cells\n       * @returns True if the command was successful, otherwise false\n       * @example editor.commands.mergeCells()\n       */\n      mergeCells: () => ReturnType\n\n      /**\n       * Split the currently selected cell\n       * @returns True if the command was successful, otherwise false\n       * @example editor.commands.splitCell()\n       */\n      splitCell: () => ReturnType\n\n      /**\n       * Toggle the header column\n       * @returns True if the command was successful, otherwise false\n       * @example editor.commands.toggleHeaderColumn()\n       */\n      toggleHeaderColumn: () => ReturnType\n\n      /**\n       * Toggle the header row\n       * @returns True if the command was successful, otherwise false\n       * @example editor.commands.toggleHeaderRow()\n       */\n      toggleHeaderRow: () => ReturnType\n\n      /**\n       * Toggle the header cell\n       * @returns True if the command was successful, otherwise false\n       * @example editor.commands.toggleHeaderCell()\n       */\n      toggleHeaderCell: () => ReturnType\n\n      /**\n       * Merge or split the currently selected cells\n       * @returns True if the command was successful, otherwise false\n       * @example editor.commands.mergeOrSplit()\n       */\n      mergeOrSplit: () => ReturnType\n\n      /**\n       * Set a cell attribute\n       * @param name The attribute name\n       * @param value The attribute value\n       * @returns True if the command was successful, otherwise false\n       * @example editor.commands.setCellAttribute('align', 'right')\n       */\n      setCellAttribute: (name: string, value: any) => ReturnType\n\n      /**\n       * Moves the selection to the next cell\n       * @returns True if the command was successful, otherwise false\n       * @example editor.commands.goToNextCell()\n       */\n      goToNextCell: () => ReturnType\n\n      /**\n       * Moves the selection to the previous cell\n       * @returns True if the command was successful, otherwise false\n       * @example editor.commands.goToPreviousCell()\n       */\n      goToPreviousCell: () => ReturnType\n\n      /**\n       * Try to fix the table structure if necessary\n       * @returns True if the command was successful, otherwise false\n       * @example editor.commands.fixTables()\n       */\n      fixTables: () => ReturnType\n\n      /**\n       * Set a cell selection inside the current table\n       * @param position The cell position\n       * @returns True if the command was successful, otherwise false\n       * @example editor.commands.setCellSelection({ anchorCell: 1, headCell: 2 })\n       */\n      setCellSelection: (position: { anchorCell: number; headCell?: number }) => ReturnType\n    }\n  }\n}\n\n/**\n * This extension allows you to create tables.\n * @see https://www.tiptap.dev/api/nodes/table\n */\nexport const Table = Node.create<TableOptions>({\n  name: 'table',\n\n  // @ts-ignore\n  addOptions() {\n    return {\n      HTMLAttributes: {},\n      resizable: false,\n      renderWrapper: false,\n      handleWidth: 5,\n      cellMinWidth: 25,\n      // TODO: fix\n      View: TableView,\n      lastColumnResizable: true,\n      allowTableNodeSelection: false,\n    }\n  },\n\n  content: 'tableRow+',\n\n  tableRole: 'table',\n\n  isolating: true,\n\n  group: 'block',\n\n  parseHTML() {\n    return [{ tag: 'table' }]\n  },\n\n  renderHTML({ node, HTMLAttributes }) {\n    const { colgroup, tableWidth, tableMinWidth } = createColGroup(node, this.options.cellMinWidth)\n\n    const userStyles = HTMLAttributes.style as string | undefined\n\n    function getTableStyle() {\n      if (userStyles) {\n        return userStyles\n      }\n\n      return tableWidth ? `width: ${tableWidth}` : `min-width: ${tableMinWidth}`\n    }\n\n    const table: DOMOutputSpec = [\n      'table',\n      mergeAttributes(this.options.HTMLAttributes, HTMLAttributes, {\n        style: getTableStyle(),\n      }),\n      colgroup,\n      ['tbody', 0],\n    ]\n\n    return this.options.renderWrapper ? ['div', { class: 'tableWrapper' }, table] : table\n  },\n\n  parseMarkdown: (token: MarkdownTableToken, h) => {\n    const rows = []\n    const alignments = Array.isArray(token.align) ? token.align : []\n\n    if (token.header) {\n      const headerCells: JSONContent[] = []\n\n      token.header.forEach((cell, index) => {\n        const align = normalizeTableCellAlign(alignments[index] ?? cell.align)\n        const attrs = align ? { align } : {}\n\n        headerCells.push(\n          h.createNode('tableHeader', attrs, [\n            { type: 'paragraph', content: h.parseInline(cell.tokens) },\n          ]),\n        )\n      })\n\n      rows.push(h.createNode('tableRow', {}, headerCells))\n    }\n\n    if (token.rows) {\n      token.rows.forEach(row => {\n        const bodyCells: JSONContent[] = []\n        row.forEach((cell, index) => {\n          const align = normalizeTableCellAlign(alignments[index] ?? cell.align)\n          const attrs = align ? { align } : {}\n\n          bodyCells.push(\n            h.createNode('tableCell', attrs, [\n              { type: 'paragraph', content: h.parseInline(cell.tokens) },\n            ]),\n          )\n        })\n        rows.push(h.createNode('tableRow', {}, bodyCells))\n      })\n    }\n\n    return h.createNode('table', undefined, rows)\n  },\n\n  renderMarkdown: (node, h) => {\n    return renderTableToMarkdown(node, h)\n  },\n\n  markdownTokenizer: {\n    name: 'table',\n    level: 'block' as const,\n    start: (src: string) => {\n      const lines = src.split('\\n')\n      if (lines.length < 2) return -1\n      const sep = lines[1]\n      if (!/^[ \\t|:]*-[ \\t|:-]*$/.test(sep) || !sep.includes('|')) return -1\n      return lines[0].includes('|') ? 0 : -1\n    },\n    tokenize(src, _tokens, helper) {\n      // Marked terminates a table block at a blank line. Slicing to the first\n      // \\n\\n keeps helper.blockTokens isolated to the candidate table so it\n      // cannot consume content that follows. When no blank line exists the\n      // full remaining source is used and marked's own table regex determines\n      // the boundary (it excludes headings, fences, blockquotes, etc.).\n      const blankLineIndex = src.indexOf('\\n\\n')\n      const candidate = blankLineIndex >= 0 ? src.slice(0, blankLineIndex) : src\n\n      // A GFM table needs at least a header and a separator row (two lines).\n      const candidateLines = candidate.split('\\n')\n      if (candidateLines.length < 2) return undefined\n\n      // Guard: the second line must match a GFM delimiter row (dashes, colons,\n      // pipes, spaces) AND must contain at least one '|'. A bare '---' matches\n      // the dash pattern but is a setext heading marker, not a table separator.\n      // Calling helper.blockTokens on non-table content contaminates the outer\n      // lexer's inline queue with preprocessed (backslash-modified) content.\n      const sep = candidateLines[1]\n      if (!/^[ \\t|:]*-[ \\t|:-]*$/.test(sep) || !sep.includes('|')) return undefined\n\n      const preprocessed = preprocessTablePipes(candidate)\n\n      // Nothing to fix — let marked's built-in handle it.\n      if (preprocessed === candidate) return undefined\n\n      // Re-lex only the preprocessed candidate. The recursive call to our\n      // tokenizer finds no unescaped pipes left inside code spans and returns\n      // undefined, so marked's built-in table tokenizer produces\n      // correctly-split cells.\n      const block = helper.blockTokens(preprocessed)\n      const tableToken = block[0]\n      if (tableToken?.type !== 'table' || !tableToken.raw) return undefined\n\n      // preprocessTablePipes only inserts backslashes (never adds or removes\n      // newlines), so line N in preprocessed maps 1-to-1 to line N in src.\n      // Use the token's line count to reconstruct raw from the original src so\n      // marked advances its cursor by the correct amount.\n      const lineCount = tableToken.raw.split('\\n').length\n      const raw = src.split('\\n').slice(0, lineCount).join('\\n')\n\n      return { ...tableToken, raw }\n    },\n  },\n\n  addCommands() {\n    return {\n      insertTable:\n        ({ rows = 3, cols = 3, withHeaderRow = true } = {}) =>\n        ({ tr, dispatch, editor }) => {\n          const node = createTable(editor.schema, rows, cols, withHeaderRow)\n\n          if (dispatch) {\n            const offset = tr.selection.from + 1\n\n            tr.replaceSelectionWith(node)\n              .scrollIntoView()\n              .setSelection(TextSelection.near(tr.doc.resolve(offset)))\n          }\n\n          return true\n        },\n      addColumnBefore:\n        () =>\n        ({ state, dispatch }) => {\n          return addColumnBefore(state, dispatch)\n        },\n      addColumnAfter:\n        () =>\n        ({ state, dispatch }) => {\n          return addColumnAfter(state, dispatch)\n        },\n      deleteColumn:\n        () =>\n        ({ state, dispatch }) => {\n          const table = findParentNodeClosestToPos(\n            state.selection.$from,\n            node => node.type.name === 'table',\n          )\n\n          return deleteColumn(\n            state,\n            dispatch &&\n              (tr => {\n                if (table) {\n                  keepCursorInTable(tr, table.pos)\n                }\n\n                dispatch(tr)\n              }),\n          )\n        },\n      addRowBefore:\n        () =>\n        ({ state, dispatch }) => {\n          return addRowBefore(state, dispatch)\n        },\n      addRowAfter:\n        () =>\n        ({ state, dispatch }) => {\n          return addRowAfter(state, dispatch)\n        },\n      deleteRow:\n        () =>\n        ({ state, dispatch }) => {\n          const table = findParentNodeClosestToPos(\n            state.selection.$from,\n            node => node.type.name === 'table',\n          )\n\n          return deleteRow(\n            state,\n            dispatch &&\n              (tr => {\n                if (table) {\n                  keepCursorInTable(tr, table.pos)\n                }\n\n                dispatch(tr)\n              }),\n          )\n        },\n      deleteTable:\n        () =>\n        ({ state, dispatch }) => {\n          return deleteTable(state, dispatch)\n        },\n      mergeCells:\n        () =>\n        ({ state, dispatch }) => {\n          return mergeCells(state, dispatch)\n        },\n      splitCell:\n        () =>\n        ({ state, dispatch }) => {\n          return splitCell(state, dispatch)\n        },\n      toggleHeaderColumn:\n        () =>\n        ({ state, dispatch }) => {\n          return toggleHeader('column')(state, dispatch)\n        },\n      toggleHeaderRow:\n        () =>\n        ({ state, dispatch }) => {\n          return toggleHeader('row')(state, dispatch)\n        },\n      toggleHeaderCell:\n        () =>\n        ({ state, dispatch }) => {\n          return toggleHeaderCell(state, dispatch)\n        },\n      mergeOrSplit:\n        () =>\n        ({ state, dispatch }) => {\n          if (mergeCells(state, dispatch)) {\n            return true\n          }\n\n          return splitCell(state, dispatch)\n        },\n      setCellAttribute:\n        (name, value) =>\n        ({ state, dispatch }) => {\n          return setCellAttr(name, value)(state, dispatch)\n        },\n      goToNextCell:\n        () =>\n        ({ state, dispatch }) => {\n          return goToNextCell(1)(state, dispatch)\n        },\n      goToPreviousCell:\n        () =>\n        ({ state, dispatch }) => {\n          return goToNextCell(-1)(state, dispatch)\n        },\n      fixTables:\n        () =>\n        ({ state, dispatch }) => {\n          if (dispatch) {\n            fixTables(state)\n          }\n\n          return true\n        },\n      setCellSelection:\n        position =>\n        ({ tr, dispatch }) => {\n          if (dispatch) {\n            const selection = CellSelection.create(tr.doc, position.anchorCell, position.headCell)\n\n            // @ts-ignore\n            tr.setSelection(selection)\n          }\n\n          return true\n        },\n    }\n  },\n\n  addKeyboardShortcuts() {\n    return {\n      Tab: () => {\n        if (this.editor.commands.goToNextCell()) {\n          return true\n        }\n\n        if (!this.editor.can().addRowAfter()) {\n          return false\n        }\n\n        return this.editor.chain().addRowAfter().goToNextCell().run()\n      },\n      'Shift-Tab': () => this.editor.commands.goToPreviousCell(),\n      Backspace: deleteTableWhenAllCellsSelected,\n      'Mod-Backspace': deleteTableWhenAllCellsSelected,\n      Delete: deleteTableWhenAllCellsSelected,\n      'Mod-Delete': deleteTableWhenAllCellsSelected,\n    }\n  },\n\n  addProseMirrorPlugins() {\n    const isResizable = this.options.resizable && this.editor.isEditable\n\n    return [\n      ...(isResizable\n        ? [\n            columnResizing({\n              handleWidth: this.options.handleWidth,\n              cellMinWidth: this.options.cellMinWidth,\n              defaultCellMinWidth: this.options.cellMinWidth,\n              // Let Tiptap render the table attributes.\n              View: null,\n              lastColumnResizable: this.options.lastColumnResizable,\n            }),\n          ]\n        : []),\n      tableEditing({\n        allowTableNodeSelection: this.options.allowTableNodeSelection,\n      }),\n      preserveCellSelectionOnContextMenu(),\n    ]\n  },\n\n  addNodeView() {\n    const View = this.options.View\n\n    if (!View) {\n      return null\n    }\n\n    return ({ node, view, HTMLAttributes }) => {\n      const mergedAttributes = mergeAttributes(this.options.HTMLAttributes, HTMLAttributes)\n\n      return new View(node, this.options.cellMinWidth, view, mergedAttributes) as NodeView\n    }\n  },\n\n  extendNodeSchema(extension) {\n    const context = {\n      name: extension.name,\n      options: extension.options,\n      storage: extension.storage,\n    }\n\n    return {\n      tableRole: callOrReturn(getExtensionField(extension, 'tableRole', context)),\n    }\n  },\n})\n", "import { Extension } from '@tiptap/core'\n\nimport type { TableCellOptions } from '../cell/index.js'\nimport { TableCell } from '../cell/index.js'\nimport type { TableHeaderOptions } from '../header/index.js'\nimport { TableHeader } from '../header/index.js'\nimport type { TableRowOptions } from '../row/index.js'\nimport { TableRow } from '../row/index.js'\nimport type { TableOptions } from '../table/index.js'\nimport { Table } from '../table/index.js'\n\nexport interface TableKitOptions {\n  /**\n   * If set to false, the table extension will not be registered\n   * @example table: false\n   */\n  table: Partial<TableOptions> | false\n  /**\n   * If set to false, the table extension will not be registered\n   * @example tableCell: false\n   */\n  tableCell: Partial<TableCellOptions> | false\n  /**\n   * If set to false, the table extension will not be registered\n   * @example tableHeader: false\n   */\n  tableHeader: Partial<TableHeaderOptions> | false\n  /**\n   * If set to false, the table extension will not be registered\n   * @example tableRow: false\n   */\n  tableRow: Partial<TableRowOptions> | false\n}\n\n/**\n * The table kit is a collection of table editor extensions.\n *\n * It’s a good starting point for building your own table in Tiptap.\n */\nexport const TableKit = Extension.create<TableKitOptions>({\n  name: 'tableKit',\n\n  addExtensions() {\n    const extensions = []\n\n    if (this.options.table !== false) {\n      extensions.push(Table.configure(this.options.table))\n    }\n\n    if (this.options.tableCell !== false) {\n      extensions.push(TableCell.configure(this.options.tableCell))\n    }\n\n    if (this.options.tableHeader !== false) {\n      extensions.push(TableHeader.configure(this.options.tableHeader))\n    }\n\n    if (this.options.tableRow !== false) {\n      extensions.push(TableRow.configure(this.options.tableRow))\n    }\n\n    return extensions\n  },\n})\n", "import { TaskList } from '@tiptap/extension-list'\n\nexport type { TaskListOptions } from '@tiptap/extension-list'\nexport { TaskList } from '@tiptap/extension-list'\n\nexport default TaskList\n", "import { TaskItem } from '@tiptap/extension-list'\n\nexport type { TaskItemOptions } from '@tiptap/extension-list'\nexport { TaskItem } from '@tiptap/extension-list'\n\nexport default TaskItem\n", "import { Extension, isValidCSSStyleValue } from '@tiptap/core'\n\nexport interface TextAlignOptions {\n  /**\n   * The types where the text align attribute can be applied.\n   * @default []\n   * @example ['heading', 'paragraph']\n   */\n  types: string[]\n\n  /**\n   * The alignments which are allowed.\n   * @default ['left', 'center', 'right', 'justify']\n   * @example ['left', 'right']\n   */\n  alignments: string[]\n\n  /**\n   * The default alignment.\n   * @default null\n   * @example 'center'\n   */\n  defaultAlignment: string | null\n}\n\ndeclare module '@tiptap/core' {\n  interface Commands<ReturnType> {\n    textAlign: {\n      /**\n       * Set the text align attribute\n       * @param alignment The alignment\n       * @example editor.commands.setTextAlign('left')\n       */\n      setTextAlign: (alignment: string) => ReturnType\n      /**\n       * Unset the text align attribute\n       * @example editor.commands.unsetTextAlign()\n       */\n      unsetTextAlign: () => ReturnType\n      /**\n       * Toggle the text align attribute\n       * @param alignment The alignment\n       * @example editor.commands.toggleTextAlign('right')\n       */\n      toggleTextAlign: (alignment: string) => ReturnType\n    }\n  }\n}\n\n/**\n * This extension allows you to align text.\n * @see https://www.tiptap.dev/api/extensions/text-align\n */\nexport const TextAlign = Extension.create<TextAlignOptions>({\n  name: 'textAlign',\n\n  addOptions() {\n    return {\n      types: [],\n      alignments: ['left', 'center', 'right', 'justify'],\n      defaultAlignment: null,\n    }\n  },\n\n  addGlobalAttributes() {\n    return [\n      {\n        types: this.options.types,\n        attributes: {\n          textAlign: {\n            default: this.options.defaultAlignment,\n            parseHTML: element => {\n              const alignment = element.style.textAlign\n\n              return this.options.alignments.includes(alignment)\n                ? alignment\n                : this.options.defaultAlignment\n            },\n            renderHTML: attributes => {\n              if (\n                !isValidCSSStyleValue(attributes.textAlign) ||\n                !this.options.alignments.includes(attributes.textAlign)\n              ) {\n                return {}\n              }\n\n              return { style: `text-align: ${attributes.textAlign}` }\n            },\n          },\n        },\n      },\n    ]\n  },\n\n  addCommands() {\n    return {\n      setTextAlign:\n        (alignment: string) =>\n        ({ commands }) => {\n          if (!this.options.alignments.includes(alignment)) {\n            return false\n          }\n\n          return this.options.types\n            .map(type => commands.updateAttributes(type, { textAlign: alignment }))\n            .some(response => response)\n        },\n\n      unsetTextAlign:\n        () =>\n        ({ commands }) => {\n          return this.options.types\n            .map(type => commands.resetAttributes(type, 'textAlign'))\n            .some(response => response)\n        },\n\n      toggleTextAlign:\n        alignment =>\n        ({ editor, commands }) => {\n          if (!this.options.alignments.includes(alignment)) {\n            return false\n          }\n\n          if (editor.isActive({ textAlign: alignment })) {\n            return commands.unsetTextAlign()\n          }\n          return commands.setTextAlign(alignment)\n        },\n    }\n  },\n\n  addKeyboardShortcuts() {\n    return {\n      'Mod-Shift-l': () => this.editor.commands.setTextAlign('left'),\n      'Mod-Shift-e': () => this.editor.commands.setTextAlign('center'),\n      'Mod-Shift-r': () => this.editor.commands.setTextAlign('right'),\n      'Mod-Shift-j': () => this.editor.commands.setTextAlign('justify'),\n    }\n  },\n})\n", "import { TextAlign } from './text-align.js'\n\nexport * from './text-align.js'\n\nexport default TextAlign\n", "function extend(destination) {\n  for (var i = 1; i < arguments.length; i++) {\n    var source = arguments[i];\n    for (var key in source) {\n      if (Object.prototype.hasOwnProperty.call(source, key)) destination[key] = source[key];\n    }\n  }\n  return destination;\n}\nfunction repeat(character, count) {\n  return Array(count + 1).join(character);\n}\nfunction trimLeadingNewlines(string) {\n  return string.replace(/^\\n*/, '');\n}\nfunction trimTrailingNewlines(string) {\n  // avoid match-at-end regexp bottleneck, see #370\n  var indexEnd = string.length;\n  while (indexEnd > 0 && string[indexEnd - 1] === '\\n') indexEnd--;\n  return string.substring(0, indexEnd);\n}\nfunction trimNewlines(string) {\n  return trimTrailingNewlines(trimLeadingNewlines(string));\n}\nvar blockElements = ['ADDRESS', 'ARTICLE', 'ASIDE', 'AUDIO', 'BLOCKQUOTE', 'BODY', 'CANVAS', 'CENTER', 'DD', 'DIR', 'DIV', 'DL', 'DT', 'FIELDSET', 'FIGCAPTION', 'FIGURE', 'FOOTER', 'FORM', 'FRAMESET', 'H1', 'H2', 'H3', 'H4', 'H5', 'H6', 'HEADER', 'HGROUP', 'HR', 'HTML', 'ISINDEX', 'LI', 'MAIN', 'MENU', 'NAV', 'NOFRAMES', 'NOSCRIPT', 'OL', 'OUTPUT', 'P', 'PRE', 'SECTION', 'TABLE', 'TBODY', 'TD', 'TFOOT', 'TH', 'THEAD', 'TR', 'UL'];\nfunction isBlock(node) {\n  return is(node, blockElements);\n}\nvar voidElements = ['AREA', 'BASE', 'BR', 'COL', 'COMMAND', 'EMBED', 'HR', 'IMG', 'INPUT', 'KEYGEN', 'LINK', 'META', 'PARAM', 'SOURCE', 'TRACK', 'WBR'];\nfunction isVoid(node) {\n  return is(node, voidElements);\n}\nfunction hasVoid(node) {\n  return has(node, voidElements);\n}\nvar meaningfulWhenBlankElements = ['A', 'TABLE', 'THEAD', 'TBODY', 'TFOOT', 'TH', 'TD', 'IFRAME', 'SCRIPT', 'AUDIO', 'VIDEO'];\nfunction isMeaningfulWhenBlank(node) {\n  return is(node, meaningfulWhenBlankElements);\n}\nfunction hasMeaningfulWhenBlank(node) {\n  return has(node, meaningfulWhenBlankElements);\n}\nfunction is(node, tagNames) {\n  return tagNames.indexOf(node.nodeName) >= 0;\n}\nfunction has(node, tagNames) {\n  return node.getElementsByTagName && tagNames.some(function (tagName) {\n    return node.getElementsByTagName(tagName).length;\n  });\n}\nvar markdownEscapes = [[/\\\\/g, '\\\\\\\\'], [/\\*/g, '\\\\*'], [/^-/g, '\\\\-'], [/^\\+ /g, '\\\\+ '], [/^(=+)/g, '\\\\$1'], [/^(#{1,6}) /g, '\\\\$1 '], [/`/g, '\\\\`'], [/^~~~/g, '\\\\~~~'], [/\\[/g, '\\\\['], [/\\]/g, '\\\\]'], [/^>/g, '\\\\>'], [/_/g, '\\\\_'], [/^(\\d+)\\. /g, '$1\\\\. ']];\nfunction escapeMarkdown(string) {\n  return markdownEscapes.reduce(function (accumulator, escape) {\n    return accumulator.replace(escape[0], escape[1]);\n  }, string);\n}\n\nvar rules = {};\nrules.paragraph = {\n  filter: 'p',\n  replacement: function (content) {\n    return '\\n\\n' + content + '\\n\\n';\n  }\n};\nrules.lineBreak = {\n  filter: 'br',\n  replacement: function (content, node, options) {\n    return options.br + '\\n';\n  }\n};\nrules.heading = {\n  filter: ['h1', 'h2', 'h3', 'h4', 'h5', 'h6'],\n  replacement: function (content, node, options) {\n    var hLevel = Number(node.nodeName.charAt(1));\n    if (options.headingStyle === 'setext' && hLevel < 3) {\n      var underline = repeat(hLevel === 1 ? '=' : '-', content.length);\n      return '\\n\\n' + content + '\\n' + underline + '\\n\\n';\n    } else {\n      return '\\n\\n' + repeat('#', hLevel) + ' ' + content + '\\n\\n';\n    }\n  }\n};\nrules.blockquote = {\n  filter: 'blockquote',\n  replacement: function (content) {\n    content = trimNewlines(content).replace(/^/gm, '> ');\n    return '\\n\\n' + content + '\\n\\n';\n  }\n};\nrules.list = {\n  filter: ['ul', 'ol'],\n  replacement: function (content, node) {\n    var parent = node.parentNode;\n    if (parent.nodeName === 'LI' && parent.lastElementChild === node) {\n      return '\\n' + content;\n    } else {\n      return '\\n\\n' + content + '\\n\\n';\n    }\n  }\n};\nrules.listItem = {\n  filter: 'li',\n  replacement: function (content, node, options) {\n    var prefix = options.bulletListMarker + '   ';\n    var parent = node.parentNode;\n    if (parent.nodeName === 'OL') {\n      var start = parent.getAttribute('start');\n      var index = Array.prototype.indexOf.call(parent.children, node);\n      prefix = (start ? Number(start) + index : index + 1) + '.  ';\n    }\n    var isParagraph = /\\n$/.test(content);\n    content = trimNewlines(content) + (isParagraph ? '\\n' : '');\n    content = content.replace(/\\n/gm, '\\n' + ' '.repeat(prefix.length)); // indent\n    return prefix + content + (node.nextSibling ? '\\n' : '');\n  }\n};\nrules.indentedCodeBlock = {\n  filter: function (node, options) {\n    return options.codeBlockStyle === 'indented' && node.nodeName === 'PRE' && node.firstChild && node.firstChild.nodeName === 'CODE';\n  },\n  replacement: function (content, node, options) {\n    return '\\n\\n    ' + node.firstChild.textContent.replace(/\\n/g, '\\n    ') + '\\n\\n';\n  }\n};\nrules.fencedCodeBlock = {\n  filter: function (node, options) {\n    return options.codeBlockStyle === 'fenced' && node.nodeName === 'PRE' && node.firstChild && node.firstChild.nodeName === 'CODE';\n  },\n  replacement: function (content, node, options) {\n    var className = node.firstChild.getAttribute('class') || '';\n    var language = (className.match(/language-(\\S+)/) || [null, ''])[1];\n    var code = node.firstChild.textContent;\n    var fenceChar = options.fence.charAt(0);\n    var fenceSize = 3;\n    var fenceInCodeRegex = new RegExp('^' + fenceChar + '{3,}', 'gm');\n    var match;\n    while (match = fenceInCodeRegex.exec(code)) {\n      if (match[0].length >= fenceSize) {\n        fenceSize = match[0].length + 1;\n      }\n    }\n    var fence = repeat(fenceChar, fenceSize);\n    return '\\n\\n' + fence + language + '\\n' + code.replace(/\\n$/, '') + '\\n' + fence + '\\n\\n';\n  }\n};\nrules.horizontalRule = {\n  filter: 'hr',\n  replacement: function (content, node, options) {\n    return '\\n\\n' + options.hr + '\\n\\n';\n  }\n};\nrules.inlineLink = {\n  filter: function (node, options) {\n    return options.linkStyle === 'inlined' && node.nodeName === 'A' && node.getAttribute('href');\n  },\n  replacement: function (content, node) {\n    var href = escapeLinkDestination(node.getAttribute('href'));\n    var title = escapeLinkTitle(cleanAttribute(node.getAttribute('title')));\n    var titlePart = title ? ' \"' + title + '\"' : '';\n    return '[' + content + '](' + href + titlePart + ')';\n  }\n};\nrules.referenceLink = {\n  filter: function (node, options) {\n    return options.linkStyle === 'referenced' && node.nodeName === 'A' && node.getAttribute('href');\n  },\n  replacement: function (content, node, options) {\n    var href = escapeLinkDestination(node.getAttribute('href'));\n    var title = cleanAttribute(node.getAttribute('title'));\n    if (title) title = ' \"' + escapeLinkTitle(title) + '\"';\n    var replacement;\n    var reference;\n    switch (options.linkReferenceStyle) {\n      case 'collapsed':\n        replacement = '[' + content + '][]';\n        reference = '[' + content + ']: ' + href + title;\n        break;\n      case 'shortcut':\n        replacement = '[' + content + ']';\n        reference = '[' + content + ']: ' + href + title;\n        break;\n      default:\n        var id = this.references.length + 1;\n        replacement = '[' + content + '][' + id + ']';\n        reference = '[' + id + ']: ' + href + title;\n    }\n    this.references.push(reference);\n    return replacement;\n  },\n  references: [],\n  append: function (options) {\n    var references = '';\n    if (this.references.length) {\n      references = '\\n\\n' + this.references.join('\\n') + '\\n\\n';\n      this.references = []; // Reset references\n    }\n    return references;\n  }\n};\nrules.emphasis = {\n  filter: ['em', 'i'],\n  replacement: function (content, node, options) {\n    if (!content.trim()) return '';\n    return options.emDelimiter + content + options.emDelimiter;\n  }\n};\nrules.strong = {\n  filter: ['strong', 'b'],\n  replacement: function (content, node, options) {\n    if (!content.trim()) return '';\n    return options.strongDelimiter + content + options.strongDelimiter;\n  }\n};\nrules.code = {\n  filter: function (node) {\n    var hasSiblings = node.previousSibling || node.nextSibling;\n    var isCodeBlock = node.parentNode.nodeName === 'PRE' && !hasSiblings;\n    return node.nodeName === 'CODE' && !isCodeBlock;\n  },\n  replacement: function (content) {\n    if (!content) return '';\n    content = content.replace(/\\r?\\n|\\r/g, ' ');\n    var extraSpace = /^`|^ .*?[^ ].* $|`$/.test(content) ? ' ' : '';\n    var delimiter = '`';\n    var matches = content.match(/`+/gm) || [];\n    while (matches.indexOf(delimiter) !== -1) delimiter = delimiter + '`';\n    return delimiter + extraSpace + content + extraSpace + delimiter;\n  }\n};\nrules.image = {\n  filter: 'img',\n  replacement: function (content, node) {\n    var alt = escapeMarkdown(cleanAttribute(node.getAttribute('alt')));\n    var src = escapeLinkDestination(node.getAttribute('src') || '');\n    var title = cleanAttribute(node.getAttribute('title'));\n    var titlePart = title ? ' \"' + escapeLinkTitle(title) + '\"' : '';\n    return src ? '![' + alt + ']' + '(' + src + titlePart + ')' : '';\n  }\n};\nfunction cleanAttribute(attribute) {\n  return attribute ? attribute.replace(/(\\n+\\s*)+/g, '\\n') : '';\n}\nfunction escapeLinkDestination(destination) {\n  var escaped = destination.replace(/([<>()])/g, '\\\\$1');\n  return escaped.indexOf(' ') >= 0 ? '<' + escaped + '>' : escaped;\n}\nfunction escapeLinkTitle(title) {\n  return title.replace(/\"/g, '\\\\\"');\n}\n\n/**\n * Manages a collection of rules used to convert HTML to Markdown\n */\n\nfunction Rules(options) {\n  this.options = options;\n  this._keep = [];\n  this._remove = [];\n  this.blankRule = {\n    replacement: options.blankReplacement\n  };\n  this.keepReplacement = options.keepReplacement;\n  this.defaultRule = {\n    replacement: options.defaultReplacement\n  };\n  this.array = [];\n  for (var key in options.rules) this.array.push(options.rules[key]);\n}\nRules.prototype = {\n  add: function (key, rule) {\n    this.array.unshift(rule);\n  },\n  keep: function (filter) {\n    this._keep.unshift({\n      filter: filter,\n      replacement: this.keepReplacement\n    });\n  },\n  remove: function (filter) {\n    this._remove.unshift({\n      filter: filter,\n      replacement: function () {\n        return '';\n      }\n    });\n  },\n  forNode: function (node) {\n    if (node.isBlank) return this.blankRule;\n    var rule;\n    if (rule = findRule(this.array, node, this.options)) return rule;\n    if (rule = findRule(this._keep, node, this.options)) return rule;\n    if (rule = findRule(this._remove, node, this.options)) return rule;\n    return this.defaultRule;\n  },\n  forEach: function (fn) {\n    for (var i = 0; i < this.array.length; i++) fn(this.array[i], i);\n  }\n};\nfunction findRule(rules, node, options) {\n  for (var i = 0; i < rules.length; i++) {\n    var rule = rules[i];\n    if (filterValue(rule, node, options)) return rule;\n  }\n  return undefined;\n}\nfunction filterValue(rule, node, options) {\n  var filter = rule.filter;\n  if (typeof filter === 'string') {\n    if (filter === node.nodeName.toLowerCase()) return true;\n  } else if (Array.isArray(filter)) {\n    if (filter.indexOf(node.nodeName.toLowerCase()) > -1) return true;\n  } else if (typeof filter === 'function') {\n    if (filter.call(rule, node, options)) return true;\n  } else {\n    throw new TypeError('`filter` needs to be a string, array, or function');\n  }\n}\n\n/**\n * The collapseWhitespace function is adapted from collapse-whitespace\n * by Luc Thevenard.\n *\n * The MIT License (MIT)\n *\n * Copyright (c) 2014 Luc Thevenard <lucthevenard@gmail.com>\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n */\n\n/**\n * collapseWhitespace(options) removes extraneous whitespace from an the given element.\n *\n * @param {Object} options\n */\nfunction collapseWhitespace(options) {\n  var element = options.element;\n  var isBlock = options.isBlock;\n  var isVoid = options.isVoid;\n  var isPre = options.isPre || function (node) {\n    return node.nodeName === 'PRE';\n  };\n  if (!element.firstChild || isPre(element)) return;\n  var prevText = null;\n  var keepLeadingWs = false;\n  var prev = null;\n  var node = next(prev, element, isPre);\n  while (node !== element) {\n    if (node.nodeType === 3 || node.nodeType === 4) {\n      // Node.TEXT_NODE or Node.CDATA_SECTION_NODE\n      var text = node.data.replace(/[ \\r\\n\\t]+/g, ' ');\n      if ((!prevText || / $/.test(prevText.data)) && !keepLeadingWs && text[0] === ' ') {\n        text = text.substr(1);\n      }\n\n      // `text` might be empty at this point.\n      if (!text) {\n        node = remove(node);\n        continue;\n      }\n      node.data = text;\n      prevText = node;\n    } else if (node.nodeType === 1) {\n      // Node.ELEMENT_NODE\n      if (isBlock(node) || node.nodeName === 'BR') {\n        if (prevText) {\n          prevText.data = prevText.data.replace(/ $/, '');\n        }\n        prevText = null;\n        keepLeadingWs = false;\n      } else if (isVoid(node) || isPre(node)) {\n        // Avoid trimming space around non-block, non-BR void elements and inline PRE.\n        prevText = null;\n        keepLeadingWs = true;\n      } else if (prevText) {\n        // Drop protection if set previously.\n        keepLeadingWs = false;\n      }\n    } else {\n      node = remove(node);\n      continue;\n    }\n    var nextNode = next(prev, node, isPre);\n    prev = node;\n    node = nextNode;\n  }\n  if (prevText) {\n    prevText.data = prevText.data.replace(/ $/, '');\n    if (!prevText.data) {\n      remove(prevText);\n    }\n  }\n}\n\n/**\n * remove(node) removes the given node from the DOM and returns the\n * next node in the sequence.\n *\n * @param {Node} node\n * @return {Node} node\n */\nfunction remove(node) {\n  var next = node.nextSibling || node.parentNode;\n  node.parentNode.removeChild(node);\n  return next;\n}\n\n/**\n * next(prev, current, isPre) returns the next node in the sequence, given the\n * current and previous nodes.\n *\n * @param {Node} prev\n * @param {Node} current\n * @param {Function} isPre\n * @return {Node}\n */\nfunction next(prev, current, isPre) {\n  if (prev && prev.parentNode === current || isPre(current)) {\n    return current.nextSibling || current.parentNode;\n  }\n  return current.firstChild || current.nextSibling || current.parentNode;\n}\n\n/*\n * Set up window for Node.js\n */\n\nvar root = typeof window !== 'undefined' ? window : {};\n\n/*\n * Parsing HTML strings\n */\n\nfunction canParseHTMLNatively() {\n  var Parser = root.DOMParser;\n  var canParse = false;\n\n  // Adapted from https://gist.github.com/1129031\n  // Firefox/Opera/IE throw errors on unsupported types\n  try {\n    // WebKit returns null on unsupported types\n    if (new Parser().parseFromString('', 'text/html')) {\n      canParse = true;\n    }\n  } catch (e) {}\n  return canParse;\n}\nfunction createHTMLParser() {\n  var Parser = function () {};\n  {\n    if (shouldUseActiveX()) {\n      Parser.prototype.parseFromString = function (string) {\n        var doc = new window.ActiveXObject('htmlfile');\n        doc.designMode = 'on'; // disable on-page scripts\n        doc.open();\n        doc.write(string);\n        doc.close();\n        return doc;\n      };\n    } else {\n      Parser.prototype.parseFromString = function (string) {\n        var doc = document.implementation.createHTMLDocument('');\n        doc.open();\n        doc.write(string);\n        doc.close();\n        return doc;\n      };\n    }\n  }\n  return Parser;\n}\nfunction shouldUseActiveX() {\n  var useActiveX = false;\n  try {\n    document.implementation.createHTMLDocument('').open();\n  } catch (e) {\n    if (root.ActiveXObject) useActiveX = true;\n  }\n  return useActiveX;\n}\nvar HTMLParser = canParseHTMLNatively() ? root.DOMParser : createHTMLParser();\n\nfunction RootNode(input, options) {\n  var root;\n  if (typeof input === 'string') {\n    var doc = htmlParser().parseFromString(\n    // DOM parsers arrange elements in the <head> and <body>.\n    // Wrapping in a custom element ensures elements are reliably arranged in\n    // a single element.\n    '<x-turndown id=\"turndown-root\">' + input + '</x-turndown>', 'text/html');\n    root = doc.getElementById('turndown-root');\n  } else {\n    root = input.cloneNode(true);\n  }\n  collapseWhitespace({\n    element: root,\n    isBlock: isBlock,\n    isVoid: isVoid,\n    isPre: options.preformattedCode ? isPreOrCode : null\n  });\n  return root;\n}\nvar _htmlParser;\nfunction htmlParser() {\n  _htmlParser = _htmlParser || new HTMLParser();\n  return _htmlParser;\n}\nfunction isPreOrCode(node) {\n  return node.nodeName === 'PRE' || node.nodeName === 'CODE';\n}\n\nfunction Node(node, options) {\n  node.isBlock = isBlock(node);\n  node.isCode = node.nodeName === 'CODE' || node.parentNode.isCode;\n  node.isBlank = isBlank(node);\n  node.flankingWhitespace = flankingWhitespace(node, options);\n  return node;\n}\nfunction isBlank(node) {\n  return !isVoid(node) && !isMeaningfulWhenBlank(node) && /^\\s*$/i.test(node.textContent) && !hasVoid(node) && !hasMeaningfulWhenBlank(node);\n}\nfunction flankingWhitespace(node, options) {\n  if (node.isBlock || options.preformattedCode && node.isCode) {\n    return {\n      leading: '',\n      trailing: ''\n    };\n  }\n  var edges = edgeWhitespace(node.textContent);\n\n  // abandon leading ASCII WS if left-flanked by ASCII WS\n  if (edges.leadingAscii && isFlankedByWhitespace('left', node, options)) {\n    edges.leading = edges.leadingNonAscii;\n  }\n\n  // abandon trailing ASCII WS if right-flanked by ASCII WS\n  if (edges.trailingAscii && isFlankedByWhitespace('right', node, options)) {\n    edges.trailing = edges.trailingNonAscii;\n  }\n  return {\n    leading: edges.leading,\n    trailing: edges.trailing\n  };\n}\nfunction edgeWhitespace(string) {\n  var m = string.match(/^(([ \\t\\r\\n]*)(\\s*))(?:(?=\\S)[\\s\\S]*\\S)?((\\s*?)([ \\t\\r\\n]*))$/);\n  return {\n    leading: m[1],\n    // whole string for whitespace-only strings\n    leadingAscii: m[2],\n    leadingNonAscii: m[3],\n    trailing: m[4],\n    // empty for whitespace-only strings\n    trailingNonAscii: m[5],\n    trailingAscii: m[6]\n  };\n}\nfunction isFlankedByWhitespace(side, node, options) {\n  var sibling;\n  var regExp;\n  var isFlanked;\n  if (side === 'left') {\n    sibling = node.previousSibling;\n    regExp = / $/;\n  } else {\n    sibling = node.nextSibling;\n    regExp = /^ /;\n  }\n  if (sibling) {\n    if (sibling.nodeType === 3) {\n      isFlanked = regExp.test(sibling.nodeValue);\n    } else if (options.preformattedCode && sibling.nodeName === 'CODE') {\n      isFlanked = false;\n    } else if (sibling.nodeType === 1 && !isBlock(sibling)) {\n      isFlanked = regExp.test(sibling.textContent);\n    }\n  }\n  return isFlanked;\n}\n\nvar reduce = Array.prototype.reduce;\nfunction TurndownService(options) {\n  if (!(this instanceof TurndownService)) return new TurndownService(options);\n  var defaults = {\n    rules: rules,\n    headingStyle: 'setext',\n    hr: '* * *',\n    bulletListMarker: '*',\n    codeBlockStyle: 'indented',\n    fence: '```',\n    emDelimiter: '_',\n    strongDelimiter: '**',\n    linkStyle: 'inlined',\n    linkReferenceStyle: 'full',\n    br: '  ',\n    preformattedCode: false,\n    blankReplacement: function (content, node) {\n      return node.isBlock ? '\\n\\n' : '';\n    },\n    keepReplacement: function (content, node) {\n      return node.isBlock ? '\\n\\n' + node.outerHTML + '\\n\\n' : node.outerHTML;\n    },\n    defaultReplacement: function (content, node) {\n      return node.isBlock ? '\\n\\n' + content + '\\n\\n' : content;\n    }\n  };\n  this.options = extend({}, defaults, options);\n  this.rules = new Rules(this.options);\n}\nTurndownService.prototype = {\n  /**\n   * The entry point for converting a string or DOM node to Markdown\n   * @public\n   * @param {String|HTMLElement} input The string or DOM node to convert\n   * @returns A Markdown representation of the input\n   * @type String\n   */\n\n  turndown: function (input) {\n    if (!canConvert(input)) {\n      throw new TypeError(input + ' is not a string, or an element/document/fragment node.');\n    }\n    if (input === '') return '';\n    var output = process.call(this, new RootNode(input, this.options));\n    return postProcess.call(this, output);\n  },\n  /**\n   * Add one or more plugins\n   * @public\n   * @param {Function|Array} plugin The plugin or array of plugins to add\n   * @returns The Turndown instance for chaining\n   * @type Object\n   */\n\n  use: function (plugin) {\n    if (Array.isArray(plugin)) {\n      for (var i = 0; i < plugin.length; i++) this.use(plugin[i]);\n    } else if (typeof plugin === 'function') {\n      plugin(this);\n    } else {\n      throw new TypeError('plugin must be a Function or an Array of Functions');\n    }\n    return this;\n  },\n  /**\n   * Adds a rule\n   * @public\n   * @param {String} key The unique key of the rule\n   * @param {Object} rule The rule\n   * @returns The Turndown instance for chaining\n   * @type Object\n   */\n\n  addRule: function (key, rule) {\n    this.rules.add(key, rule);\n    return this;\n  },\n  /**\n   * Keep a node (as HTML) that matches the filter\n   * @public\n   * @param {String|Array|Function} filter The unique key of the rule\n   * @returns The Turndown instance for chaining\n   * @type Object\n   */\n\n  keep: function (filter) {\n    this.rules.keep(filter);\n    return this;\n  },\n  /**\n   * Remove a node that matches the filter\n   * @public\n   * @param {String|Array|Function} filter The unique key of the rule\n   * @returns The Turndown instance for chaining\n   * @type Object\n   */\n\n  remove: function (filter) {\n    this.rules.remove(filter);\n    return this;\n  },\n  /**\n   * Escapes Markdown syntax\n   * @public\n   * @param {String} string The string to escape\n   * @returns A string with Markdown syntax escaped\n   * @type String\n   */\n\n  escape: function (string) {\n    return escapeMarkdown(string);\n  }\n};\n\n/**\n * Reduces a DOM node down to its Markdown string equivalent\n * @private\n * @param {HTMLElement} parentNode The node to convert\n * @returns Accumulator with Markdown representation parts of the node\n * @type Array\n */\n\nfunction process(parentNode) {\n  var self = this;\n  return reduce.call(parentNode.childNodes, function (output, node) {\n    node = new Node(node, self.options);\n    var replacement = '';\n    if (node.nodeType === 3) {\n      replacement = node.isCode ? node.nodeValue : self.escape(node.nodeValue);\n    } else if (node.nodeType === 1) {\n      replacement = replacementForNode.call(self, node);\n    }\n    join(output, replacement);\n    return output;\n  }, []);\n}\n\n/**\n * Appends strings as each rule requires and trims the output\n * @private\n * @param {Array} output The conversion output accumulator\n * @returns A trimmed version of the ouput\n * @type String\n */\n\nfunction postProcess(output) {\n  var self = this;\n  this.rules.forEach(function (rule) {\n    if (typeof rule.append === 'function') {\n      join(output, rule.append(self.options));\n    }\n  });\n  return output.join('').replace(/^[\\t\\r\\n]+/, '').replace(/[\\t\\r\\n\\s]+$/, '');\n}\n\n/**\n * Converts an element node to its Markdown equivalent\n * @private\n * @param {HTMLElement} node The node to convert\n * @returns A Markdown representation of the node\n * @type String\n */\n\nfunction replacementForNode(node) {\n  var rule = this.rules.forNode(node);\n  var content = process.call(this, node).join('');\n  var whitespace = node.flankingWhitespace;\n  if (whitespace.leading || whitespace.trailing) content = content.trim();\n  return whitespace.leading + rule.replacement(content, node, this.options) + whitespace.trailing;\n}\n\n/**\n * Joins replacement with the current output accumulator using the appropriate number of new lines\n * (makes sure the only trailing whitespace will be in the last array element)\n * @private\n * @param {String} output The current conversion output accumulator\n * @param {String} replacement The string to append to the output\n */\n\nfunction join(output, replacement) {\n  var tail = output.pop() || '';\n  var s1 = trimTrailingNewlines(tail);\n  var s2 = trimLeadingNewlines(replacement);\n  var nls = Math.max(tail.length - s1.length, replacement.length - s2.length);\n  var separator = '\\n\\n'.substring(0, nls);\n  if (s1) output.push(s1);\n  if (separator) output.push(separator);\n  if (s2) output.push(s2);\n}\n\n/**\n * Determines whether an input can be converted\n * @private\n * @param {String|HTMLElement} input Describe this parameter\n * @returns Describe what it returns\n * @type String|Object|Array|Boolean|Number\n */\n\nfunction canConvert(input) {\n  return input != null && (typeof input === 'string' || input.nodeType && (input.nodeType === 1 || input.nodeType === 9 || input.nodeType === 11));\n}\n\nexport { TurndownService as default };\n", "var highlightRegExp = /highlight-(?:text|source)-([a-z0-9]+)/;\n\nfunction highlightedCodeBlock (turndownService) {\n  turndownService.addRule('highlightedCodeBlock', {\n    filter: function (node) {\n      var firstChild = node.firstChild;\n      return (\n        node.nodeName === 'DIV' &&\n        highlightRegExp.test(node.className) &&\n        firstChild &&\n        firstChild.nodeName === 'PRE'\n      )\n    },\n    replacement: function (content, node, options) {\n      var className = node.className || '';\n      var language = (className.match(highlightRegExp) || [null, ''])[1];\n\n      return (\n        '\\n\\n' + options.fence + language + '\\n' +\n        node.firstChild.textContent +\n        '\\n' + options.fence + '\\n\\n'\n      )\n    }\n  });\n}\n\nfunction strikethrough (turndownService) {\n  turndownService.addRule('strikethrough', {\n    filter: ['del', 's', 'strike'],\n    replacement: function (content) {\n      return '~' + content + '~'\n    }\n  });\n}\n\nvar indexOf = Array.prototype.indexOf;\nvar every = Array.prototype.every;\nvar rules = {};\n\nrules.tableCell = {\n  filter: ['th', 'td'],\n  replacement: function (content, node) {\n    return cell(content, node)\n  }\n};\n\nrules.tableRow = {\n  filter: 'tr',\n  replacement: function (content, node) {\n    var borderCells = '';\n    var alignMap = { left: ':--', right: '--:', center: ':-:' };\n\n    if (isHeadingRow(node)) {\n      for (var i = 0; i < node.childNodes.length; i++) {\n        var border = '---';\n        var align = (\n          node.childNodes[i].getAttribute('align') || ''\n        ).toLowerCase();\n\n        if (align) border = alignMap[align] || border;\n\n        borderCells += cell(border, node.childNodes[i]);\n      }\n    }\n    return '\\n' + content + (borderCells ? '\\n' + borderCells : '')\n  }\n};\n\nrules.table = {\n  // Only convert tables with a heading row.\n  // Tables with no heading row are kept using `keep` (see below).\n  filter: function (node) {\n    return node.nodeName === 'TABLE' && isHeadingRow(node.rows[0])\n  },\n\n  replacement: function (content) {\n    // Ensure there are no blank lines\n    content = content.replace('\\n\\n', '\\n');\n    return '\\n\\n' + content + '\\n\\n'\n  }\n};\n\nrules.tableSection = {\n  filter: ['thead', 'tbody', 'tfoot'],\n  replacement: function (content) {\n    return content\n  }\n};\n\n// A tr is a heading row if:\n// - the parent is a THEAD\n// - or if its the first child of the TABLE or the first TBODY (possibly\n//   following a blank THEAD)\n// - and every cell is a TH\nfunction isHeadingRow (tr) {\n  var parentNode = tr.parentNode;\n  return (\n    parentNode.nodeName === 'THEAD' ||\n    (\n      parentNode.firstChild === tr &&\n      (parentNode.nodeName === 'TABLE' || isFirstTbody(parentNode)) &&\n      every.call(tr.childNodes, function (n) { return n.nodeName === 'TH' })\n    )\n  )\n}\n\nfunction isFirstTbody (element) {\n  var previousSibling = element.previousSibling;\n  return (\n    element.nodeName === 'TBODY' && (\n      !previousSibling ||\n      (\n        previousSibling.nodeName === 'THEAD' &&\n        /^\\s*$/i.test(previousSibling.textContent)\n      )\n    )\n  )\n}\n\nfunction cell (content, node) {\n  var index = indexOf.call(node.parentNode.childNodes, node);\n  var prefix = ' ';\n  if (index === 0) prefix = '| ';\n  return prefix + content + ' |'\n}\n\nfunction tables (turndownService) {\n  turndownService.keep(function (node) {\n    return node.nodeName === 'TABLE' && !isHeadingRow(node.rows[0])\n  });\n  for (var key in rules) turndownService.addRule(key, rules[key]);\n}\n\nfunction taskListItems (turndownService) {\n  turndownService.addRule('taskListItems', {\n    filter: function (node) {\n      return node.type === 'checkbox' && node.parentNode.nodeName === 'LI'\n    },\n    replacement: function (content, node) {\n      return (node.checked ? '[x]' : '[ ]') + ' '\n    }\n  });\n}\n\nfunction gfm (turndownService) {\n  turndownService.use([\n    highlightedCodeBlock,\n    strikethrough,\n    tables,\n    taskListItems\n  ]);\n}\n\nexport { gfm, highlightedCodeBlock, strikethrough, tables, taskListItems };\n", "// SPDX-License-Identifier: AGPL-3.0-or-later\nimport { Editor, Mark, Node, mergeAttributes } from \"@tiptap/core\";\nimport StarterKit from \"@tiptap/starter-kit\";\nimport Image from \"@tiptap/extension-image\";\nimport { Table, TableRow, TableHeader, TableCell } from \"@tiptap/extension-table\";\nimport TaskList from \"@tiptap/extension-task-list\";\nimport TaskItem from \"@tiptap/extension-task-item\";\nimport TextAlign from \"@tiptap/extension-text-align\";\nimport TurndownService from \"turndown\";\nimport { gfm } from \"turndown-plugin-gfm\";\nimport { chartFigure, validateChart } from \"./charts.mjs\";\nimport { safeImageURL, safeLink } from \"./media.mjs\";\nimport { sanitizeHTML } from \"./render.mjs\";\n\nconst markdown = new TurndownService({ headingStyle: \"atx\", codeBlockStyle: \"fenced\", bulletListMarker: \"-\", emDelimiter: \"*\" });\nmarkdown.use(gfm);\nmarkdown.addRule(\"chart\", { filter: (node) => node.nodeName === \"DIV\" && node.hasAttribute(\"data-chart\"), replacement: (_, node) => {\n  try { return \"\\n\\n```chart\\n\" + JSON.stringify(validateChart(JSON.parse(node.getAttribute(\"data-chart\"))), null, 2) + \"\\n```\\n\\n\"; } catch { return \"\\n\\n[Invalid chart]\\n\\n\"; }\n} });\nmarkdown.addRule(\"underline\", { filter: \"u\", replacement: (content) => \"<u>\" + content + \"</u>\" });\nmarkdown.addRule(\"task\", { filter: (node) => node.nodeName === \"LI\" && node.getAttribute(\"data-type\") === \"taskItem\", replacement: (content, node) => \"\\n- [\" + (node.getAttribute(\"data-checked\") === \"true\" ? \"x\" : \" \") + \"] \" + content.trim() + \"\\n\" });\nmarkdown.addRule(\"task-label\", { filter: (node) => node.nodeName === \"LABEL\" && node.parentElement?.getAttribute(\"data-type\") === \"taskItem\", replacement: () => \"\" });\n// Keep complex table cells intact; a Markdown pipe table cannot represent a\n// chart or a nested block. Simple tables use ordinary GFM table syntax.\nmarkdown.addRule(\"complex-table\", { filter: (node) => node.nodeName === \"TABLE\" && !!node.querySelector(\"[data-chart],img,ul,ol,table\"), replacement: (_, node) => \"\\n\\n\" + node.outerHTML + \"\\n\\n\" });\nexport const toMarkdown = (html) => markdown.turndown(sanitizeHTML(html));\n// Conversion only; the sharing module supplies already-sanitized HTML with\n// local image references. Passing it through the rendering sanitizer again\n// would intentionally remove those relative URLs.\nexport const serializeShareHTML = (html) => markdown.turndown(html);\nconst Comment = Mark.create({\n  name: \"comment\", inclusive: false,\n  addAttributes() { return { id: { default: null, parseHTML: (el) => el.getAttribute(\"data-comment-id\"), renderHTML: (attrs) => ({ \"data-comment-id\": attrs.id }) } }; },\n  parseHTML() { return [{ tag: \"mark[data-comment-id]\" }]; },\n  renderHTML({ HTMLAttributes }) { return [\"mark\", mergeAttributes(HTMLAttributes, { class: \"comment-anchor\" }), 0]; },\n});\nconst Chart = Node.create({\n  name: \"chart\", group: \"block\", atom: true, draggable: true,\n  addAttributes() { return { config: { default: null, parseHTML: (el) => { try { return validateChart(JSON.parse(el.getAttribute(\"data-chart\"))); } catch { return null; } }, renderHTML: () => ({}) } }; },\n  parseHTML() { return [{ tag: \"div[data-chart]\" }]; },\n  renderHTML({ node }) { return [\"div\", { \"data-chart\": JSON.stringify(node.attrs.config) }, [\"p\", {}, \"Chart: \" + (node.attrs.config?.title || \"Untitled\")]]; },\n  addNodeView() { return ({ node }) => {\n    const dom = document.createElement(\"div\"); dom.className = \"chart-node\"; dom.contentEditable = \"false\";\n    try { dom.append(chartFigure(node.attrs.config)); } catch { dom.textContent = \"Click this chart to edit its data.\"; }\n    const hint = document.createElement(\"span\"); hint.className = \"chart-edit-hint\"; hint.textContent = \"Click for chart options\"; dom.append(hint);\n    return { dom };\n  }; },\n});\nconst LocalImage = Image.extend({\n  parseHTML() { return [{ tag: \"img[src]\", getAttrs: (el) => safeImageURL(el.getAttribute(\"src\")) ? { src: el.getAttribute(\"src\"), alt: el.getAttribute(\"alt\") || \"\" } : false }]; },\n});\nexport function createEditor({ element, content, onUpdate, onSelection, onLink, onComment, onMapping }) {\n  const editor = new Editor({\n    element, content,\n    extensions: [StarterKit.configure({ link: { openOnClick: false, autolink: true, linkOnPaste: true, isAllowedUri: safeLink, protocols: [\"https\", \"http\", \"mailto\"] }, heading: { levels: [1, 2, 3] } }), LocalImage.configure({ allowBase64: true }), Table.configure({ resizable: false }), TableRow, TableHeader, TableCell, TaskList, TaskItem.configure({ nested: true }), TextAlign.configure({ types: [\"heading\", \"paragraph\"] }), Comment, Chart],\n    editorProps: {\n      attributes: { role: \"textbox\", \"aria-label\": \"Your document\", \"aria-multiline\": \"true\", \"aria-describedby\": \"element-help\", spellcheck: \"true\", class: \"rich-writing prose\", \"data-placeholder\": \"Start anywhere. A thought, a story, a sentence that won\u2019t leave you.\" },\n      transformPastedHTML: sanitizeHTML,\n      handlePaste(view, event) {\n        const text = event.clipboardData?.getData(\"text/plain\")?.trim();\n        if (!view.state.selection.empty && safeLink(text)) { editor.chain().setLink({ href: text }).run(); return true; }\n        return false;\n      },\n      handleKeyDown(view, event) {\n        if ((event.metaKey || event.ctrlKey) && event.key.toLowerCase() === \"k\") { event.preventDefault(); onLink(); return true; }\n        if ((event.metaKey || event.ctrlKey) && event.altKey && event.key.toLowerCase() === \"m\") { event.preventDefault(); onComment(); return true; }\n        return false;\n      },\n    },\n    onUpdate: ({ editor }) => onUpdate(editor),\n    onSelectionUpdate: ({ editor }) => onSelection(editor),\n    onTransaction: ({ editor, transaction }) => { onMapping?.(transaction.mapping); onSelection(editor); },\n  });\n  return editor;\n}\n"],
  "mappings": "AAC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M,eAAe,EAAGT,EAAU,EAAU,IAChI,EACT,CACF,EACA,SAAU,CAAC,CAAE,OAAAE,CAAO,IAAML,EAASK,CAAM,EACzC,kBAAmB,CAAC,CAAE,OAAAA,CAAO,IAAMJ,EAAYI,CAAM,EACrD,cAAe,CAAC,CAAE,OAAAA,EAAQ,YAAAS,CAAY,IAAM,CAAEV,IAAYU,EAAY,OAAO,EAAGb,EAAYI,CAAM,CAAG,CACvG,CAAC,EACD,OAAOA,CACT",
  "names": ["__defProp", "__exportAll", "all", "no_symbols", "target", "name", "OrderedMap", "content", "key", "i", "found", "value", "newKey", "self", "place", "without", "f", "map", "result", "prop", "dist_default", "findDiffStart", "a", "b", "pos", "i", "childA", "childB", "tA", "tB", "j", "surrogateHigh", "surrogateLow", "inner", "findDiffEnd", "posA", "posB", "iA", "iB", "size", "ch", "Fragment", "_Fragment", "content", "from", "to", "f", "nodeStart", "parent", "child", "end", "start", "blockSeparator", "leafText", "text", "first", "node", "nodeText", "other", "last", "result", "index", "current", "copy", "found", "p", "otherPos", "retIndex", "curPos", "cur", "n", "schema", "value", "array", "joined", "nodes", "offset", "compareDeep", "Mark", "_Mark", "type", "attrs", "set", "placed", "obj", "_", "json", "marks", "ReplaceError", "Slice", "_Slice", "openStart", "openEnd", "fragment", "insertInto", "removeRange", "openIsolating", "indexTo", "offsetTo", "dist", "insert", "replace", "$from", "$to", "slice", "replaceOuter", "depth", "close", "prepareSliceForReplace", "replaceThreeWay", "replaceTwoWay", "checkJoin", "main", "sub", "joinable", "$before", "$after", "addNode", "target", "addRange", "$start", "$end", "startIndex", "endIndex", "$along", "extra", "ResolvedPos", "_ResolvedPos", "path", "parentOffset", "val", "dOff", "tmp", "after", "next", "pred", "d", "NodeRange", "str", "doc", "rem", "cache", "resolveCache", "elt", "ResolveCache", "resolveCacheSize", "emptyAttrs", "Node", "_Node", "startPos", "includeParents", "name", "wrapMarks", "match", "replacement", "one", "two", "checkAttrs", "mark", "m", "v8InternHack", "stack", "s", "TextNode", "_TextNode", "base", "values", "attr", "ContentMatch", "_ContentMatch", "validEnd", "string", "nodeTypes", "stream", "TokenStream", "expr", "parseExpr", "dfa", "nfa", "checkForDeadEnds", "frag", "toEnd", "seen", "search", "types", "finished", "tp", "computed", "active", "scan", "out", "tok", "exprs", "parseExprSeq", "parseExprSubscript", "parseExprAtom", "parseExprRange", "parseNum", "min", "max", "resolveName", "typeName", "connect", "compile", "edge", "term", "edges", "loop", "cmp", "nullFrom", "labeled", "explore", "states", "state", "work", "dead", "defaultAttrs", "defaults", "attrName", "computeAttrs", "built", "given", "initAttrs", "Attribute", "NodeType", "_NodeType", "spec", "group", "before", "matched", "markType", "topType", "validateType", "options", "MarkType", "_MarkType", "rank", "Schema", "instanceSpec", "prop", "dist_default", "contentExprCache", "contentExpr", "markExpr", "gatherMarks", "excl", "ok", "isTagRule", "rule", "isStyleRule", "DOMParser", "_DOMParser", "rules", "matchedStyles", "r", "dom", "context", "ParseContext", "matches", "style", "priority", "blockTags", "ignoreTags", "listTags", "OPT_PRESERVE_WS", "OPT_PRESERVE_WS_FULL", "OPT_OPEN_LEFT", "wsOptionsFor", "preserveWhitespace", "NodeContext", "solid", "fill", "wrap", "parser", "isOpen", "topNode", "topContext", "topOptions", "top", "preserveWS", "lines", "nodeBefore", "domNodeBefore", "matchAfter", "outerWS", "ruleID", "normalizeList", "sync", "oldNeedsBlock", "innerMarks", "styles", "continueAfter", "nodeType", "startIn", "contentDOM", "cautious", "route", "penalty", "cx", "block", "nodeMarks", "markMayApply", "applyMarks", "textNode", "parts", "option", "useRoot", "minDepth", "part", "$context", "deflt", "prevItem", "selector", "DOMSerializer", "_DOMSerializer", "keep", "rendered", "add", "markDOM", "renderSpec", "inline", "toDOM", "structure", "xmlNS", "blockArraysIn", "gatherToDOM", "suspiciousAttributeCache", "suspiciousAttributes", "suspiciousAttributesInner", "tagName", "suspicious", "space", "innerContent", "lower16", "factor16", "makeRecover", "index", "offset", "recoverIndex", "value", "recoverOffset", "DEL_BEFORE", "DEL_AFTER", "DEL_ACROSS", "DEL_SIDE", "MapResult", "pos", "delInfo", "recover", "StepMap", "_StepMap", "ranges", "inverted", "diff", "assoc", "simple", "oldIndex", "newIndex", "i", "start", "oldSize", "newSize", "end", "side", "result", "del", "f", "oldStart", "newStart", "n", "Mapping", "_Mapping", "maps", "mirror", "from", "to", "map", "mirrors", "mapping", "startSize", "mirr", "m", "totalSize", "inverse", "corr", "stepsByID", "Step", "other", "schema", "json", "type", "id", "stepClass", "StepResult", "_StepResult", "doc", "failed", "message", "slice", "e", "ReplaceError", "mapFragment", "fragment", "parent", "mapped", "child", "Fragment", "AddMarkStep", "_AddMarkStep", "mark", "oldSlice", "$from", "Slice", "node", "steps", "added", "Mark", "pushMarkStep", "RemoveMarkStep", "MarkSetStep", "_RemoveMarkStep", "cls", "target", "last", "_MarkSetStep", "step", "s", "AddNodeMarkStep", "_AddNodeMarkStep", "updated", "newSet", "RemoveNodeMarkStep", "_RemoveNodeMarkStep", "ReplaceStep", "_ReplaceStep", "structure", "contentBetween", "ReplaceAroundStep", "_ReplaceAroundStep", "gapFrom", "gapTo", "insert", "gap", "inserted", "dist", "depth", "next", "addMark", "tr", "marks", "removeMark", "matched", "toRemove", "MarkType", "set", "found", "style", "j", "clearIncompatible", "parentType", "match", "clearNewlines", "replSteps", "cur", "allowed", "newline", "fill", "canCut", "liftTarget", "range", "content", "contentBefore", "contentAfter", "endIndex", "lift", "$to", "gapStart", "gapEnd", "before", "openStart", "d", "splitting", "after", "openEnd", "findWrapping", "nodeType", "attrs", "innerRange", "around", "findWrappingOutside", "inner", "findWrappingInside", "withAttrs", "startIndex", "outer", "inside", "innerMatch", "wrap", "wrappers", "setBlockType", "mapFrom", "attrsHere", "canChangeType", "convertNewlines", "pre", "supportLinebreak", "replaceLinebreaks", "startM", "endM", "replaceNewlines", "$pos", "setNodeMarkup", "newNode", "canSplit", "typesAfter", "base", "innerType", "rest", "overrideChild", "baseType", "split", "typeAfter", "canJoin", "joinable", "canAppendWithSubstitutedLinebreaks", "a", "b", "linebreakReplacement", "joinPoint", "dir", "join", "$before", "beforeType", "$after", "$full", "insertPoint", "dropPoint", "pass", "bias", "attempt", "insertPos", "fits", "wrapping", "replaceStep", "fitsTrivially", "Fitter", "unplaced", "fit", "moveInline", "placedSize", "startDepth", "sliceDepth", "contentAt", "first", "frontierDepth", "inject", "maxOpen", "openAtEnd", "dropFromFragment", "taken", "add", "openEndCount", "matches", "closeNodeStart", "toEnd", "addToFragment", "top", "level", "contentAfterFits", "scan", "dropInner", "close", "count", "frag", "open", "invalidMarks", "definesContent", "ch", "replaceRange", "targetDepths", "coveredDepths", "preferredTarget", "spec", "preferredTargetIndex", "leftNodes", "preferredDepth", "leftNode", "def", "openDepth", "targetDepth", "expand", "closeFragment", "startSteps", "oldOpen", "newOpen", "replaceRangeWith", "point", "deleteRange", "shared", "isolated", "covered", "minDepth", "AttrStep", "_AttrStep", "attr", "name", "DocAttrStep", "_DocAttrStep", "TransformError", "err", "Transform", "_f", "_t", "fromB", "toB", "classesById", "Selection", "$anchor", "$head", "ranges", "SelectionRange", "i", "tr", "content", "Slice", "lastNode", "lastParent", "mapFrom", "$from", "$to", "mapping", "selectionToInsertionEnd", "node", "from", "to", "$pos", "dir", "textOnly", "inner", "TextSelection", "findSelectionIn", "depth", "found", "bias", "AllSelection", "doc", "json", "cls", "id", "selectionClass", "warnedAboutTextSelection", "checkTextSelection", "_TextSelection", "marks", "other", "TextBookmark", "anchor", "head", "dPos", "_TextBookmark", "NodeSelection", "_NodeSelection", "$end", "deleted", "pos", "Fragment", "NodeBookmark", "_NodeBookmark", "_AllSelection", "sel", "AllBookmark", "index", "text", "child", "startLen", "last", "step", "ReplaceStep", "ReplaceAroundStep", "map", "end", "_from", "_to", "_newFrom", "newTo", "UPDATED_SEL", "UPDATED_MARKS", "UPDATED_SCROLL", "Transaction", "Transform", "state", "selection", "Mark", "mark", "time", "slice", "inheritMarks", "schema", "key", "value", "_", "bind", "f", "self", "FieldDesc", "name", "desc", "baseFields", "config", "instance", "_marks", "_old", "prev", "Configuration", "plugins", "plugin", "EditorState", "_EditorState", "ignore", "rootTr", "trs", "newState", "seen", "haveNew", "n", "oldState", "j", "newInstance", "fields", "field", "$config", "pluginFields", "result", "m", "prop", "Node", "bindProps", "obj", "target", "val", "Plugin", "spec", "createKey", "keys", "PluginKey", "deleteSelection", "state", "dispatch", "atBlockStart", "view", "$cursor", "joinBackward", "$cut", "findCutBefore", "range", "target", "liftTarget", "before", "deleteBarrier", "textblockAt", "NodeSelection", "depth", "delStep", "replaceStep", "Slice", "tr", "Selection", "joinTextblockBackward", "joinTextblocksAround", "joinTextblockForward", "atBlockEnd", "findCutAfter", "beforeText", "beforePos", "child", "after", "afterText", "afterPos", "step", "ReplaceStep", "TextSelection", "node", "side", "only", "scan", "selectNodeBackward", "$head", "empty", "$pos", "i", "joinForward", "selectNodeForward", "parent", "joinUp", "sel", "nodeSel", "point", "canJoin", "joinPoint", "joinDown", "lift", "$from", "$to", "newlineInCode", "$anchor", "defaultBlockAt", "match", "type", "exitCode", "above", "pos", "createParagraphNear", "AllSelection", "liftEmptyBlock", "canSplit", "splitBlockAs", "splitNode", "mapFrom", "types", "splitDepth", "deflt", "atEnd", "atStart", "d", "splitType", "splitPos", "can", "mapping", "first", "$first", "splitBlock", "selectParentNode", "state", "dispatch", "$from", "to", "pos", "same", "NodeSelection", "selectAll", "AllSelection", "joinMaybeClear", "$pos", "before", "after", "index", "canJoin", "deleteBarrier", "$cut", "dir", "conn", "match", "isolated", "canDelAfter", "end", "wrap", "Fragment", "i", "tr", "ReplaceAroundStep", "Slice", "$joinAt", "selAfter", "Selection", "range", "target", "liftTarget", "textblockAt", "at", "afterText", "afterDepth", "selectTextblockSide", "side", "sel", "depth", "TextSelection", "selectTextblockStart", "selectTextblockEnd", "wrapIn", "nodeType", "attrs", "$to", "wrapping", "findWrapping", "setBlockType", "applicable", "from", "node", "chainCommands", "commands", "state", "dispatch", "view", "backspace", "deleteSelection", "joinBackward", "selectNodeBackward", "del", "joinForward", "selectNodeForward", "pcBaseKeymap", "newlineInCode", "createParagraphNear", "liftEmptyBlock", "splitBlock", "exitCode", "selectAll", "macBaseKeymap", "selectTextblockStart", "selectTextblockEnd", "key", "mac", "wrapInList", "listType", "attrs", "state", "dispatch", "$from", "$to", "range", "tr", "wrapRangeInList", "doJoin", "outerRange", "doc", "$insert", "NodeRange", "wrap", "findWrapping", "doWrapInList", "wrappers", "joinBefore", "content", "Fragment", "i", "ReplaceAroundStep", "Slice", "found", "splitDepth", "splitPos", "parent", "e", "first", "canSplit", "isItem", "itemType", "type", "NodeType", "liftListItem", "itemType", "state", "dispatch", "$from", "$to", "range", "node", "isItem", "liftToOuterList", "liftOutOfList", "tr", "end", "endOfList", "ReplaceAroundStep", "Slice", "Fragment", "NodeRange", "target", "liftTarget", "$after", "canJoin", "list", "pos", "i", "e", "$start", "item", "atStart", "atEnd", "parent", "indexBefore", "start", "sinkListItem", "startIndex", "nodeBefore", "nestedBefore", "inner", "slice", "before", "after", "domIndex", "node", "index", "parentNode", "parent", "reusedRange", "textRange", "from", "to", "range", "clearReusedRange", "isEquivalentPosition", "off", "targetNode", "targetOff", "scanFor", "atomElements", "dir", "_a", "nodeSize", "isElt", "hasNodeDesc", "child", "isText", "contains", "textNodeBefore", "offset", "textNodeAfter", "isOnEdge", "atStart", "atEnd", "dom", "isBlock", "desc", "cur", "selectionCollapsed", "domSel", "writeSelection", "sel", "keyEvent", "keyCode", "key", "event", "deepActiveElement", "doc", "elt", "caretFromPoint", "x", "y", "pos", "nav", "agent", "gecko", "_chrome", "chrome", "chrome_version", "safari", "ios", "mac", "windows", "android", "webkit", "webkit_version", "windowRect", "vp", "getSide", "value", "side", "clientRect", "rect", "scaleX", "scaleY", "rectNextTo", "singleRect", "next", "scrollRectIntoView", "view", "startDOM", "nonZero", "scrollThreshold", "scrollMargin", "atTop", "bounding", "moveX", "moveY", "startX", "startY", "dX", "dY", "storeScrollPos", "refDOM", "refTop", "localRect", "scrollStack", "stack", "resetScrollPos", "newRefTop", "restoreScrollStack", "dTop", "i", "top", "left", "preventScrollSupported", "focusPreventScroll", "stored", "findOffsetInNode", "coords", "closest", "dxClosest", "coordsClosest", "rowBot", "rowTop", "firstBelow", "coordsBelow", "childIndex", "rects", "dx", "findOffsetInText", "len", "result", "inRect", "targetKludge", "posFromElement", "bias", "affinityFromCoords", "horizDist", "before", "after", "posFromCaret", "outsideBlock", "elementFromPoint", "element", "box", "startI", "j", "posAtCoords", "caret", "affinity", "p", "prev", "found", "target", "first", "BIDI", "coordsAtPos", "atom", "supportEmptyRange", "rectBefore", "rectAfter", "flattenV", "takeSide", "flattenH", "withFlushedState", "state", "f", "viewState", "active", "endOfTextblockVertical", "$pos", "nearest", "boxes", "maybeRTL", "endOfTextblockHorizontal", "$head", "oldBidiLevel", "parentDOM", "newNode", "newOff", "cachedState", "cachedDir", "cachedResult", "endOfTextblock", "ViewDesc", "children", "contentDOM", "widget", "mark", "outerDeco", "innerDeco", "nodeName", "addedNodes", "size", "domBefore", "domAfter", "rel", "n", "search", "onlyNodes", "nodeDOM", "scan", "end", "inner", "curPos", "BufferHackViewDesc", "WidgetViewDesc", "enter", "base", "fromOffset", "toOffset", "childBase", "mutation", "damage", "text", "self", "stop", "CompositionViewDesc", "textDOM", "mut", "MarkViewDesc", "_MarkViewDesc", "spec", "inline", "custom", "DOMSerializer", "copy", "nodes", "replaceNodes", "NodeViewDesc", "_NodeViewDesc", "descObj", "applyOuterDeco", "CustomNodeViewDesc", "TextViewDesc", "rule", "Fragment", "sameOuterDeco", "composition", "localComposition", "compositionInChild", "updater", "ViewTreeUpdater", "addBuffers", "atBufferPos", "iterDeco", "insideNode", "Mark", "compIndex", "renderDescs", "iosHacks", "TextSelection", "textNode", "textPos", "findTextInFragment", "topNode", "needsWrap", "oldDOM", "patchOuterDeco", "computeOuterDeco", "docViewDesc", "prevOuterDeco", "docView", "_TextViewDesc", "skip", "_view", "descs", "written", "childDOM", "rm", "OuterDecoLevel", "noDeco", "attrs", "name", "val", "outerDOM", "prevComputed", "curComputed", "curDOM", "deco", "patchAttributes", "prevList", "curList", "prop", "m", "a", "b", "lock", "preMatch", "start", "marks", "parentIndex", "keep", "depth", "maxKeep", "scanTo", "markDesc", "targetDesc", "e", "domNode", "nextDOM", "updated", "locked", "wrapper", "ch", "lastChild", "hack", "frag", "parentDesc", "curDesc", "descI", "fI", "matched", "matches", "outer", "compareSide", "onWidget", "onNode", "locals", "decoIndex", "restNode", "widgets", "cutAt", "d", "oldCSS", "childStart", "str", "replacement", "moveSelectionBlock", "$anchor", "$side", "$start", "Selection", "apply", "selectHorizontally", "mods", "$newHead", "NodeSelection", "nodePos", "isIgnorable", "skipIgnoredNodes", "skipIgnoredNodesBefore", "skipIgnoredNodesAfter", "moveNode", "moveOffset", "force", "isBlockNode", "setSelFocus", "findDirection", "mid", "block", "selectVertically", "$from", "$to", "beyond", "AllSelection", "stopNativeHorizontalDelete", "empty", "nextNode", "tr", "switchEditable", "safariDownArrowBug", "focusNode", "focusOffset", "getMods", "captureKeyDown", "code", "serializeForClipboard", "slice", "context", "content", "openStart", "openEnd", "serializer", "detachedDoc", "wrap", "firstChild", "wrappers", "wrapMap", "parseFromClipboard", "html", "plainText", "$context", "inCode", "asText", "Slice", "parsed", "schema", "readHTML", "restoreReplacedSpaces", "contextNode", "sliceData", "DOMParser", "inlineParents", "addContext", "closeSlice", "normalizeSiblings", "fragment", "match", "lastWrap", "inLast", "addToSibling", "closeRight", "wrapped", "withWrappers", "sibling", "fill", "closeRange", "_policy", "maybeWrapTrusted", "trustedTypes", "s", "metas", "firstTag", "style", "k", "array", "type", "StoredDOMSel", "_StoredDOMSel", "anchorNode", "anchorOffset", "DOMSelState", "safariShadowSelectionRange", "hasFocusAndSelection", "syncNodeSelection", "editorOwnsSelection", "innerViewDesc", "selectCursorWrapper", "selectionToDOM", "removeClassOnSelectionChange", "selection", "rangeToSelectionRange", "read", "currentAnchor", "selectionFromDOM", "origin", "nearestDesc", "inWidget", "head", "anchor", "min", "max", "selectionBetween", "hasSelection", "resetEditableFrom", "resetEditableTo", "brokenSelectBetweenUneditable", "temporarilyEditableNear", "anchorDOM", "headDOM", "setSelection", "resetEditable", "brKludge", "selRange", "mouse", "targetOffset", "ranges", "setEditable", "clearNodeSelection", "handlers", "editHandlers", "passiveHandlers", "InputState", "initInput", "handler", "eventBelongsToView", "leaveComposition", "runCustomHandler", "ensureListeners", "setSelectionOrigin", "destroyInput", "currentHandlers", "dispatchEvent", "dispatchKey", "input", "_event", "now", "inOrNearComposition", "deflt", "eventCoords", "isNear", "click", "dy", "runHandlerOnContext", "propName", "inside", "updateSelection", "selectClickedLeaf", "selectClickedNode", "selectedNode", "selectAt", "handleSingleClick", "selectNode", "handleDoubleClick", "handleTripleClick", "selectionForTripleClick", "selectNodes", "wordRE", "getWordAt", "sawNonWS", "lastBefore", "firstAfter", "segment", "nonSpaceBefore", "nonSpaceAfter", "spaceBefore", "spaceAfter", "selectNodeModifier", "endComposition", "MouseDown", "startPos", "startBase", "docBase", "targetPos", "targetSelected", "isInSelection", "clickedRange", "timeoutComposition", "selectionBeforeUneditable", "scheduleComposeEnd", "sync", "delay", "clearComposition", "findCompositionNode", "textBefore", "textAfter", "descAfter", "lastChanged", "descBefore", "restarting", "captureCopy", "brokenClipboardAPI", "cut", "data", "sliceSingleNode", "capturePaste", "plain", "doPaste", "preferPlain", "singleNode", "getText", "clipboardData", "uris", "Dragging", "move", "dragCopyModifier", "dragMoves", "test", "mouseDown", "draggedSlice", "dragging", "_", "handleDrop", "eventPos", "$mouse", "insertPos", "dropPoint", "isNode", "beforeInsert", "_from", "_to", "_newFrom", "newTo", "startSel", "curSel", "domChangeCount", "$cursor", "compareObjs", "FragmentCursor", "WidgetType", "_WidgetType", "toDOM", "noSpec", "mapping", "span", "oldOffset", "deleted", "Decoration", "other", "InlineType", "_InlineType", "NodeType", "_NodeType", "cursor", "_Decoration", "none", "DecorationSet", "_DecorationSet", "local", "decorations", "buildTree", "predicate", "childOff", "options", "newLocal", "mapped", "mapChildren", "byPos", "childNode", "childOffset", "baseOffset", "takeSpansForNode", "moveSpans", "withoutNulls", "removed", "low", "high", "dec", "localSet", "DecorationGroup", "removeOverlap", "_DecorationGroup", "members", "mappedDecos", "member", "sorted", "r", "oldChildren", "moved", "oldStart", "oldEnd", "newStart", "newEnd", "dSize", "mustRebuild", "fromLocal", "toLocal", "mapAndGatherRemainingDecorations", "built", "spans", "gather", "set", "hasNulls", "localStart", "subtree", "working", "insertAhead", "viewDecorations", "parseBetween", "from_", "to_", "find", "startDoc", "parser", "ruleFromNode", "added", "isInline", "readDOMChange", "selChange", "typeOver", "compositionID", "newSel", "$before", "shared", "parse", "compare", "preferredPos", "preferredSide", "change", "findDiff", "resolveSelection", "$fromA", "inlineChange", "looksLikeEnter", "looksLikeBlockJoin", "chFrom", "chTo", "mkTr", "markChange", "isMarkChange", "parsedSel", "curMarks", "prevMarks", "update", "old", "$newStart", "$newEnd", "skipClosingAndOpening", "$next", "newTextlines", "newLeaves", "fromEnd", "mayOpen", "lenA", "lenB", "endA", "endB", "adjust", "observeOptions", "DOMObserver", "mutations", "always", "take", "ancestors", "container", "readSel", "brs", "br", "blockParent", "checkCSS", "fixUpBadSafariComposition", "cssChecked", "cssCheckWarned", "nextCell", "EditorView", "place", "props", "InputState", "checkStateComponent", "getEditable", "updateCursorWrapper", "buildNodeViews", "docViewDesc", "computeDocDeco", "viewDecorations", "DOMObserver", "DOMSelState", "initInput", "prev", "name", "ensureListeners", "prevProps", "updated", "state", "_a", "redraw", "updateSel", "clearComposition", "pluginsChanged", "nodeViews", "changedNodeViews", "innerDeco", "outerDeco", "scroll", "updateDoc", "oldScrollPos", "storeScrollPos", "forceSelUpdate", "chrome", "selectionContextChanged", "chromeKludge", "findCompositionNode", "prevOuter", "resetScrollPos", "startDOM", "f", "NodeSelection", "target", "isElt", "scrollRectIntoView", "view", "prevState", "i", "plugin", "pluginView", "dragging", "sel", "found", "movedPos", "Dragging", "propName", "prop", "value", "plugins", "focusPreventScroll", "connected", "cached", "search", "coords", "posAtCoords", "pos", "side", "coordsAtPos", "desc", "node", "offset", "bias", "dir", "endOfTextblock", "html", "event", "doPaste", "text", "slice", "serializeForClipboard", "destroyInput", "clearReusedRange", "dispatchEvent", "tr", "dispatchTransaction", "attrs", "attr", "Decoration", "dom", "sel1", "sel2", "depth", "result", "add", "obj", "a", "b", "nA", "nB", "_", "base", "shift", "mac", "ie", "i", "code", "keyName", "event", "ignoreKey", "name", "mac", "windows", "normalizeKeyName", "name", "parts", "result", "alt", "ctrl", "shift", "meta", "i", "mod", "normalize", "map", "copy", "prop", "modifiers", "event", "keymap", "bindings", "Plugin", "keydownHandler", "view", "keyName", "baseName", "direct", "noShift", "base", "fromCode", "GOOD_LEAF_SIZE", "RopeSequence", "other", "Append", "from", "to", "i", "f", "result", "elt", "values", "Leaf", "prototypeAccessors", "start", "left", "right", "leftLen", "inner", "dist_default", "max_empty_items", "Branch", "_Branch", "items", "eventCount", "state", "preserveItems", "end", "remap", "mapFrom", "transform", "selection", "remaining", "addAfter", "addBefore", "item", "i", "Item", "step", "map", "histOptions", "newItems", "oldItems", "lastItem", "merged", "overflow", "DEPTH_OVERFLOW", "cutOffEvents", "from", "to", "maps", "Mapping", "mirrorPos", "array", "rebasedTransform", "rebasedCount", "rebasedItems", "start", "mapping", "newUntil", "iRebased", "pos", "newMaps", "branch", "count", "upto", "events", "newItem", "last", "dist_default", "n", "cutPoint", "_Item", "mirrorOffset", "other", "HistoryState", "done", "undone", "prevRanges", "prevTime", "prevComposition", "applyTransaction", "history", "tr", "options", "historyTr", "historyKey", "rebased", "closeHistoryKey", "appended", "mustPreserveItems", "rangesFor", "composition", "newGroup", "isAdjacentTo", "mapRanges", "adjacent", "result", "_from", "_to", "ranges", "selectionFromChanges", "_start", "AddMarkStep", "RemoveMarkStep", "Selection", "histTransaction", "redo", "pop", "added", "newHist", "cachedPreserveItems", "cachedPreserveItemsPlugins", "plugins", "closeHistory", "PluginKey", "config", "Plugin", "hist", "view", "e", "inputType", "command", "undo", "buildCommand", "scroll", "dispatch", "undoNoScroll", "redoNoScroll", "isHistoryTransaction", "tr", "historyKey", "createChainableState", "config", "state", "transaction", "selection", "doc", "storedMarks", "CommandManager", "props", "rawCommands", "editor", "view", "tr", "name", "command", "args", "callback", "startTr", "shouldDispatch", "callbacks", "hasStartTransaction", "run", "chain", "_target", "property", "dispatch", "target", "blur", "_window", "clearContent", "emitUpdate", "commands", "clearNodes", "ranges", "startMapsLength", "$from", "$to", "from", "to", "depthMapping", "maxSweeps", "_node", "pos", "sweep", "docBefore", "sweepMapsLength", "rangeMapping", "cachedMapsLength", "sweepMapping", "mappedFrom", "mappedTo", "node", "$mappedFrom", "$mappedTo", "nodeRange", "targetLiftDepth", "liftTarget", "defaultType", "fn", "createParagraphNear", "originalCreateParagraphNear", "cut", "originRange", "targetPos", "contentSlice", "newPos", "TextSelection", "deleteCurrentNode", "currentNode", "$pos", "depth", "getNodeType", "nameOrType", "schema", "deleteNode", "typeOrName", "type", "deleteRange", "range", "hasTextContent", "nodeSpec", "expandSelectionForSide", "side", "parentContent", "expandSelectionForInlineText", "deleteSelection", "marks", "mapFrom", "mapping", "enter", "exitCode", "originalExitCode", "isRegExp", "value", "objectIncludes", "object1", "object2", "options", "keys", "key", "findMarkInSet", "attributes", "item", "k", "isMarkInSet", "getMarkRange", "start", "mark", "firstMark", "startIndex", "startPos", "endIndex", "endPos", "getMarkType", "extendMarkRange", "newSelection", "first", "items", "i", "isTextSelection", "minMax", "min", "max", "resolveFocusPosition", "position", "selectionAtStart", "Selection", "selectionAtEnd", "minPos", "maxPos", "isAndroid", "isiOS", "isSafari", "focus", "delayedFocus", "isSameSelection", "forEach", "index", "insertContent", "removeWhitespaces", "children", "child", "elementFromString", "wrappedValue", "html", "isProseMirrorContent", "createNodeFromContent", "content", "isJSONContent", "isTextContent", "Fragment", "error", "hasInvalidContent", "invalidContent", "contentCheckSchema", "Schema", "e", "DOMParser", "parser", "isFragment", "nodeOrFragment", "selectionToInsertionEnd", "startLen", "bias", "last", "step", "ReplaceStep", "ReplaceAroundStep", "map", "end", "_from", "_to", "_newFrom", "newTo", "insertContentAt", "emitContentError", "parseOptions", "_options$errorOnInval", "isOnlyTextContent", "isOnlyBlockContent", "nodes", "parent", "newContent", "_node$text", "$fromNode", "fromSelectionAtStart", "hasContent", "defaultBlockAt", "match", "insertDefaultBlock", "attrs", "updateSelection", "validAttrKeys", "filteredAttrs", "parsed", "joinUp", "originalJoinUp", "joinDown", "originalJoinDown", "joinBackward", "originalJoinBackward", "joinForward", "originalJoinForward", "canJoinItemsAt", "before", "after", "joinItemBackward", "point", "joinPoint", "joinItemForward", "joinTextblockBackward", "originalCommand", "joinTextblockForward", "isMacOS", "normalizeKeyName", "parts", "result", "alt", "ctrl", "shift", "meta", "mod", "keyboardShortcut", "event", "capturedTransaction", "f", "newStep", "isNodeActive", "empty", "nodeRanges", "relativeFrom", "relativeTo", "selectionRange", "matchedNodeRanges", "sum", "lift", "originalLift", "liftEmptyBlock", "originalLiftEmptyBlock", "liftListItem", "originalLiftListItem", "newlineInCode", "originalNewlineInCode", "getSchemaTypeNameByName", "deleteProps", "obj", "propOrProps", "newObj", "prop", "resetAttributes", "nodeType", "markType", "schemaType", "canReset", "scrollIntoView", "selectAll", "AllSelection", "selectNodeBackward", "originalSelectNodeBackward", "selectNodeForward", "originalSelectNodeForward", "selectParentNode", "originalSelectParentNode", "selectTextblockEnd", "originalSelectTextblockEnd", "selectTextblockStart", "originalSelectTextblockStart", "createDocument", "setContent", "errorOnInvalidContent", "document", "getMarkAttributes", "markItem", "combineTransactionSteps", "oldDoc", "transactions", "transform", "Transform", "findChildrenInRange", "node", "range", "predicate", "nodesWithPos", "child", "pos", "findParentNodeClosestToPos", "$pos", "i", "findParentNode", "selection", "getExtensionField", "extension", "field", "context", "flattenExtensions", "extensions", "addExtensions", "getHTMLFromFragment", "fragment", "schema", "documentFragment", "DOMSerializer", "container", "getSchemaAttributes", "attributes", "attributesByType", "attribute", "typeAttributes", "_attributesByType$get", "type", "_type$spec$attrs", "name", "spec", "local", "_attributesByType$get2", "hasDefault", "nodeSchemaFields", "markSchemaFields", "structuralFields", "fields", "path", "expected", "value", "mergeType", "external", "key", "checkTypes", "kind", "mergeSchemaSpec", "nodes", "marks", "findDuplicates", "items", "filtered", "el", "index", "splitExtensions", "getAttributesFromExtensions", "extensionAttributes", "nodeExtensions", "markExtensions", "nodeAndMarkExtensions", "defaultAttribute", "nodeExtensionTypes", "ext", "markExtensionTypes", "allExtensionTypes", "addGlobalAttributes", "globalAttribute", "resolvedTypes", "addAttributes", "mergedAttr", "isFunction", "callOrReturn", "props", "isEmptyObject", "splitStyleDeclarations", "styles", "result", "current", "inSingleQuote", "inDoubleQuote", "parenDepth", "length", "char", "parseStyleEntries", "pairs", "declarations", "numDeclarations", "declaration", "firstColonIndex", "property", "mergeAttributes", "objects", "item", "mergedAttributes", "valueClasses", "existingClasses", "insertClasses", "valueClass", "styleMap", "val", "getRenderedAttributes", "nodeOrMark", "fromString", "injectExtensionAttributesToParseRule", "parseRule", "oldAttributes", "newAttributes", "cleanUpSchemaItem", "data", "buildAttributeSpec", "extensionAttribute", "_extensionAttribute$a", "_extensionAttribute$a2", "getSchemaSpecByResolvedExtensions", "editor", "allAttributes", "_nodeExtensions$find", "e", "extendNodeSchema", "parseHTML", "renderHTML", "renderText", "extendMarkSchema", "mark", "getSchemaByResolvedExtensions", "schemaSpec", "Schema", "duplicates", "sortExtensions", "a", "b", "priorityA", "priorityB", "resolveExtensions", "resolvedExtensions", "duplicatedNames", "getTextBetween", "startNode", "range", "options", "from", "to", "blockSeparator", "textSerializers", "text", "node", "pos", "parent", "index", "textSerializer", "_node$text", "getText", "getTextSerializersFromSchema", "schema", "name", "getNodeAttributes", "state", "typeOrName", "type", "getNodeType", "from", "to", "nodes", "node", "nodeItem", "getAttributes", "schemaType", "getSchemaTypeNameByName", "getMarkAttributes", "removeDuplicates", "array", "by", "seen", "item", "key", "simplifyChangedRanges", "changes", "uniqueChanges", "change", "index", "_", "i", "otherChange", "getChangedRanges", "transform", "mapping", "steps", "inverted", "stepMap", "ranges", "rest", "newStart", "newEnd", "oldStart", "oldEnd", "getMarksBetween", "from", "to", "doc", "marks", "mark", "range", "getMarkRange", "node", "pos", "getNodeAtPosition", "state", "typeOrName", "maxDepth", "$pos", "currentDepth", "currentNode", "getPreviousBlockSibling", "parentDepth", "index", "getSchemaTypeByName", "name", "schema", "getSplittedAttributes", "extensionAttributes", "typeName", "attributes", "extensionAttribute", "item", "getTextContentFromNodes", "$from", "maxMatch", "textBefore", "sliceEndPos", "parent", "chunk", "_node$type$spec$toTex", "_node$type$spec", "isMarkActive", "empty", "ranges", "type", "getMarkType", "objectIncludes", "selectionRange", "markRanges", "$to", "relativeFrom", "relativeTo", "matchedRange", "markRange", "sum", "excludedRange", "isActive", "isNodeActive", "schemaType", "getSchemaTypeNameByName", "isAtEndOfNode", "nodeType", "$anchor", "parentNode", "findParentNode", "$parentPos", "isAtStartOfNode", "isExtensionRulesEnabled", "extension", "enabled", "enabledExtension", "isList", "extensions", "nodeExtensions", "splitExtensions", "group", "callOrReturn", "getExtensionField", "isNodeEmpty", "checkChildren", "ignoreWhitespace", "_node$text", "isContentEmpty", "childNode", "isNodeSelection", "value", "NodeSelection", "isProseMirrorStep", "value", "step", "isProseMirrorReplaceStep", "value", "step", "isProseMirrorStep", "json", "MappablePosition", "position", "json", "getUpdatedPosition", "transaction", "mapResult", "createMappablePosition", "canSetMark", "state", "tr", "newMarkType", "selection", "cursor", "isTextSelection", "currentMarks", "_state$storedMarks", "mark", "ranges", "$from", "$to", "someNodeSupportsMark", "node", "_pos", "parent", "parentAllowsMarkType", "currentMarksAllowMarkType", "otherMark", "setMark", "typeOrName", "attributes", "dispatch", "empty", "type", "getMarkType", "oldAttributes", "getMarkAttributes", "range", "from", "to", "pos", "trimmedFrom", "trimmedTo", "setMeta", "key", "value", "setNode", "chain", "getNodeType", "attributesToCopy", "commands", "setBlockType", "updatedState", "setNodeSelection", "position", "doc", "minMax", "NodeSelection", "setTextDirection", "direction", "setTextSelection", "minPos", "TextSelection", "maxPos", "resolvedFrom", "resolvedEnd", "sinkListItem", "originalSinkListItem", "ensureMarks", "splittableMarks", "marks", "filteredMarks", "splitBlock", "keepMarks", "editor", "extensionAttributes", "newAttributes", "getSplittedAttributes", "canSplit", "atEnd", "deflt", "defaultBlockAt", "types", "deletedTr", "EditorState", "splitDoc", "splitPos", "can", "mapFrom", "first", "$first", "splitListItem", "overrideAttrs", "grandParent", "wrap", "Fragment", "depthBefore", "d", "depthAfter", "newNextTypeAttributes", "nextType", "_type$contentMatch$de", "start", "Slice", "sel", "n", "newTypeAttributes", "splitsAtStartOfItem", "itemStart", "trailingTypeAttributes", "storedMarks", "createNode", "content", "attrs", "flushPendingContent", "itemType", "item", "appendContentNode", "appendNestedList", "sourceList", "context", "convertListItems", "nestedItems", "nestedList", "convertListItem", "sourceItem", "index", "child", "convertedItems", "items", "findNodePosition", "root", "target", "targetPos", "normalizeListType", "areListTypesCompatible", "typeA", "typeB", "joinListBackwards", "listType", "list", "findParentNode", "before", "nodeBefore", "canJoin", "joinListForwards", "after", "nodeAfter", "createInnerSelectionForWholeDocList", "$start", "$end", "toggleList", "listTypeOrName", "itemTypeOrName", "extensions", "parentList", "isList", "isAllSelection", "topLevelNodes", "soleTopLevelNode", "allSelectionList", "currentList", "isInsideExistingList", "hasWholeDocSelectedList", "trx", "disp", "nextSelection", "currentItemType", "_currentList$node$fir", "convertedContent", "$anchor", "$head", "anchorParent", "headParent", "anchorOffset", "headOffset", "newList", "anchorParentPos", "headParentPos", "anchor", "head", "canWrapInList", "toggleMark", "options", "extendEmptyMarkRange", "isMarkActive", "toggleNode", "toggleTypeOrName", "toggleType", "isActive", "isNodeActive", "toggleWrap", "undoInputRule", "plugins", "i", "plugin", "undoable", "toUndo", "j", "unsetAllMarks", "ignoreClearable", "nonClearableMarks", "clearableMarkTypes", "markType", "unsetMark", "getMarkRange", "_$from$marks$find", "unsetTextDirection", "newAttrs", "updateAttributes", "nodeType", "schemaType", "getSchemaTypeNameByName", "canUpdate", "lastPos", "lastNode", "trimmedFrom2", "trimmedTo2", "DECORATION_MANAGER_PLUGIN_KEY", "PluginKey", "updateDecorations", "extensionName", "wrapIn", "originalWrapIn", "wrapInList", "originalWrapInList", "depthByEditor", "runInDecorationApplyScope", "callback", "_depthByEditor$get", "remaining", "_depthByEditor$get2", "isInDecorationApplyScope", "EventEmitter", "event", "fn", "args", "callbacks", "onceFn", "isDev", "isWidgetDecoration", "decoration", "decorationsToPMDecorations", "decorations", "pmDecorations", "widgetKeys", "buildDecorationSet", "DecorationSet", "rangeOwnsPosition", "docSize", "filterOutOfRangeDecorations", "warnedExtensions", "widgetKeyOf", "_decoration$spec", "findDuplicateWidgetKeys", "decorationSet", "extensionsByKey", "counts", "extension", "_extensionName", "_extensionsByKey$get", "_counts$get", "_counts$get2", "isAttrStep", "step", "hasResolvableChangedRange", "hasMappedRange", "positionalStep", "blockRangeFor", "changed", "nodeStart", "nodeEnd", "getRebuildRanges", "newRanges", "getChangedRanges", "newRange", "mapping", "blockRange", "a", "b", "merged", "last", "mapDecorationSet", "set", "removedSpec", "mapDecorations", "name", "previous", "previousSet", "_previous$decorationS", "_previous$widgetKeysB", "mergeDecorationSets", "decorationSetsByExtension", "allDecorations", "unionWidgetKeys", "widgetKeysByExtension", "keys", "validateDecorationSpec", "spec", "_update", "shouldRecomputeDecoration", "props", "forced", "EMPTY_KEYS", "DecorationManager", "options", "nextState", "state", "DECORATION_MANAGER_PLUGIN_KEY", "name", "spec", "validateDecorationSpec", "_DECORATION_MANAGER_P", "_DECORATION_MANAGER_P2", "EMPTY_KEYS", "entries", "resolved", "addDecorations", "editor", "Plugin", "_config", "decorationSetsByExtension", "widgetKeysByExtension", "set", "widgetKeys", "managerState", "unionWidgetKeys", "tr", "previous", "oldState", "newState", "meta", "forceAll", "forceName", "recomputedNames", "runInDecorationApplyScope", "forced", "shouldRecomputeDecoration", "result", "mapDecorations", "_DECORATION_MANAGER_P3", "_DECORATION_MANAGER_P4", "DecorationSet", "resolution", "getRebuildRanges", "ranges", "previousSet", "_previous$decorationS", "_previous$widgetKeysB", "mapDecorationSet", "docSize", "from", "to", "stale", "decoration", "rangeOwnsPosition", "key", "widgetKeyOf", "pmDecorations", "addedKeys", "decorationsToPMDecorations", "filterOutOfRangeDecorations", "decorations", "buildDecorationSet", "method", "create", "error", "isDev", "duplicateKeys", "findDuplicateWidgetKeys", "nextWarningKeys", "extensions", "names", "doc", "mergeDecorationSets", "canInsertNode", "state", "nodeType", "selection", "$from", "NodeSelection", "index", "depth", "createStyleTag", "style", "nonce", "suffix", "tiptapStyleTag", "styleNode", "isNumber", "value", "getType", "isPlainObject", "isValidCSSStyleValue", "value", "dedentLine", "line", "indentSize", "whitespace", "columns", "character", "continuesParagraph", "blockTokens", "source", "token", "parseContinuation", "mainContent", "nestedContent", "lexer", "lines", "isContinuation", "_lexer$isParagraphCon", "continuationLength", "parseIndentedBlocks", "src", "config", "items", "totalRaw", "i", "baseIndentSize", "currentLine", "itemMatch", "itemData", "indentLevel", "itemContent", "nextLine", "nextNonEmptyIndex", "l", "_nextNonEmpty$match", "_nextLine$match", "nestedTokens", "continuation", "nestedLine", "dedentedNested", "TAB_STOP", "columnWidth", "text", "width", "renderNestedMarkdownContent", "node", "h", "prefixOrGenerator", "ctx", "options", "prefix", "content", "children", "output", "index", "child", "childContent", "_h$renderChild", "_h$renderChild2", "indentLine", "configured", "prefixWidth", "indentedChild", "mergeDeep", "target", "source", "output", "isPlainObject", "key", "updateMarkViewAttributes", "checkMark", "editor", "attrs", "state", "doc", "tr", "thisMark", "node", "pos", "from", "to", "foundMark", "mark", "needsUpdate", "k", "updatedMark", "InputRule", "config", "_config$undoable", "inputRuleMatcherHandler", "text", "find", "isRegExp", "inputRuleMatch", "result", "createRuleTransaction", "editor", "from", "to", "insertText", "inputTransaction", "EditorState", "applyRule", "rule", "match", "plugin", "view", "tr", "inputEnd", "state", "createChainableState", "range", "commands", "chain", "can", "CommandManager", "closeHistory", "matchesDocument", "$from", "matchedDocLength", "matchStartOffset", "run", "rules", "_ref", "mark", "textBefore", "getTextContentFromNodes", "inputRulesPlugin", "props", "Plugin", "prev", "stored", "_tr$getMeta", "transform", "Transform", "step", "simulatedInputMeta", "getHTMLFromFragment", "Fragment", "run$1", "$cursor", "event", "Extendable", "callOrReturn", "getExtensionField", "options", "extension", "mergeDeep", "extendedConfig", "Mark", "resolvedConfig", "currentPos", "currentMarks", "m", "removeMark", "PasteRule", "pasteRuleMatcherHandler", "matches", "pasteRuleMatch", "pasteEvent", "dropEvent", "handlers", "node", "pos", "_node$type", "contentSize", "_node$content$size", "_node$content", "resolvedFrom", "resolvedTo", "textToMatch", "start", "end", "handler", "tiptapDragFromOtherEditor", "createClipboardPasteEvent", "_event$clipboardData", "pasteRulesPlugin", "dragSourceElement", "isPastedFromProseMirror", "isDroppedFromProseMirror", "processEvent", "pasteEvt", "chainableState", "handleDragstart", "_view$dom$parentEleme", "handleDragend", "dragFromOtherEditor", "selection", "_view", "html", "_clipboardData", "transactions", "oldState", "transaction", "isPaste", "isDrop", "simulatedPasteMeta", "isSimulatedPaste", "isNumber", "ExtensionManager", "extensions", "resolveExtensions", "getSchemaByResolvedExtensions", "addCommands", "getSchemaTypeByName", "allPlugins", "sortExtensions", "context", "plugins", "addKeyboardShortcuts", "defaultBindings", "bindings", "shortcut", "method", "keyMapPlugin", "keymap", "addInputRules", "isExtensionRulesEnabled", "inputResult", "inputPlugins", "addPasteRules", "pasteRules", "addProseMirrorPlugins", "proseMirrorPlugins", "decorationPlugin", "_this$decorationManag", "entries", "addDecorations", "DecorationManager", "attributes", "getAttributesFromExtensions", "getSchemaAttributes", "nodeExtensions", "splitExtensions", "extensionAttributes", "attribute", "addNodeView", "getNodeType", "nodeViewResult", "nodeview", "getPos", "decorations", "innerDecorations", "HTMLAttributes", "getRenderedAttributes", "baseDispatch", "next", "dispatchTransaction", "baseTransform", "extensionTransform", "transformedHtml", "markExtensions", "addMarkView", "getMarkType", "markView", "inline", "attrs", "updateMarkViewAttributes", "_this$decorationManag2", "current", "parent", "_callOrReturn", "_callOrReturn2", "onBeforeCreate", "onCreate", "onUpdate", "onSelectionUpdate", "onTransaction", "onFocus", "onBlur", "onDestroy", "flattenExtensions", "Extension", "ClipboardTextSerializer", "PluginKey", "schema", "doc", "textSerializers", "getTextSerializersFromSchema", "blockSeparator", "b", "$to", "getTextBetween", "Commands", "Delete", "appendedTransactions", "callback", "_this$editor$options$", "_this$editor$options$2", "_this$editor$options$3", "nextTransaction", "combineTransactionSteps", "getChangedRanges", "change", "isFullyWithinRange", "mapping", "index", "RemoveMarkStep", "newStart", "newEnd", "oldStart", "oldEnd", "foundBeforeMark", "_nextTransaction$doc$", "foundAfterMark", "_nextTransaction$doc$2", "_this$editor$options$4", "_this$editor$options$5", "Drop", "_", "slice", "moved", "Editable", "focusEventsPluginKey", "FocusEvents", "createAndroidDeletePlugin", "isAndroid", "domObserver", "isWholeDocumentSelected", "empty", "Selection", "Keymap", "handleBackspace", "$anchor", "$parentPos", "parentIsIsolating", "parentPos", "isAtStart", "handleDelete", "baseKeymap", "pcKeymap", "macKeymap", "isiOS", "isMacOS", "newState", "docChanges", "ignoreTr", "isNodeEmpty", "Paste", "Tabindex", "_this$options$value", "TextDirection", "element", "dir", "direction", "hasChecked", "warnOnDuplicatedProseMirrorModel", "schema", "content", "step", "ReplaceStep", "isProseMirrorReplaceStep", "Fragment", "NodePos", "pos", "editor", "isBlock", "node", "_this$actualDepth", "from", "to", "parentPos", "$pos", "children", "offset", "isNonTextAtom", "isInline", "targetPos", "childNodePos", "selector", "attributes", "currentNode", "nodeAttributes", "attrKeys", "index", "key", "firstItemOnly", "nodes", "childPos", "tr", "style", "Editor", "EventEmitter", "options", "error", "getUpdatedPosition", "createMappablePosition", "event", "slice", "moved", "initialDoc", "selection", "resolveFocusPosition", "EditorState", "el", "dom", "CommandManager", "createStyleTag", "editable", "emitUpdate", "state", "obj", "isDev", "isInDecorationApplyScope", "plugin", "handlePlugins", "plugins", "isFunction", "nameOrPluginKeyToRemove", "prevPlugins", "nameOrPluginKey", "name", "allExtensions", "Editable", "ClipboardTextSerializer", "_this$options$coreExt", "Commands", "FocusEvents", "Keymap", "Tabindex", "_this$options$coreExt2", "Drop", "Paste", "Delete", "TextDirection", "ext", "extension", "ExtensionManager", "doc", "createDocument", "fallbackDoc", "_this$options$editorP", "element", "editorProps", "enableExtensionDispatchTransaction", "baseDispatch", "dispatch", "baseTransformPastedHTML", "transformPastedHTML", "EditorView", "newState", "fn", "transaction", "_this$capturedTransac", "transactions", "selectionHasChanged", "rootTrWasApplied", "prevState", "mostRecentFocusTr", "focus", "blur", "nameOrType", "getAttributes", "nameOrAttributes", "attributesOrUndefined", "isActive", "getHTMLFromFragment", "blockSeparator", "textSerializers", "getText", "getTextSerializersFromSchema", "isNodeEmpty", "_this$editorView$isDe", "_this$editorView", "_this$$doc", "_this$$doc2", "markInputRule", "config", "InputRule", "state", "range", "match", "attributes", "callOrReturn", "tr", "captureGroup", "fullMatch", "startSpaces", "textStart", "textEnd", "getMarksBetween", "item", "type", "markEnd", "nodeInputRule", "start", "end", "newNode", "matchStart", "lastChar", "insertionStart", "textblockTypeInputRule", "$start", "wrappingInputRule", "config", "InputRule", "state", "range", "match", "chain", "attributes", "callOrReturn", "tr", "blockRange", "wrapping", "findWrapping", "selection", "storedMarks", "splittableMarks", "marks", "filteredMarks", "mark", "nodeType", "before", "canJoin", "isTouchEvent", "e", "ResizableNodeView", "options", "isEditable", "event", "deltaX", "deltaY", "touch", "finalWidth", "finalHeight", "_options$options", "_options$options2", "_options$options3", "_options$options4", "_options$options5", "_options$options6", "_this$contentElement", "node", "decorations", "innerDecorations", "element", "direction", "handle", "isTop", "isBottom", "isLeft", "isRight", "el", "width", "height", "shouldPreserveAspectRatio", "constrained", "newWidth", "newHeight", "preserveAspectRatio", "constrainedWidth", "constrainedHeight", "_this$maxSize", "_this$maxSize2", "_this$maxSize3", "_this$maxSize4", "isHorizontal", "isVertical", "Node", "Extendable", "config", "resolvedConfig", "options", "extendedConfig", "markPasteRule", "config", "PasteRule", "state", "range", "match", "pasteEvent", "attributes", "callOrReturn", "tr", "captureGroup", "fullMatch", "markEnd", "startSpaces", "textStart", "textEnd", "getMarksBetween", "item", "type", "jsxElements", "jsxFragments", "createJSXElement", "spec", "element", "isJSXElement", "value", "flattenFragmentChildren", "children", "child", "render", "tag", "attributes", "result", "isJSXElement", "jsxFragments", "createJSXElement", "children", "rest", "flattenedChildren", "flattenFragmentChildren", "h", "handleBackspace", "editor", "type", "state", "selection", "$from", "parentDepth", "parent", "index", "previous", "_previous$lastChild", "targetPos", "tr", "dispatch", "content", "slice", "Slice", "TextSelection", "inputRegex", "Blockquote", "Node", "HTMLAttributes", "h", "mergeAttributes", "token", "helpers", "parseBlockChildren", "_helpers$parseBlockCh", "node", "prefix", "result", "child", "linesWithPrefix", "_h$renderChild", "_h$renderChild2", "line", "commands", "wrappingInputRule", "starInputRegex", "starPasteRegex", "underscoreInputRegex", "underscorePasteRegex", "Bold", "Mark", "node", "mark", "value", "HTMLAttributes", "h", "mergeAttributes", "token", "helpers", "commands", "markInputRule", "markPasteRule", "inputRegexMatch", "text", "match", "pasteRegexMatch", "regex", "matches", "shortestUnusedBacktickRun", "runs", "run", "length", "Code", "Mark", "HTMLAttributes", "mergeAttributes", "token", "helpers", "node", "h", "context", "markText", "_context$meta", "fence", "padding", "commands", "markInputRule", "markPasteRule", "DEFAULT_TAB_SIZE", "backtickInputRegex", "tildeInputRegex", "CodeBlock", "Node", "element", "languageClassPrefix", "language", "_element$firstElement", "className", "node", "HTMLAttributes", "mergeAttributes", "token", "helpers", "_token$raw", "_token$raw2", "h", "output", "_node$attrs", "attributes", "commands", "empty", "$anchor", "isAtStart", "editor", "tabSize", "_this$options$tabSize", "state", "selection", "$from", "indent", "tr", "from", "to", "indentedText", "line", "_this$options$tabSize2", "pos", "codeBlockStart", "codeBlockEnd", "lines", "currentLineIndex", "charCount", "relativeCursorPos", "i", "leadingSpaces", "_currentLine$match", "spacesToRemove", "lineStartPos", "TextSelection", "reverseIndentText", "_line$match", "isAtEnd", "endsWithDoubleNewline", "before", "doc", "after", "Selection", "textblockTypeInputRule", "match", "Plugin", "PluginKey", "view", "event", "text", "vscode", "vscodeData", "schema", "textNode", "Document", "Node", "node", "h", "HardBreak", "Node", "HTMLAttributes", "mergeAttributes", "commands", "chain", "state", "editor", "selection", "storedMarks", "keepMarks", "splittableMarks", "marks", "tr", "dispatch", "filteredMarks", "mark", "Heading", "Node", "level", "node", "HTMLAttributes", "mergeAttributes", "token", "helpers", "h", "_node$attrs", "headingChars", "attributes", "commands", "items", "textblockTypeInputRule", "HorizontalRule", "Node", "HTMLAttributes", "mergeAttributes", "token", "helpers", "chain", "state", "canInsertNode", "selection", "$originTo", "currentChain", "isNodeSelection", "chainState", "tr", "dispatch", "$to", "posAfter", "TextSelection", "NodeSelection", "nodeType", "node", "nodeInputRule", "starInputRegex", "starPasteRegex", "underscoreInputRegex", "underscorePasteRegex", "Italic", "Mark", "node", "mark", "HTMLAttributes", "mergeAttributes", "commands", "token", "helpers", "h", "markInputRule", "markPasteRule", "encodedTlds", "encodedUtlds", "numeric", "ascii", "alpha", "asciinumeric", "alphanumeric", "domain", "emoji", "scheme", "slashscheme", "whitespace", "registerGroup", "name", "groups", "addToGroups", "flags", "k", "group", "flagsForToken", "result", "c", "State", "token", "input", "state", "nextState", "i", "regex", "exactOnly", "inputs", "next", "regexp", "len", "t", "templateState", "allFlags", "ta", "tr", "ts", "tt", "WORD", "UWORD", "ASCIINUMERICAL", "ALPHANUMERICAL", "LOCALHOST", "TLD", "UTLD", "SCHEME", "SLASH_SCHEME", "NUM", "WS", "NL", "OPENBRACE", "CLOSEBRACE", "OPENBRACKET", "CLOSEBRACKET", "OPENPAREN", "CLOSEPAREN", "OPENANGLEBRACKET", "CLOSEANGLEBRACKET", "FULLWIDTHLEFTPAREN", "FULLWIDTHRIGHTPAREN", "LEFTCORNERBRACKET", "RIGHTCORNERBRACKET", "LEFTWHITECORNERBRACKET", "RIGHTWHITECORNERBRACKET", "FULLWIDTHLESSTHAN", "FULLWIDTHGREATERTHAN", "AMPERSAND", "APOSTROPHE", "ASTERISK", "AT", "BACKSLASH", "BACKTICK", "CARET", "COLON", "COMMA", "DOLLAR", "DOT", "EQUALS", "EXCLAMATION", "HYPHEN", "PERCENT", "PIPE", "PLUS", "POUND", "QUERY", "QUOTE", "FULLWIDTHMIDDLEDOT", "SEMI", "SLASH", "TILDE", "UNDERSCORE", "EMOJI$1", "SYM", "tk", "ASCII_LETTER", "LETTER", "EMOJI", "DIGIT", "SPACE", "CR", "LF", "EMOJI_VARIATION", "EMOJI_JOINER", "OBJECT_REPLACEMENT", "tlds", "utlds", "init$2", "customSchemes", "groups", "State", "Start", "decodeTlds", "encodedTlds", "encodedUtlds", "tt", "APOSTROPHE", "OPENBRACE", "CLOSEBRACE", "OPENBRACKET", "CLOSEBRACKET", "OPENPAREN", "CLOSEPAREN", "OPENANGLEBRACKET", "CLOSEANGLEBRACKET", "FULLWIDTHLEFTPAREN", "FULLWIDTHRIGHTPAREN", "LEFTCORNERBRACKET", "RIGHTCORNERBRACKET", "LEFTWHITECORNERBRACKET", "RIGHTWHITECORNERBRACKET", "FULLWIDTHLESSTHAN", "FULLWIDTHGREATERTHAN", "AMPERSAND", "ASTERISK", "AT", "BACKTICK", "CARET", "COLON", "COMMA", "DOLLAR", "DOT", "EQUALS", "EXCLAMATION", "HYPHEN", "PERCENT", "PIPE", "PLUS", "POUND", "QUERY", "QUOTE", "SLASH", "SEMI", "TILDE", "UNDERSCORE", "BACKSLASH", "FULLWIDTHMIDDLEDOT", "Num", "tr", "DIGIT", "NUM", "numeric", "Asciinumeric", "ASCII_LETTER", "ASCIINUMERICAL", "asciinumeric", "Alphanumeric", "LETTER", "ALPHANUMERICAL", "alphanumeric", "Word", "WORD", "ascii", "UWord", "UWORD", "alpha", "Nl", "NL", "whitespace", "Cr", "WS", "Ws", "SPACE", "Emoji", "EMOJI", "EMOJI$1", "emoji", "EmojiJoiner", "wordjr", "uwordjr", "i", "fastts", "TLD", "UTLD", "addToGroups", "SCHEME", "SLASH_SCHEME", "a", "b", "sch", "flags", "scheme", "slashscheme", "domain", "ts", "LOCALHOST", "SYM", "tk", "run$1", "start", "str", "iterable", "stringToArray", "c", "charCount", "tokens", "cursor", "charCursor", "state", "nextState", "tokenLength", "latestAccepting", "sinceAccepts", "charsSinceAccepts", "result", "len", "index", "first", "second", "char", "input", "t", "defaultt", "jr", "next", "encoded", "words", "stack", "digits", "popDigitCount", "popCount", "defaults", "noop", "Options", "opts", "defaultRender", "o", "ignoredTags", "uppercaseIgnoredTags", "classNames", "classes", "ir", "token", "key", "operator", "isCallable", "option", "obj", "val", "MultiToken", "value", "tokens", "scheme", "options", "val", "truncate", "formatted", "protocol", "defaults", "token", "href", "formattedHref", "tagName", "content", "attributes", "className", "target", "rel", "attrs", "eventListeners", "createTokenClass", "type", "props", "Token", "p", "Email", "Text", "Nl", "Url", "LOCALHOST", "COLON", "makeState", "arg", "State", "init$1", "groups", "qsAccepting", "AMPERSAND", "ASTERISK", "AT", "BACKSLASH", "BACKTICK", "CARET", "DOLLAR", "EQUALS", "HYPHEN", "NUM", "PERCENT", "PIPE", "PLUS", "POUND", "SLASH", "SYM", "TILDE", "UNDERSCORE", "qsNonAccepting", "APOSTROPHE", "COLON", "COMMA", "DOT", "EXCLAMATION", "QUERY", "QUOTE", "SEMI", "OPENANGLEBRACKET", "CLOSEANGLEBRACKET", "OPENBRACE", "CLOSEBRACE", "CLOSEBRACKET", "OPENBRACKET", "OPENPAREN", "CLOSEPAREN", "FULLWIDTHLEFTPAREN", "FULLWIDTHRIGHTPAREN", "LEFTCORNERBRACKET", "RIGHTCORNERBRACKET", "LEFTWHITECORNERBRACKET", "RIGHTWHITECORNERBRACKET", "FULLWIDTHLESSTHAN", "FULLWIDTHGREATERTHAN", "localpartAccepting", "Start", "Localpart", "tt", "ta", "Domain", "Scheme", "SlashScheme", "LocalpartAt", "LocalpartDot", "EmailDomain", "EmailDomainDot", "Email$1", "Email", "LOCALHOST", "EmailDomainHyphen", "DomainHyphen", "DomainDot", "DomainDotTld", "Url", "DomainDotTldColon", "DomainDotTldColonPort", "Url$1", "UrlNonaccept", "SchemeColon", "SlashSchemeColon", "SlashSchemeColonSlash", "UriPrefix", "bracketPairs", "i", "OPEN", "CLOSE", "UrlOpen", "UrlOpenQ", "UrlOpenSyms", "NL", "Nl", "tk", "run", "start", "input", "tokens", "len", "cursor", "multis", "textTokens", "dead", "state", "secondState", "nextState", "multiLength", "latestAccepting", "sinceAccepts", "visited", "k", "pos", "initMultiToken", "Text", "Multi", "subtokens", "startIdx", "endIdx", "value", "warn", "warnAdvice", "INIT", "reset", "registerCustomProtocol", "scheme", "optionalSlashSlash", "INIT", "warn", "warnAdvice", "init", "init$2", "i", "init$1", "tokenize", "str", "run", "run$1", "find", "type", "opts", "options", "Options", "tokens", "filtered", "token", "UNICODE_WHITESPACE_PATTERN", "UNICODE_WHITESPACE_REGEX", "UNICODE_WHITESPACE_REGEX_END", "UNICODE_WHITESPACE_REGEX_TRAILING", "UNICODE_WHITESPACE_REGEX_GLOBAL", "unlinkTrailingWhitespace", "tr", "range", "type", "rangeEnd", "_rangeEnd$nodeBefore", "trailingWhitespace", "_insertedText$match", "whitespaceFrom", "linkMarks", "getMarksBetween", "item", "nodeAfter", "storedMarks", "isValidLinkStructure", "tokens", "autolink", "options", "Plugin", "PluginKey", "transactions", "oldState", "newState", "docChanges", "transaction", "preventAutolink", "transform", "combineTransactionSteps", "isHistoryTransaction", "insertedRanges", "step", "index", "ReplaceStep", "mapping", "from", "to", "left", "right", "getChangedRanges", "newRange", "nodesInChangedRanges", "findChildrenInRange", "node", "textBlock", "textBeforeWhitespace", "endText", "wordsBeforeWhitespace", "lastWordBeforeSpace", "lastWordAndBlockOffset", "linksBeforeSpace", "tokenize", "t", "link", "clickHandler", "view", "pos", "event", "target", "root", "handled", "attrs", "getAttributes", "href", "_link$href", "_link$target", "MARKDOWN_LINK_INPUT_REGEX", "MARKDOWN_LINK_PASTE_REGEX", "isEscaped", "text", "backslashes", "position", "isInsideCodeSpan", "matchIndex", "openRunLength", "runLength", "isConvertibleLink", "match", "isAllowedHref", "linkText", "_match$index", "_match$index2", "toRuleMatch", "linkSyntax", "straightQuotedTitle", "curlyDoubleTitle", "curlySingleTitle", "title", "_ref", "_match$index3", "matchesOverlap", "a", "b", "getMarkdownLinkAttributes", "_match$data", "_match$data$title", "_match$data2", "markdownLinkInputRule", "config", "rule", "markInputRule", "InputRule", "props", "result", "markdownLinkPasteRule", "markPasteRule", "markdownMatches", "plainUrlMatches", "_config$findPlainUrls", "_config$findPlainUrls2", "urlMatch", "markdownMatch", "PasteRule", "_props$match$data", "pasteHandler", "_event", "slice", "shouldAutoLink", "state", "selection", "empty", "textContent", "find", "isAllowedUri", "uri", "protocols", "allowedProtocols", "protocol", "nextProtocol", "UNICODE_WHITESPACE_REGEX_GLOBAL", "Link", "Mark", "registerCustomProtocol", "reset", "url", "ctx", "hasProtocol", "hasMaybeProtocol", "hostname", "element", "_this$options$HTMLAtt", "_this$options$HTMLAtt2", "_this$options$HTMLAtt3", "dom", "href", "HTMLAttributes", "mergeAttributes", "token", "helpers", "node", "h", "_node$attrs$href", "_node$attrs", "title", "_node$attrs$title", "_node$attrs2", "text", "attributes", "chain", "markdownLinkInputRule", "findPlainUrls", "foundLinks", "defaultProtocol", "find", "item", "link", "markdownLinkPasteRule", "markPasteRule", "match", "_match$data", "plugins", "autolink", "clickHandler", "pasteHandler", "ListItemName", "TextStyleName", "bulletListInputRegex", "BulletList", "Node", "HTMLAttributes", "mergeAttributes", "token", "helpers", "node", "h", "commands", "chain", "inputRule", "wrappingInputRule", "getBranchingNestedListAtCursor", "state", "itemName", "wrapperNames", "selection", "$from", "listItemDepth", "depth", "listItem", "indexInListItem", "nextChild", "itemType", "hasBranching", "child", "nodeAfter", "items", "hoistBranchingNestedList", "dispatch", "context", "nestedList", "nestedListPos", "insertPos", "tr", "mappedInsertPos", "Fragment", "handleDeleteBranchingNestedList", "editor", "createBranchingListDeleteKeymap", "Extension", "handleDelete", "ROMAN_NUMERALS", "ALPHA_NUMERALS", "ORDERED_LIST_MARKER_PATTERN", "toRoman", "num", "remaining", "result", "value", "numeral", "toRomanUpper", "fromRoman", "roman", "lower", "index", "matched", "isValidRoman", "marker", "fromAlpha", "first", "second", "toRomanAlpha", "detectMarkerType", "markerToStart", "type", "start", "parsed", "startToMarker", "areOrderedListMarkersSequential", "markers", "firstType", "_detectMarkerType", "firstStart", "expected", "parseListMarker", "buildOrderedListAttrsFromMarker", "attrs", "getListMarker", "separator", "position", "ensureLeadingParagraph", "content", "hasEmptyLeadingParagraph", "_node$content", "_first$content", "EMPTY_ITEM_TEXT", "TOP_LEVEL", "isNested", "ctx", "_ctx$level", "isSameLineOrderedListToken", "nestedToken", "_token$tokens", "_token$tokens2", "parseSameLineOrderedListText", "text", "ListItem", "parseBlockChildren", "_helpers$parseBlockCh", "firstToken", "remainingTokens", "_firstToken$tokens", "t", "additionalContent", "getPrefix", "_context$meta", "_context$meta2", "output", "renderNestedMarkdownContent", "prefix", "findListItemPos", "typeOrName", "nodeType", "getNodeType", "currentNode", "currentDepth", "currentPos", "targetDepth", "getNextListDepth", "listItemPos", "getNodeAtPosition", "hasListBefore", "editorState", "name", "parentListTypes", "$anchor", "previousNodePos", "previousNode", "handleBackspace", "isNodeActive", "$listPos", "listDescendants", "pos", "lastItem", "$lastItemPos", "target", "TextSelection", "joinTextblockBackward", "isAtStartOfNode", "itemDepth", "nextListIsDeeper", "listDepth", "nextListIsHigher", "isAtEndOfNode", "joinTextblockForward", "handleTab", "previous", "getPreviousBlockSibling", "block", "blockStart", "blockEnd", "insideLastItemEnd", "ListKeymap", "Extension", "editor", "handled", "itemName", "handleDelete", "wrapperNames", "handleBackspace", "handleTab", "ORDERED_LIST_ITEM_REGEX", "ORDERED_LIST_MARKER_PATTERN", "matchOrderedListItemLine", "line", "match", "marker", "detectMarkerType", "INDENTED_LINE_REGEX", "PARAGRAPH_INTERRUPTERS", "isOrderedListMarkerLine", "isBlockContentLine", "trimmedLine", "interruptsLazyContinuation", "pattern", "splitItemContent", "contentLines", "paragraphLines", "blockLines", "reachedBlockBoundary", "collectOrderedListItems", "lines", "listItems", "currentLineIndex", "consumed", "indent", "_separator", "content", "indentLevel", "number", "markerType", "itemNumber", "markerToStart", "itemContentLines", "nextLineIndex", "itemLines", "sawBlankLine", "nextLine", "leadingWhitespace", "contentIndent", "PLAIN_TEXT_ORDERED_LIST_LINE_REGEX", "parsePlainTextOrderedListPaste", "text", "l", "parsedItems", "areOrderedListMarkersSequential", "item", "buildOrderedListAttrsFromMarker", "buildNestedStructure", "items", "baseIndent", "lexer", "result", "currentIndex", "mainText", "tokens", "additionalContent", "blockTokens", "lookAheadIndex", "nestedItems", "nestedListItems", "nestedItem", "parseListItems", "helpers", "itemToken", "inlineContent", "parsed", "ORDERED_LIST_SCAN_WINDOW", "takeLines", "source", "max", "start", "lineEnd", "collectOrderedListItemsFromSource", "firstLineEnd", "windowSize", "collected", "ListItemName", "TextStyleName", "orderedListInputRegex", "cssListStyleTypeToHtmlType", "style", "OrderedList", "Node", "element", "htmlType", "mappedFromOl", "firstLi", "liStyle", "mappedFromLi", "HTMLAttributes", "type", "attributesWithoutType", "attrs", "mergeAttributes", "token", "startValue", "typeValue", "node", "h", "src", "_tokens", "_listItems$", "_listItems$2", "commands", "chain", "Plugin", "view", "event", "html", "_event$clipboardData", "_event$clipboardData2", "orderedListContent", "orderedListNode", "tr", "joinPredicate", "inputRule", "wrappingInputRule", "inputRegex", "visuallyHiddenStyle", "getCheckboxLabel", "checked", "a11y", "_a11y$checkboxLabel", "TaskItem", "dataChecked", "attributes", "_element$querySelecto", "nestedContent", "prefix", "_node$attrs", "renderNestedMarkdownContent", "createBranchingListDeleteKeymap", "shortcuts", "getPos", "listItem", "checkboxWrapper", "checkboxStyler", "checkbox", "updateA11Y", "currentNode", "label", "position", "key", "value", "prevRenderedAttributeKeys", "updatedNode", "extensionAttributes", "newHTMLAttributes", "getRenderedAttributes", "newKeys", "staticAttrs", "TaskList", "index", "_src$match", "parseTaskListContent", "nestedResult", "parseIndentedBlocks", "data", "nestedTokens", "taskListToken", "remainder", "ListKit", "extensions", "BulletList", "ListItem", "EMPTY_PARAGRAPH_MARKDOWN", "NBSP_CHAR", "Paragraph", "Node", "HTMLAttributes", "mergeAttributes", "token", "helpers", "tokens", "content", "node", "h", "ctx", "previousContent", "_ctx$previousNode", "_ctx$previousNode2", "commands", "inputRegex", "pasteRegex", "Strike", "Mark", "style", "HTMLAttributes", "mergeAttributes", "token", "helpers", "node", "h", "commands", "markInputRule", "markPasteRule", "Text", "Node", "token", "node", "Underline", "Mark", "style", "HTMLAttributes", "mergeAttributes", "token", "helpers", "node", "src", "_tokens", "lexer", "delimiters", "match", "codeSpan", "text", "commands", "dropCursor", "options", "Plugin", "editorView", "DropCursorView", "_a", "name", "handler", "e", "prevState", "target", "pos", "$pos", "isBlock", "rect", "editorDOM", "editorRect", "scaleX", "scaleY", "before", "after", "node", "nodeRect", "top", "halfWidth", "coords", "parent", "parentLeft", "parentTop", "parentScaleX", "parentScaleY", "timeout", "event", "disableDropCursor", "disabled", "point", "dropPoint", "GapCursor", "_GapCursor", "Selection", "$pos", "doc", "mapping", "Slice", "other", "json", "GapBookmark", "parent", "closedBefore", "closedAfter", "override", "deflt", "dir", "mustMove", "search", "pos", "next", "d", "$cur", "inside", "NodeSelection", "_GapBookmark", "needsGap", "type", "index", "before", "after", "gapCursor", "Plugin", "drawGapCursor", "_view", "$anchor", "$head", "handleClick", "handleKeyDown", "beforeinput", "keydownHandler", "arrow", "axis", "dirStr", "state", "dispatch", "view", "sel", "$start", "TextSelection", "$found", "event", "clickPos", "$from", "insert", "frag", "Fragment", "i", "tr", "node", "DecorationSet", "Decoration", "CharacterCount", "Extension", "text", "word", "options", "node", "initialEvaluationDone", "Plugin", "PluginKey", "transactions", "oldState", "newState", "limit", "autoTrim", "initialContentSize", "over", "from", "to", "tr", "transaction", "state", "oldSize", "newSize", "pos", "Dropcursor", "dropCursor", "Focus", "doc", "selection", "isEditable", "isFocused", "anchor", "decorations", "DecorationSet", "maxLevels", "currentLevel", "Decoration", "Gapcursor", "gapCursor", "extension", "context", "_callOrReturn", "callOrReturn", "getExtensionField", "DEFAULT_DATA_ATTRIBUTE", "PLUGIN_KEY", "createPlaceholderDecoration", "editor", "placeholder", "dataAttribute", "isEmptyDoc", "hasAnchor", "emptyNode", "emptyEditor", "classes", "resolveEmptyNodeClass", "emptyNodeClass", "props", "scanRangeForDecorations", "isEmpty", "isNodeEmpty", "buildPlaceholderDecorations", "resolved", "nodeStart", "resolveTopLevelRange", "_resolved$nodeAfter", "nodePos", "topLevelPos", "toContentRelativeRange", "range", "getTopLevelBlocksInRange", "ranges", "offset", "nodeEnd", "absNodeStart", "absNodeEnd", "mergeRanges", "sorted", "a", "b", "merged", "i", "last", "current", "collectBlocksForChange", "change", "collectRescanRanges", "changes", "getChangedRanges", "clampRange", "clampedFrom", "updateDecorationsInRanges", "next", "existing", "decoration", "newDecos", "createPlaceholderStateField", "_config", "prev", "preparePlaceholderAttribute", "attr", "createPlaceholderPlugin", "useResolvedPath", "_PLUGIN_KEY$getState", "Placeholder", "shouldSyncDomSelection", "isNodeSelection", "shouldPreserveSelection", "clearDomSelection", "_window$getSelection", "restoreDomSelection", "view", "Selection", "nodeEqualsType", "types", "node", "TrailingNode", "Extension", "plugin", "PluginKey", "defaultNode", "_this$editor$schema$t", "disabledNodes", "value", "Plugin", "transactions", "__", "state", "doc", "tr", "schema", "shouldInsertNodeAtEnd", "endPosition", "type", "transaction", "_", "lastNode", "UndoRedo", "dispatch", "undo", "redo", "history", "StarterKit", "Extension", "extensions", "Bold", "Blockquote", "BulletList", "Code", "CodeBlock", "Document", "Dropcursor", "Gapcursor", "HardBreak", "Heading", "UndoRedo", "HorizontalRule", "Italic", "ListItem", "ListKeymap", "_this$options", "Link", "_this$options2", "OrderedList", "Paragraph", "Strike", "Text", "Underline", "_this$options3", "TrailingNode", "_this$options4", "src_default", "inputRegex", "Image", "Node", "HTMLAttributes", "mergeAttributes", "token", "helpers", "node", "src", "_node$attrs$src", "_node$attrs", "alt", "_node$attrs$alt", "_node$attrs2", "title", "_node$attrs$title", "_node$attrs3", "directions", "minWidth", "minHeight", "alwaysPreserveAspectRatio", "resizeManagedAttributes", "getPos", "editor", "el", "mergedAttributes", "key", "value", "previousHTMLAttributes", "syncImageSource", "onUpdate", "updatedNode", "extensionAttributes", "attribute", "newHTMLAttributes", "getRenderedAttributes", "nodeView", "ResizableNodeView", "width", "height", "pos", "dom", "showNodeView", "options", "commands", "nodeInputRule", "match", "src_default", "readFromCache: (key: Node) => TableMap | undefined", "addToCache: (key: Node, value: TableMap) => TableMap", "cache", "readFromCache", "key", "addToCache", "value", "cache: (Node | TableMap)[]", "cachePos", "TableMap", "width: number", "height: number", "map: number[]", "problems: Problem[] | null", "width", "height", "map", "problems", "pos", "i", "curPos", "left", "top", "right", "bottom", "j", "axis", "dir", "a", "b", "leftA", "rightA", "topA", "bottomA", "leftB", "rightB", "topB", "bottomB", "rect", "result: number[]", "seen: Record<number, boolean>", "row", "col", "index", "seen", "result", "table", "rowStart", "rowEnd", "rowEndIndex", "computeMap", "findWidth", "mapPos", "colWidths: ColWidths", "e", "rowNode", "cellNode", "colspan", "rowspan", "colwidth", "h", "start", "w", "colW", "widthIndex", "prev", "colWidths", "expectedPos", "missing", "tableMap", "badWidths", "findBadColWidths", "hasRowSpan", "rowWidth", "prevRow", "cell", "node", "updated", "attrs", "colWidth", "freshColWidth", "result: ColWidths", "tableNodeTypes", "schema", "result", "name", "type", "role", "tableEditingKey", "PluginKey", "cellAround", "$pos", "d", "cellWrapping", "isInTable", "state", "$head", "selectionCell", "sel", "$cell", "cellNear", "after", "pos", "before", "pointsAtCell", "moveCellForward", "inSameTable", "$cellA", "$cellB", "nextCell", "$pos", "axis", "dir", "table", "map", "TableMap", "tableStart", "moved", "removeColSpan", "attrs", "pos", "result: CellAttrs", "result", "w", "addColSpan", "columnIsHeader", "col", "headerCell", "tableNodeTypes", "row", "CellSelection", "Selection", "$anchorCell", "$headCell", "rect", "doc", "cells", "p", "ranges", "cell", "from", "SelectionRange", "mapping", "pointsAtCell", "inSameTable", "tableChanged", "TextSelection", "seen: Record<number, boolean>", "rows", "rowContent", "index", "seen", "cellRect", "extraLeft", "extraRight", "Fragment", "fragment", "Slice", "tr", "content", "mapFrom", "i", "$from", "$to", "sel", "node", "f", "anchorTop", "headTop", "anchorBottom", "headBottom", "anchorRect", "headRect", "anchorLeft", "headLeft", "anchorRight", "headRight", "other", "json", "anchorCell", "headCell", "CellBookmark", "anchor: number", "head: number", "anchor", "head", "drawCellSelection", "state", "cells: Decoration[]", "Decoration", "DecorationSet", "isCellBoundarySelection", "afterFrom", "beforeTo", "depth", "d", "isTextSelectionAcrossCells", "fromCellBoundaryNode: Node | undefined", "toCellBoundaryNode: Node | undefined", "fromCellBoundaryNode", "toCellBoundaryNode", "normalizeSelection", "allowTableNodeSelection", "normalize: Selection | undefined", "role: string | undefined", "NodeSelection", "role", "normalize", "$cell", "start", "lastCell", "fixTablesKey", "PluginKey", "changedDescendants", "old", "cur", "offset", "oldSize", "curSize", "outer", "j", "child", "scan", "e", "fixTables", "oldState", "tr: Transaction | undefined", "check", "fixTable", "tablePos", "mustAdd: number[]", "mustAdd", "prob", "first", "last", "end", "add", "role: TableRole", "nodes: Node[]", "nodes", "side", "selectedRect", "state", "sel", "$pos", "selectionCell", "table", "tableStart", "map", "TableMap", "CellSelection", "addColumn", "tr", "col", "refColumn: number | null", "columnIsHeader", "refColumn", "row", "index", "pos", "cell", "addColSpan", "type", "tableNodeTypes", "addColumnBefore", "dispatch", "isInTable", "rect", "addColumnAfter", "removeColumn", "mapStart", "attrs", "removeColSpan", "start", "deleteColumn", "rowIsHeader", "headerCell", "_table$nodeAt", "addRow", "rowPos", "i", "cells", "refRow: number | null", "refRow", "_table$nodeAt2", "node", "addRowBefore", "addRowAfter", "removeRow", "nextRow", "mapFrom", "seen", "copy", "newPos", "deleteRow", "isEmpty", "c", "cellsOverlapRectangle", "width", "height", "indexTop", "indexLeft", "indexBottom", "indexRight", "mergeCells", "seen: Record<number, boolean>", "content", "Fragment", "mergedPos: number | undefined", "mergedCell: Node | undefined", "cellPos", "mergedPos", "mergedCell", "mapped", "end", "splitCell", "nodeTypes", "splitCellWithType", "getCellType", "cellNode: Node | null | undefined", "cellPos: number | undefined", "cellNode", "cellWrapping", "_cellAround", "cellAround", "baseAttrs", "colwidth", "lastCell", "setCellAttr", "name", "value", "$cell", "deprecated_toggleHeader", "types", "nodes", "isHeaderEnabledByType", "cellPositions", "toggleHeader", "options", "isHeaderRowEnabled", "isHeaderColumnEnabled", "selectionStartsAt", "cellsRect", "newType", "relativeCellPos", "toggleHeaderRow: Command", "toggleHeaderColumn: Command", "toggleHeaderCell: Command", "findNextCell", "dir", "before", "rowEnd", "rowNode", "lastChild", "rowStart", "goToNextCell", "direction", "TextSelection", "moveCellForward", "deleteTable", "d", "deleteCellSelection", "baseContent", "Slice", "pastedCells", "slice", "content", "openStart", "openEnd", "first", "role", "schema", "rows", "i", "cells", "left", "right", "fitSlice", "tableNodeTypes", "Slice", "ensureRectangular", "widths: ColWidths", "row", "j", "rowspan", "colspan", "r", "widths", "width", "Fragment", "empty", "nodeType", "node", "Transform", "clipCells", "height", "newWidth", "newHeight", "added: number[]", "newRows: Fragment[]", "frag", "col", "added", "cell", "removeColSpan", "newRows", "source", "growTable", "tr", "map", "table", "start", "mapFrom", "types", "emptyHead", "rowEnd", "rowNode", "cells: Node[]", "add: Node", "add", "header", "emptyRow", "isolateHorizontal", "top", "found", "index", "pos", "cellTop", "cellLeft", "isolateVertical", "bottom", "updatePos", "insertCells", "state", "dispatch", "tableStart", "rect", "TableMap", "recomp", "from", "to", "CellSelection", "handleKeyDown", "keydownHandler", "arrow", "shiftArrow", "deleteCellSelection", "maybeSetSelection", "selection", "axis", "dir", "view", "sel", "Selection", "end", "atEndOfCell", "$cell", "$next", "nextCell", "newSel", "cellSel: CellSelection", "cellSel", "$head", "handleTripleClick", "doc", "cellAround", "handlePaste", "_", "isInTable", "selectionCell", "handleMouseDown", "startEvent", "startDOMCell", "domInCell", "$anchor", "setCellSelection", "_cellUnderMouse", "cellUnderMouse", "$anchor$1", "event", "starting", "tableEditingKey", "inSameTable", "stop", "move", "_event", "anchor", "TextSelection", "d", "parent", "cellPos", "dirStr: 'up' | 'down' | 'left' | 'right'", "dirStr", "dom", "mousePos", "inside", "TableView", "node: Node", "defaultCellMinWidth: number", "defaultCellMinWidth", "updateColumnsOnResize", "record", "colgroup", "overrideCol", "overrideValue", "totalWidth", "fixedWidth", "nextDOM", "colwidth", "hasWidth", "cssWidth", "col$1", "after", "_nextDOM$parentNode", "columnResizingPluginKey", "PluginKey", "columnResizing", "handleWidth", "cellMinWidth", "View", "lastColumnResizable", "plugin", "Plugin", "nodeViews", "_plugin$spec", "tableName", "ResizeState", "prev", "pluginState", "handleMouseMove", "handleMouseLeave", "handleDecorations", "activeHandle: number", "dragging: Dragging | false", "activeHandle", "dragging", "action", "handle", "pointsAtCell", "target", "domCellAround", "edgeCell", "updateHandle", "win", "_view$dom$ownerDocume", "currentColWidth", "finish", "event$1", "updateColumnWidth", "draggedWidth", "dragged", "displayColumnWidth", "domWidth", "parts", "side", "offset", "resizeMinWidth", "value", "mapIndex", "attrs", "zeroes", "dom: Node | null", "n", "decorations", "DecorationSet", "_columnResizingPlugin", "Decoration", "tableEditing", "allowTableNodeSelection", "cur", "set", "deleted", "drawCellSelection", "oldState", "normalizeSelection", "fixTables", "normalizeTableCellAlign", "value", "parseAlign", "element", "styleAlign", "attrAlign", "normalizeTableCellAlignFromAttributes", "attributes", "createAlignAttribute", "align", "isValidCSSStyleValue", "parseColgroupWidth", "row", "table", "cellIndex", "width", "_table$querySelectorA", "parseColwidth", "colwidth", "COLLAPSIBLE_WHITESPACE", "isEmptyCellElement", "_element$textContent", "fillEmptyCellContent", "cellType", "filled", "omitDefaultSpanAttribute", "renderedAttributes", "name", "TableCell", "Node", "node", "_node", "schema", "HTMLAttributes", "mergeAttributes", "TableHeader", "TableRow", "getColStyleDeclaration", "minWidth", "updateColumns", "colgroup", "cellMinWidth", "overrideCol", "overrideValue", "totalWidth", "fixedWidth", "nextDOM", "i", "col", "colspan", "j", "hasWidth", "cssWidth", "propertyKey", "propertyValue", "colElement", "after", "_nextDOM$parentNode", "hasUserWidth", "TableView", "_view", "key", "mutation", "target", "isInsideWrapper", "isInsideContent", "createColGroup", "cols", "property", "tableWidth", "tableMinWidth", "createCell", "cellContent", "getTableNodeTypes", "roles", "type", "nodeType", "createTable", "rowsCount", "colsCount", "withHeaderRow", "types", "headerCells", "cells", "index", "cell", "headerCell", "rows", "isCellSelection", "CellSelection", "deleteTableWhenAllCellsSelected", "editor", "selection", "cellCount", "findParentNodeClosestToPos", "keepCursorInTable", "tr", "tablePos", "mappedTablePos", "stillInTable", "tableNode", "endOfTable", "TextSelection", "escapeTableCellPipes", "line", "result", "i", "runLen", "j", "found", "closeLen", "spanContent", "match", "preprocessTablePipes", "src", "collapseWhitespace", "s", "replaceCellLineSeparator", "value", "cellLineSeparator", "escapePipesInCellText", "text", "renderTableToMarkdown", "node", "h", "options", "rows", "rowNode", "cells", "cellNode", "raw", "child", "isHeader", "align", "normalizeTableCellAlignFromAttributes", "columnCount", "max", "r", "colWidths", "len", "_r$i", "pad", "width", "headerRow", "hasHeader", "c", "colAlignments", "_r$i2", "out", "headerTexts", "_", "t", "w", "index", "dashCount", "alignment", "preserveCellSelectionOnContextMenuPluginKey", "PluginKey", "resolveClickPos", "view", "event", "coords", "isPosInsideCellSelection", "selection", "pos", "inside", "cell", "cellPos", "preserveCellSelectionOnContextMenu", "Plugin", "isCellSelection", "clickPos", "Table", "Node", "TableView", "HTMLAttributes", "colgroup", "tableWidth", "tableMinWidth", "createColGroup", "userStyles", "getTableStyle", "table", "mergeAttributes", "token", "alignments", "headerCells", "normalizeTableCellAlign", "_alignments$index", "attrs", "row", "bodyCells", "_alignments$index2", "lines", "sep", "_tokens", "helper", "blankLineIndex", "candidate", "candidateLines", "preprocessed", "tableToken", "lineCount", "cols", "withHeaderRow", "tr", "dispatch", "editor", "createTable", "offset", "TextSelection", "state", "addColumnBefore", "addColumnAfter", "findParentNodeClosestToPos", "deleteColumn", "keepCursorInTable", "addRowBefore", "addRowAfter", "deleteRow", "deleteTable", "mergeCells", "splitCell", "toggleHeader", "toggleHeaderCell", "name", "setCellAttr", "goToNextCell", "fixTables", "position", "CellSelection", "deleteTableWhenAllCellsSelected", "columnResizing", "tableEditing", "View", "mergedAttributes", "extension", "context", "callOrReturn", "getExtensionField", "TableKit", "Extension", "extensions", "TableCell", "TableHeader", "TableRow", "src_default", "TaskList", "src_default", "TaskItem", "TextAlign", "Extension", "element", "alignment", "attributes", "isValidCSSStyleValue", "commands", "type", "response", "editor", "src_default", "extend", "destination", "i", "source", "key", "repeat", "character", "count", "trimLeadingNewlines", "string", "trimTrailingNewlines", "indexEnd", "trimNewlines", "blockElements", "isBlock", "node", "is", "voidElements", "isVoid", "hasVoid", "has", "meaningfulWhenBlankElements", "isMeaningfulWhenBlank", "hasMeaningfulWhenBlank", "tagNames", "tagName", "markdownEscapes", "escapeMarkdown", "accumulator", "escape", "rules", "content", "options", "hLevel", "underline", "parent", "prefix", "start", "index", "isParagraph", "className", "language", "code", "fenceChar", "fenceSize", "fenceInCodeRegex", "match", "fence", "href", "escapeLinkDestination", "title", "escapeLinkTitle", "cleanAttribute", "titlePart", "replacement", "reference", "id", "references", "hasSiblings", "isCodeBlock", "extraSpace", "delimiter", "matches", "alt", "src", "attribute", "escaped", "Rules", "rule", "filter", "findRule", "fn", "filterValue", "collapseWhitespace", "element", "isPre", "prevText", "keepLeadingWs", "prev", "next", "text", "remove", "nextNode", "current", "root", "canParseHTMLNatively", "Parser", "canParse", "createHTMLParser", "shouldUseActiveX", "doc", "useActiveX", "HTMLParser", "RootNode", "input", "htmlParser", "isPreOrCode", "_htmlParser", "Node", "isBlank", "flankingWhitespace", "edges", "edgeWhitespace", "isFlankedByWhitespace", "m", "side", "sibling", "regExp", "isFlanked", "reduce", "TurndownService", "defaults", "canConvert", "output", "process", "postProcess", "plugin", "parentNode", "self", "replacementForNode", "join", "whitespace", "tail", "s1", "s2", "nls", "separator", "highlightRegExp", "highlightedCodeBlock", "turndownService", "node", "firstChild", "content", "options", "className", "language", "strikethrough", "indexOf", "every", "rules", "cell", "borderCells", "alignMap", "isHeadingRow", "border", "align", "tr", "parentNode", "isFirstTbody", "element", "previousSibling", "index", "prefix", "tables", "key", "taskListItems", "gfm", "chartFigure", "validateChart", "safeImageURL", "safeLink", "sanitizeHTML", "markdown", "TurndownService", "gfm", "node", "_", "content", "toMarkdown", "html", "serializeShareHTML", "Comment", "Mark", "el", "attrs", "HTMLAttributes", "mergeAttributes", "Chart", "Node", "dom", "hint", "LocalImage", "src_default", "createEditor", "element", "onUpdate", "onSelection", "onLink", "onComment", "onMapping", "editor", "Editor", "Table", "TableRow", "TableHeader", "TableCell", "view", "event", "text", "transaction"]
}
