Skip to content

[wasm] General HotReload agent for WebAssembly in browser #49800

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 22 commits into from
Jul 18, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
22 commits
Select commit Hold shift + click to select a range
6e555e8
Add HotReloadAgent.WebAssembly.Browser
maraf Jul 16, 2025
250d4a7
Update references
maraf Jul 16, 2025
7b2bd56
Implicit reference
maraf Jul 16, 2025
791a16d
Update src/BuiltInTools/HotReloadAgent.WebAssembly.Browser/WebAssembl…
maraf Jul 16, 2025
98e0db0
Ship the package
maraf Jul 16, 2025
7f74fb1
Feedback
maraf Jul 17, 2025
662b494
Disable HotReload in tests, because we don't have the HotReload packa…
maraf Jul 17, 2025
4ce0644
Disable HotReload in tests, because we don't have the HotReload packa…
maraf Jul 17, 2025
0cc2cfe
Flip the check for configuration
maraf Jul 17, 2025
b15a02e
IsImplicitlyDefined and PrivateAssets attributes on the PackageReference
maraf Jul 17, 2025
93abbd3
Fix usage outside of Blazor - need to set _internal object as well
maraf Jul 17, 2025
2e3934e
Remove PrivateAssets becase we need the script to propagate to the re…
maraf Jul 17, 2025
c799096
Disable HotReload in tests, because we don't have the HotReload packa…
maraf Jul 17, 2025
acbf36c
Include shipping packages in HelixCorrelationPayload
maraf Jul 17, 2025
c724500
Revert disable HotReload in tests
maraf Jul 17, 2025
f503e27
Update baselines
maraf Jul 18, 2025
6c93ba8
Update baselines
maraf Jul 18, 2025
d9b03a4
The newest runtime didn't land yet. Revert back to previous boot sche…
maraf Jul 18, 2025
141a57c
Update baselines
maraf Jul 18, 2025
6edb0a0
Update baselines
maraf Jul 18, 2025
7ec9a3f
Exclude modules manifest
maraf Jul 18, 2025
50f73fa
Disable HotReload in SWA integration tests, because of fingerprinted …
maraf Jul 18, 2025
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
1 change: 1 addition & 0 deletions sdk.slnx
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,7 @@
<Project Path="src/BuiltInTools/HotReloadAgent.PipeRpc/Microsoft.DotNet.HotReload.Agent.PipeRpc.shproj" />
<Project Path="src/BuiltInTools/HotReloadAgent/Microsoft.DotNet.HotReload.Agent.Package.csproj" />
<Project Path="src/BuiltInTools/HotReloadAgent/Microsoft.DotNet.HotReload.Agent.shproj" />
<Project Path="src/BuiltInTools/HotReloadAgent.WebAssembly.Browser/Microsoft.DotNet.HotReload.WebAssembly.Browser.csproj" />
</Folder>
<Folder Name="/src/Cli/">
<Project Path="src/Cli/dotnet/dotnet.csproj" />
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
<Project Sdk="Microsoft.NET.Sdk.Razor">

<PropertyGroup>
<TargetFramework>$(SdkTargetFramework)</TargetFramework>
<GenerateDocumentationFile>false</GenerateDocumentationFile>
<GenerateDependencyFile>false</GenerateDependencyFile>
<LangVersion>preview</LangVersion>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>

<!-- NuGet -->
<IsPackable>true</IsPackable>
<IsShipping>true</IsShipping>
<IsShippingPackage>true</IsShippingPackage>
<PackageId>Microsoft.DotNet.HotReload.WebAssembly.Browser</PackageId>
<Description>HotReload package for WebAssembly</Description>
<!-- Remove once https://github.com/NuGet/Home/issues/8583 is fixed -->
<NoWarn>$(NoWarn);NU5128</NoWarn>
</PropertyGroup>

<Import Project="..\HotReloadAgent\Microsoft.DotNet.HotReload.Agent.projitems" Label="Shared" />
<Import Project="..\HotReloadAgent.Data\Microsoft.DotNet.HotReload.Agent.Data.projitems" Label="Shared" />

<ItemGroup>
<InternalsVisibleTo Include="DynamicProxyGenAssembly2" Key="$(MoqPublicKey)" />
</ItemGroup>
</Project>
Original file line number Diff line number Diff line change
@@ -0,0 +1,178 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

using System.ComponentModel;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Net.Http;
using System.Reflection.Metadata;
using System.Runtime.InteropServices.JavaScript;
using System.Runtime.Versioning;
using System.Text.Json;
using System.Text.Json.Serialization;

#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member

namespace Microsoft.DotNet.HotReload.WebAssembly.Browser;

/// <summary>
/// Contains methods called by interop. Intended for framework use only, not supported for use in application
/// code.
/// </summary>
[EditorBrowsable(EditorBrowsableState.Never)]
[UnconditionalSuppressMessage(
"Trimming",
"IL2026:Members annotated with 'RequiresUnreferencedCodeAttribute' require dynamic access otherwise can break functionality when trimming application code",
Justification = "Hot Reload does not support trimming")]
internal static partial class WebAssemblyHotReload
{
/// <summary>
/// For framework use only.
/// </summary>
public readonly struct LogEntry
{
public string Message { get; init; }
public int Severity { get; init; }
}

/// <summary>
/// For framework use only.
/// </summary>
internal sealed class Update
{
public int Id { get; set; }
public Delta[] Deltas { get; set; } = default!;
}

/// <summary>
/// For framework use only.
/// </summary>
public readonly struct Delta
{
public string ModuleId { get; init; }
public byte[] MetadataDelta { get; init; }
public byte[] ILDelta { get; init; }
public byte[] PdbDelta { get; init; }
public int[] UpdatedTypes { get; init; }
}

private static readonly JsonSerializerOptions s_jsonSerializerOptions = new(JsonSerializerDefaults.Web);

private static bool s_initialized;
private static HotReloadAgent? s_hotReloadAgent;

[JSExport]
[SupportedOSPlatform("browser")]
public static async Task InitializeAsync(string baseUri)
{
if (MetadataUpdater.IsSupported && Environment.GetEnvironmentVariable("__ASPNETCORE_BROWSER_TOOLS") == "true" &&
OperatingSystem.IsBrowser())
{
s_initialized = true;

var agent = new HotReloadAgent();

var existingAgent = Interlocked.CompareExchange(ref s_hotReloadAgent, agent, null);
if (existingAgent != null)
{
throw new InvalidOperationException("Hot Reload agent already initialized");
}

await ApplyPreviousDeltasAsync(agent, baseUri);
}
}

private static async ValueTask ApplyPreviousDeltasAsync(HotReloadAgent agent, string baseUri)
{
string errorMessage;

using var client = new HttpClient()
{
BaseAddress = new Uri(baseUri, UriKind.Absolute)
};

try
{
var response = await client.GetAsync("/_framework/blazor-hotreload");
if (response.IsSuccessStatusCode)
{
var deltasJson = await response.Content.ReadAsStringAsync();
var updates = deltasJson != "" ? JsonSerializer.Deserialize<Update[]>(deltasJson, s_jsonSerializerOptions) : null;
if (updates == null)
{
agent.Reporter.Report($"No previous updates to apply.", AgentMessageSeverity.Verbose);
return;
}

var i = 1;
foreach (var update in updates)
{
agent.Reporter.Report($"Reapplying update {i}/{updates.Length}.", AgentMessageSeverity.Verbose);

agent.ApplyDeltas(
update.Deltas.Select(d => new UpdateDelta(Guid.Parse(d.ModuleId, CultureInfo.InvariantCulture), d.MetadataDelta, d.ILDelta, d.PdbDelta, d.UpdatedTypes)));

i++;
}

return;
}

errorMessage = $"HTTP GET '/_framework/blazor-hotreload' returned {response.StatusCode}";
}
catch (Exception e)
{
errorMessage = e.ToString();
}

agent.Reporter.Report($"Failed to retrieve and apply previous deltas from the server: {errorMessage}", AgentMessageSeverity.Error);
}

private static HotReloadAgent? GetAgent()
=> s_hotReloadAgent ?? (s_initialized ? throw new InvalidOperationException("Hot Reload agent not initialized") : null);

private static LogEntry[] ApplyHotReloadDeltas(Delta[] deltas, int loggingLevel)
{
var agent = GetAgent();
if (agent == null)
{
return [];
}

agent.ApplyDeltas(
deltas.Select(d => new UpdateDelta(Guid.Parse(d.ModuleId, CultureInfo.InvariantCulture), d.MetadataDelta, d.ILDelta, d.PdbDelta, d.UpdatedTypes)));

return agent.Reporter.GetAndClearLogEntries((ResponseLoggingLevel)loggingLevel)
.Select(log => new LogEntry() { Message = log.message, Severity = (int)log.severity }).ToArray();
}

private static readonly WebAssemblyHotReloadJsonSerializerContext jsonContext = new(new(JsonSerializerDefaults.Web));

[JSExport]
[SupportedOSPlatform("browser")]
public static string GetApplyUpdateCapabilities()
{
return GetAgent()?.Capabilities ?? "";
}

[JSExport]
[SupportedOSPlatform("browser")]
public static string? ApplyHotReloadDeltas(string deltasJson, int loggingLevel)
{
var deltas = JsonSerializer.Deserialize(deltasJson, jsonContext.DeltaArray);
if (deltas == null)
{
return null;
}

var result = ApplyHotReloadDeltas(deltas, loggingLevel);
return result == null ? null : JsonSerializer.Serialize(result, jsonContext.LogEntryArray);
}
}

[JsonSerializable(typeof(WebAssemblyHotReload.Delta[]))]
[JsonSerializable(typeof(WebAssemblyHotReload.LogEntry[]))]
internal sealed partial class WebAssemblyHotReloadJsonSerializerContext : JsonSerializerContext
{
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
export async function onRuntimeConfigLoaded(config) {
// If we have 'aspnetcore-browser-refresh', configure mono runtime for HotReload.
if (config.debugLevel !== 0 && globalThis.window?.document?.querySelector("script[src*='aspnetcore-browser-refresh']")) {
if (!config.environmentVariables["DOTNET_MODIFIABLE_ASSEMBLIES"]) {
config.environmentVariables["DOTNET_MODIFIABLE_ASSEMBLIES"] = "debug";
}
if (!config.environmentVariables["__ASPNETCORE_BROWSER_TOOLS"]) {
config.environmentVariables["__ASPNETCORE_BROWSER_TOOLS"] = "true";
}
}

// Disable HotReload built-into the Blazor WebAssembly runtime
config.environmentVariables["__BLAZOR_WEBASSEMBLY_LEGACY_HOTRELOAD"] = "false";
}

export async function onRuntimeReady({ getAssemblyExports }) {
const exports = await getAssemblyExports("Microsoft.DotNet.HotReload.WebAssembly.Browser");
await exports.Microsoft.DotNet.HotReload.WebAssembly.Browser.WebAssemblyHotReload.InitializeAsync(document.baseURI);

if (!window.Blazor) {
window.Blazor = {};

if (!window.Blazor._internal) {
window.Blazor._internal = {};
}
}

window.Blazor._internal.applyHotReloadDeltas = (deltas, loggingLevel) => {
const result = exports.Microsoft.DotNet.HotReload.WebAssembly.Browser.WebAssemblyHotReload.ApplyHotReloadDeltas(JSON.stringify(deltas), loggingLevel);
return result ? JSON.parse(result) : [];
};

window.Blazor._internal.getApplyUpdateCapabilities = () => {
return exports.Microsoft.DotNet.HotReload.WebAssembly.Browser.WebAssemblyHotReload.GetApplyUpdateCapabilities() ?? '';
};
}
1 change: 1 addition & 0 deletions src/BuiltInTools/dotnet-watch.slnf
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
"src\\BuiltInTools\\HotReloadAgent.Data\\Microsoft.DotNet.HotReload.Agent.Data.shproj",
"src\\BuiltInTools\\HotReloadAgent.PipeRpc\\Microsoft.DotNet.HotReload.Agent.PipeRpc.Package.csproj",
"src\\BuiltInTools\\HotReloadAgent.PipeRpc\\Microsoft.DotNet.HotReload.Agent.PipeRpc.shproj",
"src\\BuiltInTools\\HotReloadAgent.WebAssembly.Browser\\Microsoft.DotNet.HotReload.WebAssembly.Browser.csproj",
"src\\BuiltInTools\\dotnet-watch\\dotnet-watch.csproj",
"test\\Microsoft.AspNetCore.Watch.BrowserRefresh.Tests\\Microsoft.AspNetCore.Watch.BrowserRefresh.Tests.csproj",
"test\\Microsoft.Extensions.DotNetDeltaApplier.Tests\\Microsoft.Extensions.DotNetDeltaApplier.Tests.csproj",
Expand Down
12 changes: 12 additions & 0 deletions src/WasmSdk/Sdk/Sdk.targets
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,18 @@ Copyright (c) .NET Foundation. All rights reserved.
<Import Sdk="Microsoft.NET.Sdk.StaticWebAssets" Project="Sdk.targets" Condition="'$(RuntimeIdentifier)' != 'wasi-wasm' and '$(_WasmSdkImportsMicrosoftNETSdkStaticWebAssets)' == 'true'" />
<Import Sdk="Microsoft.NET.Sdk" Project="Sdk.targets" Condition="'$(RuntimeIdentifier)' == 'wasi-wasm' and '$(_WasmSdkImportsMicrosoftNetSdk)' == 'true'" />

<PropertyGroup>
<!-- Implicit HotReload package reference for .NET 10+ if not explicitly turned off -->
<_WasmEnableHotReload>$(WasmEnableHotReload)</_WasmEnableHotReload>
<_WasmEnableHotReload Condition="'$(_WasmEnableHotReload)' == '' and '$(Configuration)' != 'Debug'">false</_WasmEnableHotReload>
<_WasmEnableHotReload Condition="'$(_WasmEnableHotReload)' == '' and '$(TargetFrameworkIdentifier)' == '.NETCoreApp' and $([MSBuild]::VersionGreaterThanOrEquals('$(TargetFrameworkVersion)', '10.0'))">true</_WasmEnableHotReload>
</PropertyGroup>
<Target Name="_ImplicitlyReferenceHotReload" BeforeTargets="ProcessFrameworkReferences">
<ItemGroup Condition="'$(_WasmEnableHotReload)' == 'true'">
<PackageReference Include="Microsoft.DotNet.HotReload.WebAssembly.Browser" Version="$(NETCoreSdkVersion)" IsImplicitlyDefined="true" />
</ItemGroup>
</Target>

<Import Sdk="Microsoft.NET.Sdk.Publish" Project="Sdk.targets" Condition="'$(_WasmSdkImportsMicrosoftNETSdkPublish)' == 'true'" />
<Import Project="$(_WebAssemblyTargetsFile)" Condition="'$(_WebAssemblyTargetsFile)' != ''" />
</Project>
Original file line number Diff line number Diff line change
Expand Up @@ -302,7 +302,8 @@ public class AssetsData
/// Used in .NET < 8
/// </summary>
[DataMember(EmitDefaultValue = false)]
public List<JsAsset> libraryInitializers { get; set; }
//public List<JsAsset> libraryInitializers { get; set; }
public ResourceHashesByNameDictionary libraryInitializers { get; set; }

[DataMember(EmitDefaultValue = false)]
public List<JsAsset> modulesAfterConfigLoaded { get; set; }
Expand Down Expand Up @@ -407,6 +408,7 @@ public static BootJsonData ParseBootData(string bootConfigPath)
string jsonContent = GetJsonContent(bootConfigPath);
var options = new JsonSerializerOptions { PropertyNameCaseInsensitive = true };
options.Converters.Add(new ResourcesConverter());

BootJsonData config = JsonSerializer.Deserialize<BootJsonData>(jsonContent, options);
if (config.resourcesRaw is AssetsData assets)
{
Expand Down Expand Up @@ -454,7 +456,8 @@ static Dictionary<string, ResourceHashesByNameDictionary> ConvertVfsAssets(List<
pdb = assets.pdb?.ToDictionary(a => a.name, a => a.integrity),
satelliteResources = ConvertSatelliteResources(assets.satelliteResources),
lazyAssembly = assets.lazyAssembly?.ToDictionary(a => a.name, a => a.integrity),
libraryInitializers = assets.libraryInitializers?.ToDictionary(a => a.name, a => (string)null),
//libraryInitializers = assets.libraryInitializers?.ToDictionary(a => a.name, a => (string)null),
libraryInitializers = assets.libraryInitializers,
modulesAfterConfigLoaded = assets.modulesAfterConfigLoaded?.ToDictionary(a => a.name, a => (string)null),
modulesAfterRuntimeReady = assets.modulesAfterRuntimeReady?.ToDictionary(a => a.name, a => (string)null),
extensions = assets.extensions,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,8 @@ internal static void VerifyServiceWorkerFiles(TestAsset testAsset,
// nor do we list the service worker itself or its assets manifest, as these don't need to be fetched in the same way
if (IsCompressedFile(relativePath)
|| string.Equals(relativePath, Path.Combine(staticWebAssetsBasePath, serviceWorkerPath), StringComparison.Ordinal)
|| string.Equals(relativePath, Path.Combine(staticWebAssetsBasePath, assetsManifestPath), StringComparison.Ordinal))
|| string.Equals(relativePath, Path.Combine(staticWebAssetsBasePath, assetsManifestPath), StringComparison.Ordinal)
|| relativePath.EndsWith(".modules.json"))
{
continue;
}
Expand Down
Loading
Loading