import { isRuntimePlugin } from '../../facade'; import type { AnyBasePlugin, BasePluginInput } from '../../lib'; import { failInvariant } from '../failInvariant'; import { brandPluginDescriptor, freezePluginDataSnapshot, getPluginSchemaFamily, isImmutablePluginData, isNominalPluginDescriptor, isOpaquePluginSlotKey, } from '../utils/mergePlugins'; import type { CompiledPlateModel } from './compilePlateModel'; import { snapshotPluginState } from './pluginStore'; type PluginDescriptorSnapshotContext = Readonly<{ name: string; path: readonly PropertyKey[]; }>; const appendPluginDescriptorPath = ( context: PluginDescriptorSnapshotContext, key: PropertyKey ): PluginDescriptorSnapshotContext => ({ name: context.name, path: [...context.path, key], }); const formatPluginDescriptorPath = (path: readonly PropertyKey[]) => path.reduce((output, key) => { if (typeof key === 'number') return `${output}[${key}]`; if (typeof key === 'symbol') return `${output}[${String(key)}]`; return output ? `${output}.${key}` : key; }, ''); const createPluginDescriptorAccessorError = ( context: PluginDescriptorSnapshotContext ) => new Error( `Plate plugin "${ context.name }" descriptor path "${formatPluginDescriptorPath( context.path )}" must be data-only. Accessor properties are not supported.` ); const opaqueNativeResourceFields = new Set([ 'contributions', 'corrections', 'effectTypes', 'stateFields', ]); const isOpaquePluginDescriptorResource = ( context: PluginDescriptorSnapshotContext ) => { const { path } = context; const key = path.at(-1); const parent = path.at(-2); if ( typeof key === 'number' && (parent === 'dependencies' || parent === 'conflicts') ) { return true; } if ( key === 'component' && (path.length === 1 || path.at(-3) === 'override') ) { return true; } if ( parent === 'slots' && isOpaquePluginSlotKey(key ?? failInvariant('Expected value to be defined')) ) { return true; } if (parent === 'mark' && key === 'leafComponent') return true; if ( typeof key === 'number' && path.length === 2 && opaqueNativeResourceFields.has( parent ?? failInvariant('Expected value to be defined') ) ) { return true; } return false; }; const snapshotPluginDescriptorValue = ( value: unknown, snapshots: WeakMap, context: PluginDescriptorSnapshotContext, publishedPlugins?: ReadonlyMap ): unknown => { if (!value || typeof value !== 'object') return value; if (isRuntimePlugin(value) && !isNominalPluginDescriptor(value)) { return value; } if (isOpaquePluginDescriptorResource(context)) return value; if (isImmutablePluginData(value)) return value; if (isNominalPluginDescriptor(value)) { const published = publishedPlugins?.get(value.name); if ( published && getPluginSchemaFamily(value) === getPluginSchemaFamily(published) ) { return published; } } const existing = snapshots.get(value); if (existing !== undefined) return existing; if (Array.isArray(value)) { const snapshot: unknown[] = []; snapshots.set(value, snapshot); snapshot.push( ...value.map((item, index) => snapshotPluginDescriptorValue( item, snapshots, appendPluginDescriptorPath(context, index), publishedPlugins ) ) ); return freezePluginDataSnapshot(snapshot); } const prototype = Object.getPrototypeOf(value); if (prototype !== Object.prototype && prototype !== null) return value; const isPluginDescriptor = isNominalPluginDescriptor(value); const ownerContext = isPluginDescriptor ? { name: value.name, path: [] } : context; const snapshot: Record = Object.create(prototype); snapshots.set(value, snapshot); for (const key of Reflect.ownKeys(value)) { const descriptor = Object.getOwnPropertyDescriptor(value, key); if (!descriptor) continue; if (!Object.hasOwn(descriptor, 'value')) { throw createPluginDescriptorAccessorError( appendPluginDescriptorPath(ownerContext, key) ); } Object.defineProperty(snapshot, key, { enumerable: descriptor.enumerable, value: isPluginDescriptor && key === 'initialState' ? snapshotPluginState(descriptor.value) : snapshotPluginDescriptorValue( descriptor.value, snapshots, appendPluginDescriptorPath(ownerContext, key), publishedPlugins ), }); } return isPluginDescriptor ? brandPluginDescriptor(Object.freeze(snapshot), value) : freezePluginDataSnapshot(snapshot); }; /** Capture the immutable descriptor graph used by every Plate projection. */ export type PlatePluginSourceGroups = Readonly<{ baseCore?: readonly BasePluginInput[]; user?: readonly BasePluginInput[]; }>; export type NormalizedPlatePluginSourceGroups = Readonly<{ baseCore: readonly AnyBasePlugin[]; user: readonly AnyBasePlugin[]; }>; export type PlatePluginSourceInput = | PlatePluginSourceGroups | readonly BasePluginInput[]; const isPlatePluginSourceList = ( sources: PlatePluginSourceInput ): sources is readonly BasePluginInput[] => Array.isArray(sources); const asAnyBasePlugin = (plugin: BasePluginInput): AnyBasePlugin => { if (!isNominalPluginDescriptor(plugin)) { throw new Error( `Plate plugin source "${ (plugin as { name: string }).name }" must be created by a Plate plugin builder.` ); } return plugin as unknown as AnyBasePlugin; }; const normalizePlatePluginSourceList = ( plugins: readonly BasePluginInput[] | undefined ) => (plugins ?? []).map(asAnyBasePlugin); export const normalizePlatePluginSources = ( sources: PlatePluginSourceInput ): NormalizedPlatePluginSourceGroups => { if (isPlatePluginSourceList(sources)) { return { baseCore: [], user: normalizePlatePluginSourceList(sources), }; } return { baseCore: normalizePlatePluginSourceList(sources.baseCore), user: normalizePlatePluginSourceList(sources.user), }; }; export const getPluginDependencies = ( plugin: AnyBasePlugin ): readonly unknown[] => { const value = plugin.dependencies; return Array.isArray(value) ? value : []; }; export const collectPlatePluginSourceCandidates = ( sourceInput: PlatePluginSourceInput ) => { const sources = normalizePlatePluginSources(sourceInput); const candidates: AnyBasePlugin[] = []; const visited = new WeakSet(); const queue: unknown[] = [...sources.baseCore, ...sources.user]; for (const candidate of queue) { if (!candidate || typeof candidate !== 'object' || visited.has(candidate)) { continue; } visited.add(candidate); if (!isNominalPluginDescriptor(candidate)) continue; const plugin = candidate as AnyBasePlugin; candidates.push(plugin); queue.push(...getPluginDependencies(plugin)); } return candidates; }; export const snapshotPlatePluginSources = ( sources: PlatePluginSourceGroups ): NormalizedPlatePluginSourceGroups => { const normalized = normalizePlatePluginSources(sources); const snapshots = new WeakMap(); const snapshot = (plugin: AnyBasePlugin) => snapshotPluginDescriptorValue( plugin, snapshots, { name: plugin.name, path: [] }, undefined ) as AnyBasePlugin; return Object.freeze({ baseCore: Object.freeze(normalized.baseCore.map(snapshot)), user: Object.freeze(normalized.user.map(snapshot)), }); }; export const publishPlatePluginDescriptors = ( pluginList: readonly AnyBasePlugin[], model: CompiledPlateModel ): readonly AnyBasePlugin[] => { const publishedByName = new Map(); pluginList.forEach((plugin) => { publishedByName.set( plugin.name, brandPluginDescriptor({} as AnyBasePlugin, plugin) ); }); const snapshots = new WeakMap(); pluginList.forEach((plugin) => { const published = publishedByName.get(plugin.name) ?? failInvariant('Expected value to be defined'); for (const key of Reflect.ownKeys(plugin)) { const descriptor = Object.getOwnPropertyDescriptor(plugin, key); if (!descriptor) continue; if (!Object.hasOwn(descriptor, 'value')) { throw createPluginDescriptorAccessorError({ name: plugin.name, path: [key], }); } let value: unknown; if (key === 'dependencies' || key === 'conflicts') { const references = Array.isArray(descriptor.value) ? descriptor.value : []; value = Object.freeze( references.flatMap( (reference: unknown) => { if ( isRuntimePlugin(reference) && !isNominalPluginDescriptor(reference) ) { return [reference]; } if (!isNominalPluginDescriptor(reference)) return []; const installed = publishedByName.get(reference.name); if (installed) return [installed]; throw new Error( `Plate plugin "${plugin.name}" lost installed dependency "${reference.name}" during publication.` ); } ) ); } else if (key === 'initialState') { value = snapshotPluginState(descriptor.value); } else if (key === 'inject') { const inject = snapshotPluginDescriptorValue( descriptor.value, snapshots, { name: plugin.name, path: [key] }, publishedByName ) as AnyBasePlugin['inject']; const propertyKey = model.byName[plugin.name]?.propertyKey; value = propertyKey && inject.nodeProps && inject.nodeProps.nodeKey === undefined ? Object.freeze({ ...inject, nodeProps: Object.freeze({ ...inject.nodeProps, nodeKey: propertyKey, }), }) : inject; } else { value = snapshotPluginDescriptorValue( descriptor.value, snapshots, { name: plugin.name, path: [key] }, publishedByName ); } Object.defineProperty(published, key, { enumerable: descriptor.enumerable, value, }); } }); const publishedPluginList = pluginList.map( (plugin) => publishedByName.get(plugin.name) ?? failInvariant('Expected value to be defined') ); publishedPluginList.forEach(Object.freeze); return Object.freeze(publishedPluginList); };