Skip to content
New issue

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

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

Already on GitHub? Sign in to your account

fix: Restore offline PWA support #898

Merged
merged 1 commit into from
Sep 27, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
67 changes: 60 additions & 7 deletions src/Uno.Wasm.Bootstrap/ShellTask.cs
Original file line number Diff line number Diff line change
Expand Up @@ -161,6 +161,7 @@ public override bool Execute()
GeneratedAOTProfile();
GenerateIndexHtml();
GenerateEmbeddedJs();
RemoveDuplicateAssets();
GenerateConfig();
RemoveDuplicateAssets();
}
Expand All @@ -184,7 +185,7 @@ private void RemoveDuplicateAssets()
foreach (var existingAsset in existingAssets)
{
Log.LogMessage(MessageImportance.Low, $"Existing asset to remove [{existingAsset.ItemSpec}]");
}
}

// remove existingAssets from StaticWebContent
StaticWebContent = StaticWebContent
Expand Down Expand Up @@ -342,7 +343,29 @@ private void ExtractAdditionalJS()
{
_dependencies.Add(name);

CopyResourceToOutput(name, resource);
if (
// Process the service worker file separately to adjust its contents
source.Name.Name.Equals(GetType().Assembly.GetName().Name, StringComparison.OrdinalIgnoreCase)
&& name.Equals("service-worker.js", StringComparison.OrdinalIgnoreCase))
{
using var resourceStream = resource.GetResourceStream();
using var reader = new StreamReader(resourceStream);

var worker = TouchServiceWorker(reader.ReadToEnd());
var memoryStream = new MemoryStream();

using var writer = new StreamWriter(memoryStream, Encoding.UTF8);
writer.Write(worker);
writer.Flush();

memoryStream.Position = 0;

CopyStreamToOutput(name, memoryStream);
}
else
{
CopyResourceToOutput(name, resource);
}

Log.LogMessage($"Additional JS {name}");
}
Expand Down Expand Up @@ -431,6 +454,18 @@ private void CopyResourceToOutput(string name, EmbeddedResource resource)
AddStaticAsset(name, dest);
}

private void CopyStreamToOutput(string name, Stream stream)
{
var dest = Path.Combine(_intermediateAssetsPath, name);

using (var destStream = new FileStream(dest, FileMode.Create, FileAccess.Write))
{
stream.CopyTo(destStream);
}

AddStaticAsset(name, dest);
}

private void AddStaticAsset(string targetPath, string filePath, bool overrideExisting = false)
{
var contentRoot = targetPath.StartsWith(_intermediateAssetsPath)
Expand Down Expand Up @@ -539,7 +574,14 @@ private void GenerateConfig()
var config = new StringBuilder();

var enablePWA = !string.IsNullOrEmpty(PWAManifestFile);
//var offlineFiles = enablePWA ? string.Join(", ", GetPWACacheableFiles().Select(f => $"\".{f}\"")) : "";

var sanitizedOfflineFiles = StaticWebContent
.Select(f => f.GetMetadata("Link")
.Replace("\\", "/")
.Replace("wwwroot/", ""))
.Concat([$"uno-config.js", "_framework/blazor.boot.json", "."]);

var offlineFiles = enablePWA ? string.Join(", ", sanitizedOfflineFiles.Select(f => $"\"{WebAppBasePath}{f}\"")) : "";

var emccExportedRuntimeMethodsParams = string.Join(
",",
Expand All @@ -564,7 +606,7 @@ private void GenerateConfig()
config.AppendLine($"config.uno_dependencies = [{dependencies}];");
config.AppendLine($"config.uno_runtime_options = [{runtimeOptionsSet}];");
config.AppendLine($"config.enable_pwa = {enablePWA.ToString().ToLowerInvariant()};");
//config.AppendLine($"config.offline_files = ['{WebAppBasePath}', {offlineFiles}];");
config.AppendLine($"config.offline_files = ['{WebAppBasePath}', {offlineFiles}];");
config.AppendLine($"config.uno_shell_mode = \"{_shellMode}\";");
config.AppendLine($"config.uno_debugging_enabled = {(!Optimize).ToString().ToLowerInvariant()};");
config.AppendLine($"config.uno_enable_tracing = {EnableTracing.ToString().ToLowerInvariant()};");
Expand Down Expand Up @@ -686,8 +728,7 @@ private void GeneratePWAContent(StringBuilder extraBuilder)

extraBuilder.AppendLine($"<link rel=\"manifest\" href=\"$(WEB_MANIFEST)\" />");

// See https://developer.apple.com/library/archive/documentation/AppleApplications/Reference/SafariHTMLRef/Articles/MetaTags.html
extraBuilder.AppendLine($"<meta name=\"apple-mobile-web-app-capable\" content=\"yes\">");
extraBuilder.AppendLine($"<meta name=\"mobile-web-app-capable\" content=\"yes\">");

if (manifestDocument["icons"] is JArray array
&& array.Where(v => v["sizes"]?.Value<string>() == "1024x1024").FirstOrDefault() is JToken img)
Expand Down Expand Up @@ -720,7 +761,11 @@ string s when s.StartsWith("./") => $"{WebAppBasePath}/" + s.Substring(2),
}
}

AddStaticAsset(Path.GetFileName(PWAManifestFile), PWAManifestFile!);
var pwaManifestFileName = Path.GetFileName(PWAManifestFile);
var pwaManifestOutputPath = Path.Combine(_intermediateAssetsPath, pwaManifestFileName);
File.WriteAllText(pwaManifestOutputPath, manifestDocument.ToString());

AddStaticAsset(Path.GetFileName(PWAManifestFile), pwaManifestOutputPath);
}
}

Expand Down Expand Up @@ -860,6 +905,14 @@ private void GenerateEmbeddedJs()
AddStaticAsset("index.html", htmlPath);
}

private string TouchServiceWorker(string workerBody)
{
workerBody = workerBody.Replace("$(CACHE_KEY)", Guid.NewGuid().ToString());
workerBody = workerBody.Replace("$(REMOTE_WEBAPP_PATH)", WebAppBasePath);

return workerBody;
}

private string TryConvertLongPath(string path)
=> Environment.OSVersion.Platform == PlatformID.Win32NT
&& !string.IsNullOrEmpty(path)
Expand Down
45 changes: 40 additions & 5 deletions src/Uno.Wasm.Bootstrap/WasmScripts/service-worker.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
import { config } from "$(REMOTE_WEBAPP_PATH)$(REMOTE_BASE_PATH)/uno-config.js";
import { config as unoConfig } from "$(REMOTE_WEBAPP_PATH)uno-config.js";

if (config.environmentVariables["UNO_BOOTSTRAP_DEBUGGER_ENABLED"] !== "True") {

if (unoConfig.environmentVariables["UNO_BOOTSTRAP_DEBUGGER_ENABLED"] !== "True") {
console.debug("[ServiceWorker] Initializing");
let uno_enable_tracing = unoConfig.uno_enable_tracing;

self.addEventListener('install', function (e) {
console.debug('[ServiceWorker] Installing offline worker');
Expand All @@ -11,14 +13,47 @@ if (config.environmentVariables["UNO_BOOTSTRAP_DEBUGGER_ENABLED"] !== "True") {

// Add files one by one to avoid failed downloads to prevent the
// worker to fail installing.
for (var i = 0; i < config.offline_files.length; i++) {
for (var i = 0; i < unoConfig.offline_files.length; i++) {
try {
await cache.add(config.offline_files[i]);
if (uno_enable_tracing) {
console.debug(`[ServiceWorker] cache ${key}`);
}

await cache.add(unoConfig.offline_files[i]);
}
catch (e) {
console.debug(`[ServiceWorker] Failed to fetch ${config.offline_files[i]}`);
console.debug(`[ServiceWorker] Failed to fetch ${unoConfig.offline_files[i]}`);
}
}

// Add the runtime's own files to the cache. We cannot use the
// existing cached content from the runtime as the keys contain a
// hash we cannot reliably compute.
var c = await fetch("$(REMOTE_WEBAPP_PATH)_framework/blazor.boot.json");
const monoConfigResources = (await c.json()).resources;

var entries = {
...(monoConfigResources.coreAssembly || {})
, ...(monoConfigResources.assembly || {})
, ...(monoConfigResources.lazyAssembly || {})
, ...(monoConfigResources.jsModuleWorker || {})
, ...(monoConfigResources.jsModuleGlobalization || {})
, ...(monoConfigResources.jsModuleNative || {})
, ...(monoConfigResources.jsModuleRuntime || {})
, ...(monoConfigResources.wasmNative || {})
, ...(monoConfigResources.icu || {})
, ...(monoConfigResources.coreAssembly || {})
};

for (var key in entries) {
var uri = `$(REMOTE_WEBAPP_PATH)_framework/${key}`;

if (uno_enable_tracing) {
console.debug(`[ServiceWorker] cache ${uri}`);
}

await cache.add(uri);
}
})
);
});
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
<WasmShellMonoRuntimeExecutionMode Condition="'$(UseAOT)'=='true'">InterpreterAndAOT</WasmShellMonoRuntimeExecutionMode>
<MonoRuntimeDebuggerEnabled Condition="'$(Configuration)'=='Debug'">true</MonoRuntimeDebuggerEnabled>
<DefineConstants>$(DefineConstants);__WASM__;UWP</DefineConstants>
<WasmPWAManifestFile>manifest.json</WasmPWAManifestFile>
<WasmPWAManifestFile>app.webmanifest</WasmPWAManifestFile>
<!--<WasmShellEnableEmccProfiling>true</WasmShellEnableEmccProfiling>-->
<WasmShellPrintAOTSkippedMethods>true</WasmShellPrintAOTSkippedMethods>
<AllowUnsafeBlocks>True</AllowUnsafeBlocks>
Expand All @@ -25,6 +25,12 @@

<Import Project="..\Uno.Wasm.Bootstrap\build\Uno.Wasm.Bootstrap.props" />
<Import Project="..\Uno.Wasm.Bootstrap\build\Uno.Wasm.Bootstrap.targets" />
<ItemGroup>
<None Remove="app.webmanifest" />
</ItemGroup>
<ItemGroup>
<Content Include="app.webmanifest" />
</ItemGroup>

<ItemGroup>
<LinkerDescriptor Include="LinkerConfig.xml" />
Expand Down
Loading