[wasm] Unify boot config location (#85763)
authorMarek Fišera <mara@neptuo.com>
Fri, 12 May 2023 17:52:09 +0000 (19:52 +0200)
committerGitHub <noreply@github.com>
Fri, 12 May 2023 17:52:09 +0000 (19:52 +0200)
Load mono-config.json and blazor.boot.json from the same location

14 files changed:
src/mono/sample/wasm/browser-advanced/index.html
src/mono/sample/wasm/browser-advanced/main.js
src/mono/sample/wasm/browser-bench/appstart-frame.html
src/mono/wasi/Wasi.Build.Tests/BuildTestBase.cs
src/mono/wasm/Wasm.Build.Tests/BuildTestBase.cs
src/mono/wasm/Wasm.Build.Tests/ConfigSrcTests.cs
src/mono/wasm/build/WasmApp.targets
src/mono/wasm/runtime/loader/blazor/BootConfig.ts
src/mono/wasm/runtime/loader/blazor/_Integration.ts
src/mono/wasm/runtime/loader/config.ts
src/mono/wasm/runtime/loader/run.ts
src/mono/wasm/runtime/types/index.ts
src/mono/wasm/test-main.js
src/tasks/WasmAppBuilder/WasmAppBuilder.cs

index 3489dafc9474a62196b8e530753670f1550fb1c2..8bd0e2e22b1a0ea0443519a6d8aa841891726f11 100644 (file)
@@ -9,7 +9,7 @@
   <meta name="viewport" content="width=device-width, initial-scale=1.0">
   <script type='module' src="./main.js"></script>
   <script type='module' src="./dotnet.js"></script>
-  <link rel="preload" href="./mono-config.json" as="fetch" crossorigin="anonymous">
+  <link rel="preload" href="./_framework/blazor.boot.json" as="fetch" crossorigin="anonymous">
   <link rel="prefetch" href="./dotnet.native.js" as="fetch" crossorigin="anonymous">
   <link rel="prefetch" href="./dotnet.runtime.js" as="fetch" crossorigin="anonymous">
   <link rel="prefetch" href="./dotnet.native.wasm" as="fetch" crossorigin="anonymous">
index b6e0ef0a8d1a9217252de2699d68525224954965..a5dbaeba13088909b0e1f1b2f31e016c6c61f7e9 100644 (file)
@@ -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: "./_framework/blazor.boot.json",
             onConfigLoaded: (config) => {
                 // This is called during emscripten `dotnet.wasm` instantiation, after we fetched config.
                 console.log('user code Module.onConfigLoaded');
index fbb1c162849337b5045737a70b60623e49e25f62..684acbcb998de23ea6ab69216205a88a0cfe3fec 100644 (file)
@@ -9,7 +9,7 @@
   <meta name="viewport" content="width=device-width, initial-scale=1.0">
   <script type="module" src="./frame-main.js"></script>
   <script type='module' src="./dotnet.js"></script>
-  <link rel="preload" href="./mono-config.json" as="fetch" crossorigin="anonymous">
+  <link rel="preload" href="./_framework/blazor.boot.json" as="fetch" crossorigin="anonymous">
   <link rel="prefetch" href="./dotnet.native.js" as="fetch" crossorigin="anonymous">
   <link rel="prefetch" href="./dotnet.runtime.js" as="fetch" crossorigin="anonymous">
   <link rel="prefetch" href="./dotnet.native.wasm" as="fetch" crossorigin="anonymous">
index 8f3857c53f182eb69f9c52417189f864b1fc3441..e2980fc735746acaf1221c452e4b402bf774d5d3 100644 (file)
@@ -361,7 +361,7 @@ namespace Wasm.Build.Tests
                 "index.html",
                 mainJS,
                 "dotnet.wasm",
-                "mono-config.json",
+                "_framework/blazor.boot.json",
                 "dotnet.js"
             });
 
index cea2456182e46817abd761464deaa94250b7cef8..17bc1d17ae79f9b189a138613727565cef256345 100644 (file)
@@ -47,7 +47,7 @@ namespace Wasm.Build.Tests
         // on Linux sharding does not work because we rely on LANG env var to check locale and emcc is overwriting it
         protected static RunHost s_hostsForOSLocaleSensitiveTests = RunHost.Chrome;
         // FIXME: use an envvar to override this
-        protected static int s_defaultPerTestTimeoutMs = s_isWindows ? 30*60*1000 : 15*60*1000;
+        protected static int s_defaultPerTestTimeoutMs = s_isWindows ? 30 * 60 * 1000 : 15 * 60 * 1000;
         protected static BuildEnvironment s_buildEnv;
         private const string s_runtimePackPathPattern = "\\*\\* MicrosoftNetCoreAppRuntimePackDir : '([^ ']*)'";
         private const string s_nugetInsertionTag = "<!-- TEST_RESTORE_SOURCES_INSERTION_LINE -->";
@@ -60,7 +60,7 @@ namespace Wasm.Build.Tests
         public static bool UseWebcil => 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 @@ namespace Wasm.Build.Tests
                 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 @@ namespace Wasm.Build.Tests
             - aot but no wrapper - check that AppBundle wasn't generated
         */
 
-        public static IEnumerable<IEnumerable<object?>> ConfigWithAOTData(bool aot, string? config=null, string? extraArgs=null)
+        public static IEnumerable<IEnumerable<object?>> ConfigWithAOTData(bool aot, string? config = null, string? extraArgs = null)
         {
             if (extraArgs == null)
                 extraArgs = string.Empty;
@@ -140,7 +140,7 @@ namespace Wasm.Build.Tests
         protected string RunAndTestWasmApp(BuildArgs buildArgs,
                                            RunHost host,
                                            string id,
-                                           Action<string>? test=null,
+                                           Action<string>? test = null,
                                            string? buildDir = null,
                                            string? bundleDir = null,
                                            int expectedExitCode = 0,
@@ -205,9 +205,9 @@ namespace Wasm.Build.Tests
         }
 
         protected static string RunWithXHarness(string testCommand, string testLogPath, string projectName, string bundleDir,
-                                        ITestOutputHelper _testOutput, IDictionary<string, string>? envVars=null,
-                                        int expectedAppExitCode=0, int xharnessExitCode=0, string? extraXHarnessArgs=null,
-                                        string? appArgs=null, string? extraXHarnessMonoArgs = null, bool useWasmConsoleOutput = false)
+                                        ITestOutputHelper _testOutput, IDictionary<string, string>? 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 @@ namespace Wasm.Build.Tests
               ##INSERT_AT_END##
             </Project>";
 
-        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 @@ namespace Wasm.Build.Tests
                 extraProperties += $"\n<EmccVerbose>{s_isWindows}</EmccVerbose>\n";
             }
 
-            if (UseWebcil) {
+            if (UseWebcil)
+            {
                 extraProperties += "<WasmEnableWebcil>true</WasmEnableWebcil>\n";
             }
 
@@ -361,7 +362,7 @@ namespace Wasm.Build.Tests
             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 @@ namespace Wasm.Build.Tests
             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 @@ namespace Wasm.Build.Tests
             {
                 mainJS,
                 "dotnet.native.wasm",
-                "mono-config.json",
+                "_framework/blazor.boot.json",
                 "dotnet.js",
                 "dotnet.native.js",
                 "dotnet.runtime.js"
@@ -696,8 +697,8 @@ namespace Wasm.Build.Tests
                 //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}");
                 //}
             }
 
@@ -772,7 +773,7 @@ namespace Wasm.Build.Tests
         protected static void AssertFilesDontExist(string dir, string[] filenames, string? label = null)
             => AssertFilesExist(dir, filenames, label, expectToExist: false);
 
-        protected static void AssertFilesExist(string dir, IEnumerable<string> filenames, string? label = null, bool expectToExist=true)
+        protected static void AssertFilesExist(string dir, IEnumerable<string> filenames, string? label = null, bool expectToExist = true)
         {
             string prefix = label != null ? $"{label}: " : string.Empty;
             if (!Directory.Exists(dir))
@@ -788,10 +789,10 @@ namespace Wasm.Build.Tests
             }
         }
 
-        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}");
@@ -806,7 +807,7 @@ namespace Wasm.Build.Tests
                 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<string, string>? envVars=null, int? timeoutMs=null)
+        protected (int exitCode, string buildOutput) AssertBuild(string args, string label = "build", bool expectSuccess = true, IDictionary<string, string>? 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)
@@ -817,7 +818,7 @@ namespace Wasm.Build.Tests
             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);
 
@@ -848,7 +849,7 @@ namespace Wasm.Build.Tests
             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 == (isNet7AndBelow ? "dotnet.wasm" : "dotnet.native.wasm")).Any(), $"{msgPrefix} Could not find dotnet.native.wasm entry in blazor.boot.json");
             Assert.True(runtimeObj!.Where(kvp => kvp.Key.StartsWith("dotnet.", StringComparison.OrdinalIgnoreCase) &&
                                                     kvp.Key.EndsWith(".js", StringComparison.OrdinalIgnoreCase)).Any(),
@@ -877,14 +878,14 @@ namespace Wasm.Build.Tests
             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);
@@ -905,7 +906,7 @@ namespace Wasm.Build.Tests
             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 = $$"""
                 <p role="{{methodName}}">Output: @outputText</p>
@@ -931,10 +932,10 @@ namespace Wasm.Build.Tests
 
         // 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<IPage, Task>? test=null, string extraArgs="--no-build")
+        public Task BlazorRunForBuildWithDotnetRun(string config, Func<IPage, Task>? test = null, string extraArgs = "--no-build")
             => BlazorRunTest($"run -c {config} {extraArgs}", _projectDir!, test);
 
-        public Task BlazorRunForPublishWithWebServer(string config, Func<IPage, Task>? test=null, string extraArgs="")
+        public Task BlazorRunForPublishWithWebServer(string config, Func<IPage, Task>? 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);
@@ -1000,7 +1001,7 @@ namespace Wasm.Build.Tests
         {
             _testOutput.WriteLine($"Running {path} {args}");
             _testOutput.WriteLine($"WorkingDirectory: {workingDir}");
-            StringBuilder outputBuilder = new ();
+            StringBuilder outputBuilder = new();
             object syncObj = new();
 
             var processStartInfo = new ProcessStartInfo
@@ -1034,7 +1035,7 @@ namespace Wasm.Build.Tests
                 processStartInfo.RemoveEnvironmentVariables("MSBuildSDKsPath");
             }
 
-            Process process = new ();
+            Process process = new();
             process.StartInfo = processStartInfo;
             process.EnableRaisingEvents = true;
 
@@ -1107,10 +1108,10 @@ namespace Wasm.Build.Tests
             }
         }
 
-        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;
 
@@ -1156,7 +1157,7 @@ namespace Wasm.Build.Tests
             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");
@@ -1214,27 +1215,27 @@ namespace Wasm.Build.Tests
                             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<string, string>? ExtraBuildEnvironmentVariables = null
     );
 
@@ -1245,7 +1246,7 @@ namespace Wasm.Build.Tests
         NativeFilesType ExpectedFileType,
         string TargetFramework = BuildTestBase.DefaultTargetFrameworkForBlazor,
         bool WarnAsError = true,
-        bool ExpectRelinkDirWhenPublishing=false
+        bool ExpectRelinkDirWhenPublishing = false
     );
 
     public enum GlobalizationMode
index 9488225ccc62b4171a4c8ccd18e05fdac42f7f80..6d6a552407634c6c054b2d6c6709b609e0df1d10 100644 (file)
@@ -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 class ConfigSrcTests : BuildTestBase
 
         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, "_framework", "blazor.boot.json"));
 
         RunAndTestWasmApp(buildArgs, expectedExitCode: 42, host: host, id: id, extraXHarnessMonoArgs: $"--config-src={configSrc}");
     }
index 94bd9fe54f9d8cb0901b6988c4a126c029d5d044..3411b31824bd6d415ae9735e3770cd363632061c 100644 (file)
@@ -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 `_framework/blazor.boot.json`
                                     Eg. <WasmExtraConfig Include="xxx" Value="true" />
 
                                     - Value attribute can have a number, bool, quoted string, or json string
index d136a18b7b99a8cfcdd25bddee3e7b365841231c..9df0f5776937b101cb45bbc2de9e8fdb692829b3 100644 (file)
@@ -11,27 +11,33 @@ export class BootConfigResult {
     private constructor(public bootConfig: BootJsonData, public applicationEnvironment: string) {
     }
 
+    static fromFetchResponse(bootConfigResponse: Response, bootConfig: BootJsonData, environment?: string): BootConfigResult {
+        const applicationEnvironment = environment || (loaderHelpers.getApplicationEnvironment && loaderHelpers.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<BootConfigResult> {
+        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 {
             bootConfigResponse = await loaderResponse;
         }
 
-        const applicationEnvironment = environment || (loaderHelpers.getApplicationEnvironment && loaderHelpers.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<Response> {
             return fetch(url, {
index e81f60707e1876c6ae280279c1bef9629f616f57..393658b67668a71d71f2115d36041507bed88268 100644 (file)
@@ -2,7 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 
 import type { DotnetModuleInternal, MonoConfigInternal } from "../../types/internal";
-import type { AssetBehaviours, AssetEntry, LoadingResource, WebAssemblyBootResourceType } from "../../types";
+import type { AssetBehaviours, AssetEntry, LoadingResource, WebAssemblyBootResourceType, WebAssemblyStartOptions } from "../../types";
 import type { BootJsonData } from "../../types/blazor";
 
 import { INTERNAL, loaderHelpers } from "../globals";
@@ -18,7 +18,11 @@ export async function loadBootConfig(config: MonoConfigInternal, module: DotnetM
     const environment = candidateOptions.environment;
     const bootConfigPromise = BootConfigResult.initAsync(candidateOptions.loadBootResource, environment);
     const bootConfigResult: BootConfigResult = await bootConfigPromise;
-    INTERNAL.resourceLoader = resourceLoader = await WebAssemblyResourceLoader.initAsync(bootConfigResult.bootConfig, candidateOptions || {});
+    await initializeBootConfig(bootConfigResult, module, candidateOptions);
+}
+
+export async function initializeBootConfig(bootConfigResult: BootConfigResult, module: DotnetModuleInternal, startupOptions?: Partial<WebAssemblyStartOptions>) {
+    INTERNAL.resourceLoader = resourceLoader = await WebAssemblyResourceLoader.initAsync(bootConfigResult.bootConfig, startupOptions || {});
     mapBootConfigToMonoConfig(loaderHelpers.config, bootConfigResult.applicationEnvironment);
     setupModuleForBlazor(module);
 }
index 28fa63462cce068505dbf8e66931004e2f96fb6e..655f250a5c4abec08d04e5f4b73606dee4ea6fe2 100644 (file)
@@ -5,7 +5,9 @@ import BuildConfiguration from "consts:configuration";
 import type { DotnetModuleInternal, MonoConfigInternal } from "../types/internal";
 import type { DotnetModuleConfig } from "../types";
 import { exportedRuntimeAPI, loaderHelpers, runtimeHelpers } from "./globals";
-import { loadBootConfig } from "./blazor/_Integration";
+import { initializeBootConfig, loadBootConfig } from "./blazor/_Integration";
+import { BootConfigResult } from "./blazor/BootConfig";
+import { BootJsonData } from "../types/blazor";
 
 export function deep_merge_config(target: MonoConfigInternal, source: MonoConfigInternal): MonoConfigInternal {
     const providedConfig: MonoConfigInternal = { ...source };
@@ -80,13 +82,18 @@ export async function mono_wasm_load_config(module: DotnetModuleInternal): Promi
     try {
         const resolveSrc = loaderHelpers.locateFile(configFilePath);
         const configResponse = await loaderHelpers.fetch_like(resolveSrc);
-        const loadedConfig: MonoConfigInternal = (await configResponse.json()) || {};
-        if (loaderHelpers.config.startupOptions) {
-            await loadBootConfig(loaderHelpers.config, module);
+        const loadedAnyConfig: any = (await configResponse.json()) || {};
+        if (loadedAnyConfig.resources) {
+            await initializeBootConfig(BootConfigResult.fromFetchResponse(configResponse, loadedAnyConfig as BootJsonData), module);
         } else {
-            if (loadedConfig.environmentVariables && typeof (loadedConfig.environmentVariables) !== "object")
-                throw new Error("Expected config.environmentVariables to be unset or a dictionary-style object");
-            deep_merge_config(loaderHelpers.config, loadedConfig);
+            const loadedConfig = loadedAnyConfig as MonoConfigInternal;
+            if (loaderHelpers.config.startupOptions && loaderHelpers.config.startupOptions.loadBootResource) {
+                await loadBootConfig(loaderHelpers.config, module);
+            } else {
+                if (loadedConfig.environmentVariables && typeof (loadedConfig.environmentVariables) !== "object")
+                    throw new Error("Expected config.environmentVariables to be unset or a dictionary-style object");
+                deep_merge_config(loaderHelpers.config, loadedConfig);
+            }
         }
 
         normalizeConfig();
index 3c762a01afa7997b7d864121214d8115b061d5fc..5eebdeef4ac93d96d1fcca7936f83ac5c3b744b7 100644 (file)
@@ -290,7 +290,7 @@ export class HostBuilder implements DotnetHostBuilder {
         deep_merge_config(monoConfig, {
             startupOptions
         });
-        return this.withConfigSrc("blazor.boot.json");
+        return this;
     }
 
     async create(): Promise<RuntimeAPI> {
@@ -402,13 +402,19 @@ function initializeModules(es6Modules: [RuntimeModuleExportsInternal, NativeModu
 }
 
 async function createEmscriptenMain(): Promise<RuntimeAPI> {
+    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
-        module.configSrc = "./mono-config.json";
+        if (loaderHelpers.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";
+        }
     }
 
-    await init_polyfills(module);
-
     // download config
     await mono_wasm_load_config(module);
 
index 8698b65f5f59a0d88bc8789bb2923fb508b44427..7dfca1e092d65f18a8467756550e0f13674e04e6 100644 (file)
@@ -102,7 +102,7 @@ export interface LoadingResource {
     response: Promise<Response>;
 }
 
-// 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 _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.
index 90371a45707e30e36a2307a94fec65cd703127c4..79f5620e4b0a6e5828422ac85797df28a4f1dfef 100644 (file)
@@ -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 ? './_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;
index 7370e93939f74d912b732598488d5daa2022f757..fca7a68ac69437446e7074677f12849ede26c76a 100644 (file)
@@ -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; }
 
     // <summary>
-    // Extra json elements to add to mono-config.json
+    // Extra json elements to add to _framework/blazor.boot.json
     //
     // Metadata:
     // - Value: can be a number, bool, quoted string, or json string
@@ -59,7 +59,7 @@ public class WasmAppBuilder : WasmAppBuilderBaseTask
 
     private class AssetEntry
     {
-        protected AssetEntry (string name, string hash, string behavior)
+        protected AssetEntry(string name, string hash, string behavior)
         {
             Name = name;
             Behavior = behavior;
@@ -100,12 +100,12 @@ public class WasmAppBuilder : WasmAppBuilderBaseTask
 
     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
@@ -121,21 +121,21 @@ public class WasmAppBuilder : WasmAppBuilderBaseTask
 
     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()
@@ -168,7 +168,7 @@ public class WasmAppBuilder : WasmAppBuilderBaseTask
         }
         MainAssemblyName = Path.GetFileName(MainAssemblyName);
 
-        var config = new WasmAppConfig ()
+        var config = new WasmAppConfig()
         {
             MainAssemblyName = MainAssemblyName,
             GlobalizationMode = InvariantGlobalization ? "invariant" : HybridGlobalization ? "hybrid" : "icu"
@@ -179,7 +179,7 @@ public class WasmAppBuilder : WasmAppBuilderBaseTask
         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)
@@ -219,7 +219,7 @@ public class WasmAppBuilder : WasmAppBuilderBaseTask
             }
             else if (name == "dotnet.native.wasm")
             {
-                config.Assets.Add(new WasmEntry (name, Utils.ComputeIntegrity(item.ItemSpec)) );
+                config.Assets.Add(new WasmEntry(name, Utils.ComputeIntegrity(item.ItemSpec)));
             }
             else if (name == "dotnet.native.js")
             {
@@ -231,9 +231,9 @@ public class WasmAppBuilder : WasmAppBuilderBaseTask
             }
             else if (IncludeThreadsWorker && name == "dotnet.native.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.native.js.symbols")
+            else if (name == "dotnet.native.js.symbols")
             {
                 config.Assets.Add(new SymbolsData(name, Utils.ComputeIntegrity(item.ItemSpec)));
             }
@@ -340,7 +340,8 @@ public class WasmAppBuilder : WasmAppBuilderBaseTask
                 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);
@@ -391,16 +392,21 @@ public class WasmAppBuilder : WasmAppBuilderBaseTask
         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 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);