Skip to content

Commit

Permalink
ImportMap can now be used with ValidatedScript.
Browse files Browse the repository at this point in the history
  • Loading branch information
RyanLamansky committed Aug 24, 2024
1 parent 64fffe2 commit 6c260ac
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 1 deletion.
2 changes: 2 additions & 0 deletions HtmlUtilities/Validated/Standardized/ImportMap.cs
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,8 @@ public sealed class ImportMap
[JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)]
public IDictionary<string, IDictionary<string, string>>? Scopes { get; set; }

internal ReadOnlyMemory<byte> ToUtf8 => JsonSerializer.SerializeToUtf8Bytes(this, ImportMapSerializerContext.Default.ImportMap);

/// <inheritdoc />
public override string ToString() => JsonSerializer.Serialize(this, ImportMapSerializerContext.Default.ImportMap);
}
Expand Down
16 changes: 15 additions & 1 deletion HtmlUtilities/Validated/ValidatedScript.cs
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ public static ValidatedScript ForFileSource(ReadOnlySpan<char> source, params Va
/// Creates a validated script element that uses inline content.
/// </summary>
/// <returns>The validated script.</returns>
/// <exception cref="ArgumentException"><paramref name="script"/> contains a potentially invalid character sequence.</exception>
/// <exception cref="ArgumentException"><paramref name="script"/> contains a potentially invalid character sequence.</exception>
public static ValidatedScript ForInlineSource(ReadOnlySpan<char> script, params ValidatedAttribute[]? attributes)
{
var writer = new ArrayBuilder<byte>(script.Length);
Expand All @@ -59,6 +59,20 @@ public static ValidatedScript ForInlineSource(ReadOnlySpan<char> script, params
}
}

/// <summary>
/// Creates a validated script element that uses inline content from a <see cref="Standardized.ImportMap"/>.
/// </summary>
/// <returns>The validated script.</returns>
/// <exception cref="ArgumentNullException"><paramref name="importMap"/> cannot be null.</exception>
/// <exception cref="ArgumentException"><paramref name="importMap"/> contains a potentially invalid character sequence.</exception>
public static ValidatedScript ForInlineSource(Standardized.ImportMap importMap, params ValidatedAttribute[]? attributes)
{
ArgumentNullException.ThrowIfNull(importMap, nameof(importMap));

// Since importMap is guaranteed to be JSON-based, a fast path may be possible.
return ForInlineSource(importMap.ToString(), attributes);
}

internal static void Validate(ref ArrayBuilder<byte> writer, ReadOnlySpan<char> script)
{
// See https://html.spec.whatwg.org/#restrictions-for-contents-of-script-elements for the official rules.
Expand Down

0 comments on commit 6c260ac

Please sign in to comment.