using System.Text;
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Text.RegularExpressions;
namespace Febe.Browser.Targets;
///
/// How to find one thing in the page (spec §6.3): element role, accessible name, link shape, optional index.
/// Never fixed coordinates, never generated class names.
///
/// Identifier used by recipes (e.g. «viewer-next»).
/// Accepted ARIA roles, explicit or implicit («link», «button», ...). Empty: any.
/// Regular expression (case-insensitive) on the accessible name; may contain {parameters}.
/// Link shape on the path, e.g. «/{username}/», «/stories/**»: {name} or * is one segment, ** the rest.
/// Which of the visible matches, in document order (0 = first, -1 = last).
/// Hypothesis of spec §6.6 the target depends on (e.g. «H11»), when not yet confirmed.
public sealed record TargetSpec(string Id, IReadOnlyList Roles, string? NamePattern, string? HrefPattern, int Index, string? Hypothesis)
{
///
/// False for a placeholder of a skeleton map (role, name and href written but empty, e.g. the first
/// bersagli.instagram.json): looking it up gives without touching the page.
///
public bool IsConfigured => Roles.Count > 0 || NamePattern is not null || HrefPattern is not null;
}
///
/// The target map of one site (bersagli.instagram.json, bersagli.prova.json), editable without
/// recompiling: it is the second thing to touch, after the readers, when the site changes.
///
///
/// Format:
///
/// {
/// "site": "prova",
/// "note": "testo libero",
/// "targets": {
/// "viewer-next": { "role": "button", "name": "^avanti$", "note": "..." },
/// "profile-stories": { "role": "link", "href": "/stories/{username}/", "index": 0, "hypothesis": "H11" }
/// }
/// }
///
/// «role» may list alternatives with «|» («button|link»). At least one of role, name and href is required.
/// Unknown keys are refused, so coordinates or class names cannot slip in.
///
public sealed partial class TargetMap
{
private readonly Dictionary _targets;
public TargetMap(string? site, IEnumerable targets, string? source = null)
{
Site = site;
Source = source;
_targets = targets.ToDictionary(t => t.Id, StringComparer.Ordinal);
}
public string? Site { get; }
public string? Source { get; }
public IReadOnlyDictionary Targets => _targets;
public bool Contains(string id) => _targets.ContainsKey(id);
public TargetSpec Get(string id) =>
_targets.TryGetValue(id, out var spec)
? spec
: throw new KeyNotFoundException($"Il bersaglio «{id}» non è nella mappa {Source ?? Site ?? string.Empty}.".TrimEnd());
public static TargetMap Load(string path) => Parse(File.ReadAllText(path), path);
/// A map shipped with Febe.Core (bersagli.prova.json, bersagli.instagram.json).
public static TargetMap LoadEmbedded(string fileName) =>
Parse(Febe.Core.Collection.SiteMap.ReadEmbeddedText(fileName), fileName);
/// Loads when it exists, otherwise the embedded file with the same name.
public static TargetMap LoadOrEmbedded(string? path, string embeddedName) =>
!string.IsNullOrEmpty(path) && File.Exists(path) ? Load(path) : LoadEmbedded(embeddedName);
public static TargetMap Parse(string json, string? source = null)
{
var name = source ?? "bersagli";
TargetMapFile? file;
try
{
file = JsonSerializer.Deserialize(json, TargetMapJsonContext.Default.TargetMapFile);
}
catch (JsonException ex)
{
throw new InvalidDataException($"{name}: file non valido ({ex.Message.Split('.')[0]}).", ex);
}
if (file?.Targets is null || file.Targets.Count == 0)
{
throw new InvalidDataException($"{name}: manca l'elenco «targets».");
}
var specs = new List();
foreach (var (id, dto) in file.Targets)
{
var where = $"{name}, bersaglio «{id}»";
if (!IdShape().IsMatch(id))
{
throw new InvalidDataException($"{where}: l'identificativo usa solo lettere minuscole, cifre e trattini.");
}
var roles = (dto.Role ?? string.Empty).Split('|', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries)
.Select(r => r.ToLowerInvariant())
.ToArray();
// A skeleton entry writes the three keys empty on purpose (still to be filled from the M0 samples);
// an entry that names none of them is a mistake.
var placeholder = dto.Role is not null && dto.Name is not null && dto.Href is not null;
if (roles.Length == 0 && string.IsNullOrWhiteSpace(dto.Name) && string.IsNullOrWhiteSpace(dto.Href) && !placeholder)
{
throw new InvalidDataException($"{where}: serve almeno uno fra «role», «name» e «href» (vuoti tutti e tre per una voce ancora da compilare).");
}
if (!string.IsNullOrWhiteSpace(dto.Name))
{
try
{
_ = new Regex(PlaceholderToken().Replace(dto.Name, "x"), RegexOptions.CultureInvariant, TimeSpan.FromMilliseconds(100));
}
catch (ArgumentException ex)
{
throw new InvalidDataException($"{where}: espressione «name» non valida.", ex);
}
}
if (!string.IsNullOrWhiteSpace(dto.Href) && !dto.Href.StartsWith('/'))
{
throw new InvalidDataException($"{where}: «href» descrive un percorso e comincia con «/».");
}
specs.Add(new TargetSpec(id, roles, NullIfBlank(dto.Name), NullIfBlank(dto.Href), dto.Index ?? 0, NullIfBlank(dto.Hypothesis)));
}
return new TargetMap(file.Site, specs, source);
}
///
/// Turns a link shape into an anchored, case-insensitive-ready regular expression on the path.
/// {name} becomes the escaped parameter value when given, otherwise one segment; * is one segment; ** the rest.
///
public static string HrefPatternToRegex(string pattern, IReadOnlyDictionary? parameters = null)
{
ArgumentNullException.ThrowIfNull(pattern);
var sb = new StringBuilder("^");
var i = 0;
while (i < pattern.Length)
{
if (pattern[i] == '{')
{
var end = pattern.IndexOf('}', i);
if (end < 0)
{
throw new FormatException($"Segnaposto non chiuso in «{pattern}».");
}
var key = pattern[(i + 1)..end];
sb.Append(parameters is not null && parameters.TryGetValue(key, out var value) ? EscapeForRegex(value) : "[^/]+");
i = end + 1;
}
else if (pattern[i] == '*')
{
var isDouble = i + 1 < pattern.Length && pattern[i + 1] == '*';
sb.Append(isDouble ? ".*" : "[^/]+");
i += isDouble ? 2 : 1;
}
else
{
sb.Append(EscapeForRegex(pattern[i].ToString()));
i++;
}
}
return sb.Append('$').ToString();
}
/// Replaces {parameters} in a name pattern with their escaped values.
public static string ExpandNamePattern(string pattern, IReadOnlyDictionary? parameters) =>
PlaceholderToken().Replace(pattern, m =>
parameters is not null && parameters.TryGetValue(m.Groups[1].Value, out var value) ? EscapeForRegex(value) : ".+");
/// Escapes regular-expression metacharacters in a way valid both for .NET and JavaScript.
internal static string EscapeForRegex(string text)
{
var sb = new StringBuilder(text.Length);
foreach (var c in text)
{
if (@"\^$.|?*+()[]{}/".Contains(c, StringComparison.Ordinal))
{
sb.Append('\\');
}
sb.Append(c);
}
return sb.ToString();
}
private static string? NullIfBlank(string? s) => string.IsNullOrWhiteSpace(s) ? null : s.Trim();
[GeneratedRegex("^[a-z0-9]+(-[a-z0-9]+)*$", RegexOptions.CultureInvariant)]
private static partial Regex IdShape();
[GeneratedRegex(@"\{([A-Za-z][A-Za-z0-9_]*)\}", RegexOptions.CultureInvariant)]
private static partial Regex PlaceholderToken();
}
internal sealed class TargetMapFile
{
public string? Site { get; set; }
public string? Note { get; set; }
/// Page addresses: read by Febe.Core.Collection.SiteMap, accepted and ignored here.
public Dictionary? Pages { get; set; }
public Dictionary? Targets { get; set; }
}
internal sealed class TargetDto
{
public string? Role { get; set; }
public string? Name { get; set; }
public string? Href { get; set; }
public int? Index { get; set; }
public string? Hypothesis { get; set; }
public string? Note { get; set; }
}
[JsonSourceGenerationOptions(
PropertyNamingPolicy = JsonKnownNamingPolicy.CamelCase,
ReadCommentHandling = JsonCommentHandling.Skip,
AllowTrailingCommas = true,
UnmappedMemberHandling = JsonUnmappedMemberHandling.Disallow)]
[JsonSerializable(typeof(TargetMapFile))]
internal sealed partial class TargetMapJsonContext : JsonSerializerContext;