UNPKG

@remirror/core

Version:

Where your quest to create a world class editing experience begins.

4,048 lines 154 kB
var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __defNormalProp = (obj, key2, value) => key2 in obj ? __defProp(obj, key2, { enumerable: true, configurable: true, writable: true, value }) : obj[key2] = value;
var __export = (target, all) => {
  for (var name in all)
    __defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
  if (from && typeof from === "object" || typeof from === "function") {
    for (let key2 of __getOwnPropNames(from))
      if (!__hasOwnProp.call(to, key2) && key2 !== except)
        __defProp(to, key2, { get: () => from[key2], enumerable: !(desc = __getOwnPropDesc(from, key2)) || desc.enumerable });
  }
  return to;
};
var __reExport = (target, mod, secondTarget) => (__copyProps(target, mod, "default"), secondTarget && __copyProps(secondTarget, mod, "default"));
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, mod));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var __decorateClass = (decorators, target, key2, kind) => {
  var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc(target, key2) : target;
  for (var i = decorators.length - 1, decorator; i >= 0; i--)
    if (decorator = decorators[i])
      result = (kind ? decorator(target, key2, result) : decorator(result)) || result;
  if (kind && result)
    __defProp(target, key2, result);
  return result;
};
var __publicField = (obj, key2, value) => {
  __defNormalProp(obj, typeof key2 !== "symbol" ? key2 + "" : key2, value);
  return value;
};
var __accessCheck = (obj, member, msg) => {
  if (!member.has(obj))
    throw TypeError("Cannot " + msg);
};
var __privateGet = (obj, member, getter) => {
  __accessCheck(obj, member, "read from private field");
  return getter ? getter.call(obj) : member.get(obj);
};
var __privateAdd = (obj, member, value) => {
  if (member.has(obj))
    throw TypeError("Cannot add the same private member more than once");
  member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
};
var __privateSet = (obj, member, value, setter) => {
  __accessCheck(obj, member, "write to private field");
  setter ? setter.call(obj, value) : member.set(obj, value);
  return value;
};

// packages/remirror__core/src/index.ts
var src_exports = {};
__export(src_exports, {
  AttributesExtension: () => AttributesExtension,
  CommandsExtension: () => CommandsExtension,
  DEFAULT_SHORTCUTS: () => DEFAULT_SHORTCUTS,
  DecorationsExtension: () => DecorationsExtension,
  DelayedCommand: () => DelayedCommand,
  DocChangedExtension: () => DocChangedExtension,
  Framework: () => Framework,
  GOOGLE_DOC_SHORTCUTS: () => GOOGLE_DOC_SHORTCUTS,
  HelpersExtension: () => HelpersExtension,
  InputRulesExtension: () => InputRulesExtension,
  KeymapExtension: () => KeymapExtension,
  MarkExtension: () => MarkExtension,
  MetaExtension: () => MetaExtension,
  NodeExtension: () => NodeExtension,
  NodeViewsExtension: () => NodeViewsExtension,
  PasteRulesExtension: () => PasteRulesExtension,
  PlainExtension: () => PlainExtension,
  PluginsExtension: () => PluginsExtension,
  RemirrorManager: () => RemirrorManager,
  SchemaExtension: () => SchemaExtension,
  SuggestExtension: () => SuggestExtension,
  TagsExtension: () => TagsExtension,
  UploadExtension: () => UploadExtension,
  builtinPreset: () => builtinPreset,
  command: () => command,
  delayedCommand: () => delayedCommand,
  extension: () => extension,
  extensionDecorator: () => extensionDecorator,
  findUploadPlaceholderPayload: () => findUploadPlaceholderPayload,
  findUploadPlaceholderPos: () => findUploadPlaceholderPos,
  hasUploadingFile: () => hasUploadingFile,
  helper: () => helper,
  insertText: () => insertText,
  isDelayedValue: () => isDelayedValue,
  isExtension: () => isExtension,
  isExtensionConstructor: () => isExtensionConstructor,
  isExtensionTag: () => isExtensionTag,
  isMarkExtension: () => isMarkExtension,
  isNodeExtension: () => isNodeExtension,
  isPlainExtension: () => isPlainExtension,
  isRemirrorManager: () => isRemirrorManager,
  keyBinding: () => keyBinding,
  keyboardShortcuts: () => keyboardShortcuts,
  mutateDefaultExtensionOptions: () => mutateDefaultExtensionOptions,
  setUploadPlaceholderAction: () => setUploadPlaceholderAction,
  toggleMark: () => toggleMark,
  uploadFile: () => uploadFile
});
module.exports = __toCommonJS(src_exports);

// packages/remirror__core/src/builtins/attributes-extension.ts
var import_core_helpers5 = require("@remirror/core-helpers");

// packages/remirror__core/src/extension/extension.ts
var import_core_constants3 = require("@remirror/core-constants");
var import_core_helpers3 = require("@remirror/core-helpers");
var import_core_utils2 = require("@remirror/core-utils");

// packages/remirror__core/src/extension/base-class.ts
var import_core_constants2 = require("@remirror/core-constants");
var import_core_helpers2 = require("@remirror/core-helpers");
var import_core_utils = require("@remirror/core-utils");

// packages/remirror__core/src/helpers.ts
var import_core_constants = require("@remirror/core-constants");
var import_core_helpers = require("@remirror/core-helpers");
function defaultEquals(valueA, valueB) {
  return valueA === valueB;
}
function getChangedOptions(props) {
  const { previousOptions, update, equals = defaultEquals } = props;
  const next = (0, import_core_helpers.freeze)({ ...previousOptions, ...update });
  const changes = (0, import_core_helpers.object)();
  const optionKeys = (0, import_core_helpers.keys)(previousOptions);
  for (const key2 of optionKeys) {
    const previousValue = previousOptions[key2];
    const value = next[key2];
    if (equals(previousValue, value)) {
      changes[key2] = { changed: false };
      continue;
    }
    changes[key2] = { changed: true, previousValue, value };
  }
  const pickChanged = (keys3) => {
    const picked = (0, import_core_helpers.object)();
    for (const key2 of keys3) {
      const item = changes[key2];
      if (item == null ? void 0 : item.changed) {
        picked[key2] = item.value;
      }
    }
    return picked;
  };
  return { changes: (0, import_core_helpers.freeze)(changes), options: next, pickChanged };
}
var codeLabelMap = {
  [import_core_constants.ErrorConstant.DUPLICATE_HELPER_NAMES]: "helper method",
  [import_core_constants.ErrorConstant.DUPLICATE_COMMAND_NAMES]: "command method"
};
function throwIfNameNotUnique(props) {
  const { name, set, code } = props;
  const label = codeLabelMap[code];
  (0, import_core_helpers.invariant)(!set.has(name), {
    code,
    message: `There is a naming conflict for the name: ${name} used in this '${label}'. Please rename or remove from the editor to avoid runtime errors.`
  });
  set.add(name);
}

// packages/remirror__core/src/extension/base-class.ts
var IGNORE = "__IGNORE__";
var GENERAL_OPTIONS = "__ALL__";
var BaseClass = class {
  constructor(defaultOptions2, ...[options]) {
    __publicField(this, "~O", {});
    __publicField(this, "_initialOptions");
    __publicField(this, "_dynamicKeys");
    __publicField(this, "_options");
    __publicField(this, "_mappedHandlers");
    __publicField(this, "onAddCustomHandler");
    this._mappedHandlers = (0, import_core_helpers2.object)();
    this.populateMappedHandlers();
    this._options = this._initialOptions = (0, import_core_helpers2.deepMerge)(defaultOptions2, this.constructor.defaultOptions, options != null ? options : (0, import_core_helpers2.object)(), this.createDefaultHandlerOptions());
    this._dynamicKeys = this.getDynamicKeys();
    this.init();
  }
  get options() {
    return this._options;
  }
  get dynamicKeys() {
    return this._dynamicKeys;
  }
  get initialOptions() {
    return this._initialOptions;
  }
  init() {
  }
  getDynamicKeys() {
    const dynamicKeys = [];
    const { customHandlerKeys, handlerKeys, staticKeys } = this.constructor;
    for (const key2 of (0, import_core_helpers2.keys)(this._options)) {
      if (staticKeys.includes(key2) || handlerKeys.includes(key2) || customHandlerKeys.includes(key2)) {
        continue;
      }
      dynamicKeys.push(key2);
    }
    return dynamicKeys;
  }
  ensureAllKeysAreDynamic(update) {
    if (import_core_utils.environment.isProduction) {
      return;
    }
    const invalid = [];
    for (const key2 of (0, import_core_helpers2.keys)(update)) {
      if (this._dynamicKeys.includes(key2)) {
        continue;
      }
      invalid.push(key2);
    }
    (0, import_core_helpers2.invariant)((0, import_core_helpers2.isEmptyArray)(invalid), {
      code: import_core_constants2.ErrorConstant.INVALID_SET_EXTENSION_OPTIONS,
      message: `Invalid properties passed into the 'setOptions()' method: ${JSON.stringify(invalid)}.`
    });
  }
  setOptions(update) {
    var _a;
    const previousOptions = this.getDynamicOptions();
    this.ensureAllKeysAreDynamic(update);
    const { changes, options, pickChanged } = getChangedOptions({
      previousOptions,
      update
    });
    this.updateDynamicOptions(options);
    (_a = this.onSetOptions) == null ? void 0 : _a.call(this, {
      reason: "set",
      changes,
      options,
      pickChanged,
      initialOptions: this._initialOptions
    });
  }
  resetOptions() {
    var _a;
    const previousOptions = this.getDynamicOptions();
    const { changes, options, pickChanged } = getChangedOptions({
      previousOptions,
      update: this._initialOptions
    });
    this.updateDynamicOptions(options);
    (_a = this.onSetOptions) == null ? void 0 : _a.call(this, {
      reason: "reset",
      options,
      changes,
      pickChanged,
      initialOptions: this._initialOptions
    });
  }
  getDynamicOptions() {
    return (0, import_core_helpers2.omit)(this._options, [
      ...this.constructor.customHandlerKeys,
      ...this.constructor.handlerKeys
    ]);
  }
  updateDynamicOptions(options) {
    this._options = { ...this._options, ...options };
  }
  populateMappedHandlers() {
    for (const key2 of this.constructor.handlerKeys) {
      this._mappedHandlers[key2] = [];
    }
  }
  createDefaultHandlerOptions() {
    const methods = (0, import_core_helpers2.object)();
    for (const key2 of this.constructor.handlerKeys) {
      methods[key2] = (...args) => {
        var _a;
        const { handlerKeyOptions } = this.constructor;
        const reducer = (_a = handlerKeyOptions[key2]) == null ? void 0 : _a.reducer;
        let returnValue = reducer == null ? void 0 : reducer.getDefault(...args);
        for (const [, handler] of this._mappedHandlers[key2]) {
          const value = handler(...args);
          returnValue = reducer ? reducer.accumulator(returnValue, value, ...args) : value;
          if (shouldReturnEarly(handlerKeyOptions, returnValue, key2)) {
            return returnValue;
          }
        }
        return returnValue;
      };
    }
    return methods;
  }
  addHandler(key2, method, priority = import_core_constants2.ExtensionPriority.Default) {
    this._mappedHandlers[key2].push([priority, method]);
    this.sortHandlers(key2);
    return () => this._mappedHandlers[key2] = this._mappedHandlers[key2].filter(([, handler]) => handler !== method);
  }
  hasHandlers(key2) {
    var _a;
    return ((_a = this._mappedHandlers[key2]) != null ? _a : []).length > 0;
  }
  sortHandlers(key2) {
    this._mappedHandlers[key2] = (0, import_core_helpers2.sort)(this._mappedHandlers[key2], ([a], [z]) => z - a);
  }
  addCustomHandler(key2, value) {
    var _a, _b;
    return (_b = (_a = this.onAddCustomHandler) == null ? void 0 : _a.call(this, { [key2]: value })) != null ? _b : import_core_helpers2.noop;
  }
};
__publicField(BaseClass, "defaultOptions", {});
__publicField(BaseClass, "staticKeys", []);
__publicField(BaseClass, "handlerKeys", []);
__publicField(BaseClass, "handlerKeyOptions", {});
__publicField(BaseClass, "customHandlerKeys", []);
function shouldReturnEarly(handlerKeyOptions, returnValue, handlerKey) {
  const { [GENERAL_OPTIONS]: generalOptions } = handlerKeyOptions;
  const handlerOptions = handlerKeyOptions[handlerKey];
  if (!generalOptions && !handlerOptions) {
    return false;
  }
  if (handlerOptions && handlerOptions.earlyReturnValue !== IGNORE && ((0, import_core_helpers2.isFunction)(handlerOptions.earlyReturnValue) ? handlerOptions.earlyReturnValue(returnValue) === true : returnValue === handlerOptions.earlyReturnValue)) {
    return true;
  }
  if (generalOptions && generalOptions.earlyReturnValue !== IGNORE && ((0, import_core_helpers2.isFunction)(generalOptions.earlyReturnValue) ? generalOptions.earlyReturnValue(returnValue) === true : returnValue === generalOptions.earlyReturnValue)) {
    return true;
  }
  return false;
}

// packages/remirror__core/src/extension/extension.ts
var Extension = class extends BaseClass {
  constructor(...args) {
    super(defaultOptions, ...args);
    __publicField(this, "priorityOverride");
    __publicField(this, "_extensions");
    __publicField(this, "extensionMap");
    __publicField(this, "_store");
    __publicField(this, "~E", {});
    this._extensions = (0, import_core_helpers3.uniqueBy)(this.createExtensions(), (extension2) => extension2.constructor);
    this.extensionMap = /* @__PURE__ */ new Map();
    for (const extension2 of this._extensions) {
      this.extensionMap.set(extension2.constructor, extension2);
    }
  }
  get priority() {
    var _a, _b;
    return (_b = (_a = this.priorityOverride) != null ? _a : this.options.priority) != null ? _b : this.constructor.defaultPriority;
  }
  get constructorName() {
    return `${(0, import_core_helpers3.pascalCase)(this.name)}Extension`;
  }
  get store() {
    (0, import_core_helpers3.invariant)(this._store, {
      code: import_core_constants3.ErrorConstant.MANAGER_PHASE_ERROR,
      message: `An error occurred while attempting to access the 'extension.store' when the Manager has not yet set created the lifecycle methods.`
    });
    return (0, import_core_helpers3.freeze)(this._store, { requireKeys: true });
  }
  get extensions() {
    return this._extensions;
  }
  replaceChildExtension(constructor, extension2) {
    if (!this.extensionMap.has(constructor)) {
      return;
    }
    this.extensionMap.set(constructor, extension2);
    this._extensions = this.extensions.map((currentExtension) => extension2.constructor === constructor ? extension2 : currentExtension);
  }
  createExtensions() {
    return [];
  }
  getExtension(Constructor) {
    const extension2 = this.extensionMap.get(Constructor);
    (0, import_core_helpers3.invariant)(extension2, {
      code: import_core_constants3.ErrorConstant.INVALID_GET_EXTENSION,
      message: `'${Constructor.name}' does not exist within the preset: '${this.name}'`
    });
    return extension2;
  }
  isOfType(Constructor) {
    return this.constructor === Constructor;
  }
  setStore(store) {
    if (this._store) {
      return;
    }
    this._store = store;
  }
  clone(...args) {
    return new this.constructor(...args);
  }
  setPriority(priority) {
    this.priorityOverride = priority;
  }
};
__publicField(Extension, "defaultPriority", import_core_constants3.ExtensionPriority.Default);
var PlainExtension = class extends Extension {
  static get [import_core_constants3.__INTERNAL_REMIRROR_IDENTIFIER_KEY__]() {
    return import_core_constants3.RemirrorIdentifier.PlainExtensionConstructor;
  }
  get [import_core_constants3.__INTERNAL_REMIRROR_IDENTIFIER_KEY__]() {
    return import_core_constants3.RemirrorIdentifier.PlainExtension;
  }
};
var MarkExtension = class extends Extension {
  static get [import_core_constants3.__INTERNAL_REMIRROR_IDENTIFIER_KEY__]() {
    return import_core_constants3.RemirrorIdentifier.MarkExtensionConstructor;
  }
  get [import_core_constants3.__INTERNAL_REMIRROR_IDENTIFIER_KEY__]() {
    return import_core_constants3.RemirrorIdentifier.MarkExtension;
  }
  get type() {
    return (0, import_core_helpers3.assertGet)(this.store.schema.marks, this.name);
  }
  constructor(...args) {
    super(...args);
  }
};
__publicField(MarkExtension, "disableExtraAttributes", false);
var NodeExtension = class extends Extension {
  static get [import_core_constants3.__INTERNAL_REMIRROR_IDENTIFIER_KEY__]() {
    return import_core_constants3.RemirrorIdentifier.NodeExtensionConstructor;
  }
  get [import_core_constants3.__INTERNAL_REMIRROR_IDENTIFIER_KEY__]() {
    return import_core_constants3.RemirrorIdentifier.NodeExtension;
  }
  get type() {
    return (0, import_core_helpers3.assertGet)(this.store.schema.nodes, this.name);
  }
  constructor(...args) {
    super(...args);
  }
};
__publicField(NodeExtension, "disableExtraAttributes", false);
var defaultOptions = {
  priority: void 0,
  extraAttributes: {},
  disableExtraAttributes: false,
  exclude: {}
};
function mutateDefaultExtensionOptions(mutatorMethod) {
  mutatorMethod(defaultOptions);
}
function isExtension(value) {
  return (0, import_core_utils2.isRemirrorType)(value) && (0, import_core_utils2.isIdentifierOfType)(value, [
    import_core_constants3.RemirrorIdentifier.PlainExtension,
    import_core_constants3.RemirrorIdentifier.MarkExtension,
    import_core_constants3.RemirrorIdentifier.NodeExtension
  ]);
}
function isExtensionConstructor(value) {
  return (0, import_core_utils2.isRemirrorType)(value) && (0, import_core_utils2.isIdentifierOfType)(value, [
    import_core_constants3.RemirrorIdentifier.PlainExtensionConstructor,
    import_core_constants3.RemirrorIdentifier.MarkExtensionConstructor,
    import_core_constants3.RemirrorIdentifier.NodeExtensionConstructor
  ]);
}
function isPlainExtension(value) {
  return (0, import_core_utils2.isRemirrorType)(value) && (0, import_core_utils2.isIdentifierOfType)(value, import_core_constants3.RemirrorIdentifier.PlainExtension);
}
function isNodeExtension(value) {
  return (0, import_core_utils2.isRemirrorType)(value) && (0, import_core_utils2.isIdentifierOfType)(value, import_core_constants3.RemirrorIdentifier.NodeExtension);
}
function isMarkExtension(value) {
  return (0, import_core_utils2.isRemirrorType)(value) && (0, import_core_utils2.isIdentifierOfType)(value, import_core_constants3.RemirrorIdentifier.MarkExtension);
}

// packages/remirror__core/src/extension/extension-decorator.ts
var import_core_helpers4 = require("@remirror/core-helpers");
function extension(options) {
  return (ReadonlyConstructor) => {
    const {
      defaultOptions: defaultOptions2,
      customHandlerKeys,
      handlerKeys,
      staticKeys,
      defaultPriority,
      handlerKeyOptions,
      ...rest
    } = options;
    const Constructor = (0, import_core_helpers4.Cast)(ReadonlyConstructor);
    if (defaultOptions2) {
      Constructor.defaultOptions = defaultOptions2;
    }
    if (defaultPriority) {
      Constructor.defaultPriority = defaultPriority;
    }
    if (handlerKeyOptions) {
      Constructor.handlerKeyOptions = handlerKeyOptions;
    }
    Constructor.staticKeys = staticKeys != null ? staticKeys : [];
    Constructor.handlerKeys = handlerKeys != null ? handlerKeys : [];
    Constructor.customHandlerKeys = customHandlerKeys != null ? customHandlerKeys : [];
    for (const [key2, value] of Object.entries(rest)) {
      if (Constructor[key2]) {
        continue;
      }
      Constructor[key2] = value;
    }
    return (0, import_core_helpers4.Cast)(Constructor);
  };
}
var extensionDecorator = extension;

// packages/remirror__core/src/builtins/attributes-extension.ts
var AttributesExtension = class extends PlainExtension {
  constructor() {
    super(...arguments);
    __publicField(this, "attributeList", []);
    __publicField(this, "attributeObject", (0, import_core_helpers5.object)());
    __publicField(this, "updateAttributes", (triggerUpdate = true) => {
      this.transformAttributes();
      if (triggerUpdate) {
        this.store.commands.forceUpdate("attributes");
      }
    });
  }
  get name() {
    return "attributes";
  }
  onCreate() {
    this.transformAttributes();
    this.store.setExtensionStore("updateAttributes", this.updateAttributes);
  }
  transformAttributes() {
    var _a, _b, _c, _d;
    this.attributeObject = (0, import_core_helpers5.object)();
    if ((_a = this.store.managerSettings.exclude) == null ? void 0 : _a.attributes) {
      this.store.setStoreKey("attributes", this.attributeObject);
      return;
    }
    this.attributeList = [];
    for (const extension2 of this.store.extensions) {
      if ((_b = extension2.options.exclude) == null ? void 0 : _b.attributes) {
        continue;
      }
      const createdAttributes = (_c = extension2.createAttributes) == null ? void 0 : _c.call(extension2);
      const attributes = {
        ...createdAttributes,
        class: (0, import_core_helpers5.cx)(...(_d = extension2.classNames) != null ? _d : [], createdAttributes == null ? void 0 : createdAttributes.class)
      };
      this.attributeList.unshift(attributes);
    }
    for (const attributes of this.attributeList) {
      this.attributeObject = {
        ...this.attributeObject,
        ...attributes,
        class: (0, import_core_helpers5.cx)(this.attributeObject.class, attributes.class)
      };
    }
    this.store.setStoreKey("attributes", this.attributeObject);
  }
};

// packages/remirror__core/src/builtins/builtin-decorators.ts
function helper(options = {}) {
  return (target, propertyKey, _descriptor) => {
    var _a;
    ((_a = target.decoratedHelpers) != null ? _a : target.decoratedHelpers = {})[propertyKey] = options;
  };
}
function command(options = {}) {
  return (target, propertyKey, _descriptor) => {
    var _a;
    ((_a = target.decoratedCommands) != null ? _a : target.decoratedCommands = {})[propertyKey] = options;
  };
}
function keyBinding(options) {
  return (target, propertyKey, _descriptor) => {
    var _a;
    ((_a = target.decoratedKeybindings) != null ? _a : target.decoratedKeybindings = {})[propertyKey] = options;
  };
}

// packages/remirror__core/src/builtins/builtin-preset.ts
var import_core_helpers18 = require("@remirror/core-helpers");

// packages/remirror__core/src/builtins/commands-extension.ts
var import_core_constants5 = require("@remirror/core-constants");
var import_core_helpers7 = require("@remirror/core-helpers");
var import_core_utils4 = require("@remirror/core-utils");
var import_messages = require("@remirror/messages");
var import_model = require("@remirror/pm/model");
var import_state = require("@remirror/pm/state");

// packages/remirror__core/src/commands.ts
var import_core_constants4 = require("@remirror/core-constants");
var import_core_helpers6 = require("@remirror/core-helpers");
var import_core_utils3 = require("@remirror/core-utils");
var import_commands = require("@remirror/pm/commands");
function isDelayedValue(value) {
  return (0, import_core_helpers6.isFunction)(value) || (0, import_core_helpers6.isPromise)(value);
}
function delayedCommand({
  immediate,
  promise,
  onDone,
  onFail
}) {
  return (props) => {
    const { view } = props;
    if ((immediate == null ? void 0 : immediate(props)) === false) {
      return false;
    }
    if (!view) {
      return true;
    }
    const deferred = (0, import_core_helpers6.isFunction)(promise) ? promise() : promise;
    deferred.then((value) => {
      onDone({ state: view.state, tr: view.state.tr, dispatch: view.dispatch, view, value });
    }).catch(() => {
      onFail == null ? void 0 : onFail({ state: view.state, tr: view.state.tr, dispatch: view.dispatch, view });
    });
    return true;
  };
}
var DelayedCommand = class {
  constructor(promiseCreator) {
    this.promiseCreator = promiseCreator;
    __publicField(this, "failureHandlers", []);
    __publicField(this, "successHandlers", []);
    __publicField(this, "validateHandlers", []);
    __publicField(this, "generateCommand", () => {
      return (props) => {
        let isValid = true;
        const { view, tr, dispatch } = props;
        if (!view) {
          return false;
        }
        for (const handler of this.validateHandlers) {
          if (!handler({ ...props, dispatch: () => {
          } })) {
            isValid = false;
            break;
          }
        }
        if (!dispatch || !isValid) {
          return isValid;
        }
        const deferred = this.promiseCreator(props);
        deferred.then((value) => {
          this.runHandlers(this.successHandlers, {
            value,
            state: view.state,
            tr: view.state.tr,
            dispatch: view.dispatch,
            view
          });
        }).catch((error) => {
          this.runHandlers(this.failureHandlers, {
            error,
            state: view.state,
            tr: view.state.tr,
            dispatch: view.dispatch,
            view
          });
        });
        dispatch(tr);
        return true;
      };
    });
  }
  validate(handler, method = "push") {
    this.validateHandlers[method](handler);
    return this;
  }
  success(handler, method = "push") {
    this.successHandlers[method](handler);
    return this;
  }
  failure(handler, method = "push") {
    this.failureHandlers[method](handler);
    return this;
  }
  runHandlers(handlers, param) {
    var _a;
    for (const handler of handlers) {
      if (!handler({ ...param, dispatch: () => {
      } })) {
        break;
      }
    }
    (_a = param.dispatch) == null ? void 0 : _a.call(param, param.tr);
  }
};
function toggleMark(props) {
  const { type, attrs, range, selection } = props;
  return (props2) => {
    var _a;
    const { dispatch, tr, state } = props2;
    const markType = (0, import_core_helpers6.isString)(type) ? state.schema.marks[type] : type;
    (0, import_core_helpers6.invariant)(markType, {
      code: import_core_constants4.ErrorConstant.SCHEMA,
      message: `Mark type: ${type} does not exist on the current schema.`
    });
    if (range || selection) {
      const { from, to } = (0, import_core_utils3.getTextSelection)((_a = selection != null ? selection : range) != null ? _a : tr.selection, tr.doc);
      (0, import_core_utils3.isMarkActive)({ trState: tr, type, ...range }) ? dispatch == null ? void 0 : dispatch(tr.removeMark(from, to, markType)) : dispatch == null ? void 0 : dispatch(tr.addMark(from, to, markType.create(attrs)));
      return true;
    }
    return (0, import_core_utils3.convertCommand)((0, import_commands.toggleMark)(markType, attrs))(props2);
  };
}
function markApplies(type, doc, ranges) {
  for (const { $from, $to } of ranges) {
    let markIsAllowed = $from.depth === 0 ? doc.type.allowsMarkType(type) : false;
    doc.nodesBetween($from.pos, $to.pos, (node) => {
      if (markIsAllowed) {
        return false;
      }
      markIsAllowed = node.inlineContent && node.type.allowsMarkType(type);
      return;
    });
    if (markIsAllowed) {
      return true;
    }
  }
  return false;
}
function applyMark(type, attrs, selectionPoint) {
  return ({ tr, dispatch, state }) => {
    const selection = (0, import_core_utils3.getTextSelection)(selectionPoint != null ? selectionPoint : tr.selection, tr.doc);
    const $cursor = (0, import_core_utils3.getCursor)(selection);
    const markType = (0, import_core_helpers6.isString)(type) ? state.schema.marks[type] : type;
    (0, import_core_helpers6.invariant)(markType, {
      code: import_core_constants4.ErrorConstant.SCHEMA,
      message: `Mark type: ${type} does not exist on the current schema.`
    });
    if (selection.empty && !$cursor || !markApplies(markType, tr.doc, selection.ranges)) {
      return false;
    }
    if (!dispatch) {
      return true;
    }
    if ($cursor) {
      tr.removeStoredMark(markType);
      if (attrs) {
        tr.addStoredMark(markType.create(attrs));
      }
      dispatch(tr);
      return true;
    }
    let containsMark = false;
    for (const { $from, $to } of selection.ranges) {
      if (containsMark) {
        break;
      }
      containsMark = tr.doc.rangeHasMark($from.pos, $to.pos, markType);
    }
    for (const { $from, $to } of selection.ranges) {
      if (containsMark) {
        tr.removeMark($from.pos, $to.pos, markType);
      }
      if (attrs) {
        tr.addMark($from.pos, $to.pos, markType.create(attrs));
      }
    }
    dispatch(tr);
    return true;
  };
}
function insertText(text, options = {}) {
  return ({ tr, dispatch, state }) => {
    const schema = state.schema;
    const selection = tr.selection;
    const { from = selection.from, to = from != null ? from : selection.to, marks = {} } = options;
    if (!dispatch) {
      return true;
    }
    tr.insertText(text, from, to);
    const end = (0, import_core_helpers6.assertGet)(tr.steps, tr.steps.length - 1).getMap().map(to);
    for (const [markName, attributes] of (0, import_core_helpers6.entries)(marks)) {
      tr.addMark(from, end, (0, import_core_helpers6.assertGet)(schema.marks, markName).create(attributes));
    }
    dispatch(tr);
    return true;
  };
}

// packages/remirror__core/src/builtins/commands-extension.ts
var CommandsExtension = class extends PlainExtension {
  constructor() {
    super(...arguments);
    __publicField(this, "_transaction");
    __publicField(this, "decorated", /* @__PURE__ */ new Map());
    __publicField(this, "forceUpdateTransaction", (tr, ...keys3) => {
      const { forcedUpdates } = this.getCommandMeta(tr);
      this.setCommandMeta(tr, { forcedUpdates: (0, import_core_helpers7.uniqueArray)([...forcedUpdates, ...keys3]) });
      return tr;
    });
  }
  get name() {
    return "commands";
  }
  get transaction() {
    const state = this.store.getState();
    if (!this._transaction) {
      this._transaction = state.tr;
    }
    const isValid = this._transaction.before.eq(state.doc);
    const hasSteps = !(0, import_core_helpers7.isEmptyArray)(this._transaction.steps);
    if (!isValid) {
      const tr = state.tr;
      if (hasSteps) {
        for (const step of this._transaction.steps) {
          tr.step(step);
        }
      }
      this._transaction = tr;
    }
    return this._transaction;
  }
  onCreate() {
    this.store.setStoreKey("getForcedUpdates", this.getForcedUpdates.bind(this));
  }
  onView(view) {
    var _a, _b, _c;
    const { extensions, helpers } = this.store;
    const commands = (0, import_core_helpers7.object)();
    const names = /* @__PURE__ */ new Set();
    let allDecoratedCommands = (0, import_core_helpers7.object)();
    const chain = (tr) => {
      var _a2;
      const customChain = (0, import_core_helpers7.object)();
      const getTr = () => tr != null ? tr : this.transaction;
      let commandChain = [];
      const getChain = () => commandChain;
      for (const [name, command2] of Object.entries(commands)) {
        if ((_a2 = allDecoratedCommands[name]) == null ? void 0 : _a2.disableChaining) {
          continue;
        }
        customChain[name] = this.chainedFactory({
          chain: customChain,
          command: command2.original,
          getTr,
          getChain
        });
      }
      const dispatch = (transaction) => {
        (0, import_core_helpers7.invariant)(transaction === getTr(), {
          message: "Chaining currently only supports `CommandFunction` methods which do not use the `state.tr` property. Instead you should use the provided `tr` property."
        });
      };
      customChain.run = (options = {}) => {
        const commands2 = commandChain;
        commandChain = [];
        for (const cmd of commands2) {
          if (!cmd(dispatch) && options.exitEarly) {
            return;
          }
        }
        view.dispatch(getTr());
      };
      customChain.tr = () => {
        const commands2 = commandChain;
        commandChain = [];
        for (const cmd of commands2) {
          cmd(dispatch);
        }
        return getTr();
      };
      customChain.enabled = () => {
        for (const cmd of commandChain) {
          if (!cmd()) {
            return false;
          }
        }
        return true;
      };
      return customChain;
    };
    for (const extension2 of extensions) {
      const extensionCommands = (_b = (_a = extension2.createCommands) == null ? void 0 : _a.call(extension2)) != null ? _b : {};
      const decoratedCommands = (_c = extension2.decoratedCommands) != null ? _c : {};
      const active = {};
      allDecoratedCommands = { ...allDecoratedCommands, decoratedCommands };
      for (const [commandName, options] of Object.entries(decoratedCommands)) {
        const shortcut = (0, import_core_helpers7.isString)(options.shortcut) && options.shortcut.startsWith("_|") ? { shortcut: helpers.getNamedShortcut(options.shortcut, extension2.options) } : void 0;
        this.updateDecorated(commandName, { ...options, name: extension2.name, ...shortcut });
        extensionCommands[commandName] = extension2[commandName].bind(extension2);
        if (options.active) {
          active[commandName] = () => {
            var _a2, _b2;
            return (_b2 = (_a2 = options.active) == null ? void 0 : _a2.call(options, extension2.options, this.store)) != null ? _b2 : false;
          };
        }
      }
      if ((0, import_core_helpers7.isEmptyObject)(extensionCommands)) {
        continue;
      }
      this.addCommands({ active, names, commands, extensionCommands });
    }
    const chainProperty = chain();
    for (const [key2, command2] of Object.entries(chainProperty)) {
      chain[key2] = command2;
    }
    this.store.setStoreKey("commands", commands);
    this.store.setStoreKey("chain", chain);
    this.store.setExtensionStore("commands", commands);
    this.store.setExtensionStore("chain", chain);
  }
  onStateUpdate({ state }) {
    this._transaction = state.tr;
  }
  createPlugin() {
    return {};
  }
  customDispatch(command2) {
    return command2;
  }
  insertText(text, options = {}) {
    if ((0, import_core_helpers7.isString)(text)) {
      return insertText(text, options);
    }
    return this.store.createPlaceholderCommand({
      promise: text,
      placeholder: { type: "inline" },
      onSuccess: (value, range, props) => {
        return this.insertText(value, { ...options, ...range })(props);
      }
    }).generateCommand();
  }
  selectText(selection, options = {}) {
    return ({ tr, dispatch }) => {
      const textSelection = (0, import_core_utils4.getTextSelection)(selection, tr.doc);
      const selectionUnchanged = tr.selection.anchor === textSelection.anchor && tr.selection.head === textSelection.head;
      if (selectionUnchanged && !options.forceUpdate) {
        return false;
      }
      dispatch == null ? void 0 : dispatch(tr.setSelection(textSelection));
      return true;
    };
  }
  selectMark(type) {
    return (props) => {
      const { tr } = props;
      const range = (0, import_core_utils4.getMarkRange)(tr.selection.$from, type);
      if (!range) {
        return false;
      }
      return this.store.commands.selectText.original({ from: range.from, to: range.to })(props);
    };
  }
  delete(range) {
    return ({ tr, dispatch }) => {
      const { from, to } = range != null ? range : tr.selection;
      dispatch == null ? void 0 : dispatch(tr.delete(from, to));
      return true;
    };
  }
  emptyUpdate(action) {
    return ({ tr, dispatch }) => {
      if (dispatch) {
        action == null ? void 0 : action();
        dispatch(tr);
      }
      return true;
    };
  }
  forceUpdate(...keys3) {
    return ({ tr, dispatch }) => {
      dispatch == null ? void 0 : dispatch(this.forceUpdateTransaction(tr, ...keys3));
      return true;
    };
  }
  updateNodeAttributes(pos, attrs) {
    return ({ tr, dispatch }) => {
      dispatch == null ? void 0 : dispatch(tr.setNodeMarkup(pos, void 0, attrs));
      return true;
    };
  }
  setContent(content, selection) {
    return (props) => {
      const { tr, dispatch } = props;
      const state = this.store.manager.createState({ content, selection });
      if (!state) {
        return false;
      }
      dispatch == null ? void 0 : dispatch(tr.replaceRangeWith(0, tr.doc.nodeSize - 2, state.doc));
      return true;
    };
  }
  resetContent() {
    return (props) => {
      const { tr, dispatch } = props;
      const doc = this.store.manager.createEmptyDoc();
      if (doc) {
        return this.setContent(doc)(props);
      }
      dispatch == null ? void 0 : dispatch(tr.delete(0, tr.doc.nodeSize));
      return true;
    };
  }
  emptySelection() {
    return ({ tr, dispatch }) => {
      if (tr.selection.empty) {
        return false;
      }
      dispatch == null ? void 0 : dispatch(tr.setSelection(import_state.TextSelection.near(tr.selection.$anchor)));
      return true;
    };
  }
  insertNewLine() {
    return ({ dispatch, tr }) => {
      if (!(0, import_core_utils4.isTextSelection)(tr.selection)) {
        return false;
      }
      dispatch == null ? void 0 : dispatch(tr.insertText("\n"));
      return true;
    };
  }
  insertNode(node, options = {}) {
    return ({ dispatch, tr, state }) => {
      var _a, _b;
      const { attrs, range, selection, replaceEmptyParentBlock = false } = options;
      const { from, to, $from } = (0, import_core_utils4.getTextSelection)((_a = selection != null ? selection : range) != null ? _a : tr.selection, tr.doc);
      if ((0, import_core_utils4.isProsemirrorNode)(node) || (0, import_core_utils4.isProsemirrorFragment)(node)) {
        const pos = $from.before($from.depth);
        dispatch == null ? void 0 : dispatch(replaceEmptyParentBlock && from === to && (0, import_core_utils4.isEmptyBlockNode)($from.parent) ? tr.replaceWith(pos, pos + $from.parent.nodeSize, node) : tr.replaceWith(from, to, node));
        return true;
      }
      const nodeType = (0, import_core_helpers7.isString)(node) ? state.schema.nodes[node] : node;
      (0, import_core_helpers7.invariant)(nodeType, {
        code: import_core_constants5.ErrorConstant.SCHEMA,
        message: `The requested node type ${node} does not exist in the schema.`
      });
      const marks = (_b = options.marks) == null ? void 0 : _b.map((mark) => {
        if (mark instanceof import_model.Mark) {
          return mark;
        }
        const markType = (0, import_core_helpers7.isString)(mark) ? state.schema.marks[mark] : mark;
        (0, import_core_helpers7.invariant)(markType, {
          code: import_core_constants5.ErrorConstant.SCHEMA,
          message: `The requested mark type ${mark} does not exist in the schema.`
        });
        return markType.create();
      });
      const content = nodeType.createAndFill(attrs, (0, import_core_helpers7.isString)(options.content) ? state.schema.text(options.content) : options.content, marks);
      if (!content) {
        return false;
      }
      const isReplacement = from !== to;
      dispatch == null ? void 0 : dispatch(isReplacement ? tr.replaceRangeWith(from, to, content) : tr.insert(from, content));
      return true;
    };
  }
  focus(position) {
    return (props) => {
      const { dispatch, tr } = props;
      const { view } = this.store;
      if (position === false) {
        return false;
      }
      if (view.hasFocus() && (position === void 0 || position === true)) {
        return false;
      }
      if (position === void 0 || position === true) {
        const { from = 0, to = from } = tr.selection;
        position = { from, to };
      }
      if (dispatch) {
        this.delayedFocus();
      }
      return this.selectText(position)(props);
    };
  }
  blur(position) {
    return (props) => {
      const { view } = this.store;
      if (!view.hasFocus()) {
        return false;
      }
      requestAnimationFrame(() => {
        view.dom.blur();
      });
      return position ? this.selectText(position)(props) : true;
    };
  }
  setBlockNodeType(nodeType, attrs, selection, preserveAttrs = true) {
    return (0, import_core_utils4.setBlockType)(nodeType, attrs, selection, preserveAttrs);
  }
  toggleWrappingNode(nodeType, attrs, selection) {
    return (0, import_core_utils4.toggleWrap)(nodeType, attrs, selection);
  }
  toggleBlockNodeItem(toggleProps) {
    return (0, import_core_utils4.toggleBlockItem)(toggleProps);
  }
  wrapInNode(nodeType, attrs, range) {
    return (0, import_core_utils4.wrapIn)(nodeType, attrs, range);
  }
  applyMark(markType, attrs, selection) {
    return applyMark(markType, attrs, selection);
  }
  toggleMark(props) {
    return toggleMark(props);
  }
  removeMark(props) {
    return (0, import_core_utils4.removeMark)(props);
  }
  setMeta(name, value) {
    return ({ tr }) => {
      tr.setMeta(name, value);
      return true;
    };
  }
  selectAll() {
    return this.selectText("all");
  }
  copy() {
    return (props) => {
      if (props.tr.selection.empty) {
        return false;
      }
      if (props.dispatch) {
        document.execCommand("copy");
      }
      return true;
    };
  }
  paste() {
    return this.store.createPlaceholderCommand({
      promise: () => navigator.clipboard.readText(),
      placeholder: { type: "inline" },
      onSuccess: (value, selection, props) => {
        return this.insertNode((0, import_core_utils4.htmlToProsemirrorNode)({ content: value, schema: props.state.schema }), { selection })(props);
      }
    }).generateCommand();
  }
  cut() {
    return (props) => {
      if (props.tr.selection.empty) {
        return false;
      }
      if (props.dispatch) {
        document.execCommand("cut");
      }
      return true;
    };
  }
  replaceText(props) {
    return (0, import_core_utils4.replaceText)(props);
  }
  getAllCommandOptions() {
    const uiCommands = {};
    for (const [name, options] of this.decorated) {
      if ((0, import_core_helpers7.isEmptyObject)(options)) {
        continue;
      }
      uiCommands[name] = options;
    }
    return uiCommands;
  }
  getCommandOptions(name) {
    return this.decorated.get(name);
  }
  getCommandProp() {
    return {
      tr: this.transaction,
      dispatch: this.store.view.dispatch,
      state: this.store.view.state,
      view: this.store.view
    };
  }
  updateDecorated(name, options) {
    var _a;
    if (!options) {
      this.decorated.delete(name);
      return;
    }
    const decoratorOptions = (_a = this.decorated.get(name)) != null ? _a : { name: "" };
    this.decorated.set(name, { ...decoratorOptions, ...options });
  }
  handleIosFocus() {
    if (!import_core_utils4.environment.isIos) {
      return;
    }
    this.store.view.dom.focus();
  }
  delayedFocus() {
    this.handleIosFocus();
    requestAnimationFrame(() => {
      this.store.view.focus();
      this.store.view.dispatch(this.transaction.scrollIntoView());
    });
  }
  getForcedUpdates(tr) {
    return this.getCommandMeta(tr).forcedUpdates;
  }
  getCommandMeta(tr) {
    var _a;
    const meta = (_a = tr.getMeta(this.pluginKey)) != null ? _a : {};
    return { ...DEFAULT_COMMAND_META, ...meta };
  }
  setCommandMeta(tr, update) {
    const meta = this.getCommandMeta(tr);
    tr.setMeta(this.pluginKey, { ...meta, ...update });
  }
  addCommands(props) {
    const { extensionCommands, commands, names, active } = props;
    for (const [name, command2] of (0, import_core_helpers7.entries)(extensionCommands)) {
      throwIfNameNotUnique({ name, set: names, code: import_core_constants5.ErrorConstant.DUPLICATE_COMMAND_NAMES });
      (0, import_core_helpers7.invariant)(!forbiddenNames.has(name), {
        code: import_core_constants5.ErrorConstant.DUPLICATE_COMMAND_NAMES,
        message: "The command name you chose is forbidden."
      });
      commands[name] = this.createUnchainedCommand(command2, active[name]);
    }
  }
  unchainedFactory(props) {
    return (...args) => {
      const { shouldDispatch = true, command: command2 } = props;
      const { view } = this.store;
      const { state } = view;
      let dispatch;
      if (shouldDispatch) {
        dispatch = view.dispatch;
      }
      return command2(...args)({ state, dispatch, view, tr: state.tr });
    };
  }
  createUnchainedCommand(command2, active) {
    const unchainedCommand = this.unchainedFactory({ command: command2 });
    unchainedCommand.enabled = this.unchainedFactory({ command: command2, shouldDispatch: false });
    unchainedCommand.isEnabled = unchainedCommand.enabled;
    unchainedCommand.original = command2;
    unchainedCommand.active = active;
    return unchainedCommand;
  }
  chainedFactory(props) {
    return (...args) => {
      const { chain: chained, command: command2, getTr, getChain } = props;
      const lazyChain = getChain();
      const { view } = this.store;
      const { state } = view;
      lazyChain.push((dispatch) => {
        return command2(...args)({ state, dispatch, view, tr: getTr() });
      });
      return chained;
    };
  }
};
__decorateClass([
  command()
], CommandsExtension.prototype, "customDispatch", 1);
__decorateClass([
  command()
], CommandsExtension.prototype, "insertText", 1);
__decorateClass([
  command()
], CommandsExtension.prototype, "selectText", 1);
__decorateClass([
  command()
], CommandsExtension.prototype, "selectMark", 1);
__decorateClass([
  command()
], CommandsExtension.prototype, "delete", 1);
__decorateClass([
  command()
], CommandsExtension.prototype, "emptyUpdate", 1);
__decorateClass([
  command()
], CommandsExtension.prototype, "forceUpdate", 1);
__decorateClass([
  command()
], CommandsExtension.prototype, "updateNodeAttributes", 1);
__decorateClass([
  command()
], CommandsExtension.prototype, "setContent", 1);
__decorateClass([
  command()
], CommandsExtension.prototype, "resetContent", 1);
__decorateClass([
  command()
], CommandsExtension.prototype, "emptySelection", 1);
__decorateClass([
  command()
], CommandsExtension.prototype, "insertNewLine", 1);
__decorateClass([
  command()
], CommandsExtension.prototype, "insertNode", 1);
__decorateClass([
  command()
], CommandsExtension.prototype, "focus", 1);
__decorateClass([
  command()
], CommandsExtension.prototype, "blur", 1);
__decorateClass([
  command()
], CommandsExtension.prototype, "setBlockNodeType", 1);
__decorateClass([
  command()
], CommandsExtension.prototype, "toggleWrappingNode", 1);
__decorateClass([
  command()
], CommandsExtension.prototype, "toggleBlockNodeItem", 1);
__decorateClass([
  command()
], CommandsExtension.prototype, "wrapInNode", 1);
__decorateClass([
  command()
], CommandsExtension.prototype, "applyMark", 1);
__decorateClass([
  command()
], CommandsExtension.prototype, "toggleMark", 1);
__decorateClass([
  command()
], CommandsExtension.prototype, "removeMark", 1);
__decorateClass([
  command()
], CommandsExtension.prototype, "setMeta", 1);
__decorateClass([
  command({
    description: ({ t }) => t(import_messages.CoreMessages.SELECT_ALL_DESCRIPTION),
    label: ({ t }) => t(import_messages.CoreMessages.SELECT_ALL_LABEL),
    shortcut: import_core_constants5.NamedShortcut.SelectAll
  })
], CommandsExtension.prototype, "selectAll", 1);
__decorateClass([
  command({
    description: ({ t }) => t(import_messages.CoreMessages.COPY_DESCRIPTION),
    label: ({ t }) => t(import_messages.CoreMessages.COPY_LABEL),
    shortcut: import_core_constants5.NamedShortcut.Copy,
    icon: "fileCopyLine"
  })
], CommandsExtension.prototype, "copy", 1);
__decorateClass([
  command({
    description: ({ t }) => t(import_messages.CoreMessages.PASTE_DESCRIPTION),
    label: ({ t }) => t(import_messages.CoreMessages.PASTE_LABEL),
    shortcut: import_core_constants5.NamedShortcut.Paste,
    icon: "clipboardLine"
  })
], CommandsExtension.prototype, "paste", 1);
__decorateClass([
  command({
    description: ({ t }) => t(import_messages.CoreMessages.CUT_DESCRIPTION),
    label: ({ t }) => t(import_messages.CoreMessages.CUT_LABEL),
    shortcut: import_core_constants5.NamedShortcut.Cut,
    icon: "scissorsFill"
  })
], CommandsExtension.prototype, "cut", 1);
__decorateClass([
  command()
], CommandsExtension.prototype, "replaceText", 1);
__decorateClass([
  helper()
], CommandsExtension.prototype, "getAllCommandOptions", 1);
__decorateClass([
  helper()
], CommandsExtension.prototype, "getCommandOptions", 1);
__decorateClass([
  helper()
], CommandsExtension.prototype, "getCommandProp", 1);
CommandsExtension = __decorateClass([
  extension({
    defaultPriority: import_core_constants5.ExtensionPriority.Highest,
    defaultOptions: { trackerClassName: "remirror-tracker-position", trackerNodeName: "span" },
    staticKeys: ["trackerClassName", "trackerNodeName"]
  })
], CommandsExtension);
var DEFAULT_COMMAND_META = {
  forcedUpdates: []
};
var forbiddenNames = /* @__PURE__ */ new Set(["run", "chain", "original", "raw", "enabled", "tr"]);

// packages/remirror__core/src/builtins/decorations-extension.ts
var import_core_constants6 = require("@remirror/core-constants");
var import_core_helpers8 = require("@remirror/core-helpers");
var import_core_utils5 = require("@remirror/core-utils");
var import_view = require("@remirror/pm/view");
var DecorationsExtension = class extends PlainExtension {
  constructor() {
    super(...arguments);
    __publicField(this, "placeholders", import_view.DecorationSet.empty);
    __publicField(this, "placeholderWidgets", /* @__PURE__ */ new Map());
    __publicField(this, "createPlaceholderCommand", (props) => {
      const id = (0, import_core_helpers8.uniqueId)();
      const { promise, placeholder, onFailure, onSuccess } = props;
      return new DelayedCommand(promise).validate((props2) => {
        return this.addPlaceholder(id, placeholder)(props2);
      }).success((props2) => {
        var _a;
        const { state, tr, dispatch, view, value } = props2;
        const range = this.store.helpers.findPlaceholder(id);
        if (!range) {
          const error = new Error("The placeholder has been removed");
          return (_a = onFailure == null ? void 0 : onFailure({ error, state, tr, dispatch, view })) != null ? _a : false;
        }
        this.removePlaceholder(id)({ state, tr, view, dispatch: () => {
        } });
        return onSuccess(value, range, { state, tr, dispatch, view });
      }).failure((props2) => {
        var _a;
        this.removePlaceholder(id)({ ...props2, dispatch: () => {
        } });
        return (_a = onFailure == null ? void 0 : onFailure(props2)) != null ? _a : false;
      });
    });
  }
  get name() {
    return "decorations";
  }
  onCreate() {
    this.store.setExtensionStore("createPlaceholderCommand", this.createPlaceholderCommand);
  }
  createPlugin() {
    return {
      state: {
        init: () => {
        },
        apply: (tr) => {
          var _a, _b, _c, _d, _e, _f;
          const { added, clearTrackers, removed, updated } = this.getMeta(tr);
          if (clearTrackers) {
            this.placeholders = import_view.DecorationSet.empty;
            for (const [, widget] of this.placeholderWidgets) {
              (_b = (_a = widget.spec).onDestroy) == null ? void 0 : _b.call(_a, this.store.view, widget.spec.element);
            }
            this.placeholderWidgets.clear();
            return;
          }
          this.placeholders = this.placeholders.map(tr.mapping, tr.doc, {
            onRemove: (spec) => {
              var _a2, _b2;
              const widget = this.placeholderWidgets.get(spec.id);
              if (widget) {
                (_b2 = (_a2 = widget.spec).onDestroy) == null ? void 0 : _b2.call(_a2, this.store.view, widget.spec.element);
              }
            }
          });
          for (const [, widget] of this.placeholderWidgets) {
            (_d = (_c = widget.spec).onUpdate) == null ? void 0 : _d.call(_c, this.store.view, widget.from, widget.spec.element, widget.spec.data);
          }
          for (const placeholder of added) {
            if (placeholder.type === "inline") {
              this.addInlinePlaceholder(placeholder, tr);
              continue;
            }
            if (placeholder.type === "node") {
              this.addNodePlaceholder(placeholder, tr);
              continue;
            }
            if (placeholder.type === "widget") {
              this.addWidgetPlaceholder(placeholder, tr);
              continue;
            }
          }
          for (const { id, data } of updated) {
            const widget = this.placeholderWidgets.get(id);
            if (!widget) {
              continue;
            }
            const updatedWidget = import_view.Decoration.widget(widget.from, widget.spec.element, {
              ...widget.spec,
              data
            });
            this.placeholders = this.placeholders.remove([widget]).add(tr.doc, [updatedWidget]);
            this.placeholderWidgets.set(id, updatedWidget);
          }
          for (const id of removed) {
            const found = this.placeholders.find(void 0, void 0, (spec) => spec.id === id && spec.__type === __type);
            const widget = this.placeholderWidgets.get(id);
            if (widget) {
              (_f = (_e = widget.spec).onDestroy) == null ? void 0 : _f.call(_e, this.store.view, widget.spec.element);
            }
            this.placeholders = this.placeholders.remove(found);
            this.placeholderWidgets.delete(id);
          }
        }
      },
      props: {
        decorations: (state) => {
          let decorationSet = this.options.decorations(state);
          decorationSet = decorationSet.add(state.doc, this.placeholders.find());
          for (const extension2 of this.store.extensions) {
            if (!extension2.createDecorations) {
              continue;
            }
            const decorations = extension2.createDecorations(state).find();
            decorationSet = decorationSet.add(state.doc, decorations);
          }
          return decorationSet;
        },
        handleDOMEvents: {
          blur: (view) => {
            if (this.options.persistentSelectionClass) {
              view.dispatch(view.state.tr.setMeta(persistentSelectionFocusKey, false));
            }
            return false;
          },
          focus: (view) => {
            if (this.options.persistentSelectionClass) {
              view.dispatch(view.state.tr.setMeta(persistentSelectionFocusKey, true));
            }
            return false;
          }
        }
      }
    };
  }
  updateDecorations() {
    return ({ tr, dispatch }) => (dispatch == null ? void 0 : dispatch(tr), true);
  }
  addPlaceholder(id, placeholder, deleteSelection) {
    return ({ dispatch, tr }) => {
      return this.addPlaceholderTransaction(id, placeholder, tr, !dispatch) ? (dispatch == null ? void 0 : dispatch(deleteSelection ? tr.deleteSelection() : tr), true) : false;
    };
  }
  updatePlaceholder(id, data) {
    return ({ dispatch, tr }) => {
      return this.updatePlaceholderTransaction({ id, data, tr, checkOnly: !dispatch }) ? (dispatch == null ? void 0 : dispatch(tr), true) : false;
    };
  }
  removePlaceholder(id) {
    return ({ dispatch, tr }) => {
      return this.removePlaceholderTransaction({ id, tr, checkOnly: !dispatch }) ? (dispatch == null ? void 0 : dispatch(tr), true) : false;
    };
  }
  clearPlaceholders() {
    return ({ tr, dispatch }) => {
      return this.clearPlaceholdersTransaction({ tr, checkOnly: !dispatch }) ? (dispatch == null ? void 0 : dispatch(tr), true) : false;
    };
  }
  findPlaceholder(id) {
    return this.findAllPlaceholders().get(id);
  }
  findAllPlaceholders() {
    const trackers = /* @__PURE__ */ new Map();
    const found = this.placeholders.find(void 0, void 0, (spec) => spec.__type === __type);
    for (const decoration of found) {
      trackers.set(decoration.spec.id, { from: decoration.from, to: decoration.to });
    }
    return trackers;
  }
  createDecorations(state) {
    var _a, _b, _c;
    const { persistentSelectionClass } = this.options;
    if (!persistentSelectionClass || ((_a = this.store.view) == null ? void 0 : _a.hasFocus()) || ((_c = (_b = this.store.helpers).isInteracting) == null ? void 0 : _c.call(_b))) {
      return import_view.DecorationSet.empty;
    }
    return generatePersistentSelectionDecorations(state, import_view.DecorationSet.empty, {
      class: (0, import_core_helpers8.isString)(persistentSelectionClass) ? persistentSelectionClass : "selection"
    });
  }
  onApplyState() {
  }
  addWidgetPlaceholder(placeholder, tr) {
    var _a;
    const { pos, createElement, onDestroy, onUpdate, className, nodeName, id, type } = placeholder;
    const element = (_a = createElement == null ? void 0 : createElement(this.store.view, pos)) != null ? _a : document.createElement(nodeName);
    element.classList.add(className);
    const decoration = import_view.Decoration.widget(pos, element, {
      id,
      __type,
      type,
      element,
      onDestroy,
      onUpdate
    });
    this.placeholderWidgets.set(id, decoration);
    this.placeholders = this.placeholders.add(tr.doc, [decoration]);
  }
  addInlinePlaceholder(placeholder, tr) {
    const {
      from = tr.selection.from,
      to = tr.selection.to,
      className,
      nodeName,
      id,
      type
    } = placeholder;
    let decoration;
    if (from === to) {
      const element = document.createElement(nodeName);
      element.classList.add(className);
      decoration = import_view.Decoration.widget(from, element, {
        id,
        type,
        __type,
        widget: element
      });
    } else {
      decoration = import_view.Decoration.inline(from, to, { nodeName, class: className }, {
        id,
        __type
      });
    }
    this.placeholders = this.placeholders.add(tr.doc, [decoration]);
  }
  addNodePlaceholder(placeholder, tr) {
    const { pos, className, nodeName, id } = placeholder;
    const $pos = (0, import_core_helpers8.isNumber)(pos) ? tr.doc.resolve(pos) : tr.selection.$from;
    const found = (0, import_core_helpers8.isNumber)(pos) ? $pos.nodeAfter ? { pos, end: $pos.nodeAfter.nodeSize } : void 0 : (0, import_core_utils5.findNodeAtPosition)($pos);
    if (!found) {
      return;
    }
    const decoration = import_view.Decoration.node(found.pos, found.end, { nodeName, class: className }, { id, __type });
    this.placeholders = this.placeholders.add(tr.doc, [decoration]);
  }
  withRequiredBase(id, placeholder) {
    const { placeholderNodeName, placeholderClassName } = this.options;
    const { nodeName = placeholderNodeName, className, ...rest } = placeholder;
    const classes = (className ? [placeholderClassName, className] : [placeholderClassName]).join(" ");
    return { nodeName, className: classes, ...rest, id };
  }
  getMeta(tr) {
    var _a;
    const meta = (_a = tr.getMeta(this.pluginKey)) != null ? _a : {};
    return { ...DEFAULT_PLACEHOLDER_META, ...meta };
  }
  setMeta(tr, update) {
    const meta = this.getMeta(tr);
    tr.setMeta(this.pluginKey, { ...meta, ...update });
  }
  addPlaceholderTransaction(id, placeholder, tr, checkOnly = false) {
    const existingPosition = this.findPlaceholder(id);
    if (existingPosition) {
      return false;
    }
    if (checkOnly) {
      return true;
    }
    const { added } = this.getMeta(tr);
    this.setMeta(tr, {
      added: [...added, this.withRequiredBase(id, placeholder)]
    });
    return true;
  }
  updatePlaceholderTransaction(props) {
    const { id, tr, checkOnly = false, data } = props;
    const existingPosition = this.findPlaceholder(id);
    if (!existingPosition) {
      return false;
    }
    if (checkOnly) {
      return true;
    }
    const { updated } = this.getMeta(tr);
    this.setMeta(tr, { updated: (0, import_core_helpers8.uniqueArray)([...updated, { id, data }]) });
    return true;
  }
  removePlaceholderTransaction(props) {
    const { id, tr, checkOnly = false } = props;
    const existingPosition = this.findPlaceholder(id);
    if (!existingPosition) {
      return false;
    }
    if (checkOnly) {
      return true;
    }
    const { removed } = this.getMeta(tr);
    this.setMeta(tr, { removed: (0, import_core_helpers8.uniqueArray)([...removed, id]) });
    return true;
  }
  clearPlaceholdersTransaction(props) {
    const { tr, checkOnly = false } = props;
    const positionTrackerState = this.getPluginState();
    if (positionTrackerState === import_view.DecorationSet.empty) {
      return false;
    }
    if (checkOnly) {
      return true;
    }
    this.setMeta(tr, { clearTrackers: true });
    return true;
  }
};
__decorateClass([
  command()
], DecorationsExtension.prototype, "updateDecorations", 1);
__decorateClass([
  command()
], DecorationsExtension.prototype, "addPlaceholder", 1);
__decorateClass([
  command()
], DecorationsExtension.prototype, "updatePlaceholder", 1);
__decorateClass([
  command()
], DecorationsExtension.prototype, "removePlaceholder", 1);
__decorateClass([
  command()
], DecorationsExtension.prototype, "clearPlaceholders", 1);
__decorateClass([
  helper()
], DecorationsExtension.prototype, "findPlaceholder", 1);
__decorateClass([
  helper()
], DecorationsExtension.prototype, "findAllPlaceholders", 1);
DecorationsExtension = __decorateClass([
  extension({
    defaultOptions: {
      persistentSelectionClass: void 0,
      placeholderClassName: "placeholder",
      placeholderNodeName: "span"
    },
    staticKeys: ["placeholderClassName", "placeholderNodeName"],
    handlerKeys: ["decorations"],
    handlerKeyOptions: {
      decorations: {
        reducer: {
          accumulator: (accumulated, latestValue, state) => {
            return accumulated.add(state.doc, latestValue.find());
          },
          getDefault: () => import_view.DecorationSet.empty
        }
      }
    },
    defaultPriority: import_core_constants6.ExtensionPriority.Low
  })
], DecorationsExtension);
var DEFAULT_PLACEHOLDER_META = {
  added: [],
  updated: [],
  clearTrackers: false,
  removed: []
};
var __type = "placeholderDecoration";
var persistentSelectionFocusKey = "persistentSelectionFocus";
function generatePersistentSelectionDecorations(state, decorationSet, attrs) {
  const { selection, doc } = state;
  if (selection.empty) {
    return decorationSet;
  }
  const { from, to } = selection;
  const decoration = (0, import_core_utils5.isNodeSelection)(selection) ? import_view.Decoration.node(from, to, attrs) : import_view.Decoration.inline(from, to, attrs);
  return decorationSet.add(doc, [decoration]);
}

// packages/remirror__core/src/builtins/doc-changed-extension.ts
var import_core_constants7 = require("@remirror/core-constants");
var DocChangedExtension = class extends PlainExtension {
  get name() {
    return "docChanged";
  }
  onStateUpdate(props) {
    const { firstUpdate, transactions, tr } = props;
    if (firstUpdate) {
      return;
    }
    if ((transactions != null ? transactions : [tr]).some((tr2) => tr2 == null ? void 0 : tr2.docChanged)) {
      this.options.docChanged(props);
    }
  }
};
DocChangedExtension = __decorateClass([
  extension({
    handlerKeys: ["docChanged"],
    handlerKeyOptions: {
      docChanged: { earlyReturnValue: false }
    },
    defaultPriority: import_core_constants7.ExtensionPriority.Lowest
  })
], DocChangedExtension);

// packages/remirror__core/src/builtins/helpers-extension.ts
var import_core_constants8 = require("@remirror/core-constants");
var import_core_helpers9 = require("@remirror/core-helpers");
var import_core_utils6 = require("@remirror/core-utils");
var HelpersExtension = class extends PlainExtension {
  get name() {
    return "helpers";
  }
  onCreate() {
    var _a, _b, _c;
    this.store.setStringHandler("text", this.textToProsemirrorNode.bind(this));
    this.store.setStringHandler("html", import_core_utils6.htmlToProsemirrorNode);
    const helpers = (0, import_core_helpers9.object)();
    const active = (0, import_core_helpers9.object)();
    const attrs = (0, import_core_helpers9.object)();
    const names = /* @__PURE__ */ new Set();
    for (const extension2 of this.store.extensions) {
      if (isNodeExtension(extension2)) {
        active[extension2.name] = (attrs2) => {
          return (0, import_core_utils6.isNodeActive)({ state: this.store.getState(), type: extension2.type, attrs: attrs2 });
        };
        attrs[extension2.name] = (attrs2) => {
          var _a2;
          return (_a2 = (0, import_core_utils6.getActiveNode)({ state: this.store.getState(), type: extension2.type, attrs: attrs2 })) == null ? void 0 : _a2.node.attrs;
        };
      }
      if (isMarkExtension(extension2)) {
        active[extension2.name] = (attrs2) => {
          return (0, import_core_utils6.isMarkActive)({ trState: this.store.getState(), type: extension2.type, attrs: attrs2 });
        };
        attrs[extension2.name] = (attrs2) => {
          const markRange = (0, import_core_utils6.getMarkRange)(this.store.getState().selection.$from, extension2.type);
          if (!markRange || !attrs2) {
            return markRange == null ? void 0 : markRange.mark.attrs;
          }
          if ((0, import_core_utils6.containsAttributes)(markRange.mark, attrs2)) {
            return markRange.mark.attrs;
          }
          return;
        };
      }
      const extensionHelpers = (_b = (_a = extension2.createHelpers) == null ? void 0 : _a.call(extension2)) != null ? _b : {};
      for (const helperName of Object.keys((_c = extension2.decoratedHelpers) != null ? _c : {})) {
        extensionHelpers[helperName] = extension2[helperName].bind(extension2);
      }
      if ((0, import_core_helpers9.isEmptyObject)(extensionHelpers)) {
        continue;
      }
      for (const [name, helper2] of (0, import_core_helpers9.entries)(extensionHelpers)) {
        throwIfNameNotUnique({ name, set: names, code: import_core_constants8.ErrorConstant.DUPLICATE_HELPER_NAMES });
        helpers[name] = helper2;
      }
    }
    this.store.setStoreKey("attrs", attrs);
    this.store.setStoreKey("active", active);
    this.store.setStoreKey("helpers", helpers);
    this.store.setExtensionStore("attrs", attrs);
    this.store.setExtensionStore("active", active);
    this.store.setExtensionStore("helpers", helpers);
  }
  isSelectionEmpty(state = this.store.getState()) {
    return (0, import_core_utils6.isSelectionEmpty)(state);
  }
  isViewEditable(state = this.store.getState()) {
    var _a, _b, _c;
    return (_c = (_b = (_a = this.store.view.props).editable) == null ? void 0 : _b.call(_a, state)) != null ? _c : false;
  }
  getStateJSON(state = this.store.getState()) {
    return state.toJSON();
  }
  getJSON(state = this.store.getState()) {
    return state.doc.toJSON();
  }
  getRemirrorJSON(state = this.store.getState()) {
    return this.getJSON(state);
  }
  insertHtml(html, options) {
    return (props) => {
      const { state } = props;
      const fragment = (0, import_core_utils6.htmlToProsemirrorNode)({
        content: html,
        schema: state.schema,
        fragment: true
      });
      return this.store.commands.insertNode.original(fragment, options)(props);
    };
  }
  getText({
    lineBreakDivider = "\n\n",
    state = this.store.getState()
  } = {}) {
    return state.doc.textBetween(0, state.doc.content.size, lineBreakDivider, import_core_constants8.NULL_CHARACTER);
  }
  getTextBetween(from, to, doc = this.store.getState().doc) {
    return doc.textBetween(from, to, "\n\n", import_core_constants8.NULL_CHARACTER);
  }
  getHTML(state = this.store.getState()) {
    return (0, import_core_utils6.prosemirrorNodeToHtml)(state.doc, this.store.document);
  }
  textToProsemirrorNode(options) {
    const content = `<pre>${options.content}</pre>`;
    return this.store.stringHandlers.html({ ...options, content });
  }
};
__decorateClass([
  helper()
], HelpersExtension.prototype, "isSelectionEmpty", 1);
__decorateClass([
  helper()
], HelpersExtension.prototype, "isViewEditable", 1);
__decorateClass([
  helper()
], HelpersExtension.prototype, "getStateJSON", 1);
__decorateClass([
  helper()
], HelpersExtension.prototype, "getJSON", 1);
__decorateClass([
  helper()
], HelpersExtension.prototype, "getRemirrorJSON", 1);
__decorateClass([
  command()
], HelpersExtension.prototype, "insertHtml", 1);
__decorateClass([
  helper()
], HelpersExtension.prototype, "getText", 1);
__decorateClass([
  helper()
], HelpersExtension.prototype, "getTextBetween", 1);
__decorateClass([
  helper()
], HelpersExtension.prototype, "getHTML", 1);
HelpersExtension = __decorateClass([
  extension({})
], HelpersExtension);

// packages/remirror__core/src/builtins/input-rules-extension.ts
var import_core_constants9 = require("@remirror/core-constants");
var import_inputrules = require("@remirror/pm/inputrules");
var InputRulesExtension = class extends PlainExtension {
  get name() {
    return "inputRules";
  }
  onCreate() {
    this.store.setExtensionStore("rebuildInputRules", this.rebuildInputRules.bind(this));
  }
  createExternalPlugins() {
    return [this.generateInputRulesPlugin()];
  }
  generateInputRulesPlugin() {
    var _a, _b;
    const rules = [];
    const invalidMarks = this.store.markTags[import_core_constants9.ExtensionTag.ExcludeInputRules];
    for (const extension2 of this.store.extensions) {
      if (((_a = this.store.managerSettings.exclude) == null ? void 0 : _a.inputRules) || !extension2.createInputRules || ((_b = extension2.options.exclude) == null ? void 0 : _b.inputRules)) {
        continue;
      }
      for (const rule of extension2.createInputRules()) {
        rule.shouldSkip = this.options.shouldSkipInputRule;
        rule.invalidMarks = invalidMarks;
        rules.push(rule);
      }
    }
    return (0, import_inputrules.inputRules)({ rules });
  }
  rebuildInputRules() {
    this.store.updateExtensionPlugins(this);
  }
};
InputRulesExtension = __decorateClass([
  extension({
    defaultPriority: import_core_constants9.ExtensionPriority.Default,
    handlerKeys: ["shouldSkipInputRule"],
    handlerKeyOptions: { shouldSkipInputRule: { earlyReturnValue: true } }
  })
], InputRulesExtension);

// packages/remirror__core/src/builtins/keymap-extension.ts
var import_core_constants10 = require("@remirror/core-constants");
var import_core_helpers10 = require("@remirror/core-helpers");
var import_core_utils7 = require("@remirror/core-utils");
var import_commands4 = require("@remirror/pm/commands");
var import_inputrules2 = require("@remirror/pm/inputrules");
var import_keymap = require("@remirror/pm/keymap");
var import_state2 = require("@remirror/pm/state");
var KeymapExtension = class extends PlainExtension {
  constructor() {
    super(...arguments);
    __publicField(this, "extraKeyBindings", []);
    __publicField(this, "backwardMarkExitTracker", /* @__PURE__ */ new Map());
    __publicField(this, "keydownHandler", null);
    __publicField(this, "onAddCustomHandler", ({ keymap }) => {
      var _a, _b;
      if (!keymap) {
        return;
      }
      this.extraKeyBindings = [...this.extraKeyBindings, keymap];
      (_b = (_a = this.store).rebuildKeymap) == null ? void 0 : _b.call(_a);
      return () => {
        var _a2, _b2;
        this.extraKeyBindings = this.extraKeyBindings.filter((binding) => binding !== keymap);
        (_b2 = (_a2 = this.store).rebuildKeymap) == null ? void 0 : _b2.call(_a2);
      };
    });
    __publicField(this, "rebuildKeymap", () => {
      this.setupKeydownHandler();
    });
  }
  get name() {
    return "keymap";
  }
  get shortcutMap() {
    const { shortcuts } = this.options;
    return (0, import_core_helpers10.isString)(shortcuts) ? keyboardShortcuts[shortcuts] : shortcuts;
  }
  onCreate() {
    this.store.setExtensionStore("rebuildKeymap", this.rebuildKeymap);
  }
  createExternalPlugins() {
    var _a;
    if ((_a = this.store.managerSettings.exclude) == null ? void 0 : _a.keymap) {
      return [];
    }
    this.setupKeydownHandler();
    return [
      new import_state2.Plugin({
        props: {
          handleKeyDown: (view, event) => {
            var _a2;
            return (_a2 = this.keydownHandler) == null ? void 0 : _a2.call(this, view, event);
          }
        }
      })
    ];
  }
  setupKeydownHandler() {
    const bindings = this.generateKeymapBindings();
    this.keydownHandler = (0, import_keymap.keydownHandler)(bindings);
  }
  generateKeymapBindings() {
    var _a, _b, _c;
    const extensionKeymaps = [];
    const shortcutMap = this.shortcutMap;
    const commandsExtension = this.store.getExtension(CommandsExtension);
    const extractNamesFactory = (extension2) => (shortcut) => extractShortcutNames({
      shortcut,
      map: shortcutMap,
      store: this.store,
      options: extension2.options
    });
    for (const extension2 of this.store.extensions) {
      const decoratedKeybindings = (_a = extension2.decoratedKeybindings) != null ? _a : {};
      if ((_b = extension2.options.exclude) == null ? void 0 : _b.keymap) {
        continue;
      }
      if (extension2.createKeymap) {
        extensionKeymaps.push(updateNamedKeys(extension2.createKeymap(extractNamesFactory(extension2)), shortcutMap));
      }
      for (const [name, options] of (0, import_core_helpers10.entries)(decoratedKeybindings)) {
        if (options.isActive && !options.isActive(extension2.options, this.store)) {
          continue;
        }
        const keyBinding2 = extension2[name].bind(extension2);
        const shortcutNames = extractShortcutNames({
          shortcut: options.shortcut,
          map: shortcutMap,
          options: extension2.options,
          store: this.store
        });
        const priority = (0, import_core_helpers10.isFunction)(options.priority) ? options.priority(extension2.options, this.store) : (_c = options.priority) != null ? _c : import_core_constants10.ExtensionPriority.Low;
        const bindingObject = (0, import_core_helpers10.object)();
        for (const shortcut of shortcutNames) {
          bindingObject[shortcut] = keyBinding2;
        }
        extensionKeymaps.push([priority, bindingObject]);
        if (options.command) {
          commandsExtension.updateDecorated(options.command, { shortcut: shortcutNames });
        }
      }
    }
    const sortedKeymaps = this.sortKeymaps([...this.extraKeyBindings, ...extensionKeymaps]);
    const mappedCommands = (0, import_core_utils7.mergeProsemirrorKeyBindings)(sortedKeymaps);
    return mappedCommands;
  }
  arrowRightShortcut(props) {
    const excludedMarks = this.store.markTags[import_core_constants10.ExtensionTag.PreventExits];
    const excludedNodes = this.store.nodeTags[import_core_constants10.ExtensionTag.PreventExits];
    return this.exitMarkForwards(excludedMarks, excludedNodes)(props);
  }
  arrowLeftShortcut(props) {
    const excludedMarks = this.store.markTags[import_core_constants10.ExtensionTag.PreventExits];
    const excludedNodes = this.store.nodeTags[import_core_constants10.ExtensionTag.PreventExits];
    return (0, import_core_utils7.chainKeyBindingCommands)(this.exitNodeBackwards(excludedNodes), this.exitMarkBackwards(excludedMarks, excludedNodes))(props);
  }
  backspace(props) {
    const excludedMarks = this.store.markTags[import_core_constants10.ExtensionTag.PreventExits];
    const excludedNodes = this.store.nodeTags[import_core_constants10.ExtensionTag.PreventExits];
    return (0, import_core_utils7.chainKeyBindingCommands)(this.exitNodeBackwards(excludedNodes, true), this.exitMarkBackwards(excludedMarks, excludedNodes, true))(props);
  }
  createKeymap() {
    const { selectParentNodeOnEscape, undoInputRuleOnBackspace, excludeBaseKeymap } = this.options;
    const baseKeyBindings = (0, import_core_helpers10.object)();
    if (!excludeBaseKeymap) {
      for (const [key2, value] of (0, import_core_helpers10.entries)(import_commands4.baseKeymap)) {
        baseKeyBindings[key2] = (0, import_core_utils7.convertCommand)(value);
      }
    }
    if (undoInputRuleOnBackspace && import_commands4.baseKeymap.Backspace) {
      baseKeyBindings.Backspace = (0, import_core_utils7.convertCommand)((0, import_commands4.chainCommands)(import_inputrules2.undoInputRule, import_commands4.baseKeymap.Backspace));
    }
    if (selectParentNodeOnEscape) {
      baseKeyBindings.Escape = (0, import_core_utils7.convertCommand)(import_commands4.selectParentNode);
    }
    return [import_core_constants10.ExtensionPriority.Low, baseKeyBindings];
  }
  getNamedShortcut(shortcut, options = {}) {
    if (!shortcut.startsWith("_|")) {
      return [shortcut];
    }
    return extractShortcutNames({
      shortcut,
      map: this.shortcutMap,
      store: this.store,
      options
    });
  }
  onSetOptions(props) {
    var _a, _b;
    const { changes } = props;
    if (changes.excludeBaseKeymap.changed || changes.selectParentNodeOnEscape.changed || changes.undoInputRuleOnBackspace.changed) {
      (_b = (_a = this.store).rebuildKeymap) == null ? void 0 : _b.call(_a);
    }
  }
  sortKeymaps(bindings) {
    return (0, import_core_helpers10.sort)(bindings.map((binding) => (0, import_core_helpers10.isArray)(binding) ? binding : [import_core_constants10.ExtensionPriority.Default, binding]), (a, z) => z[0] - a[0]).map((binding) => binding[1]);
  }
  exitMarkForwards(excludedMarks, excludedNodes) {
    return (props) => {
      const { tr, dispatch } = props;
      if (!(0, import_core_utils7.isEndOfTextBlock)(tr.selection)) {
        return false;
      }
      const isInsideExcludedNode = (0, import_core_utils7.findParentNodeOfType)({
        selection: tr.selection,
        types: excludedNodes
      });
      if (isInsideExcludedNode) {
        return false;
      }
      const $pos = tr.selection.$from;
      const marksToRemove = $pos.marks().filter((mark) => !excludedMarks.includes(mark.type.name));
      if ((0, import_core_helpers10.isEmptyArray)(marksToRemove)) {
        return false;
      }
      if (!dispatch) {
        return true;
      }
      for (const mark of marksToRemove) {
        tr.removeStoredMark(mark);
      }
      dispatch(tr.insertText(" ", tr.selection.from));
      return true;
    };
  }
  exitNodeBackwards(excludedNodes, startOfDoc = false) {
    return (props) => {
      const { tr } = props;
      const checker = startOfDoc ? import_core_utils7.isStartOfDoc : import_core_utils7.isStartOfTextBlock;
      if (!checker(tr.selection)) {
        return false;
      }
      const node = tr.selection.$anchor.node();
      if (!(0, import_core_utils7.isEmptyBlockNode)(node) || (0, import_core_utils7.isDefaultBlockNode)(node) || excludedNodes.includes(node.type.name)) {
        return false;
      }
      return this.store.commands.toggleBlockNodeItem.original({ type: node.type })(props);
    };
  }
  exitMarkBackwards(excludedMarks, excludedNodes, startOfDoc = false) {
    return (props) => {
      var _a;
      const { tr, dispatch } = props;
      const checker = startOfDoc ? import_core_utils7.isStartOfDoc : import_core_utils7.isStartOfTextBlock;
      if (!checker(tr.selection) || this.backwardMarkExitTracker.has(tr.selection.anchor)) {
        this.backwardMarkExitTracker.clear();
        return false;
      }
      const isInsideExcludedNode = (0, import_core_utils7.findParentNodeOfType)({
        selection: tr.selection,
        types: excludedNodes
      });
      if (isInsideExcludedNode) {
        return false;
      }
      const marksToRemove = [...(_a = tr.storedMarks) != null ? _a : [], ...tr.selection.$from.marks()].filter((mark) => !excludedMarks.includes(mark.type.name));
      if ((0, import_core_helpers10.isEmptyArray)(marksToRemove)) {
        return false;
      }
      if (!dispatch) {
        return true;
      }
      for (const mark of marksToRemove) {
        tr.removeStoredMark(mark);
      }
      this.backwardMarkExitTracker.set(tr.selection.anchor, true);
      dispatch(tr);
      return true;
    };
  }
};
__decorateClass([
  keyBinding({
    shortcut: "ArrowRight",
    isActive: (options) => options.exitMarksOnArrowPress
  })
], KeymapExtension.prototype, "arrowRightShortcut", 1);
__decorateClass([
  keyBinding({
    shortcut: "ArrowLeft",
    isActive: (options) => options.exitMarksOnArrowPress
  })
], KeymapExtension.prototype, "arrowLeftShortcut", 1);
__decorateClass([
  keyBinding({
    shortcut: "Backspace",
    isActive: (options) => options.exitMarksOnArrowPress
  })
], KeymapExtension.prototype, "backspace", 1);
__decorateClass([
  helper()
], KeymapExtension.prototype, "getNamedShortcut", 1);
KeymapExtension = __decorateClass([
  extension({
    defaultPriority: import_core_constants10.ExtensionPriority.Low,
    defaultOptions: {
      shortcuts: "default",
      undoInputRuleOnBackspace: true,
      selectParentNodeOnEscape: false,
      excludeBaseKeymap: false,
      exitMarksOnArrowPress: true
    },
    customHandlerKeys: ["keymap"]
  })
], KeymapExtension);
function isNamedShortcut(value) {
  return (0, import_core_helpers10.includes)((0, import_core_helpers10.values)(import_core_constants10.NamedShortcut), value);
}
function extractShortcutNames({
  shortcut,
  map,
  options,
  store
}) {
  if ((0, import_core_helpers10.isString)(shortcut)) {
    return [normalizeShortcutName(shortcut, map)];
  }
  if ((0, import_core_helpers10.isArray)(shortcut)) {
    return shortcut.map((value) => normalizeShortcutName(value, map));
  }
  shortcut = shortcut(options, store);
  return extractShortcutNames({ shortcut, map, options, store });
}
function normalizeShortcutName(value, shortcutMap) {
  return isNamedShortcut(value) ? shortcutMap[value] : value;
}
function updateNamedKeys(prioritizedBindings, shortcutMap) {
  const updatedBindings = {};
  let previousBindings;
  let priority;
  if ((0, import_core_helpers10.isArray)(prioritizedBindings)) {
    [priority, previousBindings] = prioritizedBindings;
  } else {
    previousBindings = prioritizedBindings;
  }
  for (const [shortcutName, commandFunction] of (0, import_core_helpers10.entries)(previousBindings)) {
    updatedBindings[normalizeShortcutName(shortcutName, shortcutMap)] = commandFunction;
  }
  return (0, import_core_helpers10.isUndefined)(priority) ? updatedBindings : [priority, updatedBindings];
}
var DEFAULT_SHORTCUTS = {
  [import_core_constants10.NamedShortcut.Copy]: "Mod-c",
  [import_core_constants10.NamedShortcut.Cut]: "Mod-x",
  [import_core_constants10.NamedShortcut.Paste]: "Mod-v",
  [import_core_constants10.NamedShortcut.PastePlain]: "Mod-Shift-v",
  [import_core_constants10.NamedShortcut.SelectAll]: "Mod-a",
  [import_core_constants10.NamedShortcut.Undo]: "Mod-z",
  [import_core_constants10.NamedShortcut.Redo]: import_core_utils7.environment.isMac ? "Shift-Mod-z" : "Mod-y",
  [import_core_constants10.NamedShortcut.Bold]: "Mod-b",
  [import_core_constants10.NamedShortcut.Italic]: "Mod-i",
  [import_core_constants10.NamedShortcut.Underline]: "Mod-u",
  [import_core_constants10.NamedShortcut.Strike]: "Mod-d",
  [import_core_constants10.NamedShortcut.Code]: "Mod-`",
  [import_core_constants10.NamedShortcut.Paragraph]: "Mod-Shift-0",
  [import_core_constants10.NamedShortcut.H1]: "Mod-Shift-1",
  [import_core_constants10.NamedShortcut.H2]: "Mod-Shift-2",
  [import_core_constants10.NamedShortcut.H3]: "Mod-Shift-3",
  [import_core_constants10.NamedShortcut.H4]: "Mod-Shift-4",
  [import_core_constants10.NamedShortcut.H5]: "Mod-Shift-5",
  [import_core_constants10.NamedShortcut.H6]: "Mod-Shift-6",
  [import_core_constants10.NamedShortcut.TaskList]: "Mod-Shift-7",
  [import_core_constants10.NamedShortcut.BulletList]: "Mod-Shift-8",
  [import_core_constants10.NamedShortcut.OrderedList]: "Mod-Shift-9",
  [import_core_constants10.NamedShortcut.Quote]: "Mod->",
  [import_core_constants10.NamedShortcut.Divider]: "Mod-Shift-|",
  [import_core_constants10.NamedShortcut.Codeblock]: "Mod-Shift-~",
  [import_core_constants10.NamedShortcut.ClearFormatting]: "Mod-Shift-C",
  [import_core_constants10.NamedShortcut.Superscript]: "Mod-.",
  [import_core_constants10.NamedShortcut.Subscript]: "Mod-,",
  [import_core_constants10.NamedShortcut.LeftAlignment]: "Mod-Shift-L",
  [import_core_constants10.NamedShortcut.CenterAlignment]: "Mod-Shift-E",
  [import_core_constants10.NamedShortcut.RightAlignment]: "Mod-Shift-R",
  [import_core_constants10.NamedShortcut.JustifyAlignment]: "Mod-Shift-J",
  [import_core_constants10.NamedShortcut.InsertLink]: "Mod-k",
  [import_core_constants10.NamedShortcut.Find]: "Mod-f",
  [import_core_constants10.NamedShortcut.FindBackwards]: "Mod-Shift-f",
  [import_core_constants10.NamedShortcut.FindReplace]: "Mod-Shift-H",
  [import_core_constants10.NamedShortcut.AddFootnote]: "Mod-Alt-f",
  [import_core_constants10.NamedShortcut.AddComment]: "Mod-Alt-m",
  [import_core_constants10.NamedShortcut.ContextMenu]: "Mod-Shift-\\",
  [import_core_constants10.NamedShortcut.IncreaseFontSize]: "Mod-Shift-.",
  [import_core_constants10.NamedShortcut.DecreaseFontSize]: "Mod-Shift-,",
  [import_core_constants10.NamedShortcut.IncreaseIndent]: "Tab",
  [import_core_constants10.NamedShortcut.DecreaseIndent]: "Shift-Tab",
  [import_core_constants10.NamedShortcut.Shortcuts]: "Mod-/",
  [import_core_constants10.NamedShortcut.Format]: import_core_utils7.environment.isMac ? "Alt-Shift-f" : "Shift-Ctrl-f"
};
var GOOGLE_DOC_SHORTCUTS = {
  ...DEFAULT_SHORTCUTS,
  [import_core_constants10.NamedShortcut.Strike]: "Mod-Shift-S",
  [import_core_constants10.NamedShortcut.Code]: "Mod-Shift-M",
  [import_core_constants10.NamedShortcut.Paragraph]: "Mod-Alt-0",
  [import_core_constants10.NamedShortcut.H1]: "Mod-Alt-1",
  [import_core_constants10.NamedShortcut.H2]: "Mod-Alt-2",
  [import_core_constants10.NamedShortcut.H3]: "Mod-Alt-3",
  [import_core_constants10.NamedShortcut.H4]: "Mod-Alt-4",
  [import_core_constants10.NamedShortcut.H5]: "Mod-Alt-5",
  [import_core_constants10.NamedShortcut.H6]: "Mod-Alt-6",
  [import_core_constants10.NamedShortcut.OrderedList]: "Mod-Alt-7",
  [import_core_constants10.NamedShortcut.BulletList]: "Mod-Alt-8",
  [import_core_constants10.NamedShortcut.Quote]: "Mod-Alt-9",
  [import_core_constants10.NamedShortcut.ClearFormatting]: "Mod-\\",
  [import_core_constants10.NamedShortcut.IncreaseIndent]: "Mod-[",
  [import_core_constants10.NamedShortcut.DecreaseIndent]: "Mod-]"
};
var keyboardShortcuts = {
  default: DEFAULT_SHORTCUTS,
  googleDoc: GOOGLE_DOC_SHORTCUTS
};

// packages/remirror__core/src/builtins/node-views-extension.ts
var import_core_helpers11 = require("@remirror/core-helpers");
var NodeViewsExtension = class extends PlainExtension {
  get name() {
    return "nodeViews";
  }
  createPlugin() {
    var _a;
    const nodeViewList = [];
    const nodeViews = (0, import_core_helpers11.object)();
    for (const extension2 of this.store.extensions) {
      if (!extension2.createNodeViews) {
        continue;
      }
      const nodeView = extension2.createNodeViews();
      nodeViewList.unshift((0, import_core_helpers11.isFunction)(nodeView) ? { [extension2.name]: nodeView } : nodeView);
    }
    nodeViewList.unshift((_a = this.store.managerSettings.nodeViews) != null ? _a : {});
    for (const nodeView of nodeViewList) {
      Object.assign(nodeViews, nodeView);
    }
    return {
      props: { nodeViews }
    };
  }
};

// packages/remirror__core/src/builtins/paste-rules-extension.ts
var import_core_helpers12 = require("@remirror/core-helpers");
var import_paste_rules = require("@remirror/pm/paste-rules");
var PasteRulesExtension = class extends PlainExtension {
  get name() {
    return "pasteRules";
  }
  createExternalPlugins() {
    return [this.generatePasteRulesPlugin()];
  }
  generatePasteRulesPlugin() {
    var _a, _b;
    const extensionPasteRules = [];
    for (const extension2 of this.store.extensions) {
      if (((_a = this.store.managerSettings.exclude) == null ? void 0 : _a.pasteRules) || !extension2.createPasteRules || ((_b = extension2.options.exclude) == null ? void 0 : _b.pasteRules)) {
        continue;
      }
      const value = extension2.createPasteRules();
      const rules = (0, import_core_helpers12.isArray)(value) ? value : [value];
      extensionPasteRules.push(...rules);
    }
    return (0, import_paste_rules.pasteRules)(extensionPasteRules);
  }
};

// packages/remirror__core/src/builtins/plugins-extension.ts
var import_core_constants11 = require("@remirror/core-constants");
var import_core_helpers13 = require("@remirror/core-helpers");
var import_state3 = require("@remirror/pm/state");
var PluginsExtension = class extends PlainExtension {
  constructor() {
    super(...arguments);
    __publicField(this, "plugins", []);
    __publicField(this, "managerPlugins", []);
    __publicField(this, "applyStateHandlers", []);
    __publicField(this, "initStateHandlers", []);
    __publicField(this, "appendTransactionHandlers", []);
    __publicField(this, "pluginKeys", (0, import_core_helpers13.object)());
    __publicField(this, "stateGetters", /* @__PURE__ */ new Map());
    __publicField(this, "getPluginStateCreator", (key2) => (state) => {
      return key2.getState(state != null ? state : this.store.getState());
    });
    __publicField(this, "getStateByName", (identifier) => {
      const stateGetter = this.stateGetters.get(identifier);
      (0, import_core_helpers13.invariant)(stateGetter, { message: "No plugin exists for the requested extension name." });
      return stateGetter();
    });
  }
  get name() {
    return "plugins";
  }
  onCreate() {
    const { setStoreKey, setExtensionStore, managerSettings, extensions } = this.store;
    this.updateExtensionStore();
    const { plugins = [] } = managerSettings;
    this.updatePlugins(plugins, this.managerPlugins);
    for (const extension2 of extensions) {
      if (extension2.onApplyState) {
        this.applyStateHandlers.push(extension2.onApplyState.bind(extension2));
      }
      if (extension2.onInitState) {
        this.initStateHandlers.push(extension2.onInitState.bind(extension2));
      }
      if (extension2.onAppendTransaction) {
        this.appendTransactionHandlers.push(extension2.onAppendTransaction.bind(extension2));
      }
      this.extractExtensionPlugins(extension2);
    }
    this.managerPlugins = plugins;
    this.store.setStoreKey("plugins", this.plugins);
    setStoreKey("pluginKeys", this.pluginKeys);
    setStoreKey("getPluginState", this.getStateByName);
    setExtensionStore("getPluginState", this.getStateByName);
  }
  createPlugin() {
    return {
      appendTransaction: (transactions, previousState, state) => {
        const tr = state.tr;
        const props = { previousState, tr, transactions, state };
        for (const handler of this.appendTransactionHandlers) {
          handler(props);
        }
        this.options.appendTransaction(props);
        return tr.docChanged || tr.steps.length > 0 || tr.selectionSet || tr.storedMarksSet ? tr : void 0;
      },
      state: {
        init: (_, state) => {
          for (const handler of this.initStateHandlers) {
            handler(state);
          }
        },
        apply: (tr, _, previousState, state) => {
          const props = { previousState, state, tr };
          for (const handler of this.applyStateHandlers) {
            handler(props);
          }
          this.options.applyState(props);
        }
      }
    };
  }
  extractExtensionPlugins(extension2) {
    var _a, _b;
    const isNotPluginCreator = !extension2.createPlugin && !extension2.createExternalPlugins;
    if (isNotPluginCreator || ((_a = this.store.managerSettings.exclude) == null ? void 0 : _a.plugins) || ((_b = extension2.options.exclude) == null ? void 0 : _b.plugins)) {
      return;
    }
    if (extension2.createPlugin) {
      const key2 = new import_state3.PluginKey(extension2.name);
      this.pluginKeys[extension2.name] = key2;
      const getter = this.getPluginStateCreator(key2);
      extension2.pluginKey = key2;
      extension2.getPluginState = getter;
      this.stateGetters.set(extension2.name, getter);
      this.stateGetters.set(extension2.constructor, getter);
      const pluginSpec = {
        ...extension2.createPlugin(),
        key: key2
      };
      const plugin = new import_state3.Plugin(pluginSpec);
      this.updatePlugins([plugin], extension2.plugin ? [extension2.plugin] : void 0);
      extension2.plugin = plugin;
    }
    if (extension2.createExternalPlugins) {
      const externalPlugins = extension2.createExternalPlugins();
      this.updatePlugins(externalPlugins, extension2.externalPlugins);
      extension2.externalPlugins = externalPlugins;
    }
  }
  updatePlugins(plugins, previous) {
    if (!previous || (0, import_core_helpers13.isEmptyArray)(previous)) {
      this.plugins = [...this.plugins, ...plugins];
      return;
    }
    if (plugins.length !== previous.length) {
      this.plugins = [...this.plugins.filter((plugin) => !previous.includes(plugin)), ...plugins];
      return;
    }
    const pluginMap = /* @__PURE__ */ new Map();
    for (const [index, plugin] of plugins.entries()) {
      pluginMap.set((0, import_core_helpers13.assertGet)(previous, index), plugin);
    }
    this.plugins = this.plugins.map((plugin) => {
      return previous.includes(plugin) ? pluginMap.get(plugin) : plugin;
    });
  }
  updateExtensionStore() {
    const { setExtensionStore } = this.store;
    setExtensionStore("updatePlugins", this.updatePlugins.bind(this));
    setExtensionStore("dispatchPluginUpdate", this.dispatchPluginUpdate.bind(this));
    setExtensionStore("updateExtensionPlugins", this.updateExtensionPlugins.bind(this));
  }
  updateExtensionPlugins(value) {
    const extension2 = isExtension(value) ? value : isExtensionConstructor(value) ? this.store.manager.getExtension(value) : this.store.extensions.find((extension3) => extension3.name === value);
    (0, import_core_helpers13.invariant)(extension2, {
      code: import_core_constants11.ErrorConstant.INVALID_MANAGER_EXTENSION,
      message: `The extension ${value} does not exist within the editor.`
    });
    this.extractExtensionPlugins(extension2);
    this.store.setStoreKey("plugins", this.plugins);
    this.dispatchPluginUpdate();
  }
  dispatchPluginUpdate() {
    (0, import_core_helpers13.invariant)(this.store.phase >= import_core_constants11.ManagerPhase.EditorView, {
      code: import_core_constants11.ErrorConstant.MANAGER_PHASE_ERROR,
      message: "`dispatchPluginUpdate` should only be called after the view has been added to the manager."
    });
    const { view, updateState } = this.store;
    const newState = view.state.reconfigure({ plugins: this.plugins });
    updateState(newState);
  }
};
PluginsExtension = __decorateClass([
  extension({
    defaultPriority: import_core_constants11.ExtensionPriority.Highest,
    handlerKeys: ["applyState", "appendTransaction"]
  })
], PluginsExtension);

// packages/remirror__core/src/builtins/schema-extension.ts
var import_core_constants12 = require("@remirror/core-constants");
var import_core_helpers14 = require("@remirror/core-helpers");
var import_core_utils8 = require("@remirror/core-utils");
var import_model2 = require("@remirror/pm/model");
var import_suggest = require("@remirror/pm/suggest");
var SchemaExtension = class extends PlainExtension {
  constructor() {
    super(...arguments);
    __publicField(this, "dynamicAttributes", {
      marks: (0, import_core_helpers14.object)(),
      nodes: (0, import_core_helpers14.object)()
    });
  }
  get name() {
    return "schema";
  }
  onCreate() {
    var _a;
    const { managerSettings, tags, markNames, nodeNames, extensions } = this.store;
    const { defaultBlockNode, disableExtraAttributes, nodeOverride, markOverride } = managerSettings;
    const isValidDefaultBlockNode = (name) => !!(name && tags[import_core_constants12.ExtensionTag.Block].includes(name));
    if (managerSettings.schema) {
      const { nodes: nodes2, marks: marks2 } = getSpecFromSchema(managerSettings.schema);
      this.addSchema(managerSettings.schema, nodes2, marks2);
      return;
    }
    const nodes = isValidDefaultBlockNode(defaultBlockNode) ? {
      doc: (0, import_core_helpers14.object)(),
      [defaultBlockNode]: (0, import_core_helpers14.object)()
    } : (0, import_core_helpers14.object)();
    const marks = (0, import_core_helpers14.object)();
    const namedExtraAttributes = getNamedSchemaAttributes({
      settings: managerSettings,
      gatheredSchemaAttributes: this.gatherExtraAttributes(extensions),
      nodeNames,
      markNames,
      tags
    });
    for (const extension2 of extensions) {
      namedExtraAttributes[extension2.name] = {
        ...namedExtraAttributes[extension2.name],
        ...extension2.options.extraAttributes
      };
      const ignoreExtraAttributes = disableExtraAttributes === true || extension2.options.disableExtraAttributes === true || extension2.constructor.disableExtraAttributes === true;
      if (isNodeExtension(extension2)) {
        const { spec, dynamic } = createSpec({
          createExtensionSpec: (extra, override) => extension2.createNodeSpec(extra, override),
          extraAttributes: (0, import_core_helpers14.assertGet)(namedExtraAttributes, extension2.name),
          override: { ...nodeOverride, ...extension2.options.nodeOverride },
          ignoreExtraAttributes,
          name: extension2.constructorName,
          tags: extension2.tags
        });
        extension2.spec = spec;
        nodes[extension2.name] = spec;
        if (Object.keys(dynamic).length > 0) {
          this.dynamicAttributes.nodes[extension2.name] = dynamic;
        }
      }
      if (isMarkExtension(extension2)) {
        const { spec, dynamic } = createSpec({
          createExtensionSpec: (extra, override) => extension2.createMarkSpec(extra, override),
          extraAttributes: (0, import_core_helpers14.assertGet)(namedExtraAttributes, extension2.name),
          override: { ...markOverride, ...extension2.options.markOverride },
          ignoreExtraAttributes,
          name: extension2.constructorName,
          tags: (_a = extension2.tags) != null ? _a : []
        });
        extension2.spec = spec;
        marks[extension2.name] = spec;
        if (Object.keys(dynamic).length > 0) {
          this.dynamicAttributes.marks[extension2.name] = dynamic;
        }
      }
    }
    const schema = new import_model2.Schema({ nodes, marks, topNode: "doc" });
    this.addSchema(schema, nodes, marks);
  }
  createPlugin() {
    return {
      appendTransaction: (transactions, _, nextState) => {
        const { tr } = nextState;
        const documentHasChanged = transactions.some((tr2) => tr2.docChanged);
        if (!documentHasChanged) {
          return null;
        }
        if (Object.keys(this.dynamicAttributes.nodes).length === 0 && Object.keys(this.dynamicAttributes.marks).length === 0) {
          return null;
        }
        tr.doc.descendants((child, pos) => {
          this.checkAndUpdateDynamicNodes(child, pos, tr);
          this.checkAndUpdateDynamicMarks(child, pos, tr);
          return true;
        });
        return tr.steps.length > 0 ? tr : null;
      }
    };
  }
  addSchema(schema, nodes, marks) {
    this.store.setStoreKey("nodes", nodes);
    this.store.setStoreKey("marks", marks);
    this.store.setStoreKey("schema", schema);
    this.store.setExtensionStore("schema", schema);
    this.store.setStoreKey("defaultBlockNode", (0, import_core_utils8.getDefaultBlockNode)(schema).name);
    for (const type of Object.values(schema.nodes)) {
      if (type.name === "doc") {
        continue;
      }
      if (type.isBlock || type.isTextblock) {
        break;
      }
    }
  }
  checkAndUpdateDynamicNodes(node, pos, tr) {
    for (const [name, dynamic] of (0, import_core_helpers14.entries)(this.dynamicAttributes.nodes)) {
      if (node.type.name !== name) {
        continue;
      }
      for (const [attributeName, attributeCreator] of (0, import_core_helpers14.entries)(dynamic)) {
        if (!(0, import_core_helpers14.isNullOrUndefined)(node.attrs[attributeName])) {
          continue;
        }
        const attrs = { ...node.attrs, [attributeName]: attributeCreator(node) };
        tr.setNodeMarkup(pos, void 0, attrs);
        (0, import_suggest.ignoreUpdateForSuggest)(tr);
      }
    }
  }
  checkAndUpdateDynamicMarks(node, pos, tr) {
    for (const [name, dynamic] of (0, import_core_helpers14.entries)(this.dynamicAttributes.marks)) {
      const type = (0, import_core_helpers14.assertGet)(this.store.schema.marks, name);
      const mark = node.marks.find((mark2) => mark2.type.name === name);
      if (!mark) {
        continue;
      }
      for (const [attributeName, attributeCreator] of (0, import_core_helpers14.entries)(dynamic)) {
        if (!(0, import_core_helpers14.isNullOrUndefined)(mark.attrs[attributeName])) {
          continue;
        }
        const range = (0, import_core_utils8.getMarkRange)(tr.doc.resolve(pos), type);
        if (!range) {
          continue;
        }
        const { from, to } = range;
        const newMark = type.create({
          ...mark.attrs,
          [attributeName]: attributeCreator(mark)
        });
        tr.removeMark(from, to, type).addMark(from, to, newMark);
        (0, import_suggest.ignoreUpdateForSuggest)(tr);
      }
    }
  }
  gatherExtraAttributes(extensions) {
    const extraSchemaAttributes = [];
    for (const extension2 of extensions) {
      if (!extension2.createSchemaAttributes) {
        continue;
      }
      extraSchemaAttributes.push(...extension2.createSchemaAttributes());
    }
    return extraSchemaAttributes;
  }
};
SchemaExtension = __decorateClass([
  extension({ defaultPriority: import_core_constants12.ExtensionPriority.Highest })
], SchemaExtension);
function getNamedSchemaAttributes(props) {
  var _a, _b;
  const { settings, gatheredSchemaAttributes, nodeNames, markNames, tags } = props;
  const extraAttributes = (0, import_core_helpers14.object)();
  if (settings.disableExtraAttributes) {
    return extraAttributes;
  }
  const extraSchemaAttributes = [
    ...gatheredSchemaAttributes,
    ...(_a = settings.extraAttributes) != null ? _a : []
  ];
  for (const attributeGroup of extraSchemaAttributes != null ? extraSchemaAttributes : []) {
    const identifiers = getIdentifiers({
      identifiers: attributeGroup.identifiers,
      nodeNames,
      markNames,
      tags
    });
    for (const identifier of identifiers) {
      const currentValue = (_b = extraAttributes[identifier]) != null ? _b : {};
      extraAttributes[identifier] = { ...currentValue, ...attributeGroup.attributes };
    }
  }
  return extraAttributes;
}
function isIdentifiersObject(value) {
  return (0, import_core_helpers14.isPlainObject)(value) && (0, import_core_helpers14.isArray)(value.tags);
}
function getIdentifiers(props) {
  var _a;
  const { identifiers, nodeNames, markNames, tags } = props;
  if (identifiers === "nodes") {
    return nodeNames;
  }
  if (identifiers === "marks") {
    return markNames;
  }
  if (identifiers === "all") {
    return [...nodeNames, ...markNames];
  }
  if ((0, import_core_helpers14.isArray)(identifiers)) {
    return identifiers;
  }
  (0, import_core_helpers14.invariant)(isIdentifiersObject(identifiers), {
    code: import_core_constants12.ErrorConstant.EXTENSION_EXTRA_ATTRIBUTES,
    message: `Invalid value passed as an identifier when creating \`extraAttributes\`.`
  });
  const {
    tags: extensionTags = [],
    names: extensionNames = [],
    behavior = "any",
    excludeNames,
    excludeTags,
    type
  } = identifiers;
  const names = /* @__PURE__ */ new Set();
  const acceptableNames = type === "mark" ? markNames : type === "node" ? nodeNames : [...markNames, ...nodeNames];
  const isNameValid = (name) => acceptableNames.includes(name) && !(excludeNames == null ? void 0 : excludeNames.includes(name));
  for (const name of extensionNames) {
    if (isNameValid(name)) {
      names.add(name);
    }
  }
  const taggedNamesMap = /* @__PURE__ */ new Map();
  for (const tag of extensionTags) {
    if (excludeTags == null ? void 0 : excludeTags.includes(tag)) {
      continue;
    }
    for (const name of tags[tag]) {
      if (!isNameValid(name)) {
        continue;
      }
      if (behavior === "any") {
        names.add(name);
        continue;
      }
      const tagSet = (_a = taggedNamesMap.get(name)) != null ? _a : /* @__PURE__ */ new Set();
      tagSet.add(tag);
      taggedNamesMap.set(name, tagSet);
    }
  }
  for (const [name, tagSet] of taggedNamesMap) {
    if (tagSet.size === extensionTags.length) {
      names.add(name);
    }
  }
  return [...names];
}
function createSpec(props) {
  var _a, _b;
  const { createExtensionSpec, extraAttributes, ignoreExtraAttributes, name, tags, override } = props;
  const dynamic = (0, import_core_helpers14.object)();
  function addDynamic(attributeName, creator) {
    dynamic[attributeName] = creator;
  }
  let defaultsCalled = false;
  function onDefaultsCalled() {
    defaultsCalled = true;
  }
  const defaults = createDefaults(extraAttributes, ignoreExtraAttributes, onDefaultsCalled, addDynamic);
  const parse = createParseDOM(extraAttributes, ignoreExtraAttributes);
  const dom = createToDOM(extraAttributes, ignoreExtraAttributes);
  const spec = createExtensionSpec({ defaults, parse, dom }, override);
  (0, import_core_helpers14.invariant)(ignoreExtraAttributes || defaultsCalled, {
    code: import_core_constants12.ErrorConstant.EXTENSION_SPEC,
    message: `When creating a node specification you must call the 'defaults', and parse, and 'dom' methods. To avoid this error you can set the static property 'disableExtraAttributes' of '${name}' to 'true'.`
  });
  spec.group = [...(_b = (_a = spec.group) == null ? void 0 : _a.split(" ")) != null ? _b : [], ...tags].join(" ") || void 0;
  return { spec, dynamic };
}
function getExtraAttributesObject(value) {
  if ((0, import_core_helpers14.isString)(value) || (0, import_core_helpers14.isFunction)(value)) {
    return { default: value };
  }
  (0, import_core_helpers14.invariant)(value, {
    message: `${(0, import_core_helpers14.toString)(value)} is not supported`,
    code: import_core_constants12.ErrorConstant.EXTENSION_EXTRA_ATTRIBUTES
  });
  return value;
}
function createDefaults(extraAttributes, shouldIgnore, onCalled, addDynamicCreator) {
  return () => {
    onCalled();
    const attributes = (0, import_core_helpers14.object)();
    if (shouldIgnore) {
      return attributes;
    }
    for (const [name, config] of (0, import_core_helpers14.entries)(extraAttributes)) {
      const attributesObject = getExtraAttributesObject(config);
      let defaultValue = attributesObject.default;
      if ((0, import_core_helpers14.isFunction)(defaultValue)) {
        addDynamicCreator(name, defaultValue);
        defaultValue = null;
      }
      attributes[name] = defaultValue === void 0 ? {} : { default: defaultValue };
    }
    return attributes;
  };
}
function createParseDOM(extraAttributes, shouldIgnore) {
  return (domNode) => {
    var _a, _b, _c;
    const attributes = (0, import_core_helpers14.object)();
    if (shouldIgnore) {
      return attributes;
    }
    for (const [name, config] of (0, import_core_helpers14.entries)(extraAttributes)) {
      const { parseDOM, ...other } = getExtraAttributesObject(config);
      if (!(0, import_core_utils8.isElementDomNode)(domNode)) {
        continue;
      }
      if ((0, import_core_helpers14.isNullOrUndefined)(parseDOM)) {
        attributes[name] = (_a = domNode.getAttribute(name)) != null ? _a : other.default;
        continue;
      }
      if ((0, import_core_helpers14.isFunction)(parseDOM)) {
        attributes[name] = (_b = parseDOM(domNode)) != null ? _b : other.default;
        continue;
      }
      attributes[name] = (_c = domNode.getAttribute(parseDOM)) != null ? _c : other.default;
    }
    return attributes;
  };
}
function createToDOM(extraAttributes, shouldIgnore) {
  return (item) => {
    const domAttributes = (0, import_core_helpers14.object)();
    if (shouldIgnore) {
      return domAttributes;
    }
    function updateDomAttributes(value, name) {
      if (!value) {
        return;
      }
      if ((0, import_core_helpers14.isString)(value)) {
        domAttributes[name] = value;
        return;
      }
      if ((0, import_core_helpers14.isArray)(value)) {
        const [attr, val] = value;
        domAttributes[attr] = val != null ? val : item.attrs[name];
        return;
      }
      for (const [attr, val] of (0, import_core_helpers14.entries)(value)) {
        domAttributes[attr] = val;
      }
    }
    for (const [name, config] of (0, import_core_helpers14.entries)(extraAttributes)) {
      const { toDOM, parseDOM } = getExtraAttributesObject(config);
      if ((0, import_core_helpers14.isNullOrUndefined)(toDOM)) {
        const key2 = (0, import_core_helpers14.isString)(parseDOM) ? parseDOM : name;
        domAttributes[key2] = item.attrs[name];
        continue;
      }
      if ((0, import_core_helpers14.isFunction)(toDOM)) {
        updateDomAttributes(toDOM(item.attrs, getNodeMarkOptions(item)), name);
        continue;
      }
      updateDomAttributes(toDOM, name);
    }
    return domAttributes;
  };
}
function getNodeMarkOptions(item) {
  if ((0, import_core_utils8.isProsemirrorNode)(item)) {
    return { node: item };
  }
  if ((0, import_core_utils8.isProsemirrorMark)(item)) {
    return { mark: item };
  }
  return {};
}
function getSpecFromSchema(schema) {
  const nodes = (0, import_core_helpers14.object)();
  const marks = (0, import_core_helpers14.object)();
  for (const [name, type] of Object.entries(schema.nodes)) {
    nodes[name] = type.spec;
  }
  for (const [name, type] of Object.entries(schema.marks)) {
    marks[name] = type.spec;
  }
  return { nodes, marks };
}

// packages/remirror__core/src/builtins/suggest-extension.ts
var import_core_helpers15 = require("@remirror/core-helpers");
var import_suggest2 = require("@remirror/pm/suggest");
var SuggestExtension = class extends PlainExtension {
  constructor() {
    super(...arguments);
    __publicField(this, "onAddCustomHandler", ({ suggester }) => {
      var _a;
      if (!suggester || ((_a = this.store.managerSettings.exclude) == null ? void 0 : _a.suggesters)) {
        return;
      }
      return (0, import_suggest2.addSuggester)(this.store.getState(), suggester);
    });
  }
  get name() {
    return "suggest";
  }
  onCreate() {
    this.store.setExtensionStore("addSuggester", (suggester) => (0, import_suggest2.addSuggester)(this.store.getState(), suggester));
    this.store.setExtensionStore("removeSuggester", (suggester) => (0, import_suggest2.removeSuggester)(this.store.getState(), suggester));
  }
  createExternalPlugins() {
    var _a, _b;
    const suggesters = [];
    for (const extension2 of this.store.extensions) {
      if ((_a = this.store.managerSettings.exclude) == null ? void 0 : _a.suggesters) {
        break;
      }
      if (!extension2.createSuggesters || ((_b = extension2.options.exclude) == null ? void 0 : _b.suggesters)) {
        continue;
      }
      const suggester = extension2.createSuggesters();
      const suggesterList = (0, import_core_helpers15.isArray)(suggester) ? suggester : [suggester];
      suggesters.push(...suggesterList);
    }
    return [(0, import_suggest2.suggest)(...suggesters)];
  }
  getSuggestState(state) {
    return (0, import_suggest2.getSuggestPluginState)(state != null ? state : this.store.getState());
  }
  getSuggestMethods() {
    const {
      addIgnored,
      clearIgnored,
      removeIgnored,
      ignoreNextExit,
      setMarkRemoved,
      findMatchAtPosition,
      findNextTextSelection,
      setLastChangeFromAppend
    } = this.getSuggestState();
    return {
      addIgnored,
      clearIgnored,
      removeIgnored,
      ignoreNextExit,
      setMarkRemoved,
      findMatchAtPosition,
      findNextTextSelection,
      setLastChangeFromAppend
    };
  }
  isSuggesterActive(name) {
    var _a;
    return (0, import_core_helpers15.includes)((0, import_core_helpers15.isArray)(name) ? name : [name], (_a = this.getSuggestState().match) == null ? void 0 : _a.suggester.name);
  }
};
__decorateClass([
  helper()
], SuggestExtension.prototype, "getSuggestState", 1);
__decorateClass([
  helper()
], SuggestExtension.prototype, "getSuggestMethods", 1);
__decorateClass([
  helper()
], SuggestExtension.prototype, "isSuggesterActive", 1);
SuggestExtension = __decorateClass([
  extension({ customHandlerKeys: ["suggester"] })
], SuggestExtension);

// packages/remirror__core/src/builtins/tags-extension.ts
var import_core_constants13 = require("@remirror/core-constants");
var import_core_helpers16 = require("@remirror/core-helpers");
var TagsExtension = class extends PlainExtension {
  constructor() {
    super(...arguments);
    __publicField(this, "allTags", (0, import_core_helpers16.object)());
    __publicField(this, "plainTags", (0, import_core_helpers16.object)());
    __publicField(this, "markTags", (0, import_core_helpers16.object)());
    __publicField(this, "nodeTags", (0, import_core_helpers16.object)());
  }
  get name() {
    return "tags";
  }
  onCreate() {
    this.resetTags();
    for (const extension2 of this.store.extensions) {
      this.updateTagForExtension(extension2);
    }
    this.store.setStoreKey("tags", this.allTags);
    this.store.setExtensionStore("tags", this.allTags);
    this.store.setStoreKey("plainTags", this.plainTags);
    this.store.setExtensionStore("plainTags", this.plainTags);
    this.store.setStoreKey("markTags", this.markTags);
    this.store.setExtensionStore("markTags", this.markTags);
    this.store.setStoreKey("nodeTags", this.nodeTags);
    this.store.setExtensionStore("nodeTags", this.nodeTags);
  }
  resetTags() {
    const allTags = (0, import_core_helpers16.object)();
    const plainTags = (0, import_core_helpers16.object)();
    const markTags = (0, import_core_helpers16.object)();
    const nodeTags = (0, import_core_helpers16.object)();
    for (const tagName of (0, import_core_helpers16.values)(import_core_constants13.ExtensionTag)) {
      allTags[tagName] = [];
      plainTags[tagName] = [];
      markTags[tagName] = [];
      nodeTags[tagName] = [];
    }
    this.allTags = allTags;
    this.plainTags = plainTags;
    this.markTags = markTags;
    this.nodeTags = nodeTags;
  }
  updateTagForExtension(extension2) {
    var _a, _b, _c, _d, _e, _f;
    const allTags = /* @__PURE__ */ new Set([
      ...(_a = extension2.tags) != null ? _a : [],
      ...(_c = (_b = extension2.createTags) == null ? void 0 : _b.call(extension2)) != null ? _c : [],
      ...(_d = extension2.options.extraTags) != null ? _d : [],
      ...(_f = (_e = this.store.managerSettings.extraTags) == null ? void 0 : _e[extension2.name]) != null ? _f : []
    ]);
    for (const tag of allTags) {
      (0, import_core_helpers16.invariant)(isExtensionTag(tag), {
        code: import_core_constants13.ErrorConstant.EXTENSION,
        message: `The tag provided by the extension: ${extension2.constructorName} is not supported by the editor. To add custom tags you can use the 'mutateTag' method.`
      });
      this.allTags[tag].push(extension2.name);
      if (isPlainExtension(extension2)) {
        this.plainTags[tag].push(extension2.name);
      }
      if (isMarkExtension(extension2)) {
        this.markTags[tag].push(extension2.name);
      }
      if (isNodeExtension(extension2)) {
        this.nodeTags[tag].push(extension2.name);
      }
    }
    extension2.tags = [...allTags];
  }
};
TagsExtension = __decorateClass([
  extension({ defaultPriority: import_core_constants13.ExtensionPriority.Highest })
], TagsExtension);
function isExtensionTag(value) {
  return (0, import_core_helpers16.includes)((0, import_core_helpers16.values)(import_core_constants13.ExtensionTag), value);
}

// packages/remirror__core/src/builtins/upload-extension/file-placeholder-plugin.ts
var import_state4 = require("@remirror/pm/state");
var import_view2 = require("@remirror/pm/view");
var key = new import_state4.PluginKey("remirrorFilePlaceholderPlugin");
function createUploadPlaceholderPlugin() {
  const plugin = new import_state4.Plugin({
    key,
    state: {
      init() {
        return { set: import_view2.DecorationSet.empty, payloads: /* @__PURE__ */ new Map() };
      },
      apply(tr, { set, payloads }) {
        set = set.map(tr.mapping, tr.doc);
        const action = tr.getMeta(plugin);
        if (action) {
          if (action.type === 0 /* ADD_PLACEHOLDER */) {
            const widget = document.createElement("placeholder");
            const deco = import_view2.Decoration.widget(action.pos, widget, { id: action.id });
            set = set.add(tr.doc, [deco]);
            payloads.set(action.id, action.payload);
          } else if (action.type === 1 /* REMOVE_PLACEHOLDER */) {
            set = set.remove(set.find(void 0, void 0, (spec) => spec.id === action.id));
            payloads.delete(action.id);
          }
        }
        return { set, payloads };
      }
    },
    props: {
      decorations(state) {
        var _a, _b;
        return (_b = (_a = plugin.getState(state)) == null ? void 0 : _a.set) != null ? _b : null;
      }
    }
  });
  return plugin;
}
function findUploadPlaceholderPos(state, id) {
  var _a, _b;
  const set = (_a = key.getState(state)) == null ? void 0 : _a.set;
  if (set) {
    const decorations = set.find(void 0, void 0, (spec) => spec.id === id);
    const pos = (_b = decorations == null ? void 0 : decorations[0]) == null ? void 0 : _b.from;
    if (pos != null) {
      return pos;
    }
  }
  let foundPos;
  state.doc.descendants((node, pos) => {
    if (node.attrs.id === id) {
      foundPos = pos;
    }
    return foundPos === void 0;
  });
  return foundPos;
}
function findUploadPlaceholderPayload(state, id) {
  var _a;
  const payloads = (_a = key.getState(state)) == null ? void 0 : _a.payloads;
  if (!payloads) {
    return void 0;
  }
  return payloads.get(id);
}
function hasUploadingFile(state) {
  var _a, _b, _c;
  const placeholderCount = (_c = (_b = (_a = key.getState(state)) == null ? void 0 : _a.payloads) == null ? void 0 : _b.size) != null ? _c : 0;
  return placeholderCount > 0;
}
function setUploadPlaceholderAction(tr, action) {
  return tr.setMeta(key, action);
}

// packages/remirror__core/src/builtins/upload-extension/file-upload.ts
var import_core_helpers17 = require("@remirror/core-helpers");

// packages/remirror__core/src/builtins/upload-extension/upload-context.ts
var import_nanoevents = require("nanoevents");
function createUploadContext() {
  const values3 = {};
  const emitter = (0, import_nanoevents.createNanoEvents)();
  const get = (key2) => {
    return values3[key2];
  };
  const set = (key2, value) => {
    values3[key2] = value;
    emitter.emit("set", values3);
  };
  const addListener = (listener) => {
    return emitter.on("set", listener);
  };
  return { set, get, addListener };
}

// packages/remirror__core/src/builtins/upload-extension/file-upload.ts
function uploadFile({
  file,
  pos,
  view,
  fileType,
  uploadHandler
}) {
  const id = (0, import_core_helpers17.uniqueId)("file-placeholder-");
  const context = createUploadContext();
  const fileUploader = createFilePlaceholder({
    id,
    context,
    file,
    pos,
    view,
    fileType,
    uploadHandler
  });
  fileUploader == null ? void 0 : fileUploader.upload(context).then((attrs) => onFileLoaded({ id, fileType, view, attrs })).catch((error) => onFileLoaded({ id, fileType, view, attrs: { error: error.message } }));
}
function insertFilePoint(doc, pos, nodeType) {
  const $pos = doc.resolve(pos);
  if ($pos.parent.canReplaceWith($pos.index(), $pos.index(), nodeType)) {
    return pos;
  }
  if ($pos.parentOffset === 0) {
    for (let d = $pos.depth - 1; d >= 0; d--) {
      const index = $pos.index(d);
      if ($pos.node(d).canReplaceWith(index, index, nodeType)) {
        return $pos.before(d + 1);
      }
      if (index > 0) {
        return null;
      }
    }
  }
  for (let d = $pos.depth - 1; d >= 0; d--) {
    const index = $pos.indexAfter(d);
    if ($pos.node(d).canReplaceWith(index, index, nodeType)) {
      return $pos.after(d + 1);
    }
    if (index < $pos.node(d).childCount) {
      return null;
    }
  }
  return null;
}
function createFilePlaceholder({
  id,
  context,
  file,
  pos,
  view,
  fileType,
  uploadHandler
}) {
  const tr = view.state.tr;
  const insertPos = insertFilePoint(tr.doc, (0, import_core_helpers17.isNumber)(pos) ? pos : tr.selection.from, fileType);
  if (!(0, import_core_helpers17.isNumber)(insertPos)) {
    return;
  }
  const fileUploader = uploadHandler();
  const attrs = { ...fileUploader.insert(file), id };
  tr.insert(insertPos, fileType.createChecked(attrs));
  const payload = { context, fileUploader };
  setUploadPlaceholderAction(tr, { type: 0 /* ADD_PLACEHOLDER */, id, pos: insertPos, payload });
  view.dispatch(tr);
  return fileUploader;
}
function onFileLoaded({
  id,
  attrs,
  fileType,
  view
}) {
  const placeholderPos = findUploadPlaceholderPos(view.state, id);
  if (placeholderPos == null) {
    return;
  }
  const $pos = view.state.doc.resolve(placeholderPos);
  const fileNode = $pos.nodeAfter;
  if (!fileNode || fileNode.type !== fileType || fileNode.attrs.id !== id) {
    const tr2 = view.state.tr;
    setUploadPlaceholderAction(tr2, { type: 1 /* REMOVE_PLACEHOLDER */, id });
    view.dispatch(tr2);
    return;
  }
  const tr = view.state.tr;
  setUploadPlaceholderAction(tr, { type: 1 /* REMOVE_PLACEHOLDER */, id });
  const fileAttrs = { ...fileNode.attrs, ...attrs, id: null };
  tr.setNodeMarkup(placeholderPos, void 0, fileAttrs);
  view.dispatch(tr);
}

// packages/remirror__core/src/builtins/upload-extension/upload-extension.ts
var UploadExtension = class extends PlainExtension {
  get name() {
    return "upload";
  }
  createExternalPlugins() {
    return [createUploadPlaceholderPlugin()];
  }
};

// packages/remirror__core/src/builtins/builtin-preset.ts
function builtinPreset(options = {}) {
  const defaultOptions2 = {
    exitMarksOnArrowPress: KeymapExtension.defaultOptions.exitMarksOnArrowPress,
    excludeBaseKeymap: KeymapExtension.defaultOptions.excludeBaseKeymap,
    selectParentNodeOnEscape: KeymapExtension.defaultOptions.selectParentNodeOnEscape,
    undoInputRuleOnBackspace: KeymapExtension.defaultOptions.undoInputRuleOnBackspace,
    persistentSelectionClass: DecorationsExtension.defaultOptions.persistentSelectionClass
  };
  options = { ...defaultOptions2, ...options };
  const keymapOptions = (0, import_core_helpers18.pick)(options, [
    "excludeBaseKeymap",
    "selectParentNodeOnEscape",
    "undoInputRuleOnBackspace"
  ]);
  const decorationsOptions = (0, import_core_helpers18.pick)(options, ["persistentSelectionClass"]);
  return [
    new TagsExtension(),
    new SchemaExtension(),
    new AttributesExtension(),
    new PluginsExtension(),
    new InputRulesExtension(),
    new PasteRulesExtension(),
    new NodeViewsExtension(),
    new SuggestExtension(),
    new CommandsExtension(),
    new HelpersExtension(),
    new KeymapExtension(keymapOptions),
    new DocChangedExtension(),
    new UploadExtension(),
    new DecorationsExtension(decorationsOptions)
  ];
}

// packages/remirror__core/src/builtins/meta-extension.ts
var import_core_constants14 = require("@remirror/core-constants");
var import_core_utils9 = require("@remirror/core-utils");
var MetaExtension = class extends PlainExtension {
  get name() {
    return "meta";
  }
  onCreate() {
    this.store.setStoreKey("getCommandMeta", this.getCommandMeta.bind(this));
    if (!this.options.capture) {
      return;
    }
    for (const extension2 of this.store.extensions) {
      this.captureCommands(extension2);
      this.captureKeybindings(extension2);
    }
  }
  createPlugin() {
    return {};
  }
  captureCommands(extension2) {
    var _a;
    const decoratedCommands = (_a = extension2.decoratedCommands) != null ? _a : {};
    const createCommands = extension2.createCommands;
    for (const name of Object.keys(decoratedCommands)) {
      const command2 = extension2[name];
      extension2[name] = (...args) => (props) => {
        var _a2;
        const value = command2(...args)(props);
        if (props.dispatch && value) {
          this.setCommandMeta(props.tr, {
            type: "command",
            chain: props.dispatch !== ((_a2 = props.view) == null ? void 0 : _a2.dispatch),
            name,
            extension: extension2.name,
            decorated: true
          });
        }
        return value;
      };
    }
    if (createCommands) {
      extension2.createCommands = () => {
        const commandsObject = createCommands();
        for (const [name, command2] of Object.entries(commandsObject)) {
          commandsObject[name] = (...args) => (props) => {
            var _a2;
            const value = command2(...args)(props);
            if (props.dispatch && value) {
              this.setCommandMeta(props.tr, {
                type: "command",
                chain: props.dispatch !== ((_a2 = props.view) == null ? void 0 : _a2.dispatch),
                name,
                extension: extension2.name,
                decorated: false
              });
            }
            return value;
          };
        }
        return commandsObject;
      };
    }
  }
  captureKeybindings(_) {
  }
  getCommandMeta(tr) {
    var _a;
    return (_a = tr.getMeta(this.pluginKey)) != null ? _a : [];
  }
  setCommandMeta(tr, update) {
    const meta = this.getCommandMeta(tr);
    tr.setMeta(this.pluginKey, [...meta, update]);
  }
};
MetaExtension = __decorateClass([
  extension({
    defaultOptions: {
      capture: import_core_utils9.environment.isDevelopment
    },
    staticKeys: ["capture"],
    defaultPriority: import_core_constants14.ExtensionPriority.Highest
  })
], MetaExtension);

// packages/remirror__core/src/framework/framework.ts
var import_nanoevents2 = require("nanoevents");
var import_core_constants15 = require("@remirror/core-constants");
var import_core_helpers19 = require("@remirror/core-helpers");
var _uid, _getProps, _previousState, _firstRender, _events, _addHandler, _initialEditorState;
var Framework = class {
  constructor(options) {
    __privateAdd(this, _uid, (0, import_core_helpers19.uniqueId)());
    __privateAdd(this, _getProps, void 0);
    __privateAdd(this, _previousState, void 0);
    __publicField(this, "previousStateOverride");
    __privateAdd(this, _firstRender, true);
    __privateAdd(this, _events, (0, import_nanoevents2.createNanoEvents)());
    __privateAdd(this, _addHandler, void 0);
    __privateAdd(this, _initialEditorState, void 0);
    __publicField(this, "getState", () => {
      var _a;
      return (_a = this.view.state) != null ? _a : this.initialEditorState;
    });
    __publicField(this, "getPreviousState", () => this.previousState);
    __publicField(this, "dispatchTransaction", (tr) => {
      var _a, _b, _c;
      (0, import_core_helpers19.invariant)(!this.manager.destroyed, {
        code: import_core_constants15.ErrorConstant.MANAGER_PHASE_ERROR,
        message: "A transaction was dispatched to a manager that has already been destroyed. Please check your set up, or open an issue."
      });
      tr = (_c = (_b = (_a = this.props).onDispatchTransaction) == null ? void 0 : _b.call(_a, tr, this.getState())) != null ? _c : tr;
      const previousState = this.getState();
      const { state, transactions } = previousState.applyTransaction(tr);
      __privateSet(this, _previousState, previousState);
      this.updateState({ state, tr, transactions });
      const forcedUpdates = this.manager.store.getForcedUpdates(tr);
      if (!(0, import_core_helpers19.isEmptyArray)(forcedUpdates)) {
        this.updateViewProps(...forcedUpdates);
      }
    });
    __publicField(this, "onChange", (props = (0, import_core_helpers19.object)()) => {
      var _a, _b;
      const onChangeProps = this.eventListenerProps(props);
      if (__privateGet(this, _firstRender)) {
        __privateSet(this, _firstRender, false);
      }
      (_b = (_a = this.props).onChange) == null ? void 0 : _b.call(_a, onChangeProps);
    });
    __publicField(this, "onBlur", (event) => {
      var _a, _b;
      const props = this.eventListenerProps();
      (_b = (_a = this.props).onBlur) == null ? void 0 : _b.call(_a, props, event);
      __privateGet(this, _events).emit("blur", props, event);
    });
    __publicField(this, "onFocus", (event) => {
      var _a, _b;
      const props = this.eventListenerProps();
      (_b = (_a = this.props).onFocus) == null ? void 0 : _b.call(_a, props, event);
      __privateGet(this, _events).emit("focus", props, event);
    });
    __publicField(this, "setContent", (content, { triggerChange = false } = {}) => {
      const { doc } = this.manager.createState({ content });
      const previousState = this.getState();
      const { state } = this.getState().applyTransaction(previousState.tr.replaceRangeWith(0, previousState.doc.nodeSize - 2, doc));
      if (triggerChange) {
        return this.updateState({ state, triggerChange });
      }
      this.view.updateState(state);
    });
    __publicField(this, "clearContent", ({ triggerChange = false } = {}) => {
      this.setContent(this.manager.createEmptyDoc(), { triggerChange });
    });
    __publicField(this, "createStateFromContent", (content, selection) => {
      return this.manager.createState({ content, selection });
    });
    __publicField(this, "focus", (position) => {
      this.manager.store.commands.focus(position);
    });
    __publicField(this, "blur", (position) => {
      this.manager.store.commands.blur(position);
    });
    const { getProps, initialEditorState, element } = options;
    __privateSet(this, _getProps, getProps);
    __privateSet(this, _initialEditorState, initialEditorState);
    this.manager.attachFramework(this, this.updateListener.bind(this));
    if (this.manager.view) {
      return;
    }
    const view = this.createView(initialEditorState, element);
    this.manager.addView(view);
  }
  get addHandler() {
    var _a;
    return (_a = __privateGet(this, _addHandler)) != null ? _a : __privateSet(this, _addHandler, __privateGet(this, _events).on.bind(__privateGet(this, _events)));
  }
  get updatableViewProps() {
    return {
      attributes: () => this.getAttributes(),
      editable: () => {
        var _a;
        return (_a = this.props.editable) != null ? _a : true;
      }
    };
  }
  get firstRender() {
    return __privateGet(this, _firstRender);
  }
  get props() {
    return __privateGet(this, _getProps).call(this);
  }
  get previousState() {
    var _a, _b;
    return (_b = (_a = this.previousStateOverride) != null ? _a : __privateGet(this, _previousState)) != null ? _b : this.initialEditorState;
  }
  get manager() {
    return this.props.manager;
  }
  get view() {
    return this.manager.view;
  }
  get uid() {
    return __privateGet(this, _uid);
  }
  get initialEditorState() {
    return __privateGet(this, _initialEditorState);
  }
  updateListener(props) {
    const { state, tr } = props;
    return __privateGet(this, _events).emit("updated", this.eventListenerProps({ state, tr }));
  }
  update(options) {
    const { getProps } = options;
    __privateSet(this, _getProps, getProps);
    return this;
  }
  updateViewProps(...keys3) {
    const props = (0, import_core_helpers19.pick)(this.updatableViewProps, keys3);
    this.view.setProps({ ...this.view.props, ...props });
  }
  getAttributes(ssr) {
    var _a;
    const { attributes, autoFocus, classNames = [], label, editable } = this.props;
    const managerAttributes = (_a = this.manager.store) == null ? void 0 : _a.attributes;
    const propAttributes = (0, import_core_helpers19.isFunction)(attributes) ? attributes(this.eventListenerProps()) : attributes;
    let focus = {};
    if (autoFocus || (0, import_core_helpers19.isNumber)(autoFocus)) {
      focus = ssr ? { autoFocus: true } : { autofocus: "true" };
    }
    const uniqueClasses = (0, import_core_helpers19.uniqueArray)((0, import_core_helpers19.cx)(ssr && "Prosemirror", "remirror-editor", managerAttributes == null ? void 0 : managerAttributes.class, ...classNames).split(" ")).join(" ");
    const defaultAttributes = {
      role: "textbox",
      ...focus,
      "aria-multiline": "true",
      ...!(editable != null ? editable : true) ? { "aria-readonly": "true" } : {},
      "aria-label": label != null ? label : "",
      ...managerAttributes,
      class: uniqueClasses
    };
    return (0, import_core_helpers19.omitUndefined)({ ...defaultAttributes, ...propAttributes });
  }
  addFocusListeners() {
    this.view.dom.addEventListener("blur", this.onBlur);
    this.view.dom.addEventListener("focus", this.onFocus);
  }
  removeFocusListeners() {
    this.view.dom.removeEventListener("blur", this.onBlur);
    this.view.dom.removeEventListener("focus", this.onFocus);
  }
  destroy() {
    __privateGet(this, _events).emit("destroy");
    if (this.view) {
      this.removeFocusListeners();
    }
  }
  eventListenerProps(props = (0, import_core_helpers19.object)()) {
    const { state, tr, transactions } = props;
    return {
      tr,
      transactions,
      internalUpdate: !tr,
      view: this.view,
      firstRender: __privateGet(this, _firstRender),
      state: state != null ? state : this.getState(),
      createStateFromContent: this.createStateFromContent,
      previousState: this.previousState,
      helpers: this.manager.store.helpers
    };
  }
  get baseOutput() {
    return {
      manager: this.manager,
      ...this.manager.store,
      addHandler: this.addHandler,
      focus: this.focus,
      blur: this.blur,
      uid: __privateGet(this, _uid),
      view: this.view,
      getState: this.getState,
      getPreviousState: this.getPreviousState,
      getExtension: this.manager.getExtension.bind(this.manager),
      hasExtension: this.manager.hasExtension.bind(this.manager),
      clearContent: this.clearContent,
      setContent: this.setContent
    };
  }
};
_uid = new WeakMap();
_getProps = new WeakMap();
_previousState = new WeakMap();
_firstRender = new WeakMap();
_events = new WeakMap();
_addHandler = new WeakMap();
_initialEditorState = new WeakMap();

// packages/remirror__core/src/manager/remirror-manager.ts
var import_nanoevents3 = require("nanoevents");
var import_core_constants17 = require("@remirror/core-constants");
var import_core_helpers21 = require("@remirror/core-helpers");
var import_core_utils10 = require("@remirror/core-utils");
var import_state5 = require("@remirror/pm/state");

// packages/remirror__core/src/manager/remirror-manager-helpers.ts
var import_tiny_warning = __toESM(require("tiny-warning"), 1);
var import_core_constants16 = require("@remirror/core-constants");
var import_core_helpers20 = require("@remirror/core-helpers");
function transformExtensions(initialExtensions, settings) {
  const extensions = [];
  const extensionMap = /* @__PURE__ */ new WeakMap();
  const parentExtensions = [];
  const duplicateMap = /* @__PURE__ */ new WeakMap();
  let gatheredExtensions = [];
  const gatherRawExtensionConfig = { duplicateMap, parentExtensions, gatheredExtensions, settings };
  for (const extension2 of initialExtensions) {
    gatherRawExtensions(gatherRawExtensionConfig, { extension: extension2 });
  }
  gatheredExtensions = (0, import_core_helpers20.sort)(gatheredExtensions, (a, z) => z.priority - a.priority);
  const found = /* @__PURE__ */ new WeakSet();
  const names = /* @__PURE__ */ new Set();
  for (const extension2 of gatheredExtensions) {
    const key2 = extension2.constructor;
    const name = extension2.name;
    const duplicates = duplicateMap.get(key2);
    (0, import_core_helpers20.invariant)(duplicates, {
      message: `No entries were found for the ExtensionConstructor ${extension2.name}`,
      code: import_core_constants16.ErrorConstant.INTERNAL
    });
    if (found.has(key2) || names.has(name)) {
      continue;
    }
    found.add(key2);
    names.add(name);
    extensions.push(extension2);
    extensionMap.set(key2, extension2);
    duplicates.forEach((parent) => parent == null ? void 0 : parent.replaceChildExtension(key2, extension2));
  }
  const missing = [];
  for (const extension2 of extensions) {
    findMissingExtensions({ extension: extension2, found, missing });
  }
  (0, import_core_helpers20.invariant)((0, import_core_helpers20.isEmptyArray)(missing), {
    code: import_core_constants16.ErrorConstant.MISSING_REQUIRED_EXTENSION,
    message: missing.map(({ Constructor, extension: extension2 }) => `The extension '${extension2.name}' requires '${Constructor.name} in order to run correctly.`).join("\n")
  });
  return { extensions, extensionMap };
}
function gatherRawExtensions(config, props) {
  var _a;
  const { gatheredExtensions, duplicateMap, parentExtensions, settings } = config;
  const { extension: extension2, parentExtension } = props;
  let { names = [] } = props;
  (0, import_core_helpers20.invariant)(isExtension(extension2), {
    code: import_core_constants16.ErrorConstant.INVALID_MANAGER_EXTENSION,
    message: `An invalid extension: ${extension2} was provided to the [[\`RemirrorManager\`]].`
  });
  const childExtensions = extension2.extensions;
  extension2.setPriority((_a = settings.priority) == null ? void 0 : _a[extension2.name]);
  gatheredExtensions.push(extension2);
  updateExtensionDuplicates({ duplicateMap, extension: extension2, parentExtension });
  if (childExtensions.length === 0) {
    return;
  }
  if (names.includes(extension2.name)) {
    (0, import_tiny_warning.default)(false, `Circular dependency encountered when loading extensions: ${names.join(" > ")} > ${extension2.name}`);
    return;
  }
  names = [...names, extension2.name];
  parentExtensions.push(extension2);
  for (const child of childExtensions) {
    gatherRawExtensions(config, { names, extension: child, parentExtension: extension2 });
  }
}
function findMissingExtensions(props) {
  var _a;
  const { extension: extension2, found, missing } = props;
  if (!extension2.requiredExtensions) {
    return;
  }
  for (const Constructor of (_a = extension2.requiredExtensions) != null ? _a : []) {
    if (found.has(Constructor)) {
      continue;
    }
    missing.push({ Constructor, extension: extension2 });
  }
}
function updateExtensionDuplicates(props) {
  const { duplicateMap, extension: extension2, parentExtension } = props;
  const key2 = extension2.constructor;
  const duplicate = duplicateMap.get(key2);
  const parentToAdd = parentExtension ? [parentExtension] : [];
  duplicateMap.set(key2, duplicate ? [...duplicate, ...parentToAdd] : parentToAdd);
}
function extractLifecycleMethods(props) {
  var _a, _b, _c, _d;
  const { extension: extension2, nodeNames, markNames, plainNames, store, handlers } = props;
  extension2.setStore(store);
  const createHandler = (_a = extension2.onCreate) == null ? void 0 : _a.bind(extension2);
  const viewHandler = (_b = extension2.onView) == null ? void 0 : _b.bind(extension2);
  const stateUpdateHandler = (_c = extension2.onStateUpdate) == null ? void 0 : _c.bind(extension2);
  const destroyHandler = (_d = extension2.onDestroy) == null ? void 0 : _d.bind(extension2);
  if (createHandler) {
    handlers.create.push(createHandler);
  }
  if (viewHandler) {
    handlers.view.push(viewHandler);
  }
  if (stateUpdateHandler) {
    handlers.update.push(stateUpdateHandler);
  }
  if (destroyHandler) {
    handlers.destroy.push(destroyHandler);
  }
  if (isMarkExtension(extension2)) {
    markNames.push(extension2.name);
  }
  if (isNodeExtension(extension2) && extension2.name !== "doc") {
    nodeNames.push(extension2.name);
  }
  if (isPlainExtension(extension2)) {
    plainNames.push(extension2.name);
  }
}

// packages/remirror__core/src/manager/remirror-manager.ts
var _extensionStore, _stringHandlers, _store, _extensions, _extensionMap, _phase, _settings, _firstStateUpdate, _handlers, _disposers, _events2, _framework, _disposeFramework;
var _RemirrorManager = class {
  constructor(initialExtension, settings = {}) {
    __privateAdd(this, _extensionStore, void 0);
    __privateAdd(this, _stringHandlers, (0, import_core_helpers21.object)());
    __privateAdd(this, _store, (0, import_core_helpers21.object)());
    __privateAdd(this, _extensions, void 0);
    __privateAdd(this, _extensionMap, void 0);
    __privateAdd(this, _phase, import_core_constants17.ManagerPhase.None);
    __privateAdd(this, _settings, void 0);
    __privateAdd(this, _firstStateUpdate, true);
    __privateAdd(this, _handlers, {
      create: [],
      view: [],
      update: [],
      destroy: []
    });
    __privateAdd(this, _disposers, []);
    __privateAdd(this, _events2, (0, import_nanoevents3.createNanoEvents)());
    __privateAdd(this, _framework, void 0);
    __privateAdd(this, _disposeFramework, void 0);
    __publicField(this, "getState", () => {
      var _a;
      if (__privateGet(this, _phase) >= import_core_constants17.ManagerPhase.EditorView) {
        return this.view.state;
      }
      (0, import_core_helpers21.invariant)(__privateGet(this, _framework), {
        code: import_core_constants17.ErrorConstant.MANAGER_PHASE_ERROR,
        message: "`getState` can only be called after the `Framework` or the `EditorView` has been added to the manager`. Check your plugins to make sure that the decorations callback uses the state argument."
      });
      return (_a = __privateGet(this, _framework)) == null ? void 0 : _a.initialEditorState;
    });
    __publicField(this, "updateState", (state) => {
      const previousState = this.getState();
      this.view.updateState(state);
      this.onStateUpdate({ previousState, state });
    });
    const { extensions, extensionMap } = transformExtensions(initialExtension, settings);
    __privateSet(this, _settings, settings);
    __privateSet(this, _extensions, (0, import_core_helpers21.freeze)(extensions));
    __privateSet(this, _extensionMap, extensionMap);
    __privateSet(this, _extensionStore, this.createExtensionStore());
    __privateSet(this, _phase, import_core_constants17.ManagerPhase.Create);
    this.setupLifecycleHandlers();
    for (const handler of __privateGet(this, _handlers).create) {
      const disposer = handler();
      if (disposer) {
        __privateGet(this, _disposers).push(disposer);
      }
    }
  }
  static create(extensions, settings = {}) {
    return new _RemirrorManager([...(0, import_core_helpers21.getLazyArray)(extensions), ...builtinPreset(settings.builtin)], settings);
  }
  get [import_core_constants17.__INTERNAL_REMIRROR_IDENTIFIER_KEY__]() {
    return import_core_constants17.RemirrorIdentifier.Manager;
  }
  get destroyed() {
    return __privateGet(this, _phase) === import_core_constants17.ManagerPhase.Destroy;
  }
  get mounted() {
    return __privateGet(this, _phase) >= import_core_constants17.ManagerPhase.EditorView && __privateGet(this, _phase) < import_core_constants17.ManagerPhase.Destroy;
  }
  get output() {
    var _a;
    return (_a = __privateGet(this, _framework)) == null ? void 0 : _a.frameworkOutput;
  }
  get frameworkAttached() {
    return !!__privateGet(this, _framework);
  }
  get extensions() {
    return __privateGet(this, _extensions);
  }
  get stringHandlers() {
    return __privateGet(this, _stringHandlers);
  }
  get store() {
    return (0, import_core_helpers21.freeze)(__privateGet(this, _store));
  }
  get extensionStore() {
    return (0, import_core_helpers21.freeze)(__privateGet(this, _extensionStore));
  }
  get tr() {
    return this.getExtension(CommandsExtension).transaction;
  }
  get nodes() {
    return __privateGet(this, _store).nodes;
  }
  get marks() {
    return __privateGet(this, _store).marks;
  }
  get schema() {
    return __privateGet(this, _store).schema;
  }
  get extensionTags() {
    return __privateGet(this, _store).tags;
  }
  get view() {
    return __privateGet(this, _store).view;
  }
  get settings() {
    return __privateGet(this, _settings);
  }
  get document() {
    var _a;
    return (_a = __privateGet(this, _settings).document) != null ? _a : (0, import_core_utils10.getDocument)();
  }
  setupLifecycleHandlers() {
    const store = __privateGet(this, _extensionStore);
    const handlers = __privateGet(this, _handlers);
    const nodeNames = [];
    const markNames = [];
    const plainNames = [];
    store.nodeNames = nodeNames;
    store.markNames = markNames;
    store.plainNames = plainNames;
    for (const extension2 of __privateGet(this, _extensions)) {
      extractLifecycleMethods({ extension: extension2, nodeNames, markNames, plainNames, handlers, store });
    }
  }
  setStringHandler(name, handler) {
    __privateGet(this, _stringHandlers)[name] = handler;
  }
  setStoreKey(key2, value) {
    __privateGet(this, _store)[key2] = value;
  }
  getStoreKey(key2) {
    const value = __privateGet(this, _store)[key2];
    (0, import_core_helpers21.invariant)(!(0, import_core_helpers21.isNullOrUndefined)(value), {
      code: import_core_constants17.ErrorConstant.MANAGER_PHASE_ERROR,
      message: "`getStoreKey` should not be called before the values are available."
    });
    return value;
  }
  setExtensionStore(key2, value) {
    (0, import_core_helpers21.invariant)(__privateGet(this, _phase) <= import_core_constants17.ManagerPhase.EditorView, {
      code: import_core_constants17.ErrorConstant.MANAGER_PHASE_ERROR,
      message: "`setExtensionStore` should only be called during the `onCreate` lifecycle hook. Make sure to only call it within the returned methods."
    });
    __privateGet(this, _extensionStore)[key2] = value;
  }
  createExtensionStore() {
    const store = (0, import_core_helpers21.object)();
    const enumerable = true;
    let currentState;
    let previousState;
    Object.defineProperties(store, {
      extensions: { get: () => __privateGet(this, _extensions), enumerable },
      phase: { get: () => __privateGet(this, _phase), enumerable },
      view: { get: () => this.view, enumerable },
      managerSettings: { get: () => (0, import_core_helpers21.freeze)(__privateGet(this, _settings)), enumerable },
      getState: { value: this.getState, enumerable },
      updateState: { value: this.updateState, enumerable },
      isMounted: { value: () => this.mounted, enumerable },
      getExtension: { value: this.getExtension.bind(this), enumerable },
      manager: { get: () => this, enumerable },
      document: { get: () => this.document, enumerable },
      stringHandlers: { get: () => __privateGet(this, _stringHandlers), enumerable },
      currentState: {
        get: () => currentState != null ? currentState : currentState = this.getState(),
        set: (state) => {
          currentState = state;
        },
        enumerable
      },
      previousState: {
        get: () => previousState,
        set: (state) => {
          previousState = state;
        },
        enumerable
      }
    });
    store.getStoreKey = this.getStoreKey.bind(this);
    store.setStoreKey = this.setStoreKey.bind(this);
    store.setExtensionStore = this.setExtensionStore.bind(this);
    store.setStringHandler = this.setStringHandler.bind(this);
    return store;
  }
  addView(view) {
    if (__privateGet(this, _phase) >= import_core_constants17.ManagerPhase.EditorView) {
      return this;
    }
    __privateSet(this, _firstStateUpdate, true);
    __privateSet(this, _phase, import_core_constants17.ManagerPhase.EditorView);
    __privateGet(this, _store).view = view;
    for (const handler of __privateGet(this, _handlers).view) {
      const disposer = handler(view);
      if (disposer) {
        __privateGet(this, _disposers).push(disposer);
      }
    }
    return this;
  }
  attachFramework(framework, updateHandler) {
    var _a;
    if (__privateGet(this, _framework) === framework) {
      return;
    }
    if (__privateGet(this, _framework)) {
      __privateGet(this, _framework).destroy();
      (_a = __privateGet(this, _disposeFramework)) == null ? void 0 : _a.call(this);
    }
    __privateSet(this, _framework, framework);
    __privateSet(this, _disposeFramework, this.addHandler("stateUpdate", updateHandler));
  }
  createEmptyDoc() {
    var _a;
    const doc = (_a = this.schema.nodes.doc) == null ? void 0 : _a.createAndFill();
    (0, import_core_helpers21.invariant)(doc, {
      code: import_core_constants17.ErrorConstant.INVALID_CONTENT,
      message: `An empty node could not be created due to an invalid schema.`
    });
    return doc;
  }
  createState(props = {}) {
    const { onError, defaultSelection = "end" } = this.settings;
    const {
      content = this.createEmptyDoc(),
      selection = defaultSelection,
      stringHandler = this.settings.stringHandler
    } = props;
    const { schema, plugins } = this.store;
    const doc = (0, import_core_utils10.createDocumentNode)({
      stringHandler: (0, import_core_helpers21.isString)(stringHandler) ? this.stringHandlers[stringHandler] : stringHandler,
      document: this.document,
      content,
      onError,
      schema,
      selection
    });
    return import_state5.EditorState.create({
      schema,
      doc,
      plugins,
      selection: (0, import_core_utils10.getTextSelection)(selection, doc)
    });
  }
  addHandler(event, cb) {
    return __privateGet(this, _events2).on(event, cb);
  }
  onStateUpdate(props) {
    const firstUpdate = __privateGet(this, _firstStateUpdate);
    __privateGet(this, _extensionStore).currentState = props.state;
    __privateGet(this, _extensionStore).previousState = props.previousState;
    if (firstUpdate) {
      __privateSet(this, _phase, import_core_constants17.ManagerPhase.Runtime);
      __privateSet(this, _firstStateUpdate, false);
    }
    const propsWithUpdate = { ...props, firstUpdate };
    for (const handler of __privateGet(this, _handlers).update) {
      handler(propsWithUpdate);
    }
    __privateGet(this, _events2).emit("stateUpdate", propsWithUpdate);
  }
  getExtension(Constructor) {
    const extension2 = __privateGet(this, _extensionMap).get(Constructor);
    (0, import_core_helpers21.invariant)(extension2, {
      code: import_core_constants17.ErrorConstant.INVALID_MANAGER_EXTENSION,
      message: `'${Constructor.name}' doesn't exist within this manager. Make sure it is properly added before attempting to use it.`
    });
    return extension2;
  }
  hasExtension(Constructor) {
    const extension2 = __privateGet(this, _extensionMap).get(Constructor);
    return !!extension2;
  }
  clone() {
    const extensions = __privateGet(this, _extensions).map((e) => e.clone(e.options));
    const manager = _RemirrorManager.create(() => extensions, __privateGet(this, _settings));
    __privateGet(this, _events2).emit("clone", manager);
    return manager;
  }
  recreate(extensions = [], settings = {}) {
    const currentExtensions = __privateGet(this, _extensions).map((e) => e.clone(e.initialOptions));
    const manager = _RemirrorManager.create(() => [...currentExtensions, ...extensions], settings);
    __privateGet(this, _events2).emit("recreate", manager);
    return manager;
  }
  destroy() {
    var _a, _b, _c, _d, _e, _f, _g;
    __privateSet(this, _phase, import_core_constants17.ManagerPhase.Destroy);
    for (const plugin of (_b = (_a = this.view) == null ? void 0 : _a.state.plugins) != null ? _b : []) {
      (_d = (_c = plugin.getState(this.view.state)) == null ? void 0 : _c.destroy) == null ? void 0 : _d.call(_c);
    }
    (_e = __privateGet(this, _framework)) == null ? void 0 : _e.destroy();
    (_f = __privateGet(this, _disposeFramework)) == null ? void 0 : _f.call(this);
    for (const dispose of __privateGet(this, _disposers)) {
      dispose();
    }
    for (const onDestroy of __privateGet(this, _handlers).destroy) {
      onDestroy();
    }
    (_g = this.view) == null ? void 0 : _g.destroy();
    __privateGet(this, _events2).emit("destroy");
  }
  includes(mustIncludeList) {
    const names = [];
    const extensionsAndPresets = [];
    for (const item of __privateGet(this, _extensions)) {
      names.push(item.name, item.constructorName);
      extensionsAndPresets.push(item.constructor);
    }
    return mustIncludeList.every((item) => (0, import_core_helpers21.isString)(item) ? (0, import_core_helpers21.includes)(names, item) : (0, import_core_helpers21.includes)(extensionsAndPresets, item));
  }
};
var RemirrorManager = _RemirrorManager;
_extensionStore = new WeakMap();
_stringHandlers = new WeakMap();
_store = new WeakMap();
_extensions = new WeakMap();
_extensionMap = new WeakMap();
_phase = new WeakMap();
_settings = new WeakMap();
_firstStateUpdate = new WeakMap();
_handlers = new WeakMap();
_disposers = new WeakMap();
_events2 = new WeakMap();
_framework = new WeakMap();
_disposeFramework = new WeakMap();
function isRemirrorManager(value, mustIncludeList) {
  if (!(0, import_core_utils10.isRemirrorType)(value) || !(0, import_core_utils10.isIdentifierOfType)(value, import_core_constants17.RemirrorIdentifier.Manager)) {
    return false;
  }
  if (!mustIncludeList) {
    return true;
  }
  return value.includes(mustIncludeList);
}

// packages/remirror__core/src/index.ts
__reExport(src_exports, require("@remirror/core-constants"), module.exports);
__reExport(src_exports, require("@remirror/core-helpers"), module.exports);
__reExport(src_exports, require("@remirror/core-types"), module.exports);
__reExport(src_exports, require("@remirror/core-utils"), module.exports);
//# sourceMappingURL=remirror-core.cjs.map