Skip to content
Merged
Show file tree
Hide file tree
Changes from 8 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -35,12 +35,12 @@ Copyright (c) .NET Foundation. All rights reserved.
ResolveHtmlImportMapBuildStaticWebAssets
</ResolveBuildServiceWorkerStaticWebAssetsDependsOn>
<ResolveHtmlImportMapBuildStaticWebAssetsDependsOn>
GenerateHtmlImportMapBuildStaticWebAssets;
$(ResolveHtmlImportMapBuildStaticWebAssetsDependsOn)
$(ResolveHtmlImportMapBuildStaticWebAssetsDependsOn);
GenerateHtmlImportMapBuildStaticWebAssets
</ResolveHtmlImportMapBuildStaticWebAssetsDependsOn>
<GenerateHtmlImportMapBuildStaticWebAssetsDependsOn>
ResolveHtmlImportMapBuildConfiguration;
$(GenerateHtmlImportMapBuildStaticWebAssetsDependsOn)
$(GenerateHtmlImportMapBuildStaticWebAssetsDependsOn);
ResolveHtmlImportMapBuildConfiguration
</GenerateHtmlImportMapBuildStaticWebAssetsDependsOn>

<!--
Expand All @@ -62,12 +62,12 @@ Copyright (c) .NET Foundation. All rights reserved.
ResolveHtmlImportMapPublishStaticWebAssets
</ResolvePublishServiceWorkerStaticWebAssetsDependsOn>
<ResolveHtmlImportMapPublishStaticWebAssetsDependsOn>
GenerateHtmlImportMapPublishStaticWebAssets;
$(ResolveHtmlImportMapPublishStaticWebAssetsDependsOn)
$(ResolveHtmlImportMapPublishStaticWebAssetsDependsOn);
GenerateHtmlImportMapPublishStaticWebAssets
</ResolveHtmlImportMapPublishStaticWebAssetsDependsOn>
<GenerateHtmlImportMapPublishStaticWebAssetsDependsOn>
ResolveHtmlImportMapPublishConfiguration;
$(GenerateHtmlImportMapPublishStaticWebAssetsDependsOn)
$(GenerateHtmlImportMapPublishStaticWebAssetsDependsOn);
ResolveHtmlImportMapPublishConfiguration
</GenerateHtmlImportMapPublishStaticWebAssetsDependsOn>

</PropertyGroup>
Expand Down
110 changes: 94 additions & 16 deletions src/StaticWebAssetsSdk/Tasks/WriteImportMapToHtml.cs
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

using System.Text.RegularExpressions;
using Microsoft.AspNetCore.StaticWebAssets.Tasks.Utils;
using Microsoft.Build.Framework;
using Microsoft.Build.Utilities;
using System.Text.Encodings.Web;
using System.Text.Json.Serialization;
using System.Text.Json;
using Microsoft.AspNetCore.StaticWebAssets.Tasks.Utils;
using System.Text.RegularExpressions;

namespace Microsoft.AspNetCore.StaticWebAssets.Tasks;

Expand Down Expand Up @@ -42,9 +42,11 @@ public partial class WriteImportMapToHtml : Task
// 2.group = fingerprint placeholder
// 3.group = file extension
// wrapped in quotes
private static readonly Regex _assetsRegex = new Regex(@"""([^""]+)(#\[\.{fingerprint}\])([^""]+)""");
internal static readonly Regex _assetsRegex = new Regex(@"""([^""]+)(#\[\.{fingerprint}\])([^""]+)""");

internal static readonly Regex _importMapRegex = new Regex(@"<script\s+type=""importmap""\s*>\s*</script>");

private static readonly Regex _importMapRegex = new Regex(@"<script\s+type=""importmap""\s*>\s*</script>");
internal static readonly Regex _preloadRegex = new Regex(@"<link\s+rel=""preload""(\sid=""(?<group>[^""]+)"")?\s*[/]?>");

public override bool Execute()
{
Expand Down Expand Up @@ -75,6 +77,13 @@ public override bool Execute()
return $"<script type=\"importmap\">{JsonSerializer.Serialize(importMap, ImportMapSerializerContext.CustomEncoder.Options)}</script>";
});

// Generate import map
outputContent = _preloadRegex.Replace(outputContent, e =>
{
Log.LogMessage("Writing preload links to '{0}'", item.ItemSpec);
return GeneratePreloadLinks(resources, e.Groups["group"]?.Value);
});

// Fingerprint all assets used in html
outputContent = _assetsRegex.Replace(outputContent, e =>
{
Expand Down Expand Up @@ -105,6 +114,48 @@ public override bool Execute()
return true;
}

private static string GeneratePreloadLinks(List<ResourceAsset> assets, string? group)
{
var links = new List<(string? Order, string Value)>();
foreach (var asset in assets)
{
if (asset.PreloadRel == null)
{
continue;
}

if (group != null && asset.PreloadGroup != group)
{
continue;
}

var link = new StringBuilder();
link.Append($"<link href=\"").Append(asset.Url).Append("\" rel=\"").Append(asset.PreloadRel).Append('"');
if (!string.IsNullOrEmpty(asset.PreloadAs))
{
link.Append(" as=\"").Append(asset.PreloadAs).Append('"');
}
if (!string.IsNullOrEmpty(asset.PreloadPriority))
{
link.Append(" fetchpriority=\"").Append(asset.PreloadPriority).Append('"');
}
if (!string.IsNullOrEmpty(asset.PreloadCrossorigin))
{
link.Append(" crossorigin=\"").Append(asset.PreloadCrossorigin).Append('"');
}
if (!string.IsNullOrEmpty(asset.Integrity))
{
link.Append(" integrity=\"").Append(asset.Integrity).Append('"');
}

link.Append(" />");
links.Add((asset.PreloadOrder, link.ToString()));
}

links.Sort((a, b) => string.Compare(a.Order, b.Order, StringComparison.InvariantCulture));
return String.Join(Environment.NewLine, links.Select(l => l.Value));
}

private string GetFingerprintedAssetPath(Dictionary<string, ResourceAsset> urlMappings, string assetPath)
{
if (urlMappings.TryGetValue(assetPath, out var asset) && (!IncludeOnlyHardFingerprintedModules || asset.IsHardFingerprinted))
Expand All @@ -125,33 +176,54 @@ internal List<ResourceAsset> CreateResourcesFromEndpoints(IEnumerable<StaticWebA
// subresource integrity to things like images, script tags, etc.
foreach (var endpoint in endpoints)
{
string? label = null;
string? integrity = null;

// If there's a selector this means that this is an alternative representation for a resource, so skip it.
if (endpoint.Selectors?.Length == 0)
{
var resourceAsset = new ResourceAsset(endpoint.Route);
for (var i = 0; i < endpoint.EndpointProperties?.Length; i++)
{
var property = endpoint.EndpointProperties[i];
if (property.Name.Equals("label", StringComparison.OrdinalIgnoreCase))
{
label = property.Value;
resourceAsset.Label = property.Value;
}
else if (property.Name.Equals("integrity", StringComparison.OrdinalIgnoreCase))
{
integrity = property.Value;
resourceAsset.Integrity = property.Value;
}
else if (property.Name.Equals("preloadgroup", StringComparison.OrdinalIgnoreCase))
{
resourceAsset.PreloadGroup = property.Value;
}
else if (property.Name.Equals("preloadrel", StringComparison.OrdinalIgnoreCase))
{
resourceAsset.PreloadRel = property.Value;
}
else if (property.Name.Equals("preloadas", StringComparison.OrdinalIgnoreCase))
{
resourceAsset.PreloadAs = property.Value;
}
else if (property.Name.Equals("preloadpriority", StringComparison.OrdinalIgnoreCase))
{
resourceAsset.PreloadPriority = property.Value;
}
else if (property.Name.Equals("preloadcrossorigin", StringComparison.OrdinalIgnoreCase))
{
resourceAsset.PreloadCrossorigin = property.Value;
}
else if (property.Name.Equals("preloadorder", StringComparison.OrdinalIgnoreCase))
{
resourceAsset.PreloadOrder = property.Value;
}
}

bool isHardFingerprinted = true;
var asset = Assets.FirstOrDefault(a => a.ItemSpec == endpoint.AssetFile);
if (asset != null)
{
isHardFingerprinted = asset.GetMetadata("RelativePath").Contains("#[.{fingerprint}]!");
resourceAsset.IsHardFingerprinted = asset.GetMetadata("RelativePath").Contains("#[.{fingerprint}]!");
}

resources.Add(new ResourceAsset(endpoint.Route, label, integrity, isHardFingerprinted));
resources.Add(resourceAsset);
}
}

Expand Down Expand Up @@ -207,12 +279,18 @@ private static Dictionary<string, ResourceAsset> GroupResourcesByLabel(List<Reso
}
}

internal sealed class ResourceAsset(string url, string? label, string? integrity, bool isHardFingerprinted)
internal sealed class ResourceAsset(string url)
{
public string Url { get; } = url;
public string? Label { get; set; } = label;
public string? Integrity { get; set; } = integrity;
public bool IsHardFingerprinted { get; set; } = isHardFingerprinted;
public string? Label { get; set; }
public string? Integrity { get; set; }
public string? PreloadGroup { get; set; }
public string? PreloadRel { get; set; }
public string? PreloadAs { get; set; }
public string? PreloadPriority { get; set; }
public string? PreloadCrossorigin { get; set; }
public string? PreloadOrder { get; set; }
public bool IsHardFingerprinted { get; set; } = true;
}

internal class ImportMap(Dictionary<string, string> imports, Dictionary<string, Dictionary<string, string>> scopes, Dictionary<string, string> integrity)
Expand Down
Loading
Loading