Skip to content

Commit cc80345

Browse files
authored
[browser] Add application environment to boot config (#113164)
1 parent a91d820 commit cc80345

File tree

8 files changed

+73
-17
lines changed

8 files changed

+73
-17
lines changed

src/mono/browser/runtime/loader/config.ts

+6-1
Original file line numberDiff line numberDiff line change
@@ -325,6 +325,11 @@ async function loadBootConfig (module: DotnetModuleInternal): Promise<void> {
325325
}
326326
}
327327

328+
// Prefer user-defined application environment
329+
if (loaderHelpers.config.applicationEnvironment) {
330+
loadedConfig.applicationEnvironment = loaderHelpers.config.applicationEnvironment;
331+
}
332+
328333
deep_merge_config(loaderHelpers.config, loadedConfig);
329334

330335
if (!loaderHelpers.config.applicationEnvironment) {
@@ -344,7 +349,7 @@ async function readBootConfigResponse (loadConfigResponse: Response): Promise<Mo
344349
const config = loaderHelpers.config;
345350
const loadedConfig: MonoConfig = await loadConfigResponse.json();
346351

347-
if (!config.applicationEnvironment) {
352+
if (!config.applicationEnvironment && !loadedConfig.applicationEnvironment) {
348353
loadedConfig.applicationEnvironment = loadConfigResponse.headers.get("Blazor-Environment") || loadConfigResponse.headers.get("DotNet-Environment") || undefined;
349354
}
350355

src/mono/nuget/Microsoft.NET.Sdk.WebAssembly.Pack/build/Microsoft.NET.Sdk.WebAssembly.Browser.targets

+7
Original file line numberDiff line numberDiff line change
@@ -325,6 +325,8 @@ Copyright (c) .NET Foundation. All rights reserved.
325325
<Target Name="_GenerateBuildWasmBootJson" DependsOnTargets="$(GenerateBuildWasmBootJsonDependsOn)">
326326
<PropertyGroup>
327327
<_WasmBuildBootJsonPath>$(IntermediateOutputPath)$(_WasmBootConfigFileName)</_WasmBuildBootJsonPath>
328+
<_WasmBuildApplicationEnvironmentName>$(WasmApplicationEnvironmentName)</_WasmBuildApplicationEnvironmentName>
329+
<_WasmBuildApplicationEnvironmentName Condition="'$(_WasmBuildApplicationEnvironmentName)' == ''">Development</_WasmBuildApplicationEnvironmentName>
328330
</PropertyGroup>
329331

330332
<ItemGroup>
@@ -359,6 +361,7 @@ Copyright (c) .NET Foundation. All rights reserved.
359361

360362
<GenerateWasmBootJson
361363
AssemblyPath="@(IntermediateAssembly)"
364+
ApplicationEnvironment="$(_WasmBuildApplicationEnvironmentName)"
362365
Resources="@(WasmStaticWebAsset);@(_WasmJsModuleCandidatesForBuild)"
363366
Endpoints="@(_WasmResolvedEndpoints)"
364367
DebugBuild="true"
@@ -617,6 +620,9 @@ Copyright (c) .NET Foundation. All rights reserved.
617620
</Target>
618621

619622
<Target Name="GeneratePublishWasmBootJson" DependsOnTargets="$(GeneratePublishWasmBootJsonDependsOn)">
623+
<PropertyGroup>
624+
<_WasmPublishApplicationEnvironmentName>$(WasmApplicationEnvironmentName)</_WasmPublishApplicationEnvironmentName>
625+
</PropertyGroup>
620626
<ItemGroup>
621627
<_WasmPublishAsset
622628
Include="@(StaticWebAsset)"
@@ -649,6 +655,7 @@ Copyright (c) .NET Foundation. All rights reserved.
649655

650656
<GenerateWasmBootJson
651657
AssemblyPath="@(IntermediateAssembly)"
658+
ApplicationEnvironment="$(_WasmPublishApplicationEnvironmentName)"
652659
Resources="@(_WasmPublishAsset);@(_WasmJsModuleCandidatesForPublish)"
653660
Endpoints="@(_WasmResolvedEndpointsForPublish)"
654661
DebugBuild="false"

src/mono/wasm/Wasm.Build.Tests/AppSettingsTests.cs

+36-9
Original file line numberDiff line numberDiff line change
@@ -21,22 +21,49 @@ public AppSettingsTests(ITestOutputHelper output, SharedBuildPerTestClassFixture
2121
{
2222
}
2323

24+
public static IEnumerable<object?[]> LoadAppSettingsBasedOnApplicationEnvironmentData()
25+
{
26+
// Defaults
27+
yield return new object?[] { false, null, null, "Development" };
28+
yield return new object?[] { true, null, null, "Production" };
29+
30+
// Override defaults from MSBuild
31+
yield return new object?[] { false, "Production", null, "Production" };
32+
yield return new object?[] { true, "Development", null, "Development" };
33+
34+
// Override defaults from JavaScript
35+
yield return new object?[] { false, null, "Production", "Production" };
36+
yield return new object?[] { true, null, "Development", "Development" };
37+
38+
// Override MSBuild from JavaScript
39+
yield return new object?[] { false, "FromMSBuild", "Production", "Production" };
40+
yield return new object?[] { true, "FromMSBuild", "Development", "Development" };
41+
}
42+
2443
[Theory]
25-
[InlineData("Development")]
26-
[InlineData("Production")]
27-
public async Task LoadAppSettingsBasedOnApplicationEnvironment(string applicationEnvironment)
44+
[MemberData(nameof(LoadAppSettingsBasedOnApplicationEnvironmentData))]
45+
public async Task LoadAppSettingsBasedOnApplicationEnvironment(bool publish, string? msBuildApplicationEnvironment, string? queryApplicationEnvironment, string expectedApplicationEnvironment)
2846
{
2947
Configuration config = Configuration.Debug;
3048
ProjectInfo info = CopyTestAsset(config, aot: false, TestAsset.WasmBasicTestApp, "AppSettingsTest");
31-
PublishProject(info, config);
32-
BrowserRunOptions options = new(
49+
string extraMSBuildArgs = msBuildApplicationEnvironment != null ? $"-p:WasmApplicationEnvironmentName={msBuildApplicationEnvironment}" : string.Empty;
50+
51+
if (publish)
52+
PublishProject(info, config, new PublishOptions(ExtraMSBuildArgs: extraMSBuildArgs));
53+
else
54+
BuildProject(info, config, new BuildOptions(ExtraMSBuildArgs: extraMSBuildArgs));
55+
56+
BrowserRunOptions runOptions = new(
3357
config,
3458
TestScenario: "AppSettingsTest",
35-
BrowserQueryString: new NameValueCollection { { "applicationEnvironment", applicationEnvironment } }
59+
BrowserQueryString: new NameValueCollection { { "applicationEnvironment", queryApplicationEnvironment } }
3660
);
37-
RunResult result = await RunForPublishWithWebServer(options);
61+
RunResult result = publish
62+
? await RunForPublishWithWebServer(runOptions)
63+
: await RunForBuildWithDotnetRun(runOptions);
64+
3865
Assert.Contains(result.TestOutput, m => m.Contains("'/appsettings.json' exists 'True'"));
39-
Assert.Contains(result.TestOutput, m => m.Contains($"'/appsettings.Development.json' exists '{applicationEnvironment == "Development"}'"));
40-
Assert.Contains(result.TestOutput, m => m.Contains($"'/appsettings.Production.json' exists '{applicationEnvironment == "Production"}'"));
66+
Assert.Contains(result.TestOutput, m => m.Contains($"'/appsettings.Development.json' exists '{expectedApplicationEnvironment == "Development"}'"));
67+
Assert.Contains(result.TestOutput, m => m.Contains($"'/appsettings.Production.json' exists '{expectedApplicationEnvironment == "Production"}'"));
4168
}
4269
}

src/mono/wasm/Wasm.Build.Tests/Templates/WasmTemplateTestsBase.cs

+4-4
Original file line numberDiff line numberDiff line change
@@ -60,7 +60,7 @@ public ProjectInfo CreateWasmTemplateProject(
6060
Configuration config,
6161
bool aot,
6262
string idPrefix = "wbt",
63-
bool appendUnicodeToPath = true,
63+
bool? appendUnicodeToPath = null,
6464
string extraArgs = "",
6565
bool runAnalyzers = true,
6666
bool addFrameworkArg = false,
@@ -69,7 +69,7 @@ public ProjectInfo CreateWasmTemplateProject(
6969
string insertAtEnd = "")
7070
{
7171
(string projectName, string logPath, string nugetDir) =
72-
InitProjectLocation(idPrefix, config, aot, appendUnicodeToPath);
72+
InitProjectLocation(idPrefix, config, aot, appendUnicodeToPath ?? s_buildEnv.IsRunningOnCI);
7373

7474
if (addFrameworkArg)
7575
extraArgs += $" -f {DefaultTargetFramework}";
@@ -107,14 +107,14 @@ protected ProjectInfo CopyTestAsset(
107107
bool aot,
108108
TestAsset asset,
109109
string idPrefix,
110-
bool appendUnicodeToPath = true,
110+
bool? appendUnicodeToPath = null,
111111
bool runAnalyzers = true,
112112
string extraProperties = "",
113113
string extraItems = "",
114114
string insertAtEnd = "")
115115
{
116116
(string projectName, string logPath, string nugetDir) =
117-
InitProjectLocation(idPrefix, config, aot, appendUnicodeToPath, avoidAotLongPathIssue: s_isWindows && aot);
117+
InitProjectLocation(idPrefix, config, aot, appendUnicodeToPath ?? s_buildEnv.IsRunningOnCI, avoidAotLongPathIssue: s_isWindows && aot);
118118
Utils.DirectoryCopy(Path.Combine(BuildEnvironment.TestAssetsPath, asset.Name), Path.Combine(_projectDir));
119119
if (!string.IsNullOrEmpty(asset.RunnableProjectSubPath))
120120
{

src/mono/wasm/testassets/WasmBasicTestApp/App/wwwroot/main.js

+4-1
Original file line numberDiff line numberDiff line change
@@ -44,7 +44,10 @@ switch (testCase) {
4444
}
4545
break;
4646
case "AppSettingsTest":
47-
dotnet.withApplicationEnvironment(params.get("applicationEnvironment"));
47+
const applicationEnvironment = params.get("applicationEnvironment");
48+
if (applicationEnvironment) {
49+
dotnet.withApplicationEnvironment(applicationEnvironment);
50+
}
4851
break;
4952
case "LazyLoadingTest":
5053
dotnet.withDiagnosticTracing(true);

src/mono/wasm/testassets/WasmBasicTestApp/App/wwwroot/README.md renamed to src/mono/wasm/testassets/WasmBasicTestApp/README.md

+1-1
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@ It typically suits scenario where you need more than a plain template app. If th
88
The app reads `test` query parameter and uses it to switch between test cases. Entrypoint is `main.js`.
99
There is common unit, then switch based on test case for modifying app startup, then app starts and executes next switch based on test case for actually running code.
1010

11-
Some test cases passes additional parameters to differentiate behavior, see `src/mono/wasm/Wasm.Build.Tests/TestAppScenarios`.
11+
Some test cases passes additional parameters to differentiate behavior, see `src/mono/wasm/Wasm.Build.Tests`.
1212

1313
### Running out side of WBT
1414

src/tasks/Microsoft.NET.Sdk.WebAssembly.Pack.Tasks/BootJsonData.cs

+3
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,9 @@ public class BootJsonData
2424

2525
public string mainAssemblyName { get; set; }
2626

27+
[DataMember(EmitDefaultValue = false)]
28+
public string applicationEnvironment { get; set; }
29+
2730
/// <summary>
2831
/// Gets the set of resources needed to boot the application. This includes the transitive
2932
/// closure of .NET assemblies (including the entrypoint assembly), the dotnet.wasm file,

src/tasks/Microsoft.NET.Sdk.WebAssembly.Pack.Tasks/GenerateWasmBootJson.cs

+12-1
Original file line numberDiff line numberDiff line change
@@ -84,6 +84,8 @@ public class GenerateWasmBootJson : Task
8484

8585
public bool FingerprintAssets { get; set; }
8686

87+
public string ApplicationEnvironment { get; set; }
88+
8789
public override bool Execute()
8890
{
8991
var entryAssemblyName = AssemblyName.GetAssemblyName(AssemblyPath).Name;
@@ -107,9 +109,14 @@ private void WriteBootConfig(string entryAssemblyName)
107109
var result = new BootJsonData
108110
{
109111
resources = new ResourcesData(),
110-
startupMemoryCache = helper.ParseOptionalBool(StartupMemoryCache),
112+
startupMemoryCache = helper.ParseOptionalBool(StartupMemoryCache)
111113
};
112114

115+
if (IsTargeting100OrLater())
116+
{
117+
result.applicationEnvironment = ApplicationEnvironment;
118+
}
119+
113120
if (IsTargeting80OrLater())
114121
{
115122
result.mainAssemblyName = entryAssemblyName;
@@ -489,13 +496,17 @@ private static bool TryGetLazyLoadedAssembly(Dictionary<string, ITaskItem> lazyL
489496
private Version? parsedTargetFrameworkVersion;
490497
private static readonly Version version80 = new Version(8, 0);
491498
private static readonly Version version90 = new Version(9, 0);
499+
private static readonly Version version100 = new Version(10, 0);
492500

493501
private bool IsTargeting80OrLater()
494502
=> IsTargetingVersionOrLater(version80);
495503

496504
private bool IsTargeting90OrLater()
497505
=> IsTargetingVersionOrLater(version90);
498506

507+
private bool IsTargeting100OrLater()
508+
=> IsTargetingVersionOrLater(version100);
509+
499510
private bool IsTargetingVersionOrLater(Version version)
500511
{
501512
if (parsedTargetFrameworkVersion == null)

0 commit comments

Comments
 (0)