using System.Collections.Immutable; using Lua; namespace AIStudio.Tools.PluginSystem.Assistants.DataModel; public class PropSpec( IEnumerable required, IEnumerable optional, IEnumerable? nonReadable = null, IEnumerable? nonWriteable = null, IEnumerable? confidential = null, IReadOnlyDictionary? formerNames = null) { public ImmutableArray Required { get; } = MaterializeDistinct(required); public ImmutableArray Optional { get; } = MaterializeDistinct(optional); public ImmutableArray Confidential { get; } = MaterializeDistinct(confidential ?? []); public ImmutableArray NonReadable { get; } = MaterializeDistinct((nonReadable ?? []).Concat(confidential ?? [])); public ImmutableArray NonWriteable { get; } = MaterializeDistinct((nonWriteable ?? []).Concat(confidential ?? [])); /// /// The current name of each prop which had another name before, by that former name. /// /// /// Plugins keep using a former name for good, also in the props their callbacks return: a plugin /// which changes it needs a new security audit. When a plugin uses both names, the current one /// wins. Callbacks see a prop under its current name only. /// public ImmutableDictionary FormerNames { get; } = (formerNames ?? ImmutableDictionary.Empty).ToImmutableDictionary(StringComparer.Ordinal); /// /// Reads a prop from the props of a component, under its current name or under a former name /// which the plugin still uses. /// /// The props of the component, as the plugin defines them. /// The current name of the prop. /// The value of the prop, when the plugin defines it. /// True, when the plugin defines the prop. public bool TryGetValue(LuaTable propsTable, string name, out LuaValue value) { if (propsTable.TryGetValue(name, out value)) return true; foreach (var (formerName, currentName) in this.FormerNames) if (string.Equals(currentName, name, StringComparison.Ordinal) && propsTable.TryGetValue(formerName, out value)) return true; return false; } /// /// Determines the current name of a prop which a plugin names in its props, e.g., in an update /// a callback returns. /// /// The name the plugin uses. /// The props in which the plugin uses the name. /// The current name of the prop. It is the given name, unless that is a former one. /// False, when the plugin uses a former name next to the current one, which wins. public bool TryGetCurrentName(string name, LuaTable propsTable, out string currentName) { if (!this.FormerNames.TryGetValue(name, out var nameAfterRenaming)) { currentName = name; return true; } currentName = nameAfterRenaming; return !propsTable.TryGetValue(currentName, out _); } private static ImmutableArray MaterializeDistinct(IEnumerable source) { return source.Distinct(StringComparer.Ordinal).ToImmutableArray(); } }