-
Notifications
You must be signed in to change notification settings - Fork 10.5k
[Blazor] Disable built-in HotReload when environment variable is set #62735
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
+1
−1
Merged
Changes from 8 commits
Commits
Show all changes
15 commits
Select commit
Hold shift + click to select a range
32d5a36
Move HotReload to a package
maraf 43ca083
Fix
maraf 93d044a
Merge branch 'main' into BlazorHotReloadPackageV2
maraf d239c8a
Add to slnf
maraf 729b8cf
Replace assembly in JS
maraf a1df69d
Switch between built-in and referenced hotreload
maraf d563672
Switch between built-in and referenced hotreload
maraf 42bd330
Replace blazor interop with runtime
maraf fe27352
Feedback
maraf ce74cf8
Rename
maraf 89f002f
Mono environment variables
maraf 338635b
Move the package to SDK
maraf fa32e2f
Clean up
maraf 26ecd04
Clean up
maraf b843cc3
Merge remote-tracking branch 'upstream/main' into BlazorHotReloadPack…
maraf File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
30 changes: 30 additions & 0 deletions
30
src/Components/WebAssembly/HotReload/src/Microsoft.DotNet.HotReload.WebAssembly.csproj
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,30 @@ | ||
<Project Sdk="Microsoft.NET.Sdk.Razor"> | ||
|
||
<PropertyGroup> | ||
<TargetFramework>$(DefaultNetCoreTargetFramework)</TargetFramework> | ||
<Description>HotReload package for WebAssembly</Description> | ||
<NoWarn>$(NoWarn);BL0006</NoWarn> | ||
<!-- Workaround for https://github.com/dotnet/runtime/issues/52227 --> | ||
<NoWarn>$(NoWarn);CS8603</NoWarn> | ||
<GenerateDocumentationFile>true</GenerateDocumentationFile> | ||
<Nullable>enable</Nullable> | ||
<IsTrimmable>true</IsTrimmable> | ||
<AllowUnsafeBlocks>true</AllowUnsafeBlocks> | ||
<!-- TODO: Address Native AOT analyzer warnings https://github.com/dotnet/aspnetcore/issues/45473 --> | ||
<EnableAOTAnalyzer>false</EnableAOTAnalyzer> | ||
</PropertyGroup> | ||
|
||
<ItemGroup> | ||
<Reference Include="Microsoft.AspNetCore.Components.Web" /> | ||
<Reference Include="Microsoft.Extensions.Configuration.Json" /> | ||
<Reference Include="Microsoft.Extensions.Configuration.Binder" /> | ||
<Reference Include="Microsoft.Extensions.Logging" /> | ||
<Reference Include="Microsoft.JSInterop.WebAssembly" /> | ||
<Reference Include="Microsoft.DotNet.HotReload.Agent" PrivateAssets="all" /> | ||
<Reference Include="Microsoft.DotNet.HotReload.Agent.Data" PrivateAssets="all" /> | ||
</ItemGroup> | ||
|
||
<ItemGroup> | ||
<InternalsVisibleTo Include="DynamicProxyGenAssembly2" Key="$(MoqPublicKey)" /> | ||
</ItemGroup> | ||
</Project> |
Empty file.
23 changes: 23 additions & 0 deletions
23
src/Components/WebAssembly/HotReload/src/PublicAPI.Unshipped.txt
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,23 @@ | ||
#nullable enable | ||
maraf marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
Microsoft.DotNet.HotReload.WebAssembly.WebAssemblyHotReload | ||
static Microsoft.DotNet.HotReload.WebAssembly.WebAssemblyHotReload.ApplyHotReloadDelta(string! moduleIdString, byte[]! metadataDelta, byte[]! ilDelta, byte[]! pdbBytes, int[]? updatedTypes) -> void | ||
static Microsoft.DotNet.HotReload.WebAssembly.WebAssemblyHotReload.GetApplyUpdateCapabilities() -> string! | ||
Microsoft.DotNet.HotReload.WebAssembly.WebAssemblyHotReload.Delta | ||
Microsoft.DotNet.HotReload.WebAssembly.WebAssemblyHotReload.Delta.Delta() -> void | ||
Microsoft.DotNet.HotReload.WebAssembly.WebAssemblyHotReload.Delta.ILDelta.get -> byte[]! | ||
Microsoft.DotNet.HotReload.WebAssembly.WebAssemblyHotReload.Delta.ILDelta.init -> void | ||
Microsoft.DotNet.HotReload.WebAssembly.WebAssemblyHotReload.Delta.MetadataDelta.get -> byte[]! | ||
Microsoft.DotNet.HotReload.WebAssembly.WebAssemblyHotReload.Delta.MetadataDelta.init -> void | ||
Microsoft.DotNet.HotReload.WebAssembly.WebAssemblyHotReload.Delta.ModuleId.get -> string! | ||
Microsoft.DotNet.HotReload.WebAssembly.WebAssemblyHotReload.Delta.ModuleId.init -> void | ||
Microsoft.DotNet.HotReload.WebAssembly.WebAssemblyHotReload.Delta.PdbDelta.get -> byte[]! | ||
Microsoft.DotNet.HotReload.WebAssembly.WebAssemblyHotReload.Delta.PdbDelta.init -> void | ||
Microsoft.DotNet.HotReload.WebAssembly.WebAssemblyHotReload.Delta.UpdatedTypes.get -> int[]! | ||
Microsoft.DotNet.HotReload.WebAssembly.WebAssemblyHotReload.Delta.UpdatedTypes.init -> void | ||
Microsoft.DotNet.HotReload.WebAssembly.WebAssemblyHotReload.LogEntry | ||
Microsoft.DotNet.HotReload.WebAssembly.WebAssemblyHotReload.LogEntry.LogEntry() -> void | ||
Microsoft.DotNet.HotReload.WebAssembly.WebAssemblyHotReload.LogEntry.Message.get -> string! | ||
Microsoft.DotNet.HotReload.WebAssembly.WebAssemblyHotReload.LogEntry.Message.init -> void | ||
Microsoft.DotNet.HotReload.WebAssembly.WebAssemblyHotReload.LogEntry.Severity.get -> int | ||
Microsoft.DotNet.HotReload.WebAssembly.WebAssemblyHotReload.LogEntry.Severity.init -> void | ||
static Microsoft.DotNet.HotReload.WebAssembly.WebAssemblyHotReload.ApplyHotReloadDeltas(Microsoft.DotNet.HotReload.WebAssembly.WebAssemblyHotReload.Delta[]! deltas, int loggingLevel) -> Microsoft.DotNet.HotReload.WebAssembly.WebAssemblyHotReload.LogEntry[]! |
207 changes: 207 additions & 0 deletions
207
src/Components/WebAssembly/HotReload/src/WebAssemblyHotReload.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,207 @@ | ||
// 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; | ||
|
||
/// <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")] | ||
public 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 AgentReporter s_reporter = new(); | ||
private static readonly JsonSerializerOptions s_jsonSerializerOptions = new(JsonSerializerDefaults.Web); | ||
|
||
private static bool s_initialized; | ||
private static HotReloadAgent? s_hotReloadAgent; | ||
|
||
internal static async Task InitializeAsync(string baseUri) | ||
{ | ||
if (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) | ||
{ | ||
s_reporter.Report($"No previous updates to apply.", AgentMessageSeverity.Verbose); | ||
return; | ||
} | ||
|
||
var i = 1; | ||
foreach (var update in updates) | ||
{ | ||
s_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(); | ||
} | ||
|
||
s_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); | ||
|
||
/// <summary> | ||
/// For framework use only. | ||
/// </summary> | ||
[Obsolete("Use ApplyHotReloadDeltas instead")] | ||
public static void ApplyHotReloadDelta(string moduleIdString, byte[] metadataDelta, byte[] ilDelta, byte[] pdbBytes, int[]? updatedTypes) | ||
{ | ||
GetAgent()?.ApplyDeltas( | ||
[new UpdateDelta(Guid.Parse(moduleIdString, CultureInfo.InvariantCulture), metadataDelta, ilDelta, pdbBytes, updatedTypes ?? [])]); | ||
} | ||
|
||
/// <summary> | ||
/// For framework use only. | ||
/// </summary> | ||
public static LogEntry[] ApplyHotReloadDeltas(Delta[] deltas, int loggingLevel) | ||
{ | ||
var agent = GetAgent(); | ||
|
||
agent?.ApplyDeltas( | ||
deltas.Select(d => new UpdateDelta(Guid.Parse(d.ModuleId, CultureInfo.InvariantCulture), d.MetadataDelta, d.ILDelta, d.PdbDelta, d.UpdatedTypes))); | ||
|
||
return s_reporter.GetAndClearLogEntries((ResponseLoggingLevel)loggingLevel) | ||
.Select(log => new LogEntry() { Message = log.message, Severity = (int)log.severity }).ToArray(); | ||
} | ||
|
||
/// <summary> | ||
/// For framework use only. | ||
/// </summary> | ||
public static string GetApplyUpdateCapabilities() | ||
=> GetAgent()?.Capabilities ?? ""; | ||
} | ||
|
||
internal static partial class Interop | ||
{ | ||
private static readonly WebAssemblyHotReloadJsonSerializerContext jsonContext = new(new(JsonSerializerDefaults.Web)); | ||
|
||
[JSExport] | ||
[SupportedOSPlatform("browser")] | ||
public static Task InitializeAsync(string baseUri) | ||
{ | ||
if (MetadataUpdater.IsSupported) | ||
{ | ||
return WebAssemblyHotReload.InitializeAsync(baseUri); | ||
} | ||
|
||
return Task.CompletedTask; | ||
} | ||
|
||
[JSExport] | ||
[SupportedOSPlatform("browser")] | ||
public static string GetApplyUpdateCapabilities() | ||
{ | ||
return WebAssemblyHotReload.GetApplyUpdateCapabilities(); | ||
} | ||
|
||
[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 = WebAssemblyHotReload.ApplyHotReloadDeltas(deltas, loggingLevel); | ||
pavelsavara marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
return result == null ? null : JsonSerializer.Serialize(result, jsonContext.LogEntryArray); | ||
} | ||
} | ||
|
||
[JsonSerializable(typeof(WebAssemblyHotReload.Delta[]))] | ||
[JsonSerializable(typeof(WebAssemblyHotReload.LogEntry[]))] | ||
internal sealed partial class WebAssemblyHotReloadJsonSerializerContext : JsonSerializerContext | ||
{ | ||
} |
21 changes: 21 additions & 0 deletions
21
...ts/WebAssembly/HotReload/src/wwwroot/Microsoft.DotNet.HotReload.WebAssembly.lib.module.js
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,21 @@ | ||
export async function onRuntimeConfigLoaded(config) { | ||
config.environmentVariables["__BLAZOR_WEBASSEMBLY_LEGACY_HOTRELOAD"] = "false"; | ||
maraf marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
} | ||
|
||
export async function onRuntimeReady({ getAssemblyExports }) { | ||
const exports = await getAssemblyExports("Microsoft.DotNet.HotReload.WebAssembly"); | ||
await exports.Microsoft.DotNet.HotReload.WebAssembly.Interop.InitializeAsync(document.baseURI); | ||
|
||
if (!window.Blazor) { | ||
window.Blazor = {}; | ||
} | ||
|
||
window.Blazor._internal.applyHotReloadDeltas = (deltas, loggingLevel) => { | ||
maraf marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
const result = exports.Microsoft.DotNet.HotReload.WebAssembly.Interop.ApplyHotReloadDeltas(JSON.stringify(deltas), loggingLevel); | ||
return result ? JSON.parse(result) : []; | ||
}; | ||
|
||
window.Blazor._internal.getApplyUpdateCapabilities = () => { | ||
return exports.Microsoft.DotNet.HotReload.WebAssembly.Interop.GetApplyUpdateCapabilities() ?? ''; | ||
}; | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.