import type { AnyEditor as Editor, EditorCommitListener, EditorCorrection, EditorEffectType, PluginPoint, PluginReference, EditorNodeChangeHandler, EditorStateView, EditorStateField, EditorTextChangeHandler, EditorTransactionChangeHandler, EditorUpdateContext, EditorUpdateTransaction, PluginsOf, RegisteredPlugin, ValueOf, } from '../interfaces/editor'; import { assertEditorNotDestroyed } from './editor-lifetime'; import type { CompiledEditorSchema } from './schema-compiler'; import { createSchemaContributionRegistry, finalizeSchemaContributionRegistry, mergeSchemaContributionRegistries, type EditorSchemaContributionRegistry, } from './schema-contribution-registry'; type EditorStateGroupFactory = ( state: EditorStateView, PluginsOf>, editor: TEditor ) => unknown; type EditorTxGroupFactory = ( tx: EditorUpdateTransaction, PluginsOf>, editor: TEditor, context: EditorUpdateContext ) => unknown; export type EditorStateGroupRegistration = Readonly<{ pluginName: string; factory: EditorStateGroupFactory; }>; export type EditorTxGroupRegistration = Readonly<{ pluginName: string; factory: EditorTxGroupFactory; }>; export type CompiledCommandPipeline = Readonly<{ descriptor: object; entries: readonly unknown[]; hasAround: boolean; id: string; }>; export type CompiledCommandRegistry = Readonly<{ byDescriptor: ReadonlyMap; byId: ReadonlyMap; revision: number; }>; export type CompiledReadPipeline = Readonly<{ descriptor: object; entries: readonly unknown[]; id: string; }>; export type CompiledReadRegistry = Readonly<{ byDescriptor: ReadonlyMap; byId: ReadonlyMap; revision: number; }>; export type PluginRegistry = { apiGroups: Map; commands: CompiledCommandRegistry; commitListeners: Set>>; configurationRevision: number; contributions: Map; dependencyOrder: readonly PluginReference[]; effectTypes: Map; plugins: Map; pluginsByDescriptor: Map; nodeChangeListeners: Set>; corrections: Map>; reads: CompiledReadRegistry; schemaContributions: EditorSchemaContributionRegistry; schemaRevision: number; stateGroups: Map>; stateFieldIdentities: Map>; stateFields: Map; textChangeListeners: Set>; transactionChangeListeners: Set>; txGroups: Map>; }; type PluginTeardownState = { destroyRequested: boolean }; type PluginRegistryStore = { acquiring: boolean; base: PluginRegistry; baseInitialized: boolean; candidate: Readonly<{ configured: PluginRegistry; current: PluginRegistry; }> | null; configured: PluginRegistry; current: PluginRegistry; publishing: boolean; teardown: PluginTeardownState | null; }; export type EditorEffectTypeRegistration = Readonly<{ pluginName: string; type: EditorEffectType; }>; export type EditorStateFieldRegistration = Readonly<{ pluginName: string; field: EditorStateField; }>; export type PluginContributionRegistration = Readonly<{ owner: object; sourceIndex: number; value: unknown; }>; const PLUGIN_REGISTRIES = new WeakMap(); // Read groups also land on `tx`, so a read or update group with one of these // names would replace that built-in. const builtInTransactionMembers: Record< Exclude< Extract, 'plugin' >, true > = { anchor: true, annotations: true, blocks: true, break: true, changes: true, children: true, command: true, effects: true, fragment: true, getField: true, key: true, lastCommit: true, marks: true, meta: true, nodes: true, plugins: true, points: true, ranges: true, root: true, records: true, roots: true, runtime: true, schema: true, selection: true, setField: true, slice: true, tags: true, text: true, transaction: true, unique: true, value: true, view: true, }; const reservedGroupNames = new Set(Object.keys(builtInTransactionMembers)); export const createPluginRegistry = ( options: Readonly<{ configurationRevision?: number; schemaRevision?: number; stateFieldIdentities?: ReadonlyMap>; }> = {} ): PluginRegistry => ({ apiGroups: new Map(), commands: { byDescriptor: new Map(), byId: new Map(), revision: options.configurationRevision ?? 0, }, commitListeners: new Set(), configurationRevision: options.configurationRevision ?? 0, contributions: new Map(), dependencyOrder: [], effectTypes: new Map(), plugins: new Map(), pluginsByDescriptor: new Map(), nodeChangeListeners: new Set(), corrections: new Map(), reads: { byDescriptor: new Map(), byId: new Map(), revision: options.configurationRevision ?? 0, }, schemaContributions: createSchemaContributionRegistry( options.schemaRevision ?? 0 ), schemaRevision: options.schemaRevision ?? 0, stateGroups: new Map(), stateFieldIdentities: new Map(options.stateFieldIdentities), stateFields: new Map(), textChangeListeners: new Set(), transactionChangeListeners: new Set(), txGroups: new Map(), }); const immutableCollectionMutation = () => { throw new Error('Published editor plugin registries are immutable.'); }; const freezeMap = (source: ReadonlyMap) => { const map = new Map(source); const immutable: Map = new Proxy(map, { get(target, property) { if (property === 'clear' || property === 'delete' || property === 'set') { return immutableCollectionMutation; } if (property === 'forEach') { return ( callback: (value: TValue, key: TKey, map: Map) => void, thisArg?: unknown ) => { target.forEach((value, key) => { callback.call(thisArg, value, key, immutable); }); }; } const value = Reflect.get(target, property, target); return typeof value === 'function' ? value.bind(target) : value; }, }); return Object.freeze(immutable); }; const freezeSet = (source: ReadonlySet) => { const set = new Set(source); const immutable: Set = new Proxy(set, { get(target, property) { if (property === 'add' || property === 'clear' || property === 'delete') { return immutableCollectionMutation; } if (property === 'forEach') { return ( callback: (value: TValue, key: TValue, set: Set) => void, thisArg?: unknown ) => { target.forEach((value) => { callback.call(thisArg, value, value, immutable); }); }; } const value = Reflect.get(target, property, target); return typeof value === 'function' ? value.bind(target) : value; }, }); return Object.freeze(immutable); }; const freezeArrayMap = (source: ReadonlyMap) => freezeMap( new Map( [...source].map(([key, values]) => [ key, Object.freeze([...values]) as T[], ]) ) ); const finalizeCommandRegistry = ( registry: CompiledCommandRegistry ): CompiledCommandRegistry => Object.freeze({ byDescriptor: freezeMap( new Map( [...registry.byDescriptor].map(([descriptor, pipeline]) => [ descriptor, Object.freeze({ ...pipeline, entries: Object.freeze([...pipeline.entries]), }), ]) ) ), byId: freezeMap(registry.byId), revision: registry.revision, }); const finalizeReadRegistry = ( registry: CompiledReadRegistry ): CompiledReadRegistry => Object.freeze({ byDescriptor: freezeMap( new Map( [...registry.byDescriptor].map(([descriptor, pipeline]) => [ descriptor, Object.freeze({ ...pipeline, entries: Object.freeze([...pipeline.entries]), }), ]) ) ), byId: freezeMap(registry.byId), revision: registry.revision, }); /** Freeze a detached registry after all declarations have been validated. */ export const finalizePluginRegistry = ( registry: PluginRegistry ): PluginRegistry => Object.freeze({ ...registry, apiGroups: freezeArrayMap(registry.apiGroups), commands: finalizeCommandRegistry(registry.commands), commitListeners: freezeSet(registry.commitListeners), contributions: freezeArrayMap(registry.contributions), dependencyOrder: Object.freeze([...registry.dependencyOrder]), effectTypes: freezeMap(registry.effectTypes), plugins: freezeMap(registry.plugins), pluginsByDescriptor: freezeMap(registry.pluginsByDescriptor), nodeChangeListeners: freezeSet(registry.nodeChangeListeners), corrections: freezeMap(registry.corrections), reads: finalizeReadRegistry(registry.reads), schemaContributions: finalizeSchemaContributionRegistry( registry.schemaContributions ), stateGroups: freezeMap(registry.stateGroups), stateFieldIdentities: freezeMap(registry.stateFieldIdentities), stateFields: freezeMap(registry.stateFields), textChangeListeners: freezeSet(registry.textChangeListeners), transactionChangeListeners: freezeSet(registry.transactionChangeListeners), txGroups: freezeMap(registry.txGroups), }); const mergeArrayMap = ( configured: ReadonlyMap, base: ReadonlyMap ) => { const result = new Map(); for (const key of new Set([...configured.keys(), ...base.keys()])) { result.set(key, [...(configured.get(key) ?? []), ...(base.get(key) ?? [])]); } return result; }; const assertPluginPointIdentities = (points: Iterable): void => { const pointsById = new Map(); for (const point of points) { const { id } = point as Readonly<{ id: string }>; const known = pointsById.get(id); if (known && known !== point) { throw new Error( `Editor plugin point id "${id}" cannot install multiple descriptor identities.` ); } pointsById.set(id, point); } }; const mergeCommandRegistries = ( configured: CompiledCommandRegistry, base: CompiledCommandRegistry, revision: number ): CompiledCommandRegistry => { const descriptorsById = new Map(); for (const descriptor of [ ...configured.byDescriptor.keys(), ...base.byDescriptor.keys(), ]) { const { id } = descriptor as Readonly<{ id: string }>; const known = descriptorsById.get(id); if (known && known !== descriptor) { throw new Error( `Editor command id "${id}" cannot install multiple descriptor identities.` ); } descriptorsById.set(id, descriptor); } const entriesByDescriptor = mergeArrayMap( new Map( [...configured.byDescriptor].map(([descriptor, pipeline]) => [ descriptor, pipeline.entries, ]) ), new Map( [...base.byDescriptor].map(([descriptor, pipeline]) => [ descriptor, pipeline.entries, ]) ) ); return { byDescriptor: new Map( [...entriesByDescriptor].map(([descriptor, entries]) => [ descriptor, { descriptor, entries, hasAround: entries.some( (entry) => (entry as Readonly<{ kind?: string }>).kind === 'around' ), id: (descriptor as Readonly<{ id: string }>).id, }, ]) ), byId: descriptorsById, revision, }; }; const mergeReadRegistries = ( configured: CompiledReadRegistry, base: CompiledReadRegistry, revision: number ): CompiledReadRegistry => { const descriptorsById = new Map(); for (const descriptor of [ ...configured.byDescriptor.keys(), ...base.byDescriptor.keys(), ]) { const { id } = descriptor as Readonly<{ id: string }>; const known = descriptorsById.get(id); if (known && known !== descriptor) { throw new Error( `Editor read id "${id}" cannot install multiple descriptor identities.` ); } descriptorsById.set(id, descriptor); } const entriesByDescriptor = mergeArrayMap( new Map( [...configured.byDescriptor].map(([descriptor, pipeline]) => [ descriptor, pipeline.entries, ]) ), new Map( [...base.byDescriptor].map(([descriptor, pipeline]) => [ descriptor, pipeline.entries, ]) ) ); return { byDescriptor: new Map( [...entriesByDescriptor].map(([descriptor, entries]) => [ descriptor, { descriptor, entries, id: (descriptor as Readonly<{ id: string }>).id, }, ]) ), byId: descriptorsById, revision, }; }; const assertNoMapConflicts = ( kind: string, configured: ReadonlyMap, base: ReadonlyMap ) => { for (const key of configured.keys()) { if (base.has(key)) { throw new Error( `Configured editor ${kind} "${key}" conflicts with a built-in resource.` ); } } }; const mergeRegistries = ( configured: PluginRegistry, base: PluginRegistry, previousSchemaContributions: EditorSchemaContributionRegistry | null = null ): PluginRegistry => { assertPluginPointIdentities([ ...configured.contributions.keys(), ...base.contributions.keys(), ]); assertNoMapConflicts('effect', configured.effectTypes, base.effectTypes); assertNoMapConflicts('state group', configured.stateGroups, base.stateGroups); assertNoMapConflicts('state field', configured.stateFields, base.stateFields); assertNoMapConflicts('transaction group', configured.txGroups, base.txGroups); const stateFieldIdentities = new Map(configured.stateFieldIdentities); base.stateFieldIdentities.forEach((field, key) => { const known = stateFieldIdentities.get(key); if (known && known !== field) { throw new Error( `State field "${key}" does not match the stable descriptor identity already known by this editor.` ); } stateFieldIdentities.set(key, field); }); return finalizePluginRegistry({ apiGroups: mergeArrayMap(configured.apiGroups, base.apiGroups), commands: mergeCommandRegistries( configured.commands, base.commands, configured.configurationRevision ), commitListeners: new Set([ ...configured.commitListeners, ...base.commitListeners, ]), configurationRevision: configured.configurationRevision, contributions: mergeArrayMap(configured.contributions, base.contributions), dependencyOrder: [...configured.dependencyOrder], effectTypes: new Map([...configured.effectTypes, ...base.effectTypes]), plugins: new Map(configured.plugins), pluginsByDescriptor: new Map(configured.pluginsByDescriptor), nodeChangeListeners: new Set([ ...configured.nodeChangeListeners, ...base.nodeChangeListeners, ]), corrections: new Map([...configured.corrections, ...base.corrections]), reads: mergeReadRegistries( configured.reads, base.reads, configured.configurationRevision ), schemaContributions: mergeSchemaContributionRegistries( configured.schemaContributions, base.schemaContributions, Math.max(configured.schemaRevision, base.schemaRevision), previousSchemaContributions ), schemaRevision: Math.max(configured.schemaRevision, base.schemaRevision), stateGroups: new Map([...configured.stateGroups, ...base.stateGroups]), stateFieldIdentities, stateFields: new Map([...configured.stateFields, ...base.stateFields]), textChangeListeners: new Set([ ...configured.textChangeListeners, ...base.textChangeListeners, ]), transactionChangeListeners: new Set([ ...configured.transactionChangeListeners, ...base.transactionChangeListeners, ]), txGroups: new Map([...configured.txGroups, ...base.txGroups]), }); }; const createPluginRegistryStore = (): PluginRegistryStore => { const base = finalizePluginRegistry(createPluginRegistry()); const configured = finalizePluginRegistry(createPluginRegistry()); return { acquiring: false, base, baseInitialized: false, candidate: null, configured, current: mergeRegistries(configured, base), publishing: false, teardown: null, }; }; const getPluginRegistryStore = (editor: Editor) => { let store = PLUGIN_REGISTRIES.get(editor); if (!store) { store = createPluginRegistryStore(); PLUGIN_REGISTRIES.set(editor, store); } return store; }; export const isPluginPublicationActive = (editor: Editor): boolean => getPluginRegistryStore(editor).publishing; export const isPluginAcquiring = (editor: Editor): boolean => getPluginRegistryStore(editor).acquiring; export const setPluginAcquiring = (editor: Editor, acquiring: boolean) => { getPluginRegistryStore(editor).acquiring = acquiring; }; export const getPluginTeardown = (editor: Editor): PluginTeardownState | null => getPluginRegistryStore(editor).teardown; export const setPluginTeardown = ( editor: Editor, teardown: PluginTeardownState | null ) => { getPluginRegistryStore(editor).teardown = teardown; }; export const assertCanMutatePlugins = ( editor: Editor, action: 'install' | 'reconfigure' = 'install' ) => { assertEditorNotDestroyed(editor); const store = getPluginRegistryStore(editor); if (store.teardown) { throw new Error( store.teardown.destroyRequested ? `Cannot ${action} plugins while destroying an editor.` : `Cannot ${action} plugins while releasing an editor.` ); } if (store.acquiring) { throw new Error( `Cannot ${action} plugins while acquiring plugin resources.` ); } }; export const assertPluginPublicationInactive = (editor: Editor) => { if (isPluginPublicationActive(editor)) { throw new Error( 'editor writes cannot be started during plugin lifecycle publication' ); } }; /** @internal */ export const getRegistryContributions = ( registry: Pick, point: PluginPoint ) => Object.freeze( (registry.contributions.get(point) ?? []).map( ({ value }) => value as TValue ) ); /** @internal */ export const getPluginContributions = ( editor: Editor, point: PluginPoint ) => getRegistryContributions(getPluginRegistry(editor), point); export const getPluginRegistry = ( editor: TEditor ): PluginRegistry => { const store = getPluginRegistryStore(editor); return (store.candidate?.current ?? store.current) as PluginRegistry; }; /** Canonical compiled schema for the current editor configuration. */ export const getCompiledEditorSchema = (editor: Editor): CompiledEditorSchema => getPluginRegistry(editor).schemaContributions.compiled; export const getConfiguredPluginRegistry = ( editor: TEditor ): PluginRegistry => { const store = getPluginRegistryStore(editor); return (store.candidate?.configured ?? store.configured) as PluginRegistry; }; /** Run read-only lifecycle work against one detached candidate registry. */ export const runWithCandidatePluginRegistry = ( editor: TEditor, candidate: Readonly<{ configured: PluginRegistry; current: PluginRegistry; }>, fn: () => TResult ): TResult => { const store = getPluginRegistryStore(editor); if (store.publishing || store.candidate) { throw new Error('Editor plugin registry publication cannot re-enter.'); } store.publishing = true; store.candidate = candidate as Readonly<{ configured: PluginRegistry; current: PluginRegistry; }>; try { return fn(); } finally { store.candidate = null; store.publishing = false; } }; export const validateConfiguredPluginRegistry = ( editor: TEditor, registry: PluginRegistry, previousSchemaContributions?: EditorSchemaContributionRegistry ) => mergeRegistries( registry as PluginRegistry, getPluginRegistryStore(editor).base, previousSchemaContributions ?? getPluginRegistryStore(editor).current.schemaContributions ) as PluginRegistry; export const initializeBasePluginRegistry = ( editor: TEditor, registry: PluginRegistry ) => { const store = getPluginRegistryStore(editor); if (!Object.isFrozen(registry)) { throw new Error('Editor base plugin registry must be finalized.'); } if (store.baseInitialized) { throw new Error('Editor base plugin registry is already initialized.'); } store.base = registry as PluginRegistry; store.baseInitialized = true; store.current = mergeRegistries(store.configured, store.base); }; export const runWithPluginPublicationGuard = ( editor: Editor, fn: () => T ): T => { const store = getPluginRegistryStore(editor); if (store.publishing) { throw new Error('Editor plugin registry publication cannot re-enter.'); } store.publishing = true; try { return fn(); } finally { store.publishing = false; } }; export type PublishedConfiguredPluginRegistry = Readonly<{ finalize: (beforeFinalize?: () => void) => void; rollback: (beforeRollback?: () => void) => void; }>; export const publishConfiguredPluginRegistry = ( editor: TEditor, registry: PluginRegistry, afterPublish: () => void = () => {} ): PublishedConfiguredPluginRegistry => { const store = getPluginRegistryStore(editor); if (!Object.isFrozen(registry)) { throw new Error('Editor plugin registry candidates must be finalized.'); } if (store.publishing) { throw new Error('Editor plugin registry publication cannot re-enter.'); } const configured = registry as PluginRegistry; const previousConfigured = store.configured; const previousCurrent = store.current; const current = mergeRegistries( configured, store.base, previousCurrent.schemaContributions ); let publishedConfigured = configured; let publishedCurrent = current; let active = true; store.publishing = true; try { store.configured = configured; store.current = current; afterPublish(); publishedConfigured = store.configured; publishedCurrent = store.current; } catch (error) { store.configured = previousConfigured; store.current = previousCurrent; throw error; } finally { store.publishing = false; } const assertActivePublication = () => { if (!active) { throw new Error('Editor plugin publication is already settled.'); } if ( store.configured !== publishedConfigured || store.current !== publishedCurrent ) { throw new Error( 'Editor plugin publication changed before it was finalized.' ); } if (store.publishing) { throw new Error('Editor plugin registry publication cannot re-enter.'); } }; return Object.freeze({ finalize(beforeFinalize = () => {}) { assertActivePublication(); store.publishing = true; try { beforeFinalize(); active = false; } finally { store.publishing = false; } }, rollback(beforeRollback = () => {}) { assertActivePublication(); store.publishing = true; try { beforeRollback(); } finally { store.configured = previousConfigured; store.current = previousCurrent; store.publishing = false; active = false; } }, }); }; const assertEffectType = (pluginName: string, type: EditorEffectType): void => { const candidate = type as unknown as Record; const { key } = candidate; if (typeof key !== 'string' || !key) { throw new Error( `Editor plugin "${pluginName}" cannot install an effect with an empty key.` ); } if (!Object.isFrozen(type)) { throw new Error( `Editor effect "${key}" from "${pluginName}" must be created with defineEffect().` ); } if (candidate.collab !== 'local' && candidate.collab !== 'shared') { throw new Error( `Editor effect "${key}" has invalid collaboration policy "${String( candidate.collab )}."` ); } if ( (candidate.collab === 'shared' && candidate.collabReplay !== 'latest' && candidate.collabReplay !== 'live') || (candidate.collab === 'local' && candidate.collabReplay !== 'live') ) { throw new Error( `Editor effect "${key}" has invalid collaboration replay policy "${String( candidate.collabReplay )}."` ); } if ( (candidate.collabReplay === 'latest' && typeof candidate.collabSnapshot !== 'function') || (candidate.collabReplay !== 'latest' && candidate.collabSnapshot !== undefined) ) { throw new Error( `Editor effect "${key}" has an invalid collaboration snapshot policy.` ); } const effectHistory = candidate.history; const sessionHistory = typeof effectHistory === 'object' && effectHistory !== null && !Array.isArray(effectHistory) && Object.isFrozen(effectHistory) && Object.keys(effectHistory).length === 1 && Object.hasOwn(effectHistory, 'replay') && typeof (effectHistory as { replay?: unknown }).replay === 'function'; if (effectHistory !== 'push' && effectHistory !== 'skip' && !sessionHistory) { throw new Error( `Editor effect "${key}" has invalid history policy "${String( effectHistory )}."` ); } if (sessionHistory && candidate.collab !== 'local') { throw new Error( `Editor effect "${key}" has an invalid session history replay policy.` ); } if ( typeof candidate.invert !== 'function' || typeof candidate.map !== 'function' ) { throw new Error( `Editor effect "${key}" must define invert and map functions.` ); } const persistence = candidate.persist as | { decode?: unknown; encode?: unknown; version?: unknown; } | undefined; if ( persistence && (!Number.isSafeInteger(persistence.version) || typeof persistence.version !== 'number' || persistence.version < 1 || typeof persistence.encode !== 'function' || typeof persistence.decode !== 'function') ) { throw new Error(`Editor effect "${key}" has invalid persistence.`); } if (candidate.collab === 'shared' && !persistence) { throw new Error(`Shared editor effect "${key}" requires persistence.`); } const collabTransport = candidate.collabTransport as | { decode?: unknown; encode?: unknown } | undefined; if ( collabTransport && (candidate.collab !== 'shared' || !persistence || typeof collabTransport.encode !== 'function' || typeof collabTransport.decode !== 'function') ) { throw new Error( `Editor effect "${key}" has an invalid collaboration transport.` ); } }; export const registerEffectTypeInRegistry = ( registry: PluginRegistry, pluginName: string, type: EditorEffectType ) => { const existing = registry.effectTypes.get(type.key); assertEffectType(pluginName, type); if (existing) { throw new Error( `Editor effect "${type.key}" from "${pluginName}" conflicts with "${existing.pluginName}".` ); } const registration = Object.freeze({ pluginName, type }); registry.effectTypes.set(type.key, registration); return () => { if (registry.effectTypes.get(type.key) === registration) { registry.effectTypes.delete(type.key); } }; }; export const inheritPluginRegistry = (editor: Editor, source: Editor) => { PLUGIN_REGISTRIES.set(editor, getPluginRegistryStore(source)); }; export const registerApiGroupInRegistry = ( registry: PluginRegistry, name: string, value: unknown ) => { const values = registry.apiGroups.get(name) ?? []; values.push(value); registry.apiGroups.set(name, values); return () => { const current = registry.apiGroups.get(name); if (!current) { return; } const index = current.indexOf(value); if (index !== -1) { current.splice(index, 1); } if (current.length === 0) { registry.apiGroups.delete(name); } }; }; export const registerPluginContributionInRegistry = ( registry: PluginRegistry, point: object, registration: PluginContributionRegistration ) => { assertPluginPointIdentities([...registry.contributions.keys(), point]); const contributions = registry.contributions.get(point) ?? []; contributions.push(Object.freeze(registration)); registry.contributions.set(point, contributions); return () => { const current = registry.contributions.get(point); if (!current) return; const index = current.findIndex( (entry) => entry.owner === registration.owner && entry.sourceIndex === registration.sourceIndex ); if (index !== -1) current.splice(index, 1); if (current.length === 0) registry.contributions.delete(point); }; }; const DEFINED_STATE_FIELDS = new WeakSet>(); const DEFINED_STATE_FIELD_EFFECTS = new WeakSet(); export const markDefinedStateField = (field: EditorStateField) => { DEFINED_STATE_FIELDS.add(field); DEFINED_STATE_FIELD_EFFECTS.add(field.effect); }; export const isDefinedStateField = ( value: unknown ): value is EditorStateField => typeof value === 'object' && value !== null && DEFINED_STATE_FIELDS.has(value as EditorStateField); export const isStateFieldEffect = (type: EditorEffectType) => DEFINED_STATE_FIELD_EFFECTS.has(type); export const registerStateFieldDescriptorInRegistry = ( registry: PluginRegistry, pluginName: string, field: EditorStateField ) => { const known = registry.stateFieldIdentities.get(field.key); const existing = registry.stateFields.get(field.key); if (!field.key) { throw new Error( `Editor plugin "${pluginName}" cannot install a state field with an empty key.` ); } if (field.key === '__proto__' || field.key === '$configuration') { throw new Error( `Editor plugin "${pluginName}" cannot install a state field keyed "${field.key}".` ); } if (!DEFINED_STATE_FIELDS.has(field)) { throw new Error( `State field "${field.key}" from "${pluginName}" must be created with defineStateField().` ); } if (known && known !== field) { throw new Error( `State field "${field.key}" does not match the stable descriptor identity already known by this editor.` ); } if (existing) { throw new Error( `State field "${field.key}" from "${pluginName}" conflicts with "${existing.pluginName}".` ); } const registration = Object.freeze({ pluginName, field }); registry.stateFieldIdentities.set(field.key, field); registry.stateFields.set(field.key, registration); return () => { if (registry.stateFields.get(field.key) === registration) { registry.stateFields.delete(field.key); } }; }; export const registerCorrectionInRegistry = ( registry: PluginRegistry, id: string, correction: EditorCorrection ) => { registry.corrections.set(id, correction); return () => { if (registry.corrections.get(id) === correction) { registry.corrections.delete(id); } }; }; export const registerCommitListenerInRegistry = ( registry: PluginRegistry, listener: EditorCommitListener> ) => { registry.commitListeners.add(listener); return () => { registry.commitListeners.delete(listener); }; }; export const registerNodeChangeListenerInRegistry = ( registry: PluginRegistry, listener: EditorNodeChangeHandler ) => { registry.nodeChangeListeners.add(listener); return () => { registry.nodeChangeListeners.delete(listener); }; }; export const registerTextChangeListenerInRegistry = ( registry: PluginRegistry, listener: EditorTextChangeHandler ) => { registry.textChangeListeners.add(listener); return () => { registry.textChangeListeners.delete(listener); }; }; export const registerTransactionChangeListenerInRegistry = < TEditor extends Editor, >( registry: PluginRegistry, listener: EditorTransactionChangeHandler ) => { registry.transactionChangeListeners.add(listener); return () => { registry.transactionChangeListeners.delete(listener); }; }; export const hasChangeListeners = (editor: Editor) => { const registry = getPluginRegistry(editor); return ( registry.nodeChangeListeners.size > 0 || registry.textChangeListeners.size > 0 ); }; const registerViewGroup = ( groups: Map, kind: 'editor' | 'state' | 'tx', pluginName: string, groupName: string, factory: TRegistration ) => { if (reservedGroupNames.has(groupName)) { throw new Error( `Editor plugin "${pluginName}" ${kind} group "${groupName}" is reserved by the editor core.` ); } const existing = groups.get(groupName); if (existing) { throw new Error( `Editor plugin ${kind} group "${groupName}" from "${pluginName}" conflicts with "${existing.pluginName}".` ); } const registration = Object.freeze({ pluginName, factory }); groups.set(groupName, registration); return () => { if (groups.get(groupName) === registration) { groups.delete(groupName); } }; }; export const registerStateGroupInRegistry = ( registry: PluginRegistry, pluginName: string, groupName: string, factory: EditorStateGroupFactory ) => registerViewGroup( registry.stateGroups, 'state', pluginName, groupName, factory ); export const registerTxGroupInRegistry = ( registry: PluginRegistry, pluginName: string, groupName: string, factory: EditorTxGroupFactory ) => registerViewGroup(registry.txGroups, 'tx', pluginName, groupName, factory);