From 5acd40ba2bab21954caa861831ebc4265a20e47b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Marek=20Fi=C5=A1era?= Date: Thu, 4 May 2023 13:02:55 +0200 Subject: [PATCH 1/9] Rename mono-config.json to blazor.boot.json --- .../sample/wasm/browser-advanced/index.html | 2 +- src/mono/sample/wasm/browser-advanced/main.js | 2 +- .../wasm/browser-bench/appstart-frame.html | 2 +- .../wasi/Wasi.Build.Tests/BuildTestBase.cs | 78 ++++++------ .../wasm/Wasm.Build.Tests/BuildTestBase.cs | 113 +++++++++--------- .../wasm/Wasm.Build.Tests/ConfigSrcTests.cs | 4 +- src/mono/wasm/build/WasmApp.targets | 2 +- src/mono/wasm/runtime/startup.ts | 4 +- src/mono/wasm/runtime/types-api.ts | 2 +- src/mono/wasm/test-main.js | 2 +- src/tasks/WasmAppBuilder/WasmAppBuilder.cs | 37 +++--- 11 files changed, 125 insertions(+), 123 deletions(-) diff --git a/src/mono/sample/wasm/browser-advanced/index.html b/src/mono/sample/wasm/browser-advanced/index.html index 0532ef8fcef32..1ce05d184d105 100644 --- a/src/mono/sample/wasm/browser-advanced/index.html +++ b/src/mono/sample/wasm/browser-advanced/index.html @@ -9,7 +9,7 @@ - + diff --git a/src/mono/sample/wasm/browser-advanced/main.js b/src/mono/sample/wasm/browser-advanced/main.js index b6e0ef0a8d1a9..b2fde666b68a3 100644 --- a/src/mono/sample/wasm/browser-advanced/main.js +++ b/src/mono/sample/wasm/browser-advanced/main.js @@ -17,7 +17,7 @@ try { // here we show how emscripten could be further configured // It is prefered to use specific 'with***' methods instead in all other cases. .withModuleConfig({ - configSrc: "./mono-config.json", + configSrc: "./blazor.boot.json", onConfigLoaded: (config) => { // This is called during emscripten `dotnet.wasm` instantiation, after we fetched config. console.log('user code Module.onConfigLoaded'); diff --git a/src/mono/sample/wasm/browser-bench/appstart-frame.html b/src/mono/sample/wasm/browser-bench/appstart-frame.html index 4a1945c9aad6d..d98cb9c7ebc38 100644 --- a/src/mono/sample/wasm/browser-bench/appstart-frame.html +++ b/src/mono/sample/wasm/browser-bench/appstart-frame.html @@ -9,7 +9,7 @@ - + diff --git a/src/mono/wasi/Wasi.Build.Tests/BuildTestBase.cs b/src/mono/wasi/Wasi.Build.Tests/BuildTestBase.cs index 8f3857c53f182..dc432f8096ee0 100644 --- a/src/mono/wasi/Wasi.Build.Tests/BuildTestBase.cs +++ b/src/mono/wasi/Wasi.Build.Tests/BuildTestBase.cs @@ -37,7 +37,7 @@ public abstract class BuildTestBase : IClassFixture !s_buildEnv.IsWorkload; public static string GetNuGetConfigPathFor(string targetFramework) => Path.Combine(BuildEnvironment.TestDataPath, "nuget8.config"); // for now - we are still using net7, but with - // targetFramework == "net7.0" ? "nuget7.config" : "nuget8.config"); + // targetFramework == "net7.0" ? "nuget7.config" : "nuget8.config"); static BuildTestBase() { @@ -69,15 +69,15 @@ static BuildTestBase() else s_xharnessRunnerCommand = EnvironmentVariables.XHarnessCliPath; - Console.WriteLine (""); - Console.WriteLine ($"=============================================================================================="); - Console.WriteLine ($"=============== Running with {(s_buildEnv.IsWorkload ? "Workloads" : "No workloads")} ==============="); - Console.WriteLine ($"=============================================================================================="); - Console.WriteLine (""); + Console.WriteLine(""); + Console.WriteLine($"=============================================================================================="); + Console.WriteLine($"=============== Running with {(s_buildEnv.IsWorkload ? "Workloads" : "No workloads")} ==============="); + Console.WriteLine($"=============================================================================================="); + Console.WriteLine(""); } catch (Exception ex) { - Console.WriteLine ($"Exception: {ex}"); + Console.WriteLine($"Exception: {ex}"); throw; } } @@ -90,7 +90,7 @@ public BuildTestBase(ITestOutputHelper output, SharedBuildPerTestClassFixture bu _logPath = s_buildEnv.LogRootPath; // FIXME: } - public static IEnumerable> ConfigWithAOTData(bool aot, string? config=null) + public static IEnumerable> ConfigWithAOTData(bool aot, string? config = null) { if (config == null) { @@ -163,7 +163,7 @@ protected void InitProjectDir(string dir, bool addNuGetSourceForLocalPackages = ##INSERT_AT_END## "; - protected static BuildArgs ExpandBuildArgs(BuildArgs buildArgs, string extraProperties="", string extraItems="", string insertAtEnd="", string projectTemplate=SimpleProjectTemplate) + protected static BuildArgs ExpandBuildArgs(BuildArgs buildArgs, string extraProperties = "", string extraItems = "", string insertAtEnd = "", string projectTemplate = SimpleProjectTemplate) { if (buildArgs.AOT) { @@ -185,7 +185,7 @@ protected static BuildArgs ExpandBuildArgs(BuildArgs buildArgs, string extraProp string msgPrefix = options.Label != null ? $"[{options.Label}] " : string.Empty; if (options.UseCache && _buildContext.TryGetBuildFor(buildArgs, out BuildProduct? product)) { - _testOutput.WriteLine ($"Using existing build found at {product.ProjectDir}, with build log at {product.LogFile}"); + _testOutput.WriteLine($"Using existing build found at {product.ProjectDir}, with build log at {product.LogFile}"); if (!product.Result) throw new XunitException($"Found existing build at {product.ProjectDir}, but it had failed. Check build log at {product.LogFile}"); @@ -309,7 +309,7 @@ public string CreateWasmTemplateProject(string id, string template = "wasmbrowse return projectfile; } - protected (CommandResult, string) BuildInternal(string id, string config, bool publish=false, bool setWasmDevel=true, params string[] extraArgs) + protected (CommandResult, string) BuildInternal(string id, string config, bool publish = false, bool setWasmDevel = true, params string[] extraArgs) { string label = publish ? "publish" : "build"; _testOutput.WriteLine($"{Environment.NewLine}** {label} **{Environment.NewLine}"); @@ -361,7 +361,7 @@ protected static void AssertBasicAppBundle(string bundleDir, "index.html", mainJS, "dotnet.wasm", - "mono-config.json", + "blazor.boot.json", "dotnet.js" }); @@ -392,7 +392,7 @@ protected static void AssertBasicAppBundle(string bundleDir, protected static void AssertFilesDontExist(string dir, string[] filenames, string? label = null) => AssertFilesExist(dir, filenames, label, expectToExist: false); - protected static void AssertFilesExist(string dir, string[] filenames, string? label = null, bool expectToExist=true) + protected static void AssertFilesExist(string dir, string[] filenames, string? label = null, bool expectToExist = true) { string prefix = label != null ? $"{label}: " : string.Empty; if (!Directory.Exists(dir)) @@ -408,10 +408,10 @@ protected static void AssertFilesExist(string dir, string[] filenames, string? l } } - protected static void AssertSameFile(string file0, string file1, string? label=null) => AssertFile(file0, file1, label, same: true); - protected static void AssertNotSameFile(string file0, string file1, string? label=null) => AssertFile(file0, file1, label, same: false); + protected static void AssertSameFile(string file0, string file1, string? label = null) => AssertFile(file0, file1, label, same: true); + protected static void AssertNotSameFile(string file0, string file1, string? label = null) => AssertFile(file0, file1, label, same: false); - protected static void AssertFile(string file0, string file1, string? label=null, bool same=true) + protected static void AssertFile(string file0, string file1, string? label = null, bool same = true) { Assert.True(File.Exists(file0), $"{label}: Expected to find {file0}"); Assert.True(File.Exists(file1), $"{label}: Expected to find {file1}"); @@ -426,7 +426,7 @@ protected static void AssertFile(string file0, string file1, string? label=null, throw new XunitException($"{label}:{Environment.NewLine} File sizes should not match for {file0} ({finfo0.Length}), and {file1} ({finfo1.Length})"); } - protected (int exitCode, string buildOutput) AssertBuild(string args, string label="build", bool expectSuccess=true, IDictionary? envVars=null, int? timeoutMs=null) + protected (int exitCode, string buildOutput) AssertBuild(string args, string label = "build", bool expectSuccess = true, IDictionary? envVars = null, int? timeoutMs = null) { var result = RunProcess(s_buildEnv.DotNet, _testOutput, args, workingDir: _projectDir, label: label, envVars: envVars, timeoutMs: timeoutMs ?? s_defaultPerTestTimeoutMs); if (expectSuccess && result.exitCode != 0) @@ -450,14 +450,14 @@ private string FindSubDirIgnoringCase(string parentDir, string dirName) return first ?? Path.Combine(parentDir, dirName); } - protected string GetBinDir(string config, string targetFramework=DefaultTargetFramework, string? baseDir=null) + protected string GetBinDir(string config, string targetFramework = DefaultTargetFramework, string? baseDir = null) { var dir = baseDir ?? _projectDir; Assert.NotNull(dir); return Path.Combine(dir!, "bin", config, targetFramework, BuildEnvironment.DefaultRuntimeIdentifier); } - protected string GetObjDir(string config, string targetFramework=DefaultTargetFramework, string? baseDir=null) + protected string GetObjDir(string config, string targetFramework = DefaultTargetFramework, string? baseDir = null) { var dir = baseDir ?? _projectDir; Assert.NotNull(dir); @@ -489,7 +489,7 @@ public static (int exitCode, string buildOutput) RunProcess(string path, { _testOutput.WriteLine($"Running {path} {args}"); _testOutput.WriteLine($"WorkingDirectory: {workingDir}"); - StringBuilder outputBuilder = new (); + StringBuilder outputBuilder = new(); object syncObj = new(); var processStartInfo = new ProcessStartInfo @@ -523,7 +523,7 @@ public static (int exitCode, string buildOutput) RunProcess(string path, processStartInfo.RemoveEnvironmentVariables("MSBuildSDKsPath"); } - Process process = new (); + Process process = new(); process.StartInfo = processStartInfo; process.EnableRaisingEvents = true; @@ -596,7 +596,7 @@ void LogData(string label, string? message) } } - public static string AddItemsPropertiesToProject(string projectFile, string? extraProperties=null, string? extraItems=null, string? atTheEnd=null) + public static string AddItemsPropertiesToProject(string projectFile, string? extraProperties = null, string? extraItems = null, string? atTheEnd = null) { if (extraProperties == null && extraItems == null && atTheEnd == null) return projectFile; @@ -643,7 +643,7 @@ private static string GetEnvironmentVariableOrDefault(string envVarName, string return string.IsNullOrEmpty(value) ? defaultValue : value; } - internal BuildPaths GetBuildPaths(BuildArgs buildArgs, bool forPublish=true) + internal BuildPaths GetBuildPaths(BuildArgs buildArgs, bool forPublish = true) { string objDir = GetObjDir(buildArgs.Config); string bundleDir = Path.Combine(GetBinDir(baseDir: _projectDir, config: buildArgs.Config), "AppBundle"); @@ -686,25 +686,25 @@ public record BuildArgs(string ProjectName, string ProjectFileContents, string? ExtraBuildArgs); public record BuildProduct(string ProjectDir, string LogFile, bool Result); - internal record FileStat (bool Exists, DateTime LastWriteTimeUtc, long Length, string FullPath); + internal record FileStat(bool Exists, DateTime LastWriteTimeUtc, long Length, string FullPath); internal record BuildPaths(string ObjWasmDir, string ObjDir, string BinDir, string BundleDir); public record BuildProjectOptions ( - Action? InitProject = null, - bool? DotnetWasmFromRuntimePack = null, - bool HasIcudt = true, - bool UseCache = true, - bool ExpectSuccess = true, - bool AssertAppBundle = true, - bool CreateProject = true, - bool Publish = true, - bool BuildOnlyAfterPublish = true, - bool HasV8Script = true, - string? Verbosity = null, - string? Label = null, - string? TargetFramework = null, - string? MainJS = null, + Action? InitProject = null, + bool? DotnetWasmFromRuntimePack = null, + bool HasIcudt = true, + bool UseCache = true, + bool ExpectSuccess = true, + bool AssertAppBundle = true, + bool CreateProject = true, + bool Publish = true, + bool BuildOnlyAfterPublish = true, + bool HasV8Script = true, + string? Verbosity = null, + string? Label = null, + string? TargetFramework = null, + string? MainJS = null, IDictionary? ExtraBuildEnvironmentVariables = null ); diff --git a/src/mono/wasm/Wasm.Build.Tests/BuildTestBase.cs b/src/mono/wasm/Wasm.Build.Tests/BuildTestBase.cs index 6dc3e5e525468..64680a5491e57 100644 --- a/src/mono/wasm/Wasm.Build.Tests/BuildTestBase.cs +++ b/src/mono/wasm/Wasm.Build.Tests/BuildTestBase.cs @@ -47,7 +47,7 @@ public abstract class BuildTestBase : IClassFixture s_buildEnv.UseWebcil; public static string GetNuGetConfigPathFor(string targetFramework) => Path.Combine(BuildEnvironment.TestDataPath, "nuget8.config"); // for now - we are still using net7, but with - // targetFramework == "net7.0" ? "nuget7.config" : "nuget8.config"); + // targetFramework == "net7.0" ? "nuget7.config" : "nuget8.config"); static BuildTestBase() { @@ -76,17 +76,17 @@ static BuildTestBase() else s_xharnessRunnerCommand = EnvironmentVariables.XHarnessCliPath; - Console.WriteLine (""); - Console.WriteLine ($"=============================================================================================="); - Console.WriteLine ($"=============== Running with {(s_buildEnv.IsWorkload ? "Workloads" : "No workloads")} ==============="); + Console.WriteLine(""); + Console.WriteLine($"=============================================================================================="); + Console.WriteLine($"=============== Running with {(s_buildEnv.IsWorkload ? "Workloads" : "No workloads")} ==============="); if (UseWebcil) Console.WriteLine($"=============== Using .webcil ==============="); - Console.WriteLine ($"=============================================================================================="); - Console.WriteLine (""); + Console.WriteLine($"=============================================================================================="); + Console.WriteLine(""); } catch (Exception ex) { - Console.WriteLine ($"Exception: {ex}"); + Console.WriteLine($"Exception: {ex}"); throw; } } @@ -110,7 +110,7 @@ public BuildTestBase(ITestOutputHelper output, SharedBuildPerTestClassFixture bu - aot but no wrapper - check that AppBundle wasn't generated */ - public static IEnumerable> ConfigWithAOTData(bool aot, string? config=null, string? extraArgs=null) + public static IEnumerable> ConfigWithAOTData(bool aot, string? config = null, string? extraArgs = null) { if (extraArgs == null) extraArgs = string.Empty; @@ -140,7 +140,7 @@ public BuildTestBase(ITestOutputHelper output, SharedBuildPerTestClassFixture bu protected string RunAndTestWasmApp(BuildArgs buildArgs, RunHost host, string id, - Action? test=null, + Action? test = null, string? buildDir = null, string? bundleDir = null, int expectedExitCode = 0, @@ -205,9 +205,9 @@ protected string RunAndTestWasmApp(BuildArgs buildArgs, } protected static string RunWithXHarness(string testCommand, string testLogPath, string projectName, string bundleDir, - ITestOutputHelper _testOutput, IDictionary? envVars=null, - int expectedAppExitCode=0, int xharnessExitCode=0, string? extraXHarnessArgs=null, - string? appArgs=null, string? extraXHarnessMonoArgs = null, bool useWasmConsoleOutput = false) + ITestOutputHelper _testOutput, IDictionary? envVars = null, + int expectedAppExitCode = 0, int xharnessExitCode = 0, string? extraXHarnessArgs = null, + string? appArgs = null, string? extraXHarnessMonoArgs = null, bool useWasmConsoleOutput = false) { _testOutput.WriteLine($"============== {testCommand} ============="); Directory.CreateDirectory(testLogPath); @@ -333,7 +333,7 @@ protected void InitProjectDir(string dir, bool addNuGetSourceForLocalPackages = ##INSERT_AT_END## "; - protected static BuildArgs ExpandBuildArgs(BuildArgs buildArgs, string extraProperties="", string extraItems="", string insertAtEnd="", string projectTemplate=SimpleProjectTemplate) + protected static BuildArgs ExpandBuildArgs(BuildArgs buildArgs, string extraProperties = "", string extraItems = "", string insertAtEnd = "", string projectTemplate = SimpleProjectTemplate) { if (buildArgs.AOT) { @@ -341,7 +341,8 @@ protected static BuildArgs ExpandBuildArgs(BuildArgs buildArgs, string extraProp extraProperties += $"\n{s_isWindows}\n"; } - if (UseWebcil) { + if (UseWebcil) + { extraProperties += "true\n"; } @@ -361,7 +362,7 @@ protected static BuildArgs ExpandBuildArgs(BuildArgs buildArgs, string extraProp string msgPrefix = options.Label != null ? $"[{options.Label}] " : string.Empty; if (options.UseCache && _buildContext.TryGetBuildFor(buildArgs, out BuildProduct? product)) { - _testOutput.WriteLine ($"Using existing build found at {product.ProjectDir}, with build log at {product.LogFile}"); + _testOutput.WriteLine($"Using existing build found at {product.ProjectDir}, with build log at {product.LogFile}"); if (!product.Result) throw new XunitException($"Found existing build at {product.ProjectDir}, but it had failed. Check build log at {product.LogFile}"); @@ -581,7 +582,7 @@ public string CreateBlazorWasmTemplateProject(string id) return res; } - protected (CommandResult, string) BlazorBuildInternal(string id, string config, bool publish=false, bool setWasmDevel=true, params string[] extraArgs) + protected (CommandResult, string) BlazorBuildInternal(string id, string config, bool publish = false, bool setWasmDevel = true, params string[] extraArgs) { string label = publish ? "publish" : "build"; _testOutput.WriteLine($"{Environment.NewLine}** {label} **{Environment.NewLine}"); @@ -668,7 +669,7 @@ protected static void AssertBasicAppBundle(string bundleDir, { mainJS, "dotnet.wasm", - "mono-config.json", + "blazor.boot.json", "dotnet.js" }; @@ -694,8 +695,8 @@ protected static void AssertBasicAppBundle(string bundleDir, //FIXME: um.. what about these? embedded? why is linker omitting them? //foreach (string file in Directory.EnumerateFiles(managedDir, "*.dll")) //{ - //string pdb = Path.ChangeExtension(file, ".pdb"); - //Assert.True(File.Exists(pdb), $"Could not find {pdb} for {file}"); + //string pdb = Path.ChangeExtension(file, ".pdb"); + //Assert.True(File.Exists(pdb), $"Could not find {pdb} for {file}"); //} } @@ -770,7 +771,7 @@ protected static void AssertDotNetJsSymbols(string bundleDir, bool fromRuntimePa protected static void AssertFilesDontExist(string dir, string[] filenames, string? label = null) => AssertFilesExist(dir, filenames, label, expectToExist: false); - protected static void AssertFilesExist(string dir, IEnumerable filenames, string? label = null, bool expectToExist=true) + protected static void AssertFilesExist(string dir, IEnumerable filenames, string? label = null, bool expectToExist = true) { string prefix = label != null ? $"{label}: " : string.Empty; if (!Directory.Exists(dir)) @@ -786,10 +787,10 @@ protected static void AssertFilesExist(string dir, IEnumerable filenames } } - protected static void AssertSameFile(string file0, string file1, string? label=null) => AssertFile(file0, file1, label, same: true); - protected static void AssertNotSameFile(string file0, string file1, string? label=null) => AssertFile(file0, file1, label, same: false); + protected static void AssertSameFile(string file0, string file1, string? label = null) => AssertFile(file0, file1, label, same: true); + protected static void AssertNotSameFile(string file0, string file1, string? label = null) => AssertFile(file0, file1, label, same: false); - protected static void AssertFile(string file0, string file1, string? label=null, bool same=true) + protected static void AssertFile(string file0, string file1, string? label = null, bool same = true) { Assert.True(File.Exists(file0), $"{label}: Expected to find {file0}"); Assert.True(File.Exists(file1), $"{label}: Expected to find {file1}"); @@ -804,7 +805,7 @@ protected static void AssertFile(string file0, string file1, string? label=null, throw new XunitException($"{label}:{Environment.NewLine} File sizes should not match for {file0} ({finfo0.Length}), and {file1} ({finfo1.Length})"); } - protected (int exitCode, string buildOutput) AssertBuild(string args, string label="build", bool expectSuccess=true, IDictionary? envVars=null, int? timeoutMs=null) + protected (int exitCode, string buildOutput) AssertBuild(string args, string label = "build", bool expectSuccess = true, IDictionary? envVars = null, int? timeoutMs = null) { var result = RunProcess(s_buildEnv.DotNet, _testOutput, args, workingDir: _projectDir, label: label, envVars: envVars, timeoutMs: timeoutMs ?? s_defaultPerTestTimeoutMs); if (expectSuccess && result.exitCode != 0) @@ -815,7 +816,7 @@ protected static void AssertFile(string file0, string file1, string? label=null, return result; } - protected void AssertBlazorBundle(string config, bool isPublish, bool dotnetWasmFromRuntimePack, string targetFramework = DefaultTargetFrameworkForBlazor, string? binFrameworkDir=null) + protected void AssertBlazorBundle(string config, bool isPublish, bool dotnetWasmFromRuntimePack, string targetFramework = DefaultTargetFrameworkForBlazor, string? binFrameworkDir = null) { binFrameworkDir ??= FindBlazorBinFrameworkDir(config, isPublish, targetFramework); @@ -834,7 +835,7 @@ protected void AssertBlazorBundle(string config, bool isPublish, bool dotnetWasm same: dotnetWasmFromRuntimePack); } - protected void AssertBlazorBootJson(string config, bool isPublish, string targetFramework = DefaultTargetFrameworkForBlazor, string? binFrameworkDir=null) + protected void AssertBlazorBootJson(string config, bool isPublish, string targetFramework = DefaultTargetFrameworkForBlazor, string? binFrameworkDir = null) { binFrameworkDir ??= FindBlazorBinFrameworkDir(config, isPublish, targetFramework); @@ -846,7 +847,7 @@ protected void AssertBlazorBootJson(string config, bool isPublish, string target var runtimeObj = bootJsonNode?["resources"]?["runtime"]?.AsObject(); Assert.NotNull(runtimeObj); - string msgPrefix=$"[{( isPublish ? "publish" : "build" )}]"; + string msgPrefix = $"[{(isPublish ? "publish" : "build")}]"; Assert.True(runtimeObj!.Where(kvp => kvp.Key == "dotnet.wasm").Any(), $"{msgPrefix} Could not find dotnet.wasm entry in blazor.boot.json"); Assert.True(runtimeObj!.Where(kvp => kvp.Key.StartsWith("dotnet.", StringComparison.OrdinalIgnoreCase) && kvp.Key.EndsWith(".js", StringComparison.OrdinalIgnoreCase)).Any(), @@ -875,14 +876,14 @@ private string FindSubDirIgnoringCase(string parentDir, string dirName) return first ?? Path.Combine(parentDir, dirName); } - protected string GetBinDir(string config, string targetFramework=DefaultTargetFramework, string? baseDir=null) + protected string GetBinDir(string config, string targetFramework = DefaultTargetFramework, string? baseDir = null) { var dir = baseDir ?? _projectDir; Assert.NotNull(dir); return Path.Combine(dir!, "bin", config, targetFramework, "browser-wasm"); } - protected string GetObjDir(string config, string targetFramework=DefaultTargetFramework, string? baseDir=null) + protected string GetObjDir(string config, string targetFramework = DefaultTargetFramework, string? baseDir = null) { var dir = baseDir ?? _projectDir; Assert.NotNull(dir); @@ -903,7 +904,7 @@ protected string CreateProjectWithNativeReference(string id) return projectFile; } - public void BlazorAddRazorButton(string buttonText, string customCode, string methodName="test", string razorPage="Pages/Counter.razor") + public void BlazorAddRazorButton(string buttonText, string customCode, string methodName = "test", string razorPage = "Pages/Counter.razor") { string additionalCode = $$"""

Output: @outputText

@@ -929,10 +930,10 @@ public void BlazorAddRazorButton(string buttonText, string customCode, string me // Keeping these methods with explicit Build/Publish in the name // so in the test code it is evident which is being run! - public Task BlazorRunForBuildWithDotnetRun(string config, Func? test=null, string extraArgs="--no-build") + public Task BlazorRunForBuildWithDotnetRun(string config, Func? test = null, string extraArgs = "--no-build") => BlazorRunTest($"run -c {config} {extraArgs}", _projectDir!, test); - public Task BlazorRunForPublishWithWebServer(string config, Func? test=null, string extraArgs="") + public Task BlazorRunForPublishWithWebServer(string config, Func? test = null, string extraArgs = "") => BlazorRunTest($"{s_xharnessRunnerCommand} wasm webserver --app=. --web-server-use-default-files {extraArgs}", Path.GetFullPath(Path.Combine(FindBlazorBinFrameworkDir(config, forPublish: true), "..")), test); @@ -998,7 +999,7 @@ public static (int exitCode, string buildOutput) RunProcess(string path, { _testOutput.WriteLine($"Running {path} {args}"); _testOutput.WriteLine($"WorkingDirectory: {workingDir}"); - StringBuilder outputBuilder = new (); + StringBuilder outputBuilder = new(); object syncObj = new(); var processStartInfo = new ProcessStartInfo @@ -1032,7 +1033,7 @@ public static (int exitCode, string buildOutput) RunProcess(string path, processStartInfo.RemoveEnvironmentVariables("MSBuildSDKsPath"); } - Process process = new (); + Process process = new(); process.StartInfo = processStartInfo; process.EnableRaisingEvents = true; @@ -1105,10 +1106,10 @@ void LogData(string label, string? message) } } - public static string AddItemsPropertiesToProject(string projectFile, string? extraProperties=null, string? extraItems=null, string? atTheEnd=null) + public static string AddItemsPropertiesToProject(string projectFile, string? extraProperties = null, string? extraItems = null, string? atTheEnd = null) { if (!File.Exists(projectFile)) - throw new Exception ($"{projectFile} does not exist"); + throw new Exception($"{projectFile} does not exist"); if (extraProperties == null && extraItems == null && atTheEnd == null) return projectFile; @@ -1154,7 +1155,7 @@ private static string GetEnvironmentVariableOrDefault(string envVarName, string return string.IsNullOrEmpty(value) ? defaultValue : value; } - internal BuildPaths GetBuildPaths(BuildArgs buildArgs, bool forPublish=true) + internal BuildPaths GetBuildPaths(BuildArgs buildArgs, bool forPublish = true) { string objDir = GetObjDir(buildArgs.Config); string bundleDir = Path.Combine(GetBinDir(baseDir: _projectDir, config: buildArgs.Config), "AppBundle"); @@ -1212,27 +1213,27 @@ public record BuildArgs(string ProjectName, string ProjectFileContents, string? ExtraBuildArgs); public record BuildProduct(string ProjectDir, string LogFile, bool Result, string BuildOutput); - internal record FileStat (bool Exists, DateTime LastWriteTimeUtc, long Length, string FullPath); + internal record FileStat(bool Exists, DateTime LastWriteTimeUtc, long Length, string FullPath); internal record BuildPaths(string ObjWasmDir, string ObjDir, string BinDir, string BundleDir); public record BuildProjectOptions ( - Action? InitProject = null, - bool? DotnetWasmFromRuntimePack = null, - GlobalizationMode? GlobalizationMode = null, - string? PredefinedIcudt = null, - bool UseCache = true, - bool ExpectSuccess = true, - bool AssertAppBundle = true, - bool CreateProject = true, - bool Publish = true, - bool BuildOnlyAfterPublish = true, - bool HasV8Script = true, - string? Verbosity = null, - string? Label = null, - string? TargetFramework = null, - string? MainJS = null, - bool IsBrowserProject = true, + Action? InitProject = null, + bool? DotnetWasmFromRuntimePack = null, + GlobalizationMode? GlobalizationMode = null, + string? PredefinedIcudt = null, + bool UseCache = true, + bool ExpectSuccess = true, + bool AssertAppBundle = true, + bool CreateProject = true, + bool Publish = true, + bool BuildOnlyAfterPublish = true, + bool HasV8Script = true, + string? Verbosity = null, + string? Label = null, + string? TargetFramework = null, + string? MainJS = null, + bool IsBrowserProject = true, IDictionary? ExtraBuildEnvironmentVariables = null ); @@ -1243,7 +1244,7 @@ public record BlazorBuildOptions NativeFilesType ExpectedFileType, string TargetFramework = BuildTestBase.DefaultTargetFrameworkForBlazor, bool WarnAsError = true, - bool ExpectRelinkDirWhenPublishing=false + bool ExpectRelinkDirWhenPublishing = false ); public enum GlobalizationMode diff --git a/src/mono/wasm/Wasm.Build.Tests/ConfigSrcTests.cs b/src/mono/wasm/Wasm.Build.Tests/ConfigSrcTests.cs index 9488225ccc62b..925d8fa5d0212 100644 --- a/src/mono/wasm/Wasm.Build.Tests/ConfigSrcTests.cs +++ b/src/mono/wasm/Wasm.Build.Tests/ConfigSrcTests.cs @@ -12,7 +12,7 @@ namespace Wasm.Build.Tests; public class ConfigSrcTests : BuildTestBase { public ConfigSrcTests(ITestOutputHelper output, SharedBuildPerTestClassFixture buildContext) : base(output, buildContext) - {} + { } // NOTE: port number determinizes dynamically, so could not generate absolute URI [Theory] @@ -30,7 +30,7 @@ public void ConfigSrcAbsolutePath(BuildArgs buildArgs, RunHost host, string id) string binDir = GetBinDir(baseDir: _projectDir!, config: buildArgs.Config); string bundleDir = Path.Combine(binDir, "AppBundle"); - string configSrc = Path.GetFullPath(Path.Combine(bundleDir, "mono-config.json")); + string configSrc = Path.GetFullPath(Path.Combine(bundleDir, "blazor.boot.json")); RunAndTestWasmApp(buildArgs, expectedExitCode: 42, host: host, id: id, extraXHarnessMonoArgs: $"--config-src={configSrc}"); } diff --git a/src/mono/wasm/build/WasmApp.targets b/src/mono/wasm/build/WasmApp.targets index 0d50ada7ad3a2..7270e4b9d7995 100644 --- a/src/mono/wasm/build/WasmApp.targets +++ b/src/mono/wasm/build/WasmApp.targets @@ -84,7 +84,7 @@ - @(WasmFilesToIncludeInFileSystem) - Files to include in the vfs - @(WasmNativeAsset) - Native files to be added to `NativeAssets` in the bundle. - - @(WasmExtraConfig) - json elements to add to `mono-config.json` + - @(WasmExtraConfig) - json elements to add to `blazor.boot.json` Eg. - Value attribute can have a number, bool, quoted string, or json string diff --git a/src/mono/wasm/runtime/startup.ts b/src/mono/wasm/runtime/startup.ts index 1ae473cf24338..528d2e68f708d 100644 --- a/src/mono/wasm/runtime/startup.ts +++ b/src/mono/wasm/runtime/startup.ts @@ -60,7 +60,7 @@ export function configureEmscriptenStartup(module: DotnetModuleInternal): void { if (!module.configSrc && (!module.config || Object.keys(module.config).length === 0 || !module.config.assets)) { // if config file location nor assets are provided - module.configSrc = "./mono-config.json"; + module.configSrc = "./blazor.boot.json"; } if (!module["locateFile"]) { @@ -651,7 +651,7 @@ export function bindings_init(): void { } /** - * Loads the mono config file (typically called mono-config.json) asynchroniously + * Loads the mono config file (typically called blazor.boot.json) asynchroniously * Note: the run dependencies are so emsdk actually awaits it in order. * * @param {string} configFilePath - relative path to the config file diff --git a/src/mono/wasm/runtime/types-api.ts b/src/mono/wasm/runtime/types-api.ts index 3fd1c327e0c1d..04dc3e14c21ab 100644 --- a/src/mono/wasm/runtime/types-api.ts +++ b/src/mono/wasm/runtime/types-api.ts @@ -95,7 +95,7 @@ export interface LoadingResource { response: Promise; } -// Types of assets that can be in the mono-config.js/mono-config.json file (taken from /src/tasks/WasmAppBuilder/WasmAppBuilder.cs) +// Types of assets that can be in the mono-config.js/blazor.boot.json file (taken from /src/tasks/WasmAppBuilder/WasmAppBuilder.cs) export interface AssetEntry extends ResourceRequest { /** * If specified, overrides the path of the asset in the virtual filesystem and similar data structures once downloaded. diff --git a/src/mono/wasm/test-main.js b/src/mono/wasm/test-main.js index 63dc5d143f7af..a50019c6e9de1 100644 --- a/src/mono/wasm/test-main.js +++ b/src/mono/wasm/test-main.js @@ -99,7 +99,7 @@ function initRunArgs(runArgs) { runArgs.enableGC = runArgs.enableGC === undefined ? true : runArgs.enableGC; runArgs.diagnosticTracing = runArgs.diagnosticTracing === undefined ? false : runArgs.diagnosticTracing; runArgs.debugging = runArgs.debugging === undefined ? false : runArgs.debugging; - runArgs.configSrc = runArgs.configSrc === undefined ? './mono-config.json' : runArgs.configSrc; + runArgs.configSrc = runArgs.configSrc === undefined ? './blazor.boot.json' : runArgs.configSrc; // default'ing to true for tests, unless debugging runArgs.forwardConsole = runArgs.forwardConsole === undefined ? !runArgs.debugging : runArgs.forwardConsole; runArgs.memorySnapshot = runArgs.memorySnapshot === undefined ? true : runArgs.memorySnapshot; diff --git a/src/tasks/WasmAppBuilder/WasmAppBuilder.cs b/src/tasks/WasmAppBuilder/WasmAppBuilder.cs index 439ebf64e7ed5..c7a4b30e74ab9 100644 --- a/src/tasks/WasmAppBuilder/WasmAppBuilder.cs +++ b/src/tasks/WasmAppBuilder/WasmAppBuilder.cs @@ -19,12 +19,12 @@ namespace Microsoft.WebAssembly.Build.Tasks; public class WasmAppBuilder : WasmAppBuilderBaseTask { public ITaskItem[]? RemoteSources { get; set; } - public bool IncludeThreadsWorker {get; set; } - public int PThreadPoolSize {get; set; } + public bool IncludeThreadsWorker { get; set; } + public int PThreadPoolSize { get; set; } public bool UseWebcil { get; set; } // - // Extra json elements to add to mono-config.json + // Extra json elements to add to blazor.boot.json // // Metadata: // - Value: can be a number, bool, quoted string, or json string @@ -59,7 +59,7 @@ private sealed class WasmAppConfig private class AssetEntry { - protected AssetEntry (string name, string hash, string behavior) + protected AssetEntry(string name, string hash, string behavior) { Name = name; Behavior = behavior; @@ -85,12 +85,12 @@ public ThreadsWorkerEntry(string name, string hash) : base(name, hash, "js-modul private sealed class AssemblyEntry : AssetEntry { - public AssemblyEntry(string name, string hash) : base(name, hash, "assembly") {} + public AssemblyEntry(string name, string hash) : base(name, hash, "assembly") { } } private sealed class PdbEntry : AssetEntry { - public PdbEntry(string name, string hash) : base(name, hash, "pdb") {} + public PdbEntry(string name, string hash) : base(name, hash, "pdb") { } } private sealed class SatelliteAssemblyEntry : AssetEntry @@ -106,21 +106,21 @@ public SatelliteAssemblyEntry(string name, string hash, string culture) : base(n private sealed class VfsEntry : AssetEntry { - public VfsEntry(string name, string hash) : base(name, hash, "vfs") {} + public VfsEntry(string name, string hash) : base(name, hash, "vfs") { } [JsonPropertyName("virtualPath")] public string? VirtualPath { get; set; } } private sealed class IcuData : AssetEntry { - public IcuData(string name, string hash) : base(name, hash, "icu") {} + public IcuData(string name, string hash) : base(name, hash, "icu") { } [JsonPropertyName("loadRemote")] public bool LoadRemote { get; set; } } private sealed class SymbolsData : AssetEntry { - public SymbolsData(string name, string hash) : base(name, hash, "symbols") {} + public SymbolsData(string name, string hash) : base(name, hash, "symbols") { } } protected override bool ValidateArguments() @@ -153,7 +153,7 @@ protected override bool ExecuteInternal() } MainAssemblyName = Path.GetFileName(MainAssemblyName); - var config = new WasmAppConfig () + var config = new WasmAppConfig() { MainAssemblyName = MainAssemblyName, GlobalizationMode = InvariantGlobalization ? "invariant" : HybridGlobalization ? "hybrid" : "icu" @@ -164,7 +164,7 @@ protected override bool ExecuteInternal() Directory.CreateDirectory(AppDir!); Directory.CreateDirectory(asmRootPath); if (UseWebcil) - Log.LogMessage (MessageImportance.Normal, "Converting assemblies to Webcil"); + Log.LogMessage(MessageImportance.Normal, "Converting assemblies to Webcil"); foreach (var assembly in _assemblies) { if (UseWebcil) @@ -200,13 +200,13 @@ protected override bool ExecuteInternal() return false; if (name == "dotnet.wasm") { - config.Assets.Add(new WasmEntry (name, Utils.ComputeIntegrity(item.ItemSpec)) ); + config.Assets.Add(new WasmEntry(name, Utils.ComputeIntegrity(item.ItemSpec))); } else if (IncludeThreadsWorker && name == "dotnet.worker.js") { - config.Assets.Add(new ThreadsWorkerEntry (name, Utils.ComputeIntegrity(item.ItemSpec))); + config.Assets.Add(new ThreadsWorkerEntry(name, Utils.ComputeIntegrity(item.ItemSpec))); } - else if(name == "dotnet.js.symbols") + else if (name == "dotnet.js.symbols") { config.Assets.Add(new SymbolsData(name, Utils.ComputeIntegrity(item.ItemSpec))); } @@ -313,7 +313,8 @@ protected override bool ExecuteInternal() var vfsPath = Path.Combine(supportFilesDir, generatedFileName); FileCopyChecked(item.ItemSpec, vfsPath, "FilesToIncludeInFileSystem"); - var asset = new VfsEntry ($"supportFiles/{generatedFileName}", Utils.ComputeIntegrity(vfsPath)) { + var asset = new VfsEntry($"supportFiles/{generatedFileName}", Utils.ComputeIntegrity(vfsPath)) + { VirtualPath = targetPath }; config.Assets.Add(asset); @@ -364,16 +365,16 @@ protected override bool ExecuteInternal() using (var sw = File.CreateText(tmpMonoConfigPath)) { var sb = new StringBuilder(); - foreach(AssetEntry asset in config.Assets) + foreach (AssetEntry asset in config.Assets) { sb.Append(asset.Hash); } config.AssetsHash = Utils.ComputeTextIntegrity(sb.ToString()); - var json = JsonSerializer.Serialize (config, new JsonSerializerOptions { WriteIndented = true }); + var json = JsonSerializer.Serialize(config, new JsonSerializerOptions { WriteIndented = true }); sw.Write(json); } - string monoConfigPath = Path.Combine(AppDir, "mono-config.json"); + string monoConfigPath = Path.Combine(AppDir, "blazor.boot.json"); // TODO: Unify with Wasm SDK Utils.CopyIfDifferent(tmpMonoConfigPath, monoConfigPath, useHash: false); _fileWrites.Add(monoConfigPath); From 247325775dc6f3c32eb6f71732d05f2771b32232 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Marek=20Fi=C5=A1era?= Date: Thu, 4 May 2023 13:03:09 +0200 Subject: [PATCH 2/9] Move mono-config to _framework dir --- src/mono/sample/wasm/browser-advanced/main.js | 2 +- src/mono/sample/wasm/browser-bench/appstart-frame.html | 2 +- src/mono/wasi/Wasi.Build.Tests/BuildTestBase.cs | 2 +- src/mono/wasm/Wasm.Build.Tests/BuildTestBase.cs | 2 +- src/mono/wasm/Wasm.Build.Tests/ConfigSrcTests.cs | 2 +- src/mono/wasm/build/WasmApp.targets | 2 +- src/mono/wasm/runtime/run-outer.ts | 2 +- src/mono/wasm/runtime/startup.ts | 4 ++-- src/mono/wasm/runtime/types-api.ts | 2 +- src/mono/wasm/test-main.js | 2 +- src/tasks/WasmAppBuilder/WasmAppBuilder.cs | 9 +++++++-- 11 files changed, 18 insertions(+), 13 deletions(-) diff --git a/src/mono/sample/wasm/browser-advanced/main.js b/src/mono/sample/wasm/browser-advanced/main.js index b2fde666b68a3..a5dbaeba13088 100644 --- a/src/mono/sample/wasm/browser-advanced/main.js +++ b/src/mono/sample/wasm/browser-advanced/main.js @@ -17,7 +17,7 @@ try { // here we show how emscripten could be further configured // It is prefered to use specific 'with***' methods instead in all other cases. .withModuleConfig({ - configSrc: "./blazor.boot.json", + configSrc: "./_framework/blazor.boot.json", onConfigLoaded: (config) => { // This is called during emscripten `dotnet.wasm` instantiation, after we fetched config. console.log('user code Module.onConfigLoaded'); diff --git a/src/mono/sample/wasm/browser-bench/appstart-frame.html b/src/mono/sample/wasm/browser-bench/appstart-frame.html index d98cb9c7ebc38..06e597d259a3e 100644 --- a/src/mono/sample/wasm/browser-bench/appstart-frame.html +++ b/src/mono/sample/wasm/browser-bench/appstart-frame.html @@ -9,7 +9,7 @@ - + diff --git a/src/mono/wasi/Wasi.Build.Tests/BuildTestBase.cs b/src/mono/wasi/Wasi.Build.Tests/BuildTestBase.cs index dc432f8096ee0..aae838ba1bcd0 100644 --- a/src/mono/wasi/Wasi.Build.Tests/BuildTestBase.cs +++ b/src/mono/wasi/Wasi.Build.Tests/BuildTestBase.cs @@ -361,7 +361,7 @@ protected static void AssertBasicAppBundle(string bundleDir, "index.html", mainJS, "dotnet.wasm", - "blazor.boot.json", + "_framework/blazor.boot.json", "dotnet.js" }); diff --git a/src/mono/wasm/Wasm.Build.Tests/BuildTestBase.cs b/src/mono/wasm/Wasm.Build.Tests/BuildTestBase.cs index 64680a5491e57..f0077adb6e925 100644 --- a/src/mono/wasm/Wasm.Build.Tests/BuildTestBase.cs +++ b/src/mono/wasm/Wasm.Build.Tests/BuildTestBase.cs @@ -669,7 +669,7 @@ protected static void AssertBasicAppBundle(string bundleDir, { mainJS, "dotnet.wasm", - "blazor.boot.json", + "_framework/blazor.boot.json", "dotnet.js" }; diff --git a/src/mono/wasm/Wasm.Build.Tests/ConfigSrcTests.cs b/src/mono/wasm/Wasm.Build.Tests/ConfigSrcTests.cs index 925d8fa5d0212..6d6a552407634 100644 --- a/src/mono/wasm/Wasm.Build.Tests/ConfigSrcTests.cs +++ b/src/mono/wasm/Wasm.Build.Tests/ConfigSrcTests.cs @@ -30,7 +30,7 @@ public void ConfigSrcAbsolutePath(BuildArgs buildArgs, RunHost host, string id) string binDir = GetBinDir(baseDir: _projectDir!, config: buildArgs.Config); string bundleDir = Path.Combine(binDir, "AppBundle"); - string configSrc = Path.GetFullPath(Path.Combine(bundleDir, "blazor.boot.json")); + string configSrc = Path.GetFullPath(Path.Combine(bundleDir, "_framework", "blazor.boot.json")); RunAndTestWasmApp(buildArgs, expectedExitCode: 42, host: host, id: id, extraXHarnessMonoArgs: $"--config-src={configSrc}"); } diff --git a/src/mono/wasm/build/WasmApp.targets b/src/mono/wasm/build/WasmApp.targets index 7270e4b9d7995..ff43955c476a0 100644 --- a/src/mono/wasm/build/WasmApp.targets +++ b/src/mono/wasm/build/WasmApp.targets @@ -84,7 +84,7 @@ - @(WasmFilesToIncludeInFileSystem) - Files to include in the vfs - @(WasmNativeAsset) - Native files to be added to `NativeAssets` in the bundle. - - @(WasmExtraConfig) - json elements to add to `blazor.boot.json` + - @(WasmExtraConfig) - json elements to add to `_framework/blazor.boot.json` Eg. - Value attribute can have a number, bool, quoted string, or json string diff --git a/src/mono/wasm/runtime/run-outer.ts b/src/mono/wasm/runtime/run-outer.ts index 0321cd8e57410..c2f5e907e76ac 100644 --- a/src/mono/wasm/runtime/run-outer.ts +++ b/src/mono/wasm/runtime/run-outer.ts @@ -287,7 +287,7 @@ export class HostBuilder implements DotnetHostBuilder { deep_merge_config(monoConfig, { startupOptions }); - return this.withConfigSrc("blazor.boot.json"); + return this.withConfigSrc("_framework/blazor.boot.json"); } async create(): Promise { diff --git a/src/mono/wasm/runtime/startup.ts b/src/mono/wasm/runtime/startup.ts index 528d2e68f708d..c25176ecde4a9 100644 --- a/src/mono/wasm/runtime/startup.ts +++ b/src/mono/wasm/runtime/startup.ts @@ -60,7 +60,7 @@ export function configureEmscriptenStartup(module: DotnetModuleInternal): void { if (!module.configSrc && (!module.config || Object.keys(module.config).length === 0 || !module.config.assets)) { // if config file location nor assets are provided - module.configSrc = "./blazor.boot.json"; + module.configSrc = "./_framework/blazor.boot.json"; } if (!module["locateFile"]) { @@ -651,7 +651,7 @@ export function bindings_init(): void { } /** - * Loads the mono config file (typically called blazor.boot.json) asynchroniously + * Loads the mono config file (typically called _framework/blazor.boot.json) asynchroniously * Note: the run dependencies are so emsdk actually awaits it in order. * * @param {string} configFilePath - relative path to the config file diff --git a/src/mono/wasm/runtime/types-api.ts b/src/mono/wasm/runtime/types-api.ts index 04dc3e14c21ab..0c833be875c67 100644 --- a/src/mono/wasm/runtime/types-api.ts +++ b/src/mono/wasm/runtime/types-api.ts @@ -95,7 +95,7 @@ export interface LoadingResource { response: Promise; } -// Types of assets that can be in the mono-config.js/blazor.boot.json file (taken from /src/tasks/WasmAppBuilder/WasmAppBuilder.cs) +// Types of assets that can be in the _framework/blazor.boot.json file (taken from /src/tasks/WasmAppBuilder/WasmAppBuilder.cs) export interface AssetEntry extends ResourceRequest { /** * If specified, overrides the path of the asset in the virtual filesystem and similar data structures once downloaded. diff --git a/src/mono/wasm/test-main.js b/src/mono/wasm/test-main.js index a50019c6e9de1..35e3eec685257 100644 --- a/src/mono/wasm/test-main.js +++ b/src/mono/wasm/test-main.js @@ -99,7 +99,7 @@ function initRunArgs(runArgs) { runArgs.enableGC = runArgs.enableGC === undefined ? true : runArgs.enableGC; runArgs.diagnosticTracing = runArgs.diagnosticTracing === undefined ? false : runArgs.diagnosticTracing; runArgs.debugging = runArgs.debugging === undefined ? false : runArgs.debugging; - runArgs.configSrc = runArgs.configSrc === undefined ? './blazor.boot.json' : runArgs.configSrc; + runArgs.configSrc = runArgs.configSrc === undefined ? './_framework/blazor.boot.json' : runArgs.configSrc; // default'ing to true for tests, unless debugging runArgs.forwardConsole = runArgs.forwardConsole === undefined ? !runArgs.debugging : runArgs.forwardConsole; runArgs.memorySnapshot = runArgs.memorySnapshot === undefined ? true : runArgs.memorySnapshot; diff --git a/src/tasks/WasmAppBuilder/WasmAppBuilder.cs b/src/tasks/WasmAppBuilder/WasmAppBuilder.cs index c7a4b30e74ab9..ce6a9d727727e 100644 --- a/src/tasks/WasmAppBuilder/WasmAppBuilder.cs +++ b/src/tasks/WasmAppBuilder/WasmAppBuilder.cs @@ -24,7 +24,7 @@ public class WasmAppBuilder : WasmAppBuilderBaseTask public bool UseWebcil { get; set; } // - // Extra json elements to add to blazor.boot.json + // Extra json elements to add to _framework/blazor.boot.json // // Metadata: // - Value: can be a number, bool, quoted string, or json string @@ -374,7 +374,12 @@ protected override bool ExecuteInternal() var json = JsonSerializer.Serialize(config, new JsonSerializerOptions { WriteIndented = true }); sw.Write(json); } - string monoConfigPath = Path.Combine(AppDir, "blazor.boot.json"); // TODO: Unify with Wasm SDK + + string monoConfigDir = Path.Combine(AppDir, "_framework"); + if (!Directory.Exists(monoConfigDir)) + Directory.CreateDirectory(monoConfigDir); + + string monoConfigPath = Path.Combine(monoConfigDir, "blazor.boot.json"); // TODO: Unify with Wasm SDK Utils.CopyIfDifferent(tmpMonoConfigPath, monoConfigPath, useHash: false); _fileWrites.Add(monoConfigPath); From 06e53aa4f763e09db4bc74219ff7f48118673945 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Marek=20Fi=C5=A1era?= Date: Thu, 4 May 2023 13:03:21 +0200 Subject: [PATCH 3/9] Check boot config schema without startupOptions --- src/mono/wasm/runtime/blazor/BootConfig.ts | 8 ++++-- src/mono/wasm/runtime/blazor/_Integration.ts | 12 +++++--- src/mono/wasm/runtime/startup.ts | 29 ++++++++++++-------- 3 files changed, 31 insertions(+), 18 deletions(-) diff --git a/src/mono/wasm/runtime/blazor/BootConfig.ts b/src/mono/wasm/runtime/blazor/BootConfig.ts index 48c033b7368b3..fcfd0cdf1aac0 100644 --- a/src/mono/wasm/runtime/blazor/BootConfig.ts +++ b/src/mono/wasm/runtime/blazor/BootConfig.ts @@ -11,14 +11,16 @@ export class BootConfigResult { } static async initAsync(loadBootResource?: LoadBootResourceCallback, environment?: string): Promise { + const defaultBootJsonLocation = "_framework/blazor.boot.json"; + const loaderResponse = loadBootResource !== undefined ? - loadBootResource("manifest", "blazor.boot.json", "_framework/blazor.boot.json", "") : - defaultLoadBlazorBootJson("_framework/blazor.boot.json"); + loadBootResource("manifest", "blazor.boot.json", defaultBootJsonLocation, "") : + defaultLoadBlazorBootJson(defaultBootJsonLocation); let bootConfigResponse: Response; if (!loaderResponse) { - bootConfigResponse = await defaultLoadBlazorBootJson("_framework/blazor.boot.json"); + bootConfigResponse = await defaultLoadBlazorBootJson(defaultBootJsonLocation); } else if (typeof loaderResponse === "string") { bootConfigResponse = await defaultLoadBlazorBootJson(loaderResponse); } else { diff --git a/src/mono/wasm/runtime/blazor/_Integration.ts b/src/mono/wasm/runtime/blazor/_Integration.ts index 64896bfaa013c..71f5f0087edb0 100644 --- a/src/mono/wasm/runtime/blazor/_Integration.ts +++ b/src/mono/wasm/runtime/blazor/_Integration.ts @@ -1,18 +1,22 @@ import { INTERNAL, Module } from "../globals"; import { MonoConfigInternal } from "../types"; -import { AssetEntry, LoadingResource, WebAssemblyBootResourceType } from "../types-api"; +import { AssetEntry, LoadingResource, WebAssemblyBootResourceType, WebAssemblyStartOptions } from "../types-api"; import { BootConfigResult, BootJsonData, ICUDataMode } from "./BootConfig"; import { WebAssemblyResourceLoader } from "./WebAssemblyResourceLoader"; import { hasDebuggingEnabled } from "./_Polyfill"; -export async function loadBootConfig(config: MonoConfigInternal,) { +export async function loadBootConfig(config: MonoConfigInternal) { const candidateOptions = config.startupOptions ?? {}; const environment = candidateOptions.environment; const bootConfigPromise = BootConfigResult.initAsync(candidateOptions.loadBootResource, environment); const bootConfigResult: BootConfigResult = await bootConfigPromise; - const resourceLoader = await WebAssemblyResourceLoader.initAsync(bootConfigResult.bootConfig, candidateOptions || {}); + await initializeBootConfig(bootConfigResult, candidateOptions); +} + +export async function initializeBootConfig(bootConfigResult: BootConfigResult, startupOptions?: Partial) { + const resourceLoader = await WebAssemblyResourceLoader.initAsync(bootConfigResult.bootConfig, startupOptions || {}); INTERNAL.resourceLoader = resourceLoader; @@ -23,7 +27,7 @@ export async function loadBootConfig(config: MonoConfigInternal,) { let resourcesLoaded = 0; let totalResources = 0; -export function mapBootConfigToMonoConfig(moduleConfig: MonoConfigInternal, resourceLoader: WebAssemblyResourceLoader, applicationEnvironment: string): MonoConfigInternal { +function mapBootConfigToMonoConfig(moduleConfig: MonoConfigInternal, resourceLoader: WebAssemblyResourceLoader, applicationEnvironment: string): MonoConfigInternal { const resources = resourceLoader.bootConfig.resources; const assets: AssetEntry[] = []; diff --git a/src/mono/wasm/runtime/startup.ts b/src/mono/wasm/runtime/startup.ts index c25176ecde4a9..c019595300ad6 100644 --- a/src/mono/wasm/runtime/startup.ts +++ b/src/mono/wasm/runtime/startup.ts @@ -29,13 +29,14 @@ import { preAllocatePThreadWorkerPool, instantiateWasmPThreadWorkerPool } from " import { export_linker } from "./exports-linker"; import { endMeasure, MeasuredBlock, startMeasure } from "./profiler"; import { getMemorySnapshot, storeMemorySnapshot, getMemorySnapshotSize } from "./snapshot"; -import { loadBootConfig } from "./blazor/_Integration"; +import { initializeBootConfig, loadBootConfig } from "./blazor/_Integration"; // legacy import { init_legacy_exports } from "./net6-legacy/corebindings"; import { cwraps_binding_api, cwraps_mono_api } from "./net6-legacy/exports-legacy"; import { BINDING, MONO } from "./net6-legacy/globals"; import { init_globalization } from "./icu"; +import { BootConfigResult } from "./blazor/BootConfig"; let config: MonoConfigInternal = undefined as any; let configLoaded = false; @@ -670,20 +671,26 @@ export async function mono_wasm_load_config(configFilePath?: string): Promise Date: Thu, 4 May 2023 13:05:30 +0200 Subject: [PATCH 4/9] Fix changes to WBT --- .../wasi/Wasi.Build.Tests/BuildTestBase.cs | 76 +++++++++---------- 1 file changed, 38 insertions(+), 38 deletions(-) diff --git a/src/mono/wasi/Wasi.Build.Tests/BuildTestBase.cs b/src/mono/wasi/Wasi.Build.Tests/BuildTestBase.cs index aae838ba1bcd0..e2980fc735746 100644 --- a/src/mono/wasi/Wasi.Build.Tests/BuildTestBase.cs +++ b/src/mono/wasi/Wasi.Build.Tests/BuildTestBase.cs @@ -37,7 +37,7 @@ public abstract class BuildTestBase : IClassFixture !s_buildEnv.IsWorkload; public static string GetNuGetConfigPathFor(string targetFramework) => Path.Combine(BuildEnvironment.TestDataPath, "nuget8.config"); // for now - we are still using net7, but with - // targetFramework == "net7.0" ? "nuget7.config" : "nuget8.config"); + // targetFramework == "net7.0" ? "nuget7.config" : "nuget8.config"); static BuildTestBase() { @@ -69,15 +69,15 @@ static BuildTestBase() else s_xharnessRunnerCommand = EnvironmentVariables.XHarnessCliPath; - Console.WriteLine(""); - Console.WriteLine($"=============================================================================================="); - Console.WriteLine($"=============== Running with {(s_buildEnv.IsWorkload ? "Workloads" : "No workloads")} ==============="); - Console.WriteLine($"=============================================================================================="); - Console.WriteLine(""); + Console.WriteLine (""); + Console.WriteLine ($"=============================================================================================="); + Console.WriteLine ($"=============== Running with {(s_buildEnv.IsWorkload ? "Workloads" : "No workloads")} ==============="); + Console.WriteLine ($"=============================================================================================="); + Console.WriteLine (""); } catch (Exception ex) { - Console.WriteLine($"Exception: {ex}"); + Console.WriteLine ($"Exception: {ex}"); throw; } } @@ -90,7 +90,7 @@ public BuildTestBase(ITestOutputHelper output, SharedBuildPerTestClassFixture bu _logPath = s_buildEnv.LogRootPath; // FIXME: } - public static IEnumerable> ConfigWithAOTData(bool aot, string? config = null) + public static IEnumerable> ConfigWithAOTData(bool aot, string? config=null) { if (config == null) { @@ -163,7 +163,7 @@ protected void InitProjectDir(string dir, bool addNuGetSourceForLocalPackages = ##INSERT_AT_END## "; - protected static BuildArgs ExpandBuildArgs(BuildArgs buildArgs, string extraProperties = "", string extraItems = "", string insertAtEnd = "", string projectTemplate = SimpleProjectTemplate) + protected static BuildArgs ExpandBuildArgs(BuildArgs buildArgs, string extraProperties="", string extraItems="", string insertAtEnd="", string projectTemplate=SimpleProjectTemplate) { if (buildArgs.AOT) { @@ -185,7 +185,7 @@ protected static BuildArgs ExpandBuildArgs(BuildArgs buildArgs, string extraProp string msgPrefix = options.Label != null ? $"[{options.Label}] " : string.Empty; if (options.UseCache && _buildContext.TryGetBuildFor(buildArgs, out BuildProduct? product)) { - _testOutput.WriteLine($"Using existing build found at {product.ProjectDir}, with build log at {product.LogFile}"); + _testOutput.WriteLine ($"Using existing build found at {product.ProjectDir}, with build log at {product.LogFile}"); if (!product.Result) throw new XunitException($"Found existing build at {product.ProjectDir}, but it had failed. Check build log at {product.LogFile}"); @@ -309,7 +309,7 @@ public string CreateWasmTemplateProject(string id, string template = "wasmbrowse return projectfile; } - protected (CommandResult, string) BuildInternal(string id, string config, bool publish = false, bool setWasmDevel = true, params string[] extraArgs) + protected (CommandResult, string) BuildInternal(string id, string config, bool publish=false, bool setWasmDevel=true, params string[] extraArgs) { string label = publish ? "publish" : "build"; _testOutput.WriteLine($"{Environment.NewLine}** {label} **{Environment.NewLine}"); @@ -392,7 +392,7 @@ protected static void AssertBasicAppBundle(string bundleDir, protected static void AssertFilesDontExist(string dir, string[] filenames, string? label = null) => AssertFilesExist(dir, filenames, label, expectToExist: false); - protected static void AssertFilesExist(string dir, string[] filenames, string? label = null, bool expectToExist = true) + protected static void AssertFilesExist(string dir, string[] filenames, string? label = null, bool expectToExist=true) { string prefix = label != null ? $"{label}: " : string.Empty; if (!Directory.Exists(dir)) @@ -408,10 +408,10 @@ protected static void AssertFilesExist(string dir, string[] filenames, string? l } } - protected static void AssertSameFile(string file0, string file1, string? label = null) => AssertFile(file0, file1, label, same: true); - protected static void AssertNotSameFile(string file0, string file1, string? label = null) => AssertFile(file0, file1, label, same: false); + protected static void AssertSameFile(string file0, string file1, string? label=null) => AssertFile(file0, file1, label, same: true); + protected static void AssertNotSameFile(string file0, string file1, string? label=null) => AssertFile(file0, file1, label, same: false); - protected static void AssertFile(string file0, string file1, string? label = null, bool same = true) + protected static void AssertFile(string file0, string file1, string? label=null, bool same=true) { Assert.True(File.Exists(file0), $"{label}: Expected to find {file0}"); Assert.True(File.Exists(file1), $"{label}: Expected to find {file1}"); @@ -426,7 +426,7 @@ protected static void AssertFile(string file0, string file1, string? label = nul throw new XunitException($"{label}:{Environment.NewLine} File sizes should not match for {file0} ({finfo0.Length}), and {file1} ({finfo1.Length})"); } - protected (int exitCode, string buildOutput) AssertBuild(string args, string label = "build", bool expectSuccess = true, IDictionary? envVars = null, int? timeoutMs = null) + protected (int exitCode, string buildOutput) AssertBuild(string args, string label="build", bool expectSuccess=true, IDictionary? envVars=null, int? timeoutMs=null) { var result = RunProcess(s_buildEnv.DotNet, _testOutput, args, workingDir: _projectDir, label: label, envVars: envVars, timeoutMs: timeoutMs ?? s_defaultPerTestTimeoutMs); if (expectSuccess && result.exitCode != 0) @@ -450,14 +450,14 @@ private string FindSubDirIgnoringCase(string parentDir, string dirName) return first ?? Path.Combine(parentDir, dirName); } - protected string GetBinDir(string config, string targetFramework = DefaultTargetFramework, string? baseDir = null) + protected string GetBinDir(string config, string targetFramework=DefaultTargetFramework, string? baseDir=null) { var dir = baseDir ?? _projectDir; Assert.NotNull(dir); return Path.Combine(dir!, "bin", config, targetFramework, BuildEnvironment.DefaultRuntimeIdentifier); } - protected string GetObjDir(string config, string targetFramework = DefaultTargetFramework, string? baseDir = null) + protected string GetObjDir(string config, string targetFramework=DefaultTargetFramework, string? baseDir=null) { var dir = baseDir ?? _projectDir; Assert.NotNull(dir); @@ -489,7 +489,7 @@ public static (int exitCode, string buildOutput) RunProcess(string path, { _testOutput.WriteLine($"Running {path} {args}"); _testOutput.WriteLine($"WorkingDirectory: {workingDir}"); - StringBuilder outputBuilder = new(); + StringBuilder outputBuilder = new (); object syncObj = new(); var processStartInfo = new ProcessStartInfo @@ -523,7 +523,7 @@ public static (int exitCode, string buildOutput) RunProcess(string path, processStartInfo.RemoveEnvironmentVariables("MSBuildSDKsPath"); } - Process process = new(); + Process process = new (); process.StartInfo = processStartInfo; process.EnableRaisingEvents = true; @@ -596,7 +596,7 @@ void LogData(string label, string? message) } } - public static string AddItemsPropertiesToProject(string projectFile, string? extraProperties = null, string? extraItems = null, string? atTheEnd = null) + public static string AddItemsPropertiesToProject(string projectFile, string? extraProperties=null, string? extraItems=null, string? atTheEnd=null) { if (extraProperties == null && extraItems == null && atTheEnd == null) return projectFile; @@ -643,7 +643,7 @@ private static string GetEnvironmentVariableOrDefault(string envVarName, string return string.IsNullOrEmpty(value) ? defaultValue : value; } - internal BuildPaths GetBuildPaths(BuildArgs buildArgs, bool forPublish = true) + internal BuildPaths GetBuildPaths(BuildArgs buildArgs, bool forPublish=true) { string objDir = GetObjDir(buildArgs.Config); string bundleDir = Path.Combine(GetBinDir(baseDir: _projectDir, config: buildArgs.Config), "AppBundle"); @@ -686,25 +686,25 @@ public record BuildArgs(string ProjectName, string ProjectFileContents, string? ExtraBuildArgs); public record BuildProduct(string ProjectDir, string LogFile, bool Result); - internal record FileStat(bool Exists, DateTime LastWriteTimeUtc, long Length, string FullPath); + internal record FileStat (bool Exists, DateTime LastWriteTimeUtc, long Length, string FullPath); internal record BuildPaths(string ObjWasmDir, string ObjDir, string BinDir, string BundleDir); public record BuildProjectOptions ( - Action? InitProject = null, - bool? DotnetWasmFromRuntimePack = null, - bool HasIcudt = true, - bool UseCache = true, - bool ExpectSuccess = true, - bool AssertAppBundle = true, - bool CreateProject = true, - bool Publish = true, - bool BuildOnlyAfterPublish = true, - bool HasV8Script = true, - string? Verbosity = null, - string? Label = null, - string? TargetFramework = null, - string? MainJS = null, + Action? InitProject = null, + bool? DotnetWasmFromRuntimePack = null, + bool HasIcudt = true, + bool UseCache = true, + bool ExpectSuccess = true, + bool AssertAppBundle = true, + bool CreateProject = true, + bool Publish = true, + bool BuildOnlyAfterPublish = true, + bool HasV8Script = true, + string? Verbosity = null, + string? Label = null, + string? TargetFramework = null, + string? MainJS = null, IDictionary? ExtraBuildEnvironmentVariables = null ); From 1daeb6eddbd4804a224adb25909011c5289cf90f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Marek=20Fi=C5=A1era?= Date: Fri, 5 May 2023 10:55:27 +0200 Subject: [PATCH 5/9] Fix config location for blazor --- src/mono/wasm/runtime/startup.ts | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/src/mono/wasm/runtime/startup.ts b/src/mono/wasm/runtime/startup.ts index c019595300ad6..3a4f9320dbbf9 100644 --- a/src/mono/wasm/runtime/startup.ts +++ b/src/mono/wasm/runtime/startup.ts @@ -61,7 +61,13 @@ export function configureEmscriptenStartup(module: DotnetModuleInternal): void { if (!module.configSrc && (!module.config || Object.keys(module.config).length === 0 || !module.config.assets)) { // if config file location nor assets are provided - module.configSrc = "./_framework/blazor.boot.json"; + if (runtimeHelpers.scriptDirectory.indexOf("/_framework") == -1) { + // we are not inside _framework (= wasm template) + module.configSrc = "./_framework/blazor.boot.json"; + } else { + // blazor app + module.configSrc = "./blazor.boot.json"; + } } if (!module["locateFile"]) { From 7b55f1acb474be7985964b71c4b3a2fc806db072 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Marek=20Fi=C5=A1era?= Date: Fri, 5 May 2023 10:56:06 +0200 Subject: [PATCH 6/9] Properly load config and metadata in blazor case --- src/mono/wasm/runtime/blazor/BootConfig.ts | 14 +++++++++----- src/mono/wasm/runtime/run-outer.ts | 2 +- src/mono/wasm/runtime/startup.ts | 4 ++-- 3 files changed, 12 insertions(+), 8 deletions(-) diff --git a/src/mono/wasm/runtime/blazor/BootConfig.ts b/src/mono/wasm/runtime/blazor/BootConfig.ts index fcfd0cdf1aac0..0e558c56f2d4c 100644 --- a/src/mono/wasm/runtime/blazor/BootConfig.ts +++ b/src/mono/wasm/runtime/blazor/BootConfig.ts @@ -10,6 +10,14 @@ export class BootConfigResult { private constructor(public bootConfig: BootJsonData, public applicationEnvironment: string) { } + static fromFetchResponse(bootConfigResponse: Response, bootConfig: BootJsonData, environment?: string): BootConfigResult { + const applicationEnvironment = environment || (Module.getApplicationEnvironment && Module.getApplicationEnvironment(bootConfigResponse)) || "Production"; + bootConfig.modifiableAssemblies = bootConfigResponse.headers.get("DOTNET-MODIFIABLE-ASSEMBLIES"); + bootConfig.aspnetCoreBrowserTools = bootConfigResponse.headers.get("ASPNETCORE-BROWSER-TOOLS"); + + return new BootConfigResult(bootConfig, applicationEnvironment); + } + static async initAsync(loadBootResource?: LoadBootResourceCallback, environment?: string): Promise { const defaultBootJsonLocation = "_framework/blazor.boot.json"; @@ -27,12 +35,8 @@ export class BootConfigResult { bootConfigResponse = await loaderResponse; } - const applicationEnvironment = environment || (Module.getApplicationEnvironment && Module.getApplicationEnvironment(bootConfigResponse)) || "Production"; const bootConfig: BootJsonData = await bootConfigResponse.json(); - bootConfig.modifiableAssemblies = bootConfigResponse.headers.get("DOTNET-MODIFIABLE-ASSEMBLIES"); - bootConfig.aspnetCoreBrowserTools = bootConfigResponse.headers.get("ASPNETCORE-BROWSER-TOOLS"); - - return new BootConfigResult(bootConfig, applicationEnvironment); + return BootConfigResult.fromFetchResponse(bootConfigResponse, bootConfig, environment); function defaultLoadBlazorBootJson(url: string): Promise { return fetch(url, { diff --git a/src/mono/wasm/runtime/run-outer.ts b/src/mono/wasm/runtime/run-outer.ts index c2f5e907e76ac..50294c64f0ce4 100644 --- a/src/mono/wasm/runtime/run-outer.ts +++ b/src/mono/wasm/runtime/run-outer.ts @@ -287,7 +287,7 @@ export class HostBuilder implements DotnetHostBuilder { deep_merge_config(monoConfig, { startupOptions }); - return this.withConfigSrc("_framework/blazor.boot.json"); + return this; } async create(): Promise { diff --git a/src/mono/wasm/runtime/startup.ts b/src/mono/wasm/runtime/startup.ts index 3a4f9320dbbf9..927224c723ab2 100644 --- a/src/mono/wasm/runtime/startup.ts +++ b/src/mono/wasm/runtime/startup.ts @@ -36,7 +36,7 @@ import { init_legacy_exports } from "./net6-legacy/corebindings"; import { cwraps_binding_api, cwraps_mono_api } from "./net6-legacy/exports-legacy"; import { BINDING, MONO } from "./net6-legacy/globals"; import { init_globalization } from "./icu"; -import { BootConfigResult } from "./blazor/BootConfig"; +import { BootConfigResult, BootJsonData } from "./blazor/BootConfig"; let config: MonoConfigInternal = undefined as any; let configLoaded = false; @@ -684,7 +684,7 @@ export async function mono_wasm_load_config(configFilePath?: string): Promise Date: Fri, 5 May 2023 14:44:40 +0200 Subject: [PATCH 7/9] Fix config path in preload --- src/mono/sample/wasm/browser-advanced/index.html | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/mono/sample/wasm/browser-advanced/index.html b/src/mono/sample/wasm/browser-advanced/index.html index 1ce05d184d105..0ce3eea458fef 100644 --- a/src/mono/sample/wasm/browser-advanced/index.html +++ b/src/mono/sample/wasm/browser-advanced/index.html @@ -9,7 +9,7 @@ - + From 4a7695106640707a0498c3bac000bb33ffc8c64e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Marek=20Fi=C5=A1era?= Date: Fri, 12 May 2023 13:38:54 +0200 Subject: [PATCH 8/9] Fix merge --- src/mono/wasm/runtime/blazor/BootConfig.ts | 95 -------- src/mono/wasm/runtime/blazor/_Integration.ts | 224 ------------------- 2 files changed, 319 deletions(-) delete mode 100644 src/mono/wasm/runtime/blazor/BootConfig.ts delete mode 100644 src/mono/wasm/runtime/blazor/_Integration.ts diff --git a/src/mono/wasm/runtime/blazor/BootConfig.ts b/src/mono/wasm/runtime/blazor/BootConfig.ts deleted file mode 100644 index 0e558c56f2d4c..0000000000000 --- a/src/mono/wasm/runtime/blazor/BootConfig.ts +++ /dev/null @@ -1,95 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. - -import { Module } from "../globals"; -import { WebAssemblyBootResourceType } from "../types-api"; - -type LoadBootResourceCallback = (type: WebAssemblyBootResourceType, name: string, defaultUri: string, integrity: string) => string | Promise | null | undefined; - -export class BootConfigResult { - private constructor(public bootConfig: BootJsonData, public applicationEnvironment: string) { - } - - static fromFetchResponse(bootConfigResponse: Response, bootConfig: BootJsonData, environment?: string): BootConfigResult { - const applicationEnvironment = environment || (Module.getApplicationEnvironment && Module.getApplicationEnvironment(bootConfigResponse)) || "Production"; - bootConfig.modifiableAssemblies = bootConfigResponse.headers.get("DOTNET-MODIFIABLE-ASSEMBLIES"); - bootConfig.aspnetCoreBrowserTools = bootConfigResponse.headers.get("ASPNETCORE-BROWSER-TOOLS"); - - return new BootConfigResult(bootConfig, applicationEnvironment); - } - - static async initAsync(loadBootResource?: LoadBootResourceCallback, environment?: string): Promise { - const defaultBootJsonLocation = "_framework/blazor.boot.json"; - - const loaderResponse = loadBootResource !== undefined ? - loadBootResource("manifest", "blazor.boot.json", defaultBootJsonLocation, "") : - defaultLoadBlazorBootJson(defaultBootJsonLocation); - - let bootConfigResponse: Response; - - if (!loaderResponse) { - bootConfigResponse = await defaultLoadBlazorBootJson(defaultBootJsonLocation); - } else if (typeof loaderResponse === "string") { - bootConfigResponse = await defaultLoadBlazorBootJson(loaderResponse); - } else { - bootConfigResponse = await loaderResponse; - } - - const bootConfig: BootJsonData = await bootConfigResponse.json(); - return BootConfigResult.fromFetchResponse(bootConfigResponse, bootConfig, environment); - - function defaultLoadBlazorBootJson(url: string): Promise { - return fetch(url, { - method: "GET", - credentials: "include", - cache: "no-cache", - }); - } - } -} - -// Keep in sync with Microsoft.NET.Sdk.WebAssembly.BootJsonData from the WasmSDK -export interface BootJsonData { - readonly entryAssembly: string; - readonly resources: ResourceGroups; - /** Gets a value that determines if this boot config was produced from a non-published build (i.e. dotnet build or dotnet run) */ - readonly debugBuild: boolean; - readonly linkerEnabled: boolean; - readonly cacheBootResources: boolean; - readonly config: string[]; - readonly icuDataMode: ICUDataMode; - readonly startupMemoryCache: boolean | undefined; - readonly runtimeOptions: string[] | undefined; - - // These properties are tacked on, and not found in the boot.json file - modifiableAssemblies: string | null; - aspnetCoreBrowserTools: string | null; -} - -export type BootJsonDataExtension = { [extensionName: string]: ResourceList }; - -export interface ResourceGroups { - readonly assembly: ResourceList; - readonly lazyAssembly: ResourceList; - readonly pdb?: ResourceList; - readonly runtime: ResourceList; - readonly satelliteResources?: { [cultureName: string]: ResourceList }; - readonly libraryInitializers?: ResourceList, - readonly extensions?: BootJsonDataExtension - readonly runtimeAssets: ExtendedResourceList; -} - -export type ResourceList = { [name: string]: string }; -export type ExtendedResourceList = { - [name: string]: { - hash: string, - behavior: string - } -}; - -export enum ICUDataMode { - Sharded, - All, - Invariant, - Custom -} diff --git a/src/mono/wasm/runtime/blazor/_Integration.ts b/src/mono/wasm/runtime/blazor/_Integration.ts deleted file mode 100644 index 71f5f0087edb0..0000000000000 --- a/src/mono/wasm/runtime/blazor/_Integration.ts +++ /dev/null @@ -1,224 +0,0 @@ -import { INTERNAL, Module } from "../globals"; -import { MonoConfigInternal } from "../types"; -import { AssetEntry, LoadingResource, WebAssemblyBootResourceType, WebAssemblyStartOptions } from "../types-api"; -import { BootConfigResult, BootJsonData, ICUDataMode } from "./BootConfig"; -import { WebAssemblyResourceLoader } from "./WebAssemblyResourceLoader"; -import { hasDebuggingEnabled } from "./_Polyfill"; - -export async function loadBootConfig(config: MonoConfigInternal) { - const candidateOptions = config.startupOptions ?? {}; - const environment = candidateOptions.environment; - const bootConfigPromise = BootConfigResult.initAsync(candidateOptions.loadBootResource, environment); - - const bootConfigResult: BootConfigResult = await bootConfigPromise; - - await initializeBootConfig(bootConfigResult, candidateOptions); -} - -export async function initializeBootConfig(bootConfigResult: BootConfigResult, startupOptions?: Partial) { - const resourceLoader = await WebAssemblyResourceLoader.initAsync(bootConfigResult.bootConfig, startupOptions || {}); - - INTERNAL.resourceLoader = resourceLoader; - - const newConfig = mapBootConfigToMonoConfig(Module.config as MonoConfigInternal, resourceLoader, bootConfigResult.applicationEnvironment); - Module.config = newConfig; -} - -let resourcesLoaded = 0; -let totalResources = 0; - -function mapBootConfigToMonoConfig(moduleConfig: MonoConfigInternal, resourceLoader: WebAssemblyResourceLoader, applicationEnvironment: string): MonoConfigInternal { - const resources = resourceLoader.bootConfig.resources; - - const assets: AssetEntry[] = []; - const environmentVariables: any = {}; - - moduleConfig.applicationEnvironment = applicationEnvironment; - - moduleConfig.assets = assets; - moduleConfig.globalizationMode = "icu"; - moduleConfig.environmentVariables = environmentVariables; - moduleConfig.debugLevel = hasDebuggingEnabled(resourceLoader.bootConfig) ? 1 : 0; - moduleConfig.maxParallelDownloads = 1000000; // disable throttling parallel downloads - moduleConfig.enableDownloadRetry = false; // disable retry downloads - moduleConfig.mainAssemblyName = resourceLoader.bootConfig.entryAssembly; - - moduleConfig = { - ...resourceLoader.bootConfig, - ...moduleConfig - }; - - if (resourceLoader.bootConfig.startupMemoryCache !== undefined) { - moduleConfig.startupMemoryCache = resourceLoader.bootConfig.startupMemoryCache; - } - - if (resourceLoader.bootConfig.runtimeOptions) { - moduleConfig.runtimeOptions = [...(moduleConfig.runtimeOptions || []), ...resourceLoader.bootConfig.runtimeOptions]; - } - - const monoToBlazorAssetTypeMap: { [key: string]: WebAssemblyBootResourceType | undefined } = { - "assembly": "assembly", - "pdb": "pdb", - "icu": "globalization", - "vfs": "globalization", - "dotnetwasm": "dotnetwasm", - }; - - const behaviorByName = (name: string) => { - return name === "dotnet.timezones.blat" ? "vfs" - : name === "dotnet.wasm" ? "dotnetwasm" - : (name.startsWith("dotnet.worker") && name.endsWith(".js")) ? "js-module-threads" - : (name.startsWith("dotnet") && name.endsWith(".js")) ? "js-module-dotnet" - : name.startsWith("icudt") ? "icu" - : "other"; - }; - - // it would not `loadResource` on types for which there is no typesMap mapping - const downloadResource = (asset: AssetEntry): LoadingResource | undefined => { - // GOTCHA: the mapping to blazor asset type may not cover all mono owned asset types in the future in which case: - // A) we may need to add such asset types to the mapping and to WebAssemblyBootResourceType - // B) or we could add generic "runtime" type to WebAssemblyBootResourceType as fallback - // C) or we could return `undefined` and let the runtime to load the asset. In which case the progress will not be reported on it and blazor will not be able to cache it. - const type = monoToBlazorAssetTypeMap[asset.behavior]; - if (type !== undefined) { - const res = resourceLoader.loadResource(asset.name, asset.resolvedUrl!, asset.hash!, type); - asset.pendingDownload = res; - - totalResources++; - res.response.then(() => { - resourcesLoaded++; - if (Module.onDownloadResourceProgress) - Module.onDownloadResourceProgress(resourcesLoaded, totalResources); - }); - - return res; - } - return undefined; - }; - - Module.downloadResource = downloadResource; - Module.disableDotnet6Compatibility = false; - - // any runtime owned assets, with proper behavior already set - for (const name in resources.runtimeAssets) { - const asset = resources.runtimeAssets[name] as AssetEntry; - asset.name = name; - asset.resolvedUrl = `_framework/${name}`; - assets.push(asset); - if (asset.behavior === "dotnetwasm") { - downloadResource(asset); - } - } - for (const name in resources.assembly) { - const asset: AssetEntry = { - name, - resolvedUrl: `_framework/${name}`, - hash: resources.assembly[name], - behavior: "assembly", - }; - assets.push(asset); - downloadResource(asset); - } - if (hasDebuggingEnabled(resourceLoader.bootConfig) && resources.pdb) { - for (const name in resources.pdb) { - const asset: AssetEntry = { - name, - resolvedUrl: `_framework/${name}`, - hash: resources.pdb[name], - behavior: "pdb", - }; - assets.push(asset); - downloadResource(asset); - } - } - const applicationCulture = resourceLoader.startOptions.applicationCulture || (navigator.languages && navigator.languages[0]); - const icuDataResourceName = getICUResourceName(resourceLoader.bootConfig, applicationCulture); - let hasIcuData = false; - for (const name in resources.runtime) { - const behavior = behaviorByName(name) as any; - if (behavior === "icu") { - if (resourceLoader.bootConfig.icuDataMode === ICUDataMode.Invariant) { - continue; - } - if (name !== icuDataResourceName) { - continue; - } - hasIcuData = true; - } else if (behavior === "js-module-dotnet") { - continue; - } else if (behavior === "dotnetwasm") { - continue; - } - const asset: AssetEntry = { - name, - resolvedUrl: `_framework/${name}`, - hash: resources.runtime[name], - behavior, - }; - assets.push(asset); - } - - if (!hasIcuData) { - moduleConfig.globalizationMode = "invariant"; - } - - if (resourceLoader.bootConfig.modifiableAssemblies) { - // Configure the app to enable hot reload in Development. - environmentVariables["DOTNET_MODIFIABLE_ASSEMBLIES"] = resourceLoader.bootConfig.modifiableAssemblies; - } - - if (resourceLoader.startOptions.applicationCulture) { - // If a culture is specified via start options use that to initialize the Emscripten \ .NET culture. - environmentVariables["LANG"] = `${resourceLoader.startOptions.applicationCulture}.UTF-8`; - } - - if (resourceLoader.bootConfig.startupMemoryCache !== undefined) { - moduleConfig.startupMemoryCache = resourceLoader.bootConfig.startupMemoryCache; - } - - if (resourceLoader.bootConfig.runtimeOptions) { - moduleConfig.runtimeOptions = [...(moduleConfig.runtimeOptions || []), ...(resourceLoader.bootConfig.runtimeOptions || [])]; - } - - return moduleConfig; -} - -function getICUResourceName(bootConfig: BootJsonData, culture: string | undefined): string { - if (bootConfig.icuDataMode === ICUDataMode.Custom) { - const icuFiles = Object - .keys(bootConfig.resources.runtime) - .filter(n => n.startsWith("icudt") && n.endsWith(".dat")); - if (icuFiles.length === 1) { - const customIcuFile = icuFiles[0]; - return customIcuFile; - } - } - - const combinedICUResourceName = "icudt.dat"; - if (!culture || bootConfig.icuDataMode === ICUDataMode.All) { - return combinedICUResourceName; - } - - const prefix = culture.split("-")[0]; - if (prefix === "en" || - [ - "fr", - "fr-FR", - "it", - "it-IT", - "de", - "de-DE", - "es", - "es-ES", - ].includes(culture)) { - return "icudt_EFIGS.dat"; - } - if ([ - "zh", - "ko", - "ja", - ].includes(prefix)) { - return "icudt_CJK.dat"; - } - return "icudt_no_CJK.dat"; -} \ No newline at end of file From 4766f2471eb4489239e756b51792512dee45b09b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Marek=20Fi=C5=A1era?= Date: Fri, 12 May 2023 13:44:13 +0200 Subject: [PATCH 9/9] Fix scriptDirectory polyfill --- src/mono/wasm/runtime/loader/run.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/mono/wasm/runtime/loader/run.ts b/src/mono/wasm/runtime/loader/run.ts index f442ba56326c8..5eebdeef4ac93 100644 --- a/src/mono/wasm/runtime/loader/run.ts +++ b/src/mono/wasm/runtime/loader/run.ts @@ -402,6 +402,8 @@ function initializeModules(es6Modules: [RuntimeModuleExportsInternal, NativeModu } async function createEmscriptenMain(): Promise { + await init_polyfills(module); + if (!module.configSrc && (!module.config || Object.keys(module.config).length === 0 || !module.config.assets)) { // if config file location nor assets are provided if (loaderHelpers.scriptDirectory.indexOf("/_framework") == -1) { @@ -413,8 +415,6 @@ async function createEmscriptenMain(): Promise { } } - await init_polyfills(module); - // download config await mono_wasm_load_config(module);