From 4b6c2c2ab9f3d809b399a5cbc2fb776b6b5d4b22 Mon Sep 17 00:00:00 2001 From: botoddly <250804054+botoddly@users.noreply.github.com> Date: Wed, 18 Nov 2026 22:34:47 +0100 Subject: [PATCH 1/4] Make browser publishes installable with a web app manifest and playable offline with the .NET SDK's service worker --- AGENTS.md | 2 +- DECISIONS.md | 12 ++ docs/hosting.md | 98 ++++++++++ docs/sdk.md | 5 +- packaging/Pixely/Sdk/Pixely.AfterSdk.targets | 2 + packaging/Pixely/Sdk/Pixely.Browser.targets | 170 +++++++++++++++++- .../Pixely/Sdk/Pixely.BrowserOffline.targets | 17 ++ packaging/Pixely/wwwroot/main.js | 23 ++- packaging/Pixely/wwwroot/pixely-host.js | 11 +- packaging/Pixely/wwwroot/service-worker.js | 146 +++++++++++++++ tests/Pixely.Browser.Harness/README.md | 6 + tests/Pixely.Browser.Harness/run-offline.js | 142 +++++++++++++++ .../BrowserContentConsumer.csproj | 6 + .../Extras/icon-192.png | 3 + .../Extras/icon-512.png | 3 + .../PackageIntegrationTests.cs | 93 ++++++++++ tutorials/Pixely.Tutorials.AfterSdk.targets | 1 + 17 files changed, 727 insertions(+), 13 deletions(-) create mode 100644 packaging/Pixely/Sdk/Pixely.BrowserOffline.targets create mode 100644 packaging/Pixely/wwwroot/service-worker.js create mode 100644 tests/Pixely.Browser.Harness/run-offline.js create mode 100644 tests/Pixely.Package.Tests/Consumers/BrowserContentConsumer/Extras/icon-192.png create mode 100644 tests/Pixely.Package.Tests/Consumers/BrowserContentConsumer/Extras/icon-512.png diff --git a/AGENTS.md b/AGENTS.md index 554d5dff..be1ca616 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -19,7 +19,7 @@ - `docs/path-finding-grids.md` - Pixely.PathFinding.Grids: grid geometry, clearance-based agent footprints, connectivity and the corner rule, overlays, the admissible grid heuristic - `docs/development-packages.md` - Consuming packages from the public development feed - `docs/sdk.md` - Pixely as an MSBuild project SDK: the `` line, what it adds to a project, the browser build and its framework switch, central package management, the PIXELY0002 error for projects without it, the package layout with its two `lib/` folders -- `docs/hosting.md` - Hosting: opting in with `PixelyHosting`, the generated `Main`, `Configure` and `OnException` with its default message box in Release builds, diagnostics, the browser: `dotnet publish -r browser-wasm`, the `net11.0-browser` framework switch and its lateness, multi-targeting with `-f net11.0-browser`, `BrowserHost` and the frame loop, exit codes, the default page and its replacement, Mono AOT on by default (`RunAOTCompilation`), its opt-out and what IL stripping leaves readable, opt-in Brotli downloads with `PixelyBrowserBrotli` through the boot config for hosts without `Content-Encoding: br` such as GitHub Pages, XDL linked into the browser runtime from `XdlSharp.Native.browser-wasm` with the workload and `WasmBuildNative`, the formats XDL's satellites decode, native archives from a URL with `NativeUrlReference`, WebGPU in the browser: device adoption through `BrowserHost.PrepareAsync`, the fallback adapter warning, notice, `pixelygpuadapter` event and `readGpuAdapter()`, device loss and `GpuDeviceLostException`, the default page's loading indicator and stop message, the `pixelyfirstframe` event, teardown, what is unsupported +- `docs/hosting.md` - Hosting: opting in with `PixelyHosting`, the generated `Main`, `Configure` and `OnException` with its default message box in Release builds, diagnostics, the browser: `dotnet publish -r browser-wasm`, the `net11.0-browser` framework switch and its lateness, multi-targeting with `-f net11.0-browser`, `BrowserHost` and the frame loop, exit codes, the default page and its replacement, Mono AOT on by default (`RunAOTCompilation`), its opt-out and what IL stripping leaves readable, opt-in Brotli downloads with `PixelyBrowserBrotli` through the boot config for hosts without `Content-Encoding: br` such as GitHub Pages, an installable app with `PixelyBrowserInstallable`, the generated web app manifest, its icons and PIXELY0016, offline play with `PixelyBrowserOffline` through the .NET SDK's service worker targets, the worker registered after the first frame, caches named by scope, its retirement when the assets list is gone and the deletion of a stale worker, XDL linked into the browser runtime from `XdlSharp.Native.browser-wasm` with the workload and `WasmBuildNative`, the formats XDL's satellites decode, native archives from a URL with `NativeUrlReference`, WebGPU in the browser: device adoption through `BrowserHost.PrepareAsync`, the fallback adapter warning, notice, `pixelygpuadapter` event and `readGpuAdapter()`, device loss and `GpuDeviceLostException`, the default page's loading indicator and stop message, the `pixelyfirstframe` event, teardown, what is unsupported - `docs/cursors.md` - Mouse cursors through `ICursorService`: system, image and animated cursors, the hotspot, frame durations, setting, resetting and hiding the cursor, cursor lifetime and the main-thread rule, platform behavior of animated cursors, headless mode - `docs/platform-settings.md` - The user's OS or browser settings through `IPlatformSettings`: the main-thread rule, the light or dark theme with `ThemeChanged`, where SDL reads it on each platform, `Unknown` without an XDG portal and in headless mode; preferred locales with `Locale` for games that set `InvariantGlobalization`, why `CultureInfo` cannot tell them there, unvalidated codes, Linux ordering, the 127-byte limit, the `SDL_HINT_PREFERRED_LOCALES` override and its environment variable, skipped empty items, `PreferredLocalesChanged` and the platforms where SDL reports changes - `docs/taskbar-icons.md` - Application-wide taskbar and Dock icons loaded from virtual content diff --git a/DECISIONS.md b/DECISIONS.md index 3b200c24..cdd14f72 100644 --- a/DECISIONS.md +++ b/DECISIONS.md @@ -2,6 +2,18 @@ Design decisions with the constraints that decided them and their known costs, newest first. +## 2026-11-18: Offline play reuses the .NET SDK's service worker targets, and the worker retires itself + +`PixelyBrowserInstallable` generates a web app manifest and `PixelyBrowserOffline` publishes a service worker (`docs/hosting.md`). The worker is declared as the .NET SDK's `ServiceWorker` item, and its list of files is the SDK's `service-worker-assets.js`, with each file's SHA-256. + +- The static web assets SDK already lists every published file with its hash, compressed copies excepted, with the URLs the boot config requests. Pixely's own generator would repeat it. +- The two properties are separate because Chrome installs an app from its menu without a worker, while the worker delays every update to the launch after the one that found it. +- A browser keeps a registered worker when its script answers 404, so a publish without the worker cannot remove it. The worker therefore checks its list whenever it serves the page from its cache, and unregisters itself on a 4xx other than 408 and 429 or on an HTML page. That covers a later publish without the property and a build served on the same origin, and needs no retiring worker or publish mode. `dotnet publish` deletes no files, so a publish deletes the two worker files unless they are its own assets. +- Every site on an origin shares Cache Storage and scopes nest, as on one GitHub Pages account, so caches are named by scope and compared exactly. +- WriteLinesToFile turns backslashes into slashes on Unix, so the manifest and the page are written by inline tasks. + +Cost: the first visit with `PixelyBrowserBrotli` downloads the Brotli-loaded files twice, and updates download changed ones without Brotli, because the list has no `.br` copies and the worker no decoder. A deploy that loses the list, or a passing 4xx, retires offline play until the next launch with a network. A project's own `main.js` registers the worker itself, and nothing warns when it does not. The worker's behaviour in a browser is tested by hand with `tests/Pixely.Browser.Harness`, not in CI. The inline tasks compile with Roslyn on their first use in a build. + ## 2026-11-14: A test app never starts SDL, so tests run in parallel `TestApp.CreateBuilder()` builds an app without SDL (`docs/testing.md`). Its windows are `StubWindow`s without a platform, its display, cursors, clipboard and platform settings are stubs, its text uses `StubFontSystem`, and its sound `StubAudioSystem`. `Window` became platform-neutral, and `NativeWindow` holds the SDL window under `SwapchainWindow` and `OffscreenWindow`. `AudioSystem` became an abstract base with internal `*Core` methods, as `GpuDevice` is, with `SdlAudioSystem` on SDL_mixer. `PixelyAppBuilder.Build()`, `AddGpuServices` and `RegisterAudio` register a default only when nothing has registered the service, and a frame reads the platform through an internal `IEventSource`. diff --git a/docs/hosting.md b/docs/hosting.md index 299ec3e4..cb5582c0 100644 --- a/docs/hosting.md +++ b/docs/hosting.md @@ -439,3 +439,101 @@ content. Leave the property off on a host that sends `Content-Encoding: br` itself. The download is the same size, and Chrome compiles `dotnet.native.wasm` while it downloads instead of decoding it afterwards. + +While the offline worker of `PixelyBrowserOffline` controls the page, the loader stays off: the +worker answers from its cache, which holds no `.br` copies (see [Offline play](#offline-play)). + +### Installable app + +`PixelyBrowserInstallable=true` makes the published page a web app that a browser can install, as a +window of its own and an entry in the launcher or on the home screen: + +```xml + + true + Example Game + #1a1a2e + + + + + +``` + +- The SDK generates `manifest.webmanifest` with the name, `"start_url": "./"`, + `"display": "standalone"`, the colour as both theme and background colour, and the icons. + `PixelyBrowserAppName` defaults to `$(Product)`, which defaults to the assembly name. + `PixelyBrowserThemeColor` defaults to `#000`, the default page's background. +- An icon under the project's `wwwroot/` is served from there already, and the manifest names it by + its path there. Any other icon is served at its `TargetPath`, by default its file name. `Sizes` + is the manifest's space-separated `sizes`, and `Purpose`, when set, its `purpose`. +- Chrome installs an app only with a 192x192 and a 512x512 icon, so without both the build fails + with PIXELY0016. +- The package's `index.html` gets `` and + `` before ``. A project's own `wwwroot/index.html` or a page named + by `PixelyBrowserIndexHtml` adds both itself. +- A project's own `wwwroot/manifest.webmanifest` replaces the generated one; the icon check is then + the project's own. `PixelyBrowserDefaultAssets=false` turns off the generated manifest with the + rest of the page. + +A browser installs only a page from a secure context, which WebGPU needs anyway. An installed app +still needs the network unless `PixelyBrowserOffline` is on as well. + +### Offline play + +`PixelyBrowserOffline=true` makes a publish keep every file of the game in the browser, so the game +starts without a network after one visit: + +1. The publish adds `service-worker.js`, a service worker (a script the browser runs beside the + page, which can answer the page's requests). It also adds `service-worker-assets.js`, the .NET + SDK's list of every published file with its SHA-256, compressed copies excepted. Pixely uses the + .NET SDK's own service worker targets, which it turns on with `ServiceWorkerAssetsManifest`. +2. The boot config gets `"serviceWorker": true` in `extensions.pixely`. The default `main.js` + registers the worker after the first frame, so its downloads do not compete with the game's and + mostly come from the HTTP cache the game has just filled. A build has no extension and serves no + worker. +3. The worker downloads every listed file, `Content.pk3` included, and checks each against its + hash. A file an earlier version cached with the same hash is copied, not downloaded again. +4. From the next visit on, the worker answers the page and every listed file from its cache. It + answers only the page at its own folder, `index.html` or the folder itself, so a worker at the + root of an origin leaves the pages of other sites there alone. +5. A new publish gives the list new hashes. The browser installs the new worker in the background, + and it takes over when every page of the old one has closed, so players get an update on the + launch after the one that found it. + +To turn offline play off, publish without the property. Each time the worker answers the page from +its cache, it also requests `service-worker-assets.js`. When the server answers a 4xx other than 408 +and 429, or answers with an HTML page as a server that falls back to `index.html` does, the worker +unregisters itself, loads that page again from the network and deletes its caches. Other open +pages carry on until their next navigation. A 5xx or no network leaves the worker in place. A build +served on the same origin, such as `dotnet run` on `localhost`, has no list either, so it retires a +worker an earlier publish left there. `dotnet publish` deletes no file from the publish folder, so a +publish without the property deletes the two files and their compressed copies from it. + +- Caches are named `pixely||`, where the version is a hash of the list and the scope + the worker's folder. The worker deletes only caches of its own scope, compared exactly, so games + on one origin, such as the project sites of one GitHub Pages account, keep their caches. +- Under `StaticWebAssetBasePath` the SDK writes the base path in front of every URL in the list, while + the worker is served beneath it. The worker strips the path in front of `_framework/dotnet.js`, + which every publish lists. +- A project's own `wwwroot/service-worker.js` replaces the package's, in a publish and in a build, + where the SDK serves it with a build list. +- A project's own `main.js` registers the worker itself when `extensions.pixely.serviceWorker` is + true, which `onConfigLoaded` hands it: + + ```js + navigator.serviceWorker?.register('service-worker.js', { updateViaCache: 'none' }); + ``` + + `updateViaCache: 'none'` makes the browser's update check bypass the HTTP cache for the list as + well as the worker. GitHub Pages lets caches keep files for 10 minutes, so without it a new worker + can install the old list. +- With `PixelyBrowserBrotli`, the first visit downloads the Brotli-loaded files twice, once for the + page and once uncompressed for the worker, and updates download changed ones uncompressed or with + the host's gzip. The list has no `.br` copies, and the worker has no Brotli decoder. +- A wrongly retired worker, after a deploy that lost the list or a passing 4xx, comes back on the + next launch with a network. +- Service workers exist only in a secure context; elsewhere the game runs online only. + +The worker's behaviour in a browser is tested by hand with `run-offline.js` in +`tests/Pixely.Browser.Harness`. diff --git a/docs/sdk.md b/docs/sdk.md index d8e5ef40..9a518d50 100644 --- a/docs/sdk.md +++ b/docs/sdk.md @@ -63,14 +63,15 @@ lib/net11.0-browser1.0/ the library, the browser build of analyzers/dotnet/cs/ the dependency-injection and ECS generators Sdk/Sdk.props, Sdk/Sdk.targets imported by the SDK resolver Sdk/Pixely.AfterSdk.targets WebAssembly, shader and hosting targets, imported once the base SDK has set its properties +Sdk/Pixely.BrowserOffline.targets the offline worker of PixelyBrowserOffline, imported before the WebAssembly targets Sdk/Pixely.Hosting.targets the entry point generator Sdk/Pixely.Browser.props imports the WebAssembly SDK props on browser-wasm -Sdk/Pixely.Browser.targets the framework switch, browser property overrides, XDL's link settings, native URL references, PIXELY0004 to PIXELY0012, the default web assets, the Brotli boot config extension, the browser file system +Sdk/Pixely.Browser.targets the framework switch, browser property overrides, XDL's link settings, native URL references, PIXELY0004 to PIXELY0012 and PIXELY0016, the default web assets, the web app manifest, the boot config extension, the deletion of a stale offline worker, the browser file system Sdk/Pixely.Native.targets the XdlSharp.Native. reference, PIXELY0014 and PIXELY0015 Sdk/Pixely.Version.props the package version and the XdlSharp version, generated at pack time buildTransitive/Pixely.targets fails a project that reaches Pixely without the SDK tools/net11.0/any/ the shader compilation task and its props and targets -wwwroot/ index.html, main.js and pixely-host.js for the browser +wwwroot/ index.html, main.js, pixely-host.js and service-worker.js for the browser docs/ this documentation ``` diff --git a/packaging/Pixely/Sdk/Pixely.AfterSdk.targets b/packaging/Pixely/Sdk/Pixely.AfterSdk.targets index 45730d4e..95551b35 100644 --- a/packaging/Pixely/Sdk/Pixely.AfterSdk.targets +++ b/packaging/Pixely/Sdk/Pixely.AfterSdk.targets @@ -1,4 +1,6 @@ + + + + + + + + + + + + + + + + + + + + + icons = new System.Collections.Generic.List(); + foreach (Microsoft.Build.Framework.ITaskItem icon in Icons) + { + string purpose = icon.GetMetadata("Purpose"); + string purposeMember = purpose.Length > 0 ? ", \"purpose\": " + Quote(purpose) : ""; + icons.Add(" { \"src\": " + Quote(icon.GetMetadata("Src")) + ", \"sizes\": " + Quote(icon.GetMetadata("Sizes")) + purposeMember + " }"); + } + Text = "{\n" + + " \"name\": " + Quote(Name) + ",\n" + + " \"start_url\": \"./\",\n" + + " \"display\": \"standalone\",\n" + + " \"background_color\": " + Quote(ThemeColor) + ",\n" + + " \"theme_color\": " + Quote(ThemeColor) + ",\n" + + " \"icons\": [\n" + string.Join(",\n", icons) + "\n ]\n" + + "}\n"; + ]]> + + + + + + + <_PixelyBrowserGeneratedRoot>$([MSBuild]::NormalizeDirectory('$(MSBuildProjectDirectory)', '$(IntermediateOutputPath)', 'pixely-browser-generated')) + <_PixelyBrowserWwwroot>$([MSBuild]::NormalizeDirectory('$(MSBuildProjectDirectory)', 'wwwroot')) + <_PixelyBrowserAppName>$(PixelyBrowserAppName) + <_PixelyBrowserAppName Condition="'$(PixelyBrowserAppName.Length)' == '0'">$(Product) + <_PixelyBrowserThemeColor>$(PixelyBrowserThemeColor) + <_PixelyBrowserThemeColor Condition="'$(PixelyBrowserThemeColor.Length)' == '0'">#000 + <_PixelyBrowserThemeColorHtml>$(_PixelyBrowserThemeColor.Replace('&', '&amp;').Replace('"', '&quot;').Replace(`'`, '&#39;').Replace('<', '&lt;')) + <_PixelyBrowserOwnManifest>false + <_PixelyBrowserOwnManifest Condition="Exists('$(_PixelyBrowserWwwroot)manifest.webmanifest')">true + + + <_PixelyBrowserAppIcon Include="@(PixelyBrowserAppIcon->'%(FullPath)')" /> + <_PixelyBrowserAppIcon Update="@(_PixelyBrowserAppIcon)" Condition="'%(_PixelyBrowserAppIcon.TargetPath)' == ''" TargetPath="%(Filename)%(Extension)" /> + <_PixelyBrowserAppIcon Update="@(_PixelyBrowserAppIcon)" Src="$([System.String]::Copy('%(TargetPath)').Replace('\', '/'))" /> + <_PixelyBrowserAppIcon Update="@(_PixelyBrowserAppIcon)" Condition="$([System.String]::Copy('%(_PixelyBrowserAppIcon.FullPath)').StartsWith('$(_PixelyBrowserWwwroot)'))" + Src="$([MSBuild]::MakeRelative('$(_PixelyBrowserWwwroot)', '%(FullPath)').Replace('\', '/'))" InWwwroot="true" /> + + + + <_PixelyBrowserAppIconSizes>|@(_PixelyBrowserAppIcon->'%(Sizes)', '|')| + <_PixelyBrowserAppIconSizes>$(_PixelyBrowserAppIconSizes.Replace(' ', '|').ToLowerInvariant()) + + + <_PixelyFormatWebAppManifest Name="$(_PixelyBrowserAppName)" ThemeColor="$(_PixelyBrowserThemeColor)" Icons="@(_PixelyBrowserAppIcon)" Condition="'$(_PixelyBrowserOwnManifest)' != 'true'"> + + + <_PixelyWriteTextFile File="$(_PixelyBrowserGeneratedRoot)manifest.webmanifest" Text="$(_PixelyBrowserManifest)" Condition="'$(_PixelyBrowserOwnManifest)' != 'true'" /> + + <_PixelyBrowserInstallableAssetSource Include="$(_PixelyBrowserGeneratedRoot)manifest.webmanifest" RelativePath="manifest.webmanifest" /> + <_PixelyBrowserInstallableAssetSource Include="@(_PixelyBrowserAppIcon)" Condition="'%(_PixelyBrowserAppIcon.InWwwroot)' != 'true'" RelativePath="%(_PixelyBrowserAppIcon.TargetPath)" /> + + + + + <_PixelyBrowserInstallableHead> <link rel="manifest" href="manifest.webmanifest" /> + <meta name="theme-color" content="$(_PixelyBrowserThemeColorHtml)" /> +</head> + <_PixelyBrowserIndexHtmlSource>$(_PixelyBrowserGeneratedRoot)index.html + + <_PixelyWriteTextFile File="$(_PixelyBrowserIndexHtmlSource)" Text="$([System.IO.File]::ReadAllText('$(_PixelyBrowserPackageIndexHtml)').Replace('</head>', '$(_PixelyBrowserInstallableHead)'))" + Condition="'$(PixelyBrowserIndexHtml)' == '$(_PixelyBrowserPackageIndexHtml)'" /> + + + + + + DependsOnTargets="_PixelyGenerateBrowserInstallableAssets" Condition="'$(_PixelyBrowser)' == 'true' and '$(PixelyBrowserDefaultAssets)' == 'true'"> <_PixelyBrowserAssetsRoot>$([MSBuild]::NormalizeDirectory('$(MSBuildProjectDirectory)', '$(IntermediateOutputPath)', 'pixely-browser')) + <_PixelyBrowserIndexHtmlSource Condition="'$(_PixelyBrowserIndexHtmlSource)' == ''">$(PixelyBrowserIndexHtml) - <_PixelyBrowserDefaultAssetSource Include="$(PixelyBrowserIndexHtml)" RelativePath="index.html" /> + <_PixelyBrowserDefaultAssetSource Include="$(_PixelyBrowserIndexHtmlSource)" RelativePath="index.html" /> <_PixelyBrowserDefaultAssetSource Include="$(PixelyBrowserMainJs)" RelativePath="main.js" /> <_PixelyBrowserDefaultAssetSource Include="$(_PixelyBrowserHostJs)" RelativePath="pixely-host.js" /> + <_PixelyBrowserDefaultAssetSource Include="@(_PixelyBrowserInstallableAssetSource)" /> <_PixelyBrowserDefaultAssetSource Remove="@(_PixelyBrowserDefaultAssetSource)" Condition="Exists('$(MSBuildProjectDirectory)/wwwroot/%(RelativePath)')" /> @@ -188,9 +319,10 @@ @@ -200,16 +332,40 @@ <_PixelyPublishWritesBrotli Condition="'$(CompressionEnabled)' == 'true' and '$(_PixelyPublishCompressionFormats.Contains(`;brotli;`))' == 'true'">true <_PixelyBrowserBrotli>false <_PixelyBrowserBrotli Condition="'$(PixelyBrowserBrotli)' == 'true' and '$(_PixelyPublishWritesBrotli)' == 'true'">true + <_PixelyBrowserServiceWorker>false + <_PixelyBrowserServiceWorker Condition="'$(PixelyBrowserOffline)' == 'true'">true - + + + + + <_PixelyBrowserPublishDir>$([MSBuild]::NormalizeDirectory('$(MSBuildProjectDirectory)', '$(PublishDir)')) + <_PixelyBrowserPublishRoot>$([MSBuild]::NormalizeDirectory('$(_PixelyBrowserPublishDir)', 'wwwroot', '$(StaticWebAssetBasePath.Replace(`\`, `/`).Trim(`/`))')) + + + <_PixelyBrowserServiceWorkerFileName Include="service-worker.js;service-worker-assets.js" /> + <_PixelyBrowserStaleServiceWorkerFile Include="@(_PixelyBrowserServiceWorkerFileName->'$(_PixelyBrowserPublishRoot)%(Identity)')" /> + <_PixelyBrowserStaleServiceWorkerFile Include="@(_PixelyBrowserServiceWorkerFileName->'$(_PixelyBrowserPublishRoot)%(Identity).br')" /> + <_PixelyBrowserStaleServiceWorkerFile Include="@(_PixelyBrowserServiceWorkerFileName->'$(_PixelyBrowserPublishRoot)%(Identity).gz')" /> + <_PixelyBrowserPublishedFile Include="$([System.IO.Path]::GetFullPath('$(_PixelyBrowserPublishDir)%(_PublishStaticWebAssetsTargetPath.TargetPath)'))" /> + <_PixelyBrowserStaleServiceWorkerFile Remove="@(_PixelyBrowserPublishedFile)" /> + + + + + + service-worker-assets.js + <_PixelyBrowserOfflineWorker>$(MSBuildThisFileDirectory)..\wwwroot\service-worker.js + <_PixelyBrowserOfflineWorker Condition="Exists('$(MSBuildProjectDirectory)/wwwroot/service-worker.js')">$(MSBuildProjectDirectory)/wwwroot/service-worker.js + + + + + diff --git a/packaging/Pixely/wwwroot/main.js b/packaging/Pixely/wwwroot/main.js index b7b6c67e..94f51067 100644 --- a/packaging/Pixely/wwwroot/main.js +++ b/packaging/Pixely/wwwroot/main.js @@ -13,13 +13,25 @@ globalThis.addEventListener('pixelygpuadapter', event => { showFallbackNotice(); } }); -globalThis.addEventListener('pixelyfirstframe', () => loading.indicator.remove(), { once: true }); +// A publish with PixelyBrowserOffline puts serviceWorker in the boot config. The worker is registered after the first frame, so that +// its downloads do not compete with the game's and find most files in the HTTP cache the game has just filled. +let offline = false; +globalThis.addEventListener('pixelyfirstframe', () => { + loading.indicator.remove(); + if (offline) { + registerServiceWorker(); + } +}, { once: true }); try { // runMain resolves with the value the managed Main returns; it rejects when Main throws, which the default OnException does. // The loader reads PixelyBrowserBrotli from the boot config that onConfigLoaded hands it, before the runtime downloads any file. // onRuntimeInitialized runs once every file the runtime needs to start is in memory. - const moduleConfig = { canvas, onConfigLoaded: host.configureCompressedResources, onRuntimeInitialized: () => { loading.stage.textContent = 'Starting…'; } }; + const onConfigLoaded = config => { + offline = config.extensions?.pixely?.serviceWorker === true; + return host.configureCompressedResources?.(config); + }; + const moduleConfig = { canvas, onConfigLoaded, onRuntimeInitialized: () => { loading.stage.textContent = 'Starting…'; } }; const exitCode = await dotnet.withModuleConfig(moduleConfig).withResourceLoader(host.loadCompressedResource).runMain(); console.log(`Pixely exited with code ${exitCode}`); if (exitCode !== 0) { @@ -54,6 +66,13 @@ function showLoading() { return { indicator, stage }; } +// The worker sits beside the page. updateViaCache 'none' makes the browser's update check also bypass the HTTP cache for the assets +// list the worker imports, which a host such as GitHub Pages lets caches keep for 10 minutes. Browsers hide serviceWorker outside a +// secure context, where the game then runs online only. +function registerServiceWorker() { + navigator.serviceWorker?.register('service-worker.js', { updateViaCache: 'none' }).catch(error => console.warn('Pixely could not register its offline worker', error)); +} + // A managed exception reaches the page with its message only, so the type comes from the record BrowserHost.ReportExceptionAsync left. function describeException() { const exception = host.readException?.(); diff --git a/packaging/Pixely/wwwroot/pixely-host.js b/packaging/Pixely/wwwroot/pixely-host.js index 9e40988d..fcc28588 100644 --- a/packaging/Pixely/wwwroot/pixely-host.js +++ b/packaging/Pixely/wwwroot/pixely-host.js @@ -148,12 +148,21 @@ let brotliFetchPolicy = null; // An onConfigLoaded callback for dotnet.withModuleConfig, which runs before the runtime downloads any file. The SDK puts // PixelyBrowserBrotli in a publish's boot config as extensions.pixely.brotli; a build has no .br files and no extension. The loader // follows the config's disableIntegrityCheck and disableNoCacheFetch; it never sees a file's own cache or credentials setting. +// It stays off while the offline worker of PixelyBrowserOffline controls the page, since that worker answers from its cache and has +// no .br copies; a worker of another site on the origin can control the page too, so the check is by the worker's URL. export function configureCompressedResources(config) { - brotliFetchPolicy = config.extensions?.pixely?.brotli === true + const pixely = config.extensions?.pixely; + brotliFetchPolicy = pixely?.brotli === true && !(pixely.serviceWorker === true && isControlledByOfflineWorker()) ? { integrity: !config.disableIntegrityCheck, cache: config.disableNoCacheFetch ? undefined : 'no-cache' } : null; } +// Node has no service workers and no document. +function isControlledByOfflineWorker() { + const scriptUrl = globalThis.navigator?.serviceWorker?.controller?.scriptURL; + return scriptUrl !== undefined && scriptUrl === new URL('service-worker.js', globalThis.document?.baseURI ?? globalThis.location?.href).href; +} + // A loader for dotnet.withResourceLoader that fetches the Brotli copy a publish writes beside each runtime file and decompresses it // in the page. A static host such as GitHub Pages serves foo.wasm.br as an opaque file and compresses foo.wasm with gzip at best, // since it sets no Content-Encoding: br. DecompressionStream keeps compilation streaming where it decodes Brotli; elsewhere, Chrome diff --git a/packaging/Pixely/wwwroot/service-worker.js b/packaging/Pixely/wwwroot/service-worker.js new file mode 100644 index 00000000..56bf0cf4 --- /dev/null +++ b/packaging/Pixely/wwwroot/service-worker.js @@ -0,0 +1,146 @@ +// Pixely's offline worker, which a publish with PixelyBrowserOffline serves as service-worker.js and main.js registers after the first +// frame. service-worker-assets.js is the .NET SDK's list of every file of the publish with its SHA-256, compressed copies excepted. +self.importScripts('./service-worker-assets.js'); + +// Every site on an origin shares Cache Storage, as the project sites of one GitHub Pages account do, and scopes nest, so a cache is +// named by the scope it belongs to and compared by it exactly. The version is the list's own hash: a project can set the SDK's. +const scope = self.registration.scope; +const cacheNamePrefix = 'pixely|'; +// The SDK writes StaticWebAssetBasePath in front of every URL of the list, while the worker is served beneath it. Every publish lists +// the runtime at _framework/dotnet.js below that path, so the shortest URL ending there gives the prefix to strip. +const dotnetJs = '_framework/dotnet.js'; +const basePath = self.assetsManifest.assets.map(asset => asset.url).filter(url => url === dotnetJs || url.endsWith(`/${dotnetJs}`)) + .reduce((shortest, url) => shortest === undefined || url.length < shortest.length ? url : shortest, undefined)?.slice(0, -dotnetJs.length) ?? ''; +const assets = self.assetsManifest.assets.map(asset => ({ + url: new URL(asset.url.startsWith(basePath) ? asset.url.slice(basePath.length) : asset.url, scope).href, + hash: asset.hash, +})); +const assetUrls = new Set(assets.map(asset => asset.url)); +const indexUrl = new URL('index.html', scope).href; +const assetsListUrl = new URL('service-worker-assets.js', self.location.href).href; +const cacheNamePromise = hashAssets().then(version => `${cacheNamePrefix}${version}|${scope}`); +// Each cached response carries the hash it was fetched for, so an install reuses what an earlier version cached. +const hashHeader = 'X-Pixely-Asset-Hash'; + +self.addEventListener('install', event => event.waitUntil(install())); +self.addEventListener('activate', event => event.waitUntil(deleteEarlierCaches())); +self.addEventListener('fetch', onFetch); + +// Fills this version's cache. An asset already cached with the same hash, in this cache or one of an earlier version, is not +// downloaded again; the rest is fetched past the HTTP cache's freshness and checked against its hash. The cache is only added to, +// so a new worker of the same version leaves the active worker's cache intact. +async function install() { + const cacheName = await cacheNamePromise; + const cache = await caches.open(cacheName); + const earlierNames = (await ownCacheNames()).filter(name => name !== cacheName); + await Promise.all(assets.map(async asset => { + if (await findCached(asset, [cacheName])) { + return; + } + const earlier = await findCached(asset, earlierNames); + if (earlier) { + await cache.put(asset.url, earlier); + return; + } + const response = await fetch(new Request(asset.url, { integrity: asset.hash, cache: 'no-cache' })); + if (!response.ok) { + throw new Error(`${asset.url} answered ${response.status}`); + } + const headers = new Headers(response.headers); + headers.set(hashHeader, asset.hash); + // A new response also drops the redirected flag, which a navigation must not be answered with. + await cache.put(asset.url, new Response(response.body, { status: response.status, statusText: response.statusText, headers })); + })); +} + +async function findCached(asset, cacheNames) { + for (const cacheName of cacheNames) { + const response = await caches.match(asset.url, { cacheName }); + if (response?.headers.get(hashHeader) === asset.hash) { + return response; + } + } + return undefined; +} + +function onFetch(event) { + const request = event.request; + if (request.method !== 'GET') { + return; + } + const url = new URL(request.url); + url.hash = ''; + if (request.mode === 'navigate') { + // Only the page itself: a worker at / would otherwise answer the pages of every other site on the origin. + url.search = ''; + if (url.href === scope || url.href === indexUrl) { + const served = serveIndex(request); + event.respondWith(served.then(result => result.response)); + event.waitUntil(served.then(result => result.fromCache ? retireIfUnpublished(event.resultingClientId) : undefined)); + } + return; + } + if (assetUrls.has(url.href)) { + event.respondWith(serveAsset(request)); + } +} + +// caches.match never creates a cache, so a page still controlled after a retirement cannot bring a deleted one back. +async function serveIndex(request) { + const cached = await caches.match(indexUrl, { cacheName: await cacheNamePromise }); + return cached ? { response: cached, fromCache: true } : { response: await fetch(request), fromCache: false }; +} + +async function serveAsset(request) { + return await caches.match(request, { cacheName: await cacheNamePromise }) ?? fetch(request); +} + +// A publish without PixelyBrowserOffline, or a build served on the same origin, has no assets list. The browser's update check then +// fails and keeps this worker, so the worker checks the list itself whenever it served the page from its cache. A missing file is a +// 4xx (S3 answers 403) or, from a server that falls back to index.html, a page; a timeout, a rate limit, a 5xx and no network leave +// the worker in place. Unregistering takes effect at once, so the page this navigation created is loaded again from the network, and +// any other page reaches the network on its next navigation without being interrupted. +async function retireIfUnpublished(resultingClientId) { + let response; + try { + response = await fetch(assetsListUrl, { cache: 'no-cache' }); + } catch { + return; + } + const page = response.headers.get('Content-Type')?.toLowerCase().startsWith('text/html'); + await response.body?.cancel(); + const missing = response.status >= 400 && response.status < 500 && response.status !== 408 && response.status !== 429; + if (!missing && !(response.ok && page)) { + return; + } + await self.registration.unregister(); + const client = resultingClientId ? await self.clients.get(resultingClientId) : undefined; + await client?.navigate(client.url).catch(() => {}); + await deleteAllCaches(); +} + +async function deleteEarlierCaches() { + const cacheName = await cacheNamePromise; + await Promise.all((await ownCacheNames()).filter(name => name !== cacheName).map(name => caches.delete(name))); +} + +async function deleteAllCaches() { + await Promise.all((await ownCacheNames()).map(name => caches.delete(name))); +} + +async function ownCacheNames() { + return (await caches.keys()).filter(name => { + if (!name.startsWith(cacheNamePrefix)) { + return false; + } + const end = name.indexOf('|', cacheNamePrefix.length); + return end !== -1 && name.slice(end + 1) === scope; + }); +} + +// The list is sorted by URL, so its pairs hash the same way every time. +async function hashAssets() { + const text = self.assetsManifest.assets.map(asset => `${asset.url} ${asset.hash}`).join('\n'); + const digest = new Uint8Array(await crypto.subtle.digest('SHA-256', new TextEncoder().encode(text))); + return Array.from(digest, byte => byte.toString(16).padStart(2, '0')).join(''); +} diff --git a/tests/Pixely.Browser.Harness/README.md b/tests/Pixely.Browser.Harness/README.md index f9a0a90a..3216e6ef 100644 --- a/tests/Pixely.Browser.Harness/README.md +++ b/tests/Pixely.Browser.Harness/README.md @@ -9,3 +9,9 @@ node run-page.js ../../tutorials/Pixely.Tutorials.Browser/bin/Release/net11.0-br ``` `PIXELY_CHROMIUM` names another Chromium executable than the one Playwright installed. Chromium on Linux exposes the hardware adapter only headed with `--enable-features=Vulkan`; headless gets SwiftShader, which loses the device after the first presented frame. `--headless` is there for the window-only case. + +`run-offline.js` checks the offline worker of a publish with `PixelyBrowserOffline` (docs/hosting.md, Offline play): it installs, a reload comes from its cache, and once the server answers 404 for the worker and its assets list, as after a publish without the property, it unregisters itself, loads the page again from the network and deletes its caches. One server on one port serves every step. `--nested` also serves the publish at `/proj/`, inside the scope of the one at `/`, and checks that retiring the worker at `/` keeps the worker and the caches of `/proj/`. `--register` registers the worker from the harness, for a publish that never draws the first frame after which `main.js` registers it. + +```shell +node run-offline.js ../../tutorials/Pixely.Tutorials.Browser/bin/Release/net11.0-browser/browser-wasm/publish/wwwroot --nested +``` diff --git a/tests/Pixely.Browser.Harness/run-offline.js b/tests/Pixely.Browser.Harness/run-offline.js new file mode 100644 index 00000000..225d7672 --- /dev/null +++ b/tests/Pixely.Browser.Harness/run-offline.js @@ -0,0 +1,142 @@ +// Checks the offline worker of a publish with PixelyBrowserOffline in Chromium: it installs after the first frame, a reload is answered +// from its cache, and once the server has no assets list, as after a publish without the property, it retires: the page loads again +// from the network, the registration is gone and so are its caches. With --nested the same publish is also served at /proj/, a site +// inside the scope of the one at /, as on one GitHub Pages account; retiring the worker at / must keep the caches and the worker of +// /proj/. One server on one port serves every step, so the origin stays the same. +// +// usage: node run-offline.js [--nested] [--register] [--headless] +// +// main.js registers the worker after the first frame. --register registers it from here once the page has loaded, for a publish +// that never draws a frame, such as a package test fixture. +// +// Exit code 0 means every check passed. +const { chromium } = require('playwright'); +const http = require('http'); +const fs = require('fs'); +const path = require('path'); + +const options = { nested: false, register: false, headless: false }; +const positional = []; +for (let index = 2; index < process.argv.length; index++) { + const argument = process.argv[index]; + if (argument === '--nested') { + options.nested = true; + } else if (argument === '--register') { + options.register = true; + } else if (argument === '--headless') { + options.headless = true; + } else { + positional.push(argument); + } +} +const root = positional[0]; +if (!root) { + console.error('usage: node run-offline.js [--nested] [--register] [--headless]'); + process.exit(2); +} + +const contentTypes = { '.html': 'text/html', '.js': 'text/javascript', '.mjs': 'text/javascript', '.wasm': 'application/wasm', '.json': 'application/json', '.webmanifest': 'application/manifest+json' }; +// Paths the server answers with 404 although the file exists, and the paths requested since the last reset. +const missing = new Set(); +let requested = []; +const server = http.createServer((request, response) => { + const url = new URL(request.url, 'http://localhost'); + requested.push(url.pathname); + if (url.pathname === '/favicon.ico') { + response.writeHead(204); + response.end(); + return; + } + const relative = options.nested && url.pathname.startsWith('/proj/') ? url.pathname.slice('/proj'.length) : url.pathname; + const file = path.join(root, decodeURIComponent(relative.endsWith('/') ? `${relative}index.html` : relative)); + if (missing.has(url.pathname) || !fs.existsSync(file) || fs.statSync(file).isDirectory()) { + response.writeHead(404); + response.end(); + return; + } + response.writeHead(200, { 'Content-Type': contentTypes[path.extname(file)] ?? 'application/octet-stream' }); + fs.createReadStream(file).pipe(response); +}); + +const failures = []; +function check(condition, message) { + console.log(`[${condition ? 'ok' : 'FAIL'}] ${message}`); + if (!condition) { + failures.push(message); + } +} + +async function waitFor(page, predicate, argument, timeoutMs = 30000) { + try { + await page.waitForFunction(predicate, argument, { timeout: timeoutMs, polling: 250 }); + return true; + } catch { + return false; + } +} + +// The worker registers after the first frame and is ready once it has cached every file. +async function waitForActiveWorker(page) { + if (options.register) { + await page.evaluate(() => navigator.serviceWorker.register('service-worker.js', { updateViaCache: 'none' })); + } + return waitFor(page, async () => (await navigator.serviceWorker.getRegistration())?.active?.state === 'activated'); +} + +async function cacheNames(page) { + return page.evaluate(async () => (await caches.keys()).filter(name => name.startsWith('pixely|'))); +} + +(async () => { + await new Promise(resolve => server.listen(0, resolve)); + const origin = `http://localhost:${server.address().port}`; + const browser = await chromium.launch({ + executablePath: process.env.PIXELY_CHROMIUM || undefined, + headless: options.headless, + args: ['--enable-features=Vulkan', '--enable-unsafe-webgpu', '--ignore-gpu-blocklist'] + }); + const context = await browser.newContext({ viewport: { width: 640, height: 400 } }); + const page = await context.newPage(); + page.on('console', message => console.log(`[${message.type()}] ${message.text()}`)); + + await page.goto(`${origin}/`, { waitUntil: 'load' }); + check(await waitForActiveWorker(page), 'the worker at / installs and activates'); + if (options.nested) { + await page.goto(`${origin}/proj/`, { waitUntil: 'load' }); + check(await waitForActiveWorker(page), 'the worker at /proj/ installs and activates'); + check((await cacheNames(page)).filter(name => name.endsWith(`|${origin}/proj/`)).length === 1, 'the worker at /proj/ has one cache of its scope'); + await page.goto(`${origin}/`, { waitUntil: 'load' }); + } + check((await cacheNames(page)).filter(name => name.endsWith(`|${origin}/`)).length === 1, 'the worker at / has one cache of its scope'); + + requested = []; + await page.reload({ waitUntil: 'load' }); + check(await page.evaluate(() => navigator.serviceWorker.controller?.scriptURL), `the reloaded page is controlled (${await page.evaluate(() => navigator.serviceWorker.controller?.scriptURL)})`); + await page.waitForTimeout(3000); + const fromNetwork = requested.filter(pathname => !pathname.endsWith('/service-worker.js') && !pathname.endsWith('/service-worker-assets.js') && pathname !== '/favicon.ico'); + check(fromNetwork.length === 0, `the reload fetched nothing else from the network (${fromNetwork.join(', ') || 'nothing'})`); + + // As after a publish without PixelyBrowserOffline: neither the worker nor its list is there. + missing.add('/service-worker.js'); + missing.add('/service-worker-assets.js'); + requested = []; + await page.reload({ waitUntil: 'load' }); + check(await waitFor(page, async () => (await navigator.serviceWorker.getRegistrations()).every(registration => registration.scope !== `${location.origin}/`)), + 'the worker at / unregisters itself'); + check(await waitFor(page, origin => caches.keys().then(names => !names.some(name => name.startsWith('pixely|') && name.endsWith(`|${origin}/`))), origin), + 'the caches of / are gone'); + check(await waitFor(page, () => document.readyState === 'complete' && !navigator.serviceWorker.controller), 'the page was loaded again from the network'); + check(requested.includes('/index.html') || requested.includes('/'), 'the page itself came from the network'); + if (options.nested) { + check((await cacheNames(page)).some(name => name.endsWith(`|${origin}/proj/`)), 'the cache of /proj/ is kept'); + check(await page.evaluate(async () => (await navigator.serviceWorker.getRegistrations()).some(registration => registration.scope.endsWith('/proj/'))), 'the worker at /proj/ is kept'); + } + + await browser.close(); + server.close(); + if (failures.length > 0) { + console.error(`FAILED\n${failures.map(failure => ` ${failure}`).join('\n')}`); + process.exit(1); + } + console.log('PASSED'); +})(); diff --git a/tests/Pixely.Package.Tests/Consumers/BrowserContentConsumer/BrowserContentConsumer.csproj b/tests/Pixely.Package.Tests/Consumers/BrowserContentConsumer/BrowserContentConsumer.csproj index e4dc1902..9087dd9f 100644 --- a/tests/Pixely.Package.Tests/Consumers/BrowserContentConsumer/BrowserContentConsumer.csproj +++ b/tests/Pixely.Package.Tests/Consumers/BrowserContentConsumer/BrowserContentConsumer.csproj @@ -28,6 +28,12 @@ + + + + + + diff --git a/tests/Pixely.Package.Tests/Consumers/BrowserContentConsumer/Extras/icon-192.png b/tests/Pixely.Package.Tests/Consumers/BrowserContentConsumer/Extras/icon-192.png new file mode 100644 index 00000000..3d877ad3 --- /dev/null +++ b/tests/Pixely.Package.Tests/Consumers/BrowserContentConsumer/Extras/icon-192.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:c2153f77e11087fcb078ae38527fa83bef29791e3700e30cc87fec4405a66d0f +size 70 diff --git a/tests/Pixely.Package.Tests/Consumers/BrowserContentConsumer/Extras/icon-512.png b/tests/Pixely.Package.Tests/Consumers/BrowserContentConsumer/Extras/icon-512.png new file mode 100644 index 00000000..3d877ad3 --- /dev/null +++ b/tests/Pixely.Package.Tests/Consumers/BrowserContentConsumer/Extras/icon-512.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:c2153f77e11087fcb078ae38527fa83bef29791e3700e30cc87fec4405a66d0f +size 70 diff --git a/tests/Pixely.Package.Tests/PackageIntegrationTests.cs b/tests/Pixely.Package.Tests/PackageIntegrationTests.cs index 0a6d0c1b..da8b799e 100644 --- a/tests/Pixely.Package.Tests/PackageIntegrationTests.cs +++ b/tests/Pixely.Package.Tests/PackageIntegrationTests.cs @@ -1153,6 +1153,99 @@ public async Task BrowserAppWithoutContentArchiveNamesTheArchiveInTheError() Assert.That(result, Does.Contain("RESULT error").And.Contain("PixelyBrowserVfsFile with TargetPath Content.pk3").And.Contain("RESULT exit code 1")); } + // One publish covers the manifest with a name that needs escaping, the icons at their target paths, the tags in the package's page, + // the offline worker with its assets list and the boot config flag. A second publish into the same folder without the worker + // deletes the worker's files, so a worker installed from the first retires. + [Test] + public async Task BrowserPublishMakesAnInstallableOfflineAppAndRetiresItsWorker() + { + string consumerDirectory = GetConsumerDirectory("BrowserContentConsumer"); + DeleteConsumerOutputs("BrowserContentConsumer"); + string[] installable = ["PixelyBrowserInstallable=true", "BrowserContentConsumerIcons=true", "PixelyBrowserAppName=Pixely%3B C:\\Games 'Game'", "PixelyBrowserThemeColor=#123456"]; + + await PublishConsumerAsync(consumerDirectory, "browser-wasm", properties: [.. installable, "PixelyBrowserOffline=true"]); + string wwwroot = GetPublishedWwwroot(consumerDirectory); + using (JsonDocument manifest = JsonDocument.Parse(File.ReadAllText(Path.Combine(wwwroot, "manifest.webmanifest")))) + { + JsonElement root = manifest.RootElement; + JsonElement[] icons = root.GetProperty("icons").EnumerateArray().ToArray(); + Assert.Multiple(() => + { + Assert.That(root.GetProperty("name").GetString(), Is.EqualTo("Pixely; C:\\Games 'Game'")); + Assert.That(root.GetProperty("start_url").GetString(), Is.EqualTo("./")); + Assert.That(root.GetProperty("display").GetString(), Is.EqualTo("standalone")); + Assert.That(root.GetProperty("theme_color").GetString(), Is.EqualTo("#123456")); + Assert.That(root.GetProperty("background_color").GetString(), Is.EqualTo("#123456")); + Assert.That(icons.Select(icon => icon.GetProperty("src").GetString()), Is.EqualTo(new[] { "icon-192.png", "icons/icon-512.png" })); + Assert.That(icons.Select(icon => icon.GetProperty("sizes").GetString()), Is.EqualTo(new[] { "192x192", "512x512" })); + Assert.That(icons[0].TryGetProperty("purpose", out _), Is.False); + Assert.That(icons[1].GetProperty("purpose").GetString(), Is.EqualTo("any maskable")); + }); + } + string serviceWorker = File.ReadAllText(Path.Combine(wwwroot, "service-worker.js")); + string assetsList = File.ReadAllText(Path.Combine(wwwroot, "service-worker-assets.js")); + Assert.Multiple(() => + { + Assert.That(File.Exists(Path.Combine(wwwroot, "icon-192.png")), Is.True); + Assert.That(File.Exists(Path.Combine(wwwroot, "icons", "icon-512.png")), Is.True); + Assert.That(File.ReadAllText(Path.Combine(wwwroot, "index.html")), + Does.Contain("\n \n").And.Contain(" + { + Assert.That(Directory.GetFiles(wwwroot, "service-worker*"), Is.Empty); + Assert.That(File.Exists(Path.Combine(wwwroot, "manifest.webmanifest")), Is.True); + Assert.That(File.ReadAllText(Path.Combine(wwwroot, "_framework", "dotnet.js")), Does.Match(@"""serviceWorker"":\s*false")); + }); + } + + // Under a base path the SDK writes the prefix in front of every URL of the assets list, the runtime's included, which the worker + // strips, and publishes the worker beneath it, where the deletion looks. + [Test] + public async Task BrowserPublishUnderABasePathListsItAndDeletesTheWorkerThere() + { + string consumerDirectory = GetConsumerDirectory("BrowserContentConsumer"); + DeleteConsumerOutputs("BrowserContentConsumer"); + + await PublishConsumerAsync(consumerDirectory, "browser-wasm", properties: ["StaticWebAssetBasePath=app", "PixelyBrowserOffline=true"]); + string appRoot = Path.Combine(GetPublishedWwwroot(consumerDirectory), "app"); + Assert.Multiple(() => + { + Assert.That(File.Exists(Path.Combine(appRoot, "service-worker.js")), Is.True); + Assert.That(File.ReadAllText(Path.Combine(appRoot, "service-worker-assets.js")), Does.Contain("\"app/Content.pk3\"").And.Contain("\"app/_framework/dotnet.js\"")); + }); + + await PublishConsumerAsync(consumerDirectory, "browser-wasm", properties: ["StaticWebAssetBasePath=app"]); + Assert.That(Directory.GetFiles(appRoot, "service-worker*"), Is.Empty); + } + + // A build has no assets list and no worker, which is what retires a worker an earlier publish left on the same origin. + [Test] + public async Task BrowserBuildWithOfflineServesNoWorker() + { + string consumerDirectory = GetConsumerDirectory("BrowserContentConsumer"); + DeleteConsumerOutputs("BrowserContentConsumer"); + + await BuildConsumerAsync(consumerDirectory, runtimeIdentifier: "browser-wasm", properties: ["PixelyBrowserOffline=true"]); + Assert.That(File.ReadAllText(Path.Combine(GetBrowserIntermediateDirectory(consumerDirectory), "staticwebassets.build.json")), Does.Not.Contain("service-worker")); + } + + [Test] + public async Task BrowserBuildOfAnInstallableAppWithoutBothIconsFailsWithPixely0016() + { + string consumerDirectory = GetConsumerDirectory("BrowserContentConsumer"); + DeleteConsumerOutputs("BrowserContentConsumer"); + + string output = await BuildConsumerAsync(consumerDirectory, runtimeIdentifier: "browser-wasm", expectSuccess: false, properties: ["PixelyBrowserInstallable=true"]); + Assert.That(output, Does.Contain("error PIXELY0016").And.Contain("192x192 and 512x512")); + } + // On the desktop the item is inert and the loader finds the Content directory through the project tree. [Test] public async Task DesktopBuildIgnoresPixelyBrowserVfsFile() diff --git a/tutorials/Pixely.Tutorials.AfterSdk.targets b/tutorials/Pixely.Tutorials.AfterSdk.targets index 3121c35b..2dc412f3 100644 --- a/tutorials/Pixely.Tutorials.AfterSdk.targets +++ b/tutorials/Pixely.Tutorials.AfterSdk.targets @@ -1,5 +1,6 @@ + From 2fadc0144355ff9afce1c8df528326c591ce9da3 Mon Sep 17 00:00:00 2001 From: botoddly <250804054+botoddly@users.noreply.github.com> Date: Wed, 18 Nov 2026 22:58:35 +0100 Subject: [PATCH 2/4] Serve icons beside a project's own manifest and handle quotes in browser asset, icon and page paths --- DECISIONS.md | 4 +- docs/hosting.md | 6 +- packaging/Pixely/Sdk/Pixely.Browser.targets | 161 ++++++++++-------- .../BrowserContentConsumer.csproj | 4 + .../PackageIntegrationTests.cs | 34 ++++ 5 files changed, 132 insertions(+), 77 deletions(-) diff --git a/DECISIONS.md b/DECISIONS.md index cdd14f72..335d6787 100644 --- a/DECISIONS.md +++ b/DECISIONS.md @@ -10,9 +10,9 @@ Design decisions with the constraints that decided them and their known costs, n - The two properties are separate because Chrome installs an app from its menu without a worker, while the worker delays every update to the launch after the one that found it. - A browser keeps a registered worker when its script answers 404, so a publish without the worker cannot remove it. The worker therefore checks its list whenever it serves the page from its cache, and unregisters itself on a 4xx other than 408 and 429 or on an HTML page. That covers a later publish without the property and a build served on the same origin, and needs no retiring worker or publish mode. `dotnet publish` deletes no files, so a publish deletes the two worker files unless they are its own assets. - Every site on an origin shares Cache Storage and scopes nest, as on one GitHub Pages account, so caches are named by scope and compared exactly. -- WriteLinesToFile turns backslashes into slashes on Unix, so the manifest and the page are written by inline tasks. +- WriteLinesToFile turns backslashes into slashes on Unix, and a quote in a path ends a property function's argument, so an inline task resolves the icons and writes the manifest and the page. -Cost: the first visit with `PixelyBrowserBrotli` downloads the Brotli-loaded files twice, and updates download changed ones without Brotli, because the list has no `.br` copies and the worker no decoder. A deploy that loses the list, or a passing 4xx, retires offline play until the next launch with a network. A project's own `main.js` registers the worker itself, and nothing warns when it does not. The worker's behaviour in a browser is tested by hand with `tests/Pixely.Browser.Harness`, not in CI. The inline tasks compile with Roslyn on their first use in a build. +Cost: the first visit with `PixelyBrowserBrotli` downloads the Brotli-loaded files twice, and updates download changed ones without Brotli, because the list has no `.br` copies and the worker no decoder. A deploy that loses the list, or a passing 4xx, retires offline play until the next launch with a network. A project's own `main.js` registers the worker itself, and nothing warns when it does not. The worker's behaviour in a browser is tested by hand with `tests/Pixely.Browser.Harness`, not in CI. The inline task compiles with Roslyn on its first use in a build. ## 2026-11-14: A test app never starts SDL, so tests run in parallel diff --git a/docs/hosting.md b/docs/hosting.md index cb5582c0..e9f5c386 100644 --- a/docs/hosting.md +++ b/docs/hosting.md @@ -472,9 +472,9 @@ window of its own and an entry in the launcher or on the home screen: - The package's `index.html` gets `` and `` before ``. A project's own `wwwroot/index.html` or a page named by `PixelyBrowserIndexHtml` adds both itself. -- A project's own `wwwroot/manifest.webmanifest` replaces the generated one; the icon check is then - the project's own. `PixelyBrowserDefaultAssets=false` turns off the generated manifest with the - rest of the page. +- A project's own `wwwroot/manifest.webmanifest` replaces the generated one. Its icons are still + served, and the icon check is then the project's own. `PixelyBrowserDefaultAssets=false` turns off the generated manifest, the + served icons and the tags with the rest of the page, since Pixely then adds no web asset. A browser installs only a page from a secure context, which WebGPU needs anyway. An installed app still needs the network unless `PixelyBrowserOffline` is on as well. diff --git a/packaging/Pixely/Sdk/Pixely.Browser.targets b/packaging/Pixely/Sdk/Pixely.Browser.targets index 41cf9dc9..c7121bdd 100644 --- a/packaging/Pixely/Sdk/Pixely.Browser.targets +++ b/packaging/Pixely/Sdk/Pixely.Browser.targets @@ -154,35 +154,36 @@ - + - - + + + + + + + + + - - - - - - - - - - - icons = new System.Collections.Generic.List(); - foreach (Microsoft.Build.Framework.ITaskItem icon in Icons) + string wwwroot = System.IO.Path.GetFullPath(Wwwroot).TrimEnd(System.IO.Path.DirectorySeparatorChar) + System.IO.Path.DirectorySeparatorChar; + System.Collections.Generic.List resolved = new System.Collections.Generic.List(); + foreach (Microsoft.Build.Framework.ITaskItem icon in Icons ?? new Microsoft.Build.Framework.ITaskItem[0]) + { + Microsoft.Build.Utilities.TaskItem item = new Microsoft.Build.Utilities.TaskItem(icon); + string fullPath = System.IO.Path.GetFullPath(icon.GetMetadata("FullPath")); + bool inWwwroot = fullPath.StartsWith(wwwroot, System.StringComparison.Ordinal); + string relativeToWwwroot = inWwwroot ? fullPath.Substring(wwwroot.Length) : ""; + string targetPath = icon.GetMetadata("TargetPath"); + if (targetPath.Length == 0) + { + targetPath = icon.GetMetadata("Filename") + icon.GetMetadata("Extension"); + } + item.SetMetadata("Src", (inWwwroot ? relativeToWwwroot : targetPath).Replace('\\', '/')); + item.SetMetadata("InWwwroot", inWwwroot ? "true" : "false"); + item.SetMetadata("RelativePath", targetPath); + resolved.Add(item); + } + ResolvedIcons = resolved.ToArray(); + + if (!string.IsNullOrEmpty(ManifestFile)) + { + System.Collections.Generic.List icons = new System.Collections.Generic.List(); + foreach (Microsoft.Build.Framework.ITaskItem icon in resolved) + { + string purpose = icon.GetMetadata("Purpose"); + string purposeMember = purpose.Length > 0 ? ", \"purpose\": " + Quote(purpose) : ""; + icons.Add(" { \"src\": " + Quote(icon.GetMetadata("Src")) + ", \"sizes\": " + Quote(icon.GetMetadata("Sizes")) + purposeMember + " }"); + } + WriteIfChanged(ManifestFile, "{\n" + + " \"name\": " + Quote(Name) + ",\n" + + " \"start_url\": \"./\",\n" + + " \"display\": \"standalone\",\n" + + " \"background_color\": " + Quote(ThemeColor) + ",\n" + + " \"theme_color\": " + Quote(ThemeColor) + ",\n" + + " \"icons\": [\n" + string.Join(",\n", icons) + "\n ]\n" + + "}\n"); + } + + // The package's page ends its head with a line of its own, so the two tags go in before it. + if (System.IO.Path.GetFullPath(Page) == System.IO.Path.GetFullPath(PackagePage)) { - string purpose = icon.GetMetadata("Purpose"); - string purposeMember = purpose.Length > 0 ? ", \"purpose\": " + Quote(purpose) : ""; - icons.Add(" { \"src\": " + Quote(icon.GetMetadata("Src")) + ", \"sizes\": " + Quote(icon.GetMetadata("Sizes")) + purposeMember + " }"); + string color = System.Net.WebUtility.HtmlEncode(ThemeColor); + string head = " \n \n"; + WriteIfChanged(PageFile, System.IO.File.ReadAllText(PackagePage).Replace("", head)); + Page = PageFile; } - Text = "{\n" - + " \"name\": " + Quote(Name) + ",\n" - + " \"start_url\": \"./\",\n" - + " \"display\": \"standalone\",\n" - + " \"background_color\": " + Quote(ThemeColor) + ",\n" - + " \"theme_color\": " + Quote(ThemeColor) + ",\n" - + " \"icons\": [\n" + string.Join(",\n", icons) + "\n ]\n" - + "}\n"; ]]> @@ -226,10 +259,9 @@ @@ -239,45 +271,27 @@ <_PixelyBrowserAppName Condition="'$(PixelyBrowserAppName.Length)' == '0'">$(Product) <_PixelyBrowserThemeColor>$(PixelyBrowserThemeColor) <_PixelyBrowserThemeColor Condition="'$(PixelyBrowserThemeColor.Length)' == '0'">#000 - <_PixelyBrowserThemeColorHtml>$(_PixelyBrowserThemeColor.Replace('&', '&amp;').Replace('"', '&quot;').Replace(`'`, '&#39;').Replace('<', '&lt;')) <_PixelyBrowserOwnManifest>false <_PixelyBrowserOwnManifest Condition="Exists('$(_PixelyBrowserWwwroot)manifest.webmanifest')">true + <_PixelyBrowserManifestFile Condition="'$(_PixelyBrowserOwnManifest)' != 'true'">$(_PixelyBrowserGeneratedRoot)manifest.webmanifest - - <_PixelyBrowserAppIcon Include="@(PixelyBrowserAppIcon->'%(FullPath)')" /> - <_PixelyBrowserAppIcon Update="@(_PixelyBrowserAppIcon)" Condition="'%(_PixelyBrowserAppIcon.TargetPath)' == ''" TargetPath="%(Filename)%(Extension)" /> - <_PixelyBrowserAppIcon Update="@(_PixelyBrowserAppIcon)" Src="$([System.String]::Copy('%(TargetPath)').Replace('\', '/'))" /> - <_PixelyBrowserAppIcon Update="@(_PixelyBrowserAppIcon)" Condition="$([System.String]::Copy('%(_PixelyBrowserAppIcon.FullPath)').StartsWith('$(_PixelyBrowserWwwroot)'))" - Src="$([MSBuild]::MakeRelative('$(_PixelyBrowserWwwroot)', '%(FullPath)').Replace('\', '/'))" InWwwroot="true" /> - - <_PixelyBrowserAppIconSizes>|@(_PixelyBrowserAppIcon->'%(Sizes)', '|')| + <_PixelyBrowserAppIconSizes>|@(PixelyBrowserAppIcon->'%(Sizes)', '|')| <_PixelyBrowserAppIconSizes>$(_PixelyBrowserAppIconSizes.Replace(' ', '|').ToLowerInvariant()) - <_PixelyFormatWebAppManifest Name="$(_PixelyBrowserAppName)" ThemeColor="$(_PixelyBrowserThemeColor)" Icons="@(_PixelyBrowserAppIcon)" Condition="'$(_PixelyBrowserOwnManifest)' != 'true'"> - - - <_PixelyWriteTextFile File="$(_PixelyBrowserGeneratedRoot)manifest.webmanifest" Text="$(_PixelyBrowserManifest)" Condition="'$(_PixelyBrowserOwnManifest)' != 'true'" /> - - <_PixelyBrowserInstallableAssetSource Include="$(_PixelyBrowserGeneratedRoot)manifest.webmanifest" RelativePath="manifest.webmanifest" /> - <_PixelyBrowserInstallableAssetSource Include="@(_PixelyBrowserAppIcon)" Condition="'%(_PixelyBrowserAppIcon.InWwwroot)' != 'true'" RelativePath="%(_PixelyBrowserAppIcon.TargetPath)" /> - - - - - <_PixelyBrowserInstallableHead> <link rel="manifest" href="manifest.webmanifest" /> - <meta name="theme-color" content="$(_PixelyBrowserThemeColorHtml)" /> -</head> - <_PixelyBrowserIndexHtmlSource>$(_PixelyBrowserGeneratedRoot)index.html - - <_PixelyWriteTextFile File="$(_PixelyBrowserIndexHtmlSource)" Text="$([System.IO.File]::ReadAllText('$(_PixelyBrowserPackageIndexHtml)').Replace('</head>', '$(_PixelyBrowserInstallableHead)'))" - Condition="'$(PixelyBrowserIndexHtml)' == '$(_PixelyBrowserPackageIndexHtml)'" /> - - + <_PixelyWriteInstallableAssets Icons="@(PixelyBrowserAppIcon)" Wwwroot="$(_PixelyBrowserWwwroot)" Name="$(_PixelyBrowserAppName)" ThemeColor="$(_PixelyBrowserThemeColor)" + ManifestFile="$(_PixelyBrowserManifestFile)" PackagePage="$(_PixelyBrowserPackageIndexHtml)" PageFile="$(_PixelyBrowserGeneratedRoot)index.html" Page="$(PixelyBrowserIndexHtml)"> + + + + + <_PixelyBrowserInstallableAssetSource Include="$(_PixelyBrowserManifestFile)" RelativePath="manifest.webmanifest" Condition="'$(_PixelyBrowserManifestFile.Length)' != '0'" /> + <_PixelyBrowserInstallableAssetSource Include="@(_PixelyBrowserAppIcon->WithMetadataValue('InWwwroot', 'false'))" /> + @@ -291,7 +305,7 @@ DependsOnTargets="_PixelyGenerateBrowserInstallableAssets" Condition="'$(_PixelyBrowser)' == 'true' and '$(PixelyBrowserDefaultAssets)' == 'true'"> <_PixelyBrowserAssetsRoot>$([MSBuild]::NormalizeDirectory('$(MSBuildProjectDirectory)', '$(IntermediateOutputPath)', 'pixely-browser')) - <_PixelyBrowserIndexHtmlSource Condition="'$(_PixelyBrowserIndexHtmlSource)' == ''">$(PixelyBrowserIndexHtml) + <_PixelyBrowserIndexHtmlSource Condition="'$(_PixelyBrowserIndexHtmlSource.Length)' == '0'">$(PixelyBrowserIndexHtml) <_PixelyBrowserDefaultAssetSource Include="$(_PixelyBrowserIndexHtmlSource)" RelativePath="index.html" /> @@ -357,10 +371,13 @@ <_PixelyBrowserServiceWorkerFileName Include="service-worker.js;service-worker-assets.js" /> - <_PixelyBrowserStaleServiceWorkerFile Include="@(_PixelyBrowserServiceWorkerFileName->'$(_PixelyBrowserPublishRoot)%(Identity)')" /> - <_PixelyBrowserStaleServiceWorkerFile Include="@(_PixelyBrowserServiceWorkerFileName->'$(_PixelyBrowserPublishRoot)%(Identity).br')" /> - <_PixelyBrowserStaleServiceWorkerFile Include="@(_PixelyBrowserServiceWorkerFileName->'$(_PixelyBrowserPublishRoot)%(Identity).gz')" /> - <_PixelyBrowserPublishedFile Include="$([System.IO.Path]::GetFullPath('$(_PixelyBrowserPublishDir)%(_PublishStaticWebAssetsTargetPath.TargetPath)'))" /> + <_PixelyBrowserServiceWorkerFile Include="@(_PixelyBrowserServiceWorkerFileName->'$(_PixelyBrowserPublishRoot)%(Identity)')" /> + <_PixelyBrowserServiceWorkerFile Include="@(_PixelyBrowserServiceWorkerFileName->'$(_PixelyBrowserPublishRoot)%(Identity).br')" /> + <_PixelyBrowserServiceWorkerFile Include="@(_PixelyBrowserServiceWorkerFileName->'$(_PixelyBrowserPublishRoot)%(Identity).gz')" /> + + <_PixelyBrowserStaleServiceWorkerFile Include="@(_PixelyBrowserServiceWorkerFile->'%(FullPath)')" /> + <_PixelyBrowserPublishedFileSpec Include="$(_PixelyBrowserPublishDir)%(_PublishStaticWebAssetsTargetPath.TargetPath)" /> + <_PixelyBrowserPublishedFile Include="@(_PixelyBrowserPublishedFileSpec->'%(FullPath)')" /> <_PixelyBrowserStaleServiceWorkerFile Remove="@(_PixelyBrowserPublishedFile)" /> diff --git a/tests/Pixely.Package.Tests/Consumers/BrowserContentConsumer/BrowserContentConsumer.csproj b/tests/Pixely.Package.Tests/Consumers/BrowserContentConsumer/BrowserContentConsumer.csproj index 9087dd9f..7202c471 100644 --- a/tests/Pixely.Package.Tests/Consumers/BrowserContentConsumer/BrowserContentConsumer.csproj +++ b/tests/Pixely.Package.Tests/Consumers/BrowserContentConsumer/BrowserContentConsumer.csproj @@ -33,6 +33,10 @@ + + + + diff --git a/tests/Pixely.Package.Tests/PackageIntegrationTests.cs b/tests/Pixely.Package.Tests/PackageIntegrationTests.cs index da8b799e..0eb435eb 100644 --- a/tests/Pixely.Package.Tests/PackageIntegrationTests.cs +++ b/tests/Pixely.Package.Tests/PackageIntegrationTests.cs @@ -1225,6 +1225,40 @@ public async Task BrowserPublishUnderABasePathListsItAndDeletesTheWorkerThere() Assert.That(Directory.GetFiles(appRoot, "service-worker*"), Is.Empty); } + // A project's own manifest replaces the generated one, and the icons it names are still served. A quote in an icon's path passes + // through the icons, and one in a static web asset's path through the deletion of a stale worker, which every browser publish runs. + [Test] + public async Task BrowserPublishWithAnOwnManifestServesTheIcons() + { + string consumerDirectory = GetConsumerDirectory("BrowserContentConsumer"); + DeleteConsumerOutputs("BrowserContentConsumer"); + string consumerWwwroot = Path.Combine(consumerDirectory, "wwwroot"); + string quotedIcon = Path.Combine(consumerDirectory, "Extras", "it's.png"); + Directory.CreateDirectory(consumerWwwroot); + try + { + File.WriteAllText(Path.Combine(consumerWwwroot, "manifest.webmanifest"), "{ \"name\": \"Own\" }\n"); + File.WriteAllText(Path.Combine(consumerWwwroot, "it's.txt"), "quoted\n"); + File.Copy(Path.Combine(consumerDirectory, "Extras", "icon-192.png"), quotedIcon, overwrite: true); + + await PublishConsumerAsync(consumerDirectory, "browser-wasm", properties: ["PixelyBrowserInstallable=true", "BrowserContentConsumerIcons=true", "BrowserContentConsumerQuotedIcon=true"]); + string wwwroot = GetPublishedWwwroot(consumerDirectory); + Assert.Multiple(() => + { + Assert.That(File.ReadAllText(Path.Combine(wwwroot, "manifest.webmanifest")), Does.Contain("\"Own\"")); + Assert.That(File.Exists(Path.Combine(wwwroot, "icon-192.png")), Is.True); + Assert.That(File.Exists(Path.Combine(wwwroot, "icons", "icon-512.png")), Is.True); + Assert.That(File.Exists(Path.Combine(wwwroot, "it's.txt")), Is.True); + Assert.That(File.Exists(Path.Combine(wwwroot, "it's.png")), Is.True); + }); + } + finally + { + DeleteDirectory(consumerWwwroot); + File.Delete(quotedIcon); + } + } + // A build has no assets list and no worker, which is what retires a worker an earlier publish left on the same origin. [Test] public async Task BrowserBuildWithOfflineServesNoWorker() From 0307f2556cb9af8c4ac48e9157c0f3bc5924222d Mon Sep 17 00:00:00 2001 From: botoddly <250804054+botoddly@users.noreply.github.com> Date: Thu, 19 Nov 2026 20:38:02 +0100 Subject: [PATCH 3/4] Drop offline play from browser publishes and keep them installable online --- AGENTS.md | 2 +- DECISIONS.md | 11 +- docs/hosting.md | 64 +------- docs/sdk.md | 5 +- packaging/Pixely/Sdk/Pixely.AfterSdk.targets | 2 - packaging/Pixely/Sdk/Pixely.Browser.targets | 36 +---- .../Pixely/Sdk/Pixely.BrowserOffline.targets | 17 -- packaging/Pixely/wwwroot/main.js | 23 +-- packaging/Pixely/wwwroot/pixely-host.js | 11 +- packaging/Pixely/wwwroot/service-worker.js | 146 ------------------ tests/Pixely.Browser.Harness/README.md | 6 - tests/Pixely.Browser.Harness/run-offline.js | 142 ----------------- .../PackageIntegrationTests.cs | 58 +------ tutorials/Pixely.Tutorials.AfterSdk.targets | 1 - 14 files changed, 19 insertions(+), 505 deletions(-) delete mode 100644 packaging/Pixely/Sdk/Pixely.BrowserOffline.targets delete mode 100644 packaging/Pixely/wwwroot/service-worker.js delete mode 100644 tests/Pixely.Browser.Harness/run-offline.js diff --git a/AGENTS.md b/AGENTS.md index be1ca616..21a5f4ae 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -19,7 +19,7 @@ - `docs/path-finding-grids.md` - Pixely.PathFinding.Grids: grid geometry, clearance-based agent footprints, connectivity and the corner rule, overlays, the admissible grid heuristic - `docs/development-packages.md` - Consuming packages from the public development feed - `docs/sdk.md` - Pixely as an MSBuild project SDK: the `` line, what it adds to a project, the browser build and its framework switch, central package management, the PIXELY0002 error for projects without it, the package layout with its two `lib/` folders -- `docs/hosting.md` - Hosting: opting in with `PixelyHosting`, the generated `Main`, `Configure` and `OnException` with its default message box in Release builds, diagnostics, the browser: `dotnet publish -r browser-wasm`, the `net11.0-browser` framework switch and its lateness, multi-targeting with `-f net11.0-browser`, `BrowserHost` and the frame loop, exit codes, the default page and its replacement, Mono AOT on by default (`RunAOTCompilation`), its opt-out and what IL stripping leaves readable, opt-in Brotli downloads with `PixelyBrowserBrotli` through the boot config for hosts without `Content-Encoding: br` such as GitHub Pages, an installable app with `PixelyBrowserInstallable`, the generated web app manifest, its icons and PIXELY0016, offline play with `PixelyBrowserOffline` through the .NET SDK's service worker targets, the worker registered after the first frame, caches named by scope, its retirement when the assets list is gone and the deletion of a stale worker, XDL linked into the browser runtime from `XdlSharp.Native.browser-wasm` with the workload and `WasmBuildNative`, the formats XDL's satellites decode, native archives from a URL with `NativeUrlReference`, WebGPU in the browser: device adoption through `BrowserHost.PrepareAsync`, the fallback adapter warning, notice, `pixelygpuadapter` event and `readGpuAdapter()`, device loss and `GpuDeviceLostException`, the default page's loading indicator and stop message, the `pixelyfirstframe` event, teardown, what is unsupported +- `docs/hosting.md` - Hosting: opting in with `PixelyHosting`, the generated `Main`, `Configure` and `OnException` with its default message box in Release builds, diagnostics, the browser: `dotnet publish -r browser-wasm`, the `net11.0-browser` framework switch and its lateness, multi-targeting with `-f net11.0-browser`, `BrowserHost` and the frame loop, exit codes, the default page and its replacement, Mono AOT on by default (`RunAOTCompilation`), its opt-out and what IL stripping leaves readable, opt-in Brotli downloads with `PixelyBrowserBrotli` through the boot config for hosts without `Content-Encoding: br` such as GitHub Pages, an installable app with `PixelyBrowserInstallable`, the generated web app manifest, its icons and PIXELY0016, XDL linked into the browser runtime from `XdlSharp.Native.browser-wasm` with the workload and `WasmBuildNative`, the formats XDL's satellites decode, native archives from a URL with `NativeUrlReference`, WebGPU in the browser: device adoption through `BrowserHost.PrepareAsync`, the fallback adapter warning, notice, `pixelygpuadapter` event and `readGpuAdapter()`, device loss and `GpuDeviceLostException`, the default page's loading indicator and stop message, the `pixelyfirstframe` event, teardown, what is unsupported - `docs/cursors.md` - Mouse cursors through `ICursorService`: system, image and animated cursors, the hotspot, frame durations, setting, resetting and hiding the cursor, cursor lifetime and the main-thread rule, platform behavior of animated cursors, headless mode - `docs/platform-settings.md` - The user's OS or browser settings through `IPlatformSettings`: the main-thread rule, the light or dark theme with `ThemeChanged`, where SDL reads it on each platform, `Unknown` without an XDG portal and in headless mode; preferred locales with `Locale` for games that set `InvariantGlobalization`, why `CultureInfo` cannot tell them there, unvalidated codes, Linux ordering, the 127-byte limit, the `SDL_HINT_PREFERRED_LOCALES` override and its environment variable, skipped empty items, `PreferredLocalesChanged` and the platforms where SDL reports changes - `docs/taskbar-icons.md` - Application-wide taskbar and Dock icons loaded from virtual content diff --git a/DECISIONS.md b/DECISIONS.md index 335d6787..e1c48e96 100644 --- a/DECISIONS.md +++ b/DECISIONS.md @@ -2,17 +2,14 @@ Design decisions with the constraints that decided them and their known costs, newest first. -## 2026-11-18: Offline play reuses the .NET SDK's service worker targets, and the worker retires itself +## 2026-11-18: An installable browser app gets a generated manifest and no service worker -`PixelyBrowserInstallable` generates a web app manifest and `PixelyBrowserOffline` publishes a service worker (`docs/hosting.md`). The worker is declared as the .NET SDK's `ServiceWorker` item, and its list of files is the SDK's `service-worker-assets.js`, with each file's SHA-256. +`PixelyBrowserInstallable` generates a web app manifest (`docs/hosting.md`). A publish has no service worker, so an installed game still needs the network to start. -- The static web assets SDK already lists every published file with its hash, compressed copies excepted, with the URLs the boot config requests. Pixely's own generator would repeat it. -- The two properties are separate because Chrome installs an app from its menu without a worker, while the worker delays every update to the launch after the one that found it. -- A browser keeps a registered worker when its script answers 404, so a publish without the worker cannot remove it. The worker therefore checks its list whenever it serves the page from its cache, and unregisters itself on a 4xx other than 408 and 429 or on an HTML page. That covers a later publish without the property and a build served on the same origin, and needs no retiring worker or publish mode. `dotnet publish` deletes no files, so a publish deletes the two worker files unless they are its own assets. -- Every site on an origin shares Cache Storage and scopes nest, as on one GitHub Pages account, so caches are named by scope and compared exactly. +- Chrome installs an app from its menu without a worker. - WriteLinesToFile turns backslashes into slashes on Unix, and a quote in a path ends a property function's argument, so an inline task resolves the icons and writes the manifest and the page. -Cost: the first visit with `PixelyBrowserBrotli` downloads the Brotli-loaded files twice, and updates download changed ones without Brotli, because the list has no `.br` copies and the worker no decoder. A deploy that loses the list, or a passing 4xx, retires offline play until the next launch with a network. A project's own `main.js` registers the worker itself, and nothing warns when it does not. The worker's behaviour in a browser is tested by hand with `tests/Pixely.Browser.Harness`, not in CI. The inline task compiles with Roslyn on its first use in a build. +Cost: the inline task compiles with Roslyn on its first use in a build. ## 2026-11-14: A test app never starts SDL, so tests run in parallel diff --git a/docs/hosting.md b/docs/hosting.md index e9f5c386..56fbbf21 100644 --- a/docs/hosting.md +++ b/docs/hosting.md @@ -440,9 +440,6 @@ content. Leave the property off on a host that sends `Content-Encoding: br` itself. The download is the same size, and Chrome compiles `dotnet.native.wasm` while it downloads instead of decoding it afterwards. -While the offline worker of `PixelyBrowserOffline` controls the page, the loader stays off: the -worker answers from its cache, which holds no `.br` copies (see [Offline play](#offline-play)). - ### Installable app `PixelyBrowserInstallable=true` makes the published page a web app that a browser can install, as a @@ -477,63 +474,4 @@ window of its own and an entry in the launcher or on the home screen: served icons and the tags with the rest of the page, since Pixely then adds no web asset. A browser installs only a page from a secure context, which WebGPU needs anyway. An installed app -still needs the network unless `PixelyBrowserOffline` is on as well. - -### Offline play - -`PixelyBrowserOffline=true` makes a publish keep every file of the game in the browser, so the game -starts without a network after one visit: - -1. The publish adds `service-worker.js`, a service worker (a script the browser runs beside the - page, which can answer the page's requests). It also adds `service-worker-assets.js`, the .NET - SDK's list of every published file with its SHA-256, compressed copies excepted. Pixely uses the - .NET SDK's own service worker targets, which it turns on with `ServiceWorkerAssetsManifest`. -2. The boot config gets `"serviceWorker": true` in `extensions.pixely`. The default `main.js` - registers the worker after the first frame, so its downloads do not compete with the game's and - mostly come from the HTTP cache the game has just filled. A build has no extension and serves no - worker. -3. The worker downloads every listed file, `Content.pk3` included, and checks each against its - hash. A file an earlier version cached with the same hash is copied, not downloaded again. -4. From the next visit on, the worker answers the page and every listed file from its cache. It - answers only the page at its own folder, `index.html` or the folder itself, so a worker at the - root of an origin leaves the pages of other sites there alone. -5. A new publish gives the list new hashes. The browser installs the new worker in the background, - and it takes over when every page of the old one has closed, so players get an update on the - launch after the one that found it. - -To turn offline play off, publish without the property. Each time the worker answers the page from -its cache, it also requests `service-worker-assets.js`. When the server answers a 4xx other than 408 -and 429, or answers with an HTML page as a server that falls back to `index.html` does, the worker -unregisters itself, loads that page again from the network and deletes its caches. Other open -pages carry on until their next navigation. A 5xx or no network leaves the worker in place. A build -served on the same origin, such as `dotnet run` on `localhost`, has no list either, so it retires a -worker an earlier publish left there. `dotnet publish` deletes no file from the publish folder, so a -publish without the property deletes the two files and their compressed copies from it. - -- Caches are named `pixely||`, where the version is a hash of the list and the scope - the worker's folder. The worker deletes only caches of its own scope, compared exactly, so games - on one origin, such as the project sites of one GitHub Pages account, keep their caches. -- Under `StaticWebAssetBasePath` the SDK writes the base path in front of every URL in the list, while - the worker is served beneath it. The worker strips the path in front of `_framework/dotnet.js`, - which every publish lists. -- A project's own `wwwroot/service-worker.js` replaces the package's, in a publish and in a build, - where the SDK serves it with a build list. -- A project's own `main.js` registers the worker itself when `extensions.pixely.serviceWorker` is - true, which `onConfigLoaded` hands it: - - ```js - navigator.serviceWorker?.register('service-worker.js', { updateViaCache: 'none' }); - ``` - - `updateViaCache: 'none'` makes the browser's update check bypass the HTTP cache for the list as - well as the worker. GitHub Pages lets caches keep files for 10 minutes, so without it a new worker - can install the old list. -- With `PixelyBrowserBrotli`, the first visit downloads the Brotli-loaded files twice, once for the - page and once uncompressed for the worker, and updates download changed ones uncompressed or with - the host's gzip. The list has no `.br` copies, and the worker has no Brotli decoder. -- A wrongly retired worker, after a deploy that lost the list or a passing 4xx, comes back on the - next launch with a network. -- Service workers exist only in a secure context; elsewhere the game runs online only. - -The worker's behaviour in a browser is tested by hand with `run-offline.js` in -`tests/Pixely.Browser.Harness`. +still needs the network to start. diff --git a/docs/sdk.md b/docs/sdk.md index 9a518d50..2c2b0c05 100644 --- a/docs/sdk.md +++ b/docs/sdk.md @@ -63,15 +63,14 @@ lib/net11.0-browser1.0/ the library, the browser build of analyzers/dotnet/cs/ the dependency-injection and ECS generators Sdk/Sdk.props, Sdk/Sdk.targets imported by the SDK resolver Sdk/Pixely.AfterSdk.targets WebAssembly, shader and hosting targets, imported once the base SDK has set its properties -Sdk/Pixely.BrowserOffline.targets the offline worker of PixelyBrowserOffline, imported before the WebAssembly targets Sdk/Pixely.Hosting.targets the entry point generator Sdk/Pixely.Browser.props imports the WebAssembly SDK props on browser-wasm -Sdk/Pixely.Browser.targets the framework switch, browser property overrides, XDL's link settings, native URL references, PIXELY0004 to PIXELY0012 and PIXELY0016, the default web assets, the web app manifest, the boot config extension, the deletion of a stale offline worker, the browser file system +Sdk/Pixely.Browser.targets the framework switch, browser property overrides, XDL's link settings, native URL references, PIXELY0004 to PIXELY0012 and PIXELY0016, the default web assets, the web app manifest, the Brotli boot config extension, the browser file system Sdk/Pixely.Native.targets the XdlSharp.Native. reference, PIXELY0014 and PIXELY0015 Sdk/Pixely.Version.props the package version and the XdlSharp version, generated at pack time buildTransitive/Pixely.targets fails a project that reaches Pixely without the SDK tools/net11.0/any/ the shader compilation task and its props and targets -wwwroot/ index.html, main.js, pixely-host.js and service-worker.js for the browser +wwwroot/ index.html, main.js and pixely-host.js for the browser docs/ this documentation ``` diff --git a/packaging/Pixely/Sdk/Pixely.AfterSdk.targets b/packaging/Pixely/Sdk/Pixely.AfterSdk.targets index 95551b35..45730d4e 100644 --- a/packaging/Pixely/Sdk/Pixely.AfterSdk.targets +++ b/packaging/Pixely/Sdk/Pixely.AfterSdk.targets @@ -1,6 +1,4 @@ - - @@ -346,43 +345,16 @@ <_PixelyPublishWritesBrotli Condition="'$(CompressionEnabled)' == 'true' and '$(_PixelyPublishCompressionFormats.Contains(`;brotli;`))' == 'true'">true <_PixelyBrowserBrotli>false <_PixelyBrowserBrotli Condition="'$(PixelyBrowserBrotli)' == 'true' and '$(_PixelyPublishWritesBrotli)' == 'true'">true - <_PixelyBrowserServiceWorker>false - <_PixelyBrowserServiceWorker Condition="'$(PixelyBrowserOffline)' == 'true'">true - + - - - - <_PixelyBrowserPublishDir>$([MSBuild]::NormalizeDirectory('$(MSBuildProjectDirectory)', '$(PublishDir)')) - <_PixelyBrowserPublishRoot>$([MSBuild]::NormalizeDirectory('$(_PixelyBrowserPublishDir)', 'wwwroot', '$(StaticWebAssetBasePath.Replace(`\`, `/`).Trim(`/`))')) - - - <_PixelyBrowserServiceWorkerFileName Include="service-worker.js;service-worker-assets.js" /> - <_PixelyBrowserServiceWorkerFile Include="@(_PixelyBrowserServiceWorkerFileName->'$(_PixelyBrowserPublishRoot)%(Identity)')" /> - <_PixelyBrowserServiceWorkerFile Include="@(_PixelyBrowserServiceWorkerFileName->'$(_PixelyBrowserPublishRoot)%(Identity).br')" /> - <_PixelyBrowserServiceWorkerFile Include="@(_PixelyBrowserServiceWorkerFileName->'$(_PixelyBrowserPublishRoot)%(Identity).gz')" /> - - <_PixelyBrowserStaleServiceWorkerFile Include="@(_PixelyBrowserServiceWorkerFile->'%(FullPath)')" /> - <_PixelyBrowserPublishedFileSpec Include="$(_PixelyBrowserPublishDir)%(_PublishStaticWebAssetsTargetPath.TargetPath)" /> - <_PixelyBrowserPublishedFile Include="@(_PixelyBrowserPublishedFileSpec->'%(FullPath)')" /> - <_PixelyBrowserStaleServiceWorkerFile Remove="@(_PixelyBrowserPublishedFile)" /> - - - - - - service-worker-assets.js - <_PixelyBrowserOfflineWorker>$(MSBuildThisFileDirectory)..\wwwroot\service-worker.js - <_PixelyBrowserOfflineWorker Condition="Exists('$(MSBuildProjectDirectory)/wwwroot/service-worker.js')">$(MSBuildProjectDirectory)/wwwroot/service-worker.js - - - - - diff --git a/packaging/Pixely/wwwroot/main.js b/packaging/Pixely/wwwroot/main.js index 94f51067..b7b6c67e 100644 --- a/packaging/Pixely/wwwroot/main.js +++ b/packaging/Pixely/wwwroot/main.js @@ -13,25 +13,13 @@ globalThis.addEventListener('pixelygpuadapter', event => { showFallbackNotice(); } }); -// A publish with PixelyBrowserOffline puts serviceWorker in the boot config. The worker is registered after the first frame, so that -// its downloads do not compete with the game's and find most files in the HTTP cache the game has just filled. -let offline = false; -globalThis.addEventListener('pixelyfirstframe', () => { - loading.indicator.remove(); - if (offline) { - registerServiceWorker(); - } -}, { once: true }); +globalThis.addEventListener('pixelyfirstframe', () => loading.indicator.remove(), { once: true }); try { // runMain resolves with the value the managed Main returns; it rejects when Main throws, which the default OnException does. // The loader reads PixelyBrowserBrotli from the boot config that onConfigLoaded hands it, before the runtime downloads any file. // onRuntimeInitialized runs once every file the runtime needs to start is in memory. - const onConfigLoaded = config => { - offline = config.extensions?.pixely?.serviceWorker === true; - return host.configureCompressedResources?.(config); - }; - const moduleConfig = { canvas, onConfigLoaded, onRuntimeInitialized: () => { loading.stage.textContent = 'Starting…'; } }; + const moduleConfig = { canvas, onConfigLoaded: host.configureCompressedResources, onRuntimeInitialized: () => { loading.stage.textContent = 'Starting…'; } }; const exitCode = await dotnet.withModuleConfig(moduleConfig).withResourceLoader(host.loadCompressedResource).runMain(); console.log(`Pixely exited with code ${exitCode}`); if (exitCode !== 0) { @@ -66,13 +54,6 @@ function showLoading() { return { indicator, stage }; } -// The worker sits beside the page. updateViaCache 'none' makes the browser's update check also bypass the HTTP cache for the assets -// list the worker imports, which a host such as GitHub Pages lets caches keep for 10 minutes. Browsers hide serviceWorker outside a -// secure context, where the game then runs online only. -function registerServiceWorker() { - navigator.serviceWorker?.register('service-worker.js', { updateViaCache: 'none' }).catch(error => console.warn('Pixely could not register its offline worker', error)); -} - // A managed exception reaches the page with its message only, so the type comes from the record BrowserHost.ReportExceptionAsync left. function describeException() { const exception = host.readException?.(); diff --git a/packaging/Pixely/wwwroot/pixely-host.js b/packaging/Pixely/wwwroot/pixely-host.js index fcc28588..9e40988d 100644 --- a/packaging/Pixely/wwwroot/pixely-host.js +++ b/packaging/Pixely/wwwroot/pixely-host.js @@ -148,21 +148,12 @@ let brotliFetchPolicy = null; // An onConfigLoaded callback for dotnet.withModuleConfig, which runs before the runtime downloads any file. The SDK puts // PixelyBrowserBrotli in a publish's boot config as extensions.pixely.brotli; a build has no .br files and no extension. The loader // follows the config's disableIntegrityCheck and disableNoCacheFetch; it never sees a file's own cache or credentials setting. -// It stays off while the offline worker of PixelyBrowserOffline controls the page, since that worker answers from its cache and has -// no .br copies; a worker of another site on the origin can control the page too, so the check is by the worker's URL. export function configureCompressedResources(config) { - const pixely = config.extensions?.pixely; - brotliFetchPolicy = pixely?.brotli === true && !(pixely.serviceWorker === true && isControlledByOfflineWorker()) + brotliFetchPolicy = config.extensions?.pixely?.brotli === true ? { integrity: !config.disableIntegrityCheck, cache: config.disableNoCacheFetch ? undefined : 'no-cache' } : null; } -// Node has no service workers and no document. -function isControlledByOfflineWorker() { - const scriptUrl = globalThis.navigator?.serviceWorker?.controller?.scriptURL; - return scriptUrl !== undefined && scriptUrl === new URL('service-worker.js', globalThis.document?.baseURI ?? globalThis.location?.href).href; -} - // A loader for dotnet.withResourceLoader that fetches the Brotli copy a publish writes beside each runtime file and decompresses it // in the page. A static host such as GitHub Pages serves foo.wasm.br as an opaque file and compresses foo.wasm with gzip at best, // since it sets no Content-Encoding: br. DecompressionStream keeps compilation streaming where it decodes Brotli; elsewhere, Chrome diff --git a/packaging/Pixely/wwwroot/service-worker.js b/packaging/Pixely/wwwroot/service-worker.js deleted file mode 100644 index 56bf0cf4..00000000 --- a/packaging/Pixely/wwwroot/service-worker.js +++ /dev/null @@ -1,146 +0,0 @@ -// Pixely's offline worker, which a publish with PixelyBrowserOffline serves as service-worker.js and main.js registers after the first -// frame. service-worker-assets.js is the .NET SDK's list of every file of the publish with its SHA-256, compressed copies excepted. -self.importScripts('./service-worker-assets.js'); - -// Every site on an origin shares Cache Storage, as the project sites of one GitHub Pages account do, and scopes nest, so a cache is -// named by the scope it belongs to and compared by it exactly. The version is the list's own hash: a project can set the SDK's. -const scope = self.registration.scope; -const cacheNamePrefix = 'pixely|'; -// The SDK writes StaticWebAssetBasePath in front of every URL of the list, while the worker is served beneath it. Every publish lists -// the runtime at _framework/dotnet.js below that path, so the shortest URL ending there gives the prefix to strip. -const dotnetJs = '_framework/dotnet.js'; -const basePath = self.assetsManifest.assets.map(asset => asset.url).filter(url => url === dotnetJs || url.endsWith(`/${dotnetJs}`)) - .reduce((shortest, url) => shortest === undefined || url.length < shortest.length ? url : shortest, undefined)?.slice(0, -dotnetJs.length) ?? ''; -const assets = self.assetsManifest.assets.map(asset => ({ - url: new URL(asset.url.startsWith(basePath) ? asset.url.slice(basePath.length) : asset.url, scope).href, - hash: asset.hash, -})); -const assetUrls = new Set(assets.map(asset => asset.url)); -const indexUrl = new URL('index.html', scope).href; -const assetsListUrl = new URL('service-worker-assets.js', self.location.href).href; -const cacheNamePromise = hashAssets().then(version => `${cacheNamePrefix}${version}|${scope}`); -// Each cached response carries the hash it was fetched for, so an install reuses what an earlier version cached. -const hashHeader = 'X-Pixely-Asset-Hash'; - -self.addEventListener('install', event => event.waitUntil(install())); -self.addEventListener('activate', event => event.waitUntil(deleteEarlierCaches())); -self.addEventListener('fetch', onFetch); - -// Fills this version's cache. An asset already cached with the same hash, in this cache or one of an earlier version, is not -// downloaded again; the rest is fetched past the HTTP cache's freshness and checked against its hash. The cache is only added to, -// so a new worker of the same version leaves the active worker's cache intact. -async function install() { - const cacheName = await cacheNamePromise; - const cache = await caches.open(cacheName); - const earlierNames = (await ownCacheNames()).filter(name => name !== cacheName); - await Promise.all(assets.map(async asset => { - if (await findCached(asset, [cacheName])) { - return; - } - const earlier = await findCached(asset, earlierNames); - if (earlier) { - await cache.put(asset.url, earlier); - return; - } - const response = await fetch(new Request(asset.url, { integrity: asset.hash, cache: 'no-cache' })); - if (!response.ok) { - throw new Error(`${asset.url} answered ${response.status}`); - } - const headers = new Headers(response.headers); - headers.set(hashHeader, asset.hash); - // A new response also drops the redirected flag, which a navigation must not be answered with. - await cache.put(asset.url, new Response(response.body, { status: response.status, statusText: response.statusText, headers })); - })); -} - -async function findCached(asset, cacheNames) { - for (const cacheName of cacheNames) { - const response = await caches.match(asset.url, { cacheName }); - if (response?.headers.get(hashHeader) === asset.hash) { - return response; - } - } - return undefined; -} - -function onFetch(event) { - const request = event.request; - if (request.method !== 'GET') { - return; - } - const url = new URL(request.url); - url.hash = ''; - if (request.mode === 'navigate') { - // Only the page itself: a worker at / would otherwise answer the pages of every other site on the origin. - url.search = ''; - if (url.href === scope || url.href === indexUrl) { - const served = serveIndex(request); - event.respondWith(served.then(result => result.response)); - event.waitUntil(served.then(result => result.fromCache ? retireIfUnpublished(event.resultingClientId) : undefined)); - } - return; - } - if (assetUrls.has(url.href)) { - event.respondWith(serveAsset(request)); - } -} - -// caches.match never creates a cache, so a page still controlled after a retirement cannot bring a deleted one back. -async function serveIndex(request) { - const cached = await caches.match(indexUrl, { cacheName: await cacheNamePromise }); - return cached ? { response: cached, fromCache: true } : { response: await fetch(request), fromCache: false }; -} - -async function serveAsset(request) { - return await caches.match(request, { cacheName: await cacheNamePromise }) ?? fetch(request); -} - -// A publish without PixelyBrowserOffline, or a build served on the same origin, has no assets list. The browser's update check then -// fails and keeps this worker, so the worker checks the list itself whenever it served the page from its cache. A missing file is a -// 4xx (S3 answers 403) or, from a server that falls back to index.html, a page; a timeout, a rate limit, a 5xx and no network leave -// the worker in place. Unregistering takes effect at once, so the page this navigation created is loaded again from the network, and -// any other page reaches the network on its next navigation without being interrupted. -async function retireIfUnpublished(resultingClientId) { - let response; - try { - response = await fetch(assetsListUrl, { cache: 'no-cache' }); - } catch { - return; - } - const page = response.headers.get('Content-Type')?.toLowerCase().startsWith('text/html'); - await response.body?.cancel(); - const missing = response.status >= 400 && response.status < 500 && response.status !== 408 && response.status !== 429; - if (!missing && !(response.ok && page)) { - return; - } - await self.registration.unregister(); - const client = resultingClientId ? await self.clients.get(resultingClientId) : undefined; - await client?.navigate(client.url).catch(() => {}); - await deleteAllCaches(); -} - -async function deleteEarlierCaches() { - const cacheName = await cacheNamePromise; - await Promise.all((await ownCacheNames()).filter(name => name !== cacheName).map(name => caches.delete(name))); -} - -async function deleteAllCaches() { - await Promise.all((await ownCacheNames()).map(name => caches.delete(name))); -} - -async function ownCacheNames() { - return (await caches.keys()).filter(name => { - if (!name.startsWith(cacheNamePrefix)) { - return false; - } - const end = name.indexOf('|', cacheNamePrefix.length); - return end !== -1 && name.slice(end + 1) === scope; - }); -} - -// The list is sorted by URL, so its pairs hash the same way every time. -async function hashAssets() { - const text = self.assetsManifest.assets.map(asset => `${asset.url} ${asset.hash}`).join('\n'); - const digest = new Uint8Array(await crypto.subtle.digest('SHA-256', new TextEncoder().encode(text))); - return Array.from(digest, byte => byte.toString(16).padStart(2, '0')).join(''); -} diff --git a/tests/Pixely.Browser.Harness/README.md b/tests/Pixely.Browser.Harness/README.md index 3216e6ef..f9a0a90a 100644 --- a/tests/Pixely.Browser.Harness/README.md +++ b/tests/Pixely.Browser.Harness/README.md @@ -9,9 +9,3 @@ node run-page.js ../../tutorials/Pixely.Tutorials.Browser/bin/Release/net11.0-br ``` `PIXELY_CHROMIUM` names another Chromium executable than the one Playwright installed. Chromium on Linux exposes the hardware adapter only headed with `--enable-features=Vulkan`; headless gets SwiftShader, which loses the device after the first presented frame. `--headless` is there for the window-only case. - -`run-offline.js` checks the offline worker of a publish with `PixelyBrowserOffline` (docs/hosting.md, Offline play): it installs, a reload comes from its cache, and once the server answers 404 for the worker and its assets list, as after a publish without the property, it unregisters itself, loads the page again from the network and deletes its caches. One server on one port serves every step. `--nested` also serves the publish at `/proj/`, inside the scope of the one at `/`, and checks that retiring the worker at `/` keeps the worker and the caches of `/proj/`. `--register` registers the worker from the harness, for a publish that never draws the first frame after which `main.js` registers it. - -```shell -node run-offline.js ../../tutorials/Pixely.Tutorials.Browser/bin/Release/net11.0-browser/browser-wasm/publish/wwwroot --nested -``` diff --git a/tests/Pixely.Browser.Harness/run-offline.js b/tests/Pixely.Browser.Harness/run-offline.js deleted file mode 100644 index 225d7672..00000000 --- a/tests/Pixely.Browser.Harness/run-offline.js +++ /dev/null @@ -1,142 +0,0 @@ -// Checks the offline worker of a publish with PixelyBrowserOffline in Chromium: it installs after the first frame, a reload is answered -// from its cache, and once the server has no assets list, as after a publish without the property, it retires: the page loads again -// from the network, the registration is gone and so are its caches. With --nested the same publish is also served at /proj/, a site -// inside the scope of the one at /, as on one GitHub Pages account; retiring the worker at / must keep the caches and the worker of -// /proj/. One server on one port serves every step, so the origin stays the same. -// -// usage: node run-offline.js [--nested] [--register] [--headless] -// -// main.js registers the worker after the first frame. --register registers it from here once the page has loaded, for a publish -// that never draws a frame, such as a package test fixture. -// -// Exit code 0 means every check passed. -const { chromium } = require('playwright'); -const http = require('http'); -const fs = require('fs'); -const path = require('path'); - -const options = { nested: false, register: false, headless: false }; -const positional = []; -for (let index = 2; index < process.argv.length; index++) { - const argument = process.argv[index]; - if (argument === '--nested') { - options.nested = true; - } else if (argument === '--register') { - options.register = true; - } else if (argument === '--headless') { - options.headless = true; - } else { - positional.push(argument); - } -} -const root = positional[0]; -if (!root) { - console.error('usage: node run-offline.js [--nested] [--register] [--headless]'); - process.exit(2); -} - -const contentTypes = { '.html': 'text/html', '.js': 'text/javascript', '.mjs': 'text/javascript', '.wasm': 'application/wasm', '.json': 'application/json', '.webmanifest': 'application/manifest+json' }; -// Paths the server answers with 404 although the file exists, and the paths requested since the last reset. -const missing = new Set(); -let requested = []; -const server = http.createServer((request, response) => { - const url = new URL(request.url, 'http://localhost'); - requested.push(url.pathname); - if (url.pathname === '/favicon.ico') { - response.writeHead(204); - response.end(); - return; - } - const relative = options.nested && url.pathname.startsWith('/proj/') ? url.pathname.slice('/proj'.length) : url.pathname; - const file = path.join(root, decodeURIComponent(relative.endsWith('/') ? `${relative}index.html` : relative)); - if (missing.has(url.pathname) || !fs.existsSync(file) || fs.statSync(file).isDirectory()) { - response.writeHead(404); - response.end(); - return; - } - response.writeHead(200, { 'Content-Type': contentTypes[path.extname(file)] ?? 'application/octet-stream' }); - fs.createReadStream(file).pipe(response); -}); - -const failures = []; -function check(condition, message) { - console.log(`[${condition ? 'ok' : 'FAIL'}] ${message}`); - if (!condition) { - failures.push(message); - } -} - -async function waitFor(page, predicate, argument, timeoutMs = 30000) { - try { - await page.waitForFunction(predicate, argument, { timeout: timeoutMs, polling: 250 }); - return true; - } catch { - return false; - } -} - -// The worker registers after the first frame and is ready once it has cached every file. -async function waitForActiveWorker(page) { - if (options.register) { - await page.evaluate(() => navigator.serviceWorker.register('service-worker.js', { updateViaCache: 'none' })); - } - return waitFor(page, async () => (await navigator.serviceWorker.getRegistration())?.active?.state === 'activated'); -} - -async function cacheNames(page) { - return page.evaluate(async () => (await caches.keys()).filter(name => name.startsWith('pixely|'))); -} - -(async () => { - await new Promise(resolve => server.listen(0, resolve)); - const origin = `http://localhost:${server.address().port}`; - const browser = await chromium.launch({ - executablePath: process.env.PIXELY_CHROMIUM || undefined, - headless: options.headless, - args: ['--enable-features=Vulkan', '--enable-unsafe-webgpu', '--ignore-gpu-blocklist'] - }); - const context = await browser.newContext({ viewport: { width: 640, height: 400 } }); - const page = await context.newPage(); - page.on('console', message => console.log(`[${message.type()}] ${message.text()}`)); - - await page.goto(`${origin}/`, { waitUntil: 'load' }); - check(await waitForActiveWorker(page), 'the worker at / installs and activates'); - if (options.nested) { - await page.goto(`${origin}/proj/`, { waitUntil: 'load' }); - check(await waitForActiveWorker(page), 'the worker at /proj/ installs and activates'); - check((await cacheNames(page)).filter(name => name.endsWith(`|${origin}/proj/`)).length === 1, 'the worker at /proj/ has one cache of its scope'); - await page.goto(`${origin}/`, { waitUntil: 'load' }); - } - check((await cacheNames(page)).filter(name => name.endsWith(`|${origin}/`)).length === 1, 'the worker at / has one cache of its scope'); - - requested = []; - await page.reload({ waitUntil: 'load' }); - check(await page.evaluate(() => navigator.serviceWorker.controller?.scriptURL), `the reloaded page is controlled (${await page.evaluate(() => navigator.serviceWorker.controller?.scriptURL)})`); - await page.waitForTimeout(3000); - const fromNetwork = requested.filter(pathname => !pathname.endsWith('/service-worker.js') && !pathname.endsWith('/service-worker-assets.js') && pathname !== '/favicon.ico'); - check(fromNetwork.length === 0, `the reload fetched nothing else from the network (${fromNetwork.join(', ') || 'nothing'})`); - - // As after a publish without PixelyBrowserOffline: neither the worker nor its list is there. - missing.add('/service-worker.js'); - missing.add('/service-worker-assets.js'); - requested = []; - await page.reload({ waitUntil: 'load' }); - check(await waitFor(page, async () => (await navigator.serviceWorker.getRegistrations()).every(registration => registration.scope !== `${location.origin}/`)), - 'the worker at / unregisters itself'); - check(await waitFor(page, origin => caches.keys().then(names => !names.some(name => name.startsWith('pixely|') && name.endsWith(`|${origin}/`))), origin), - 'the caches of / are gone'); - check(await waitFor(page, () => document.readyState === 'complete' && !navigator.serviceWorker.controller), 'the page was loaded again from the network'); - check(requested.includes('/index.html') || requested.includes('/'), 'the page itself came from the network'); - if (options.nested) { - check((await cacheNames(page)).some(name => name.endsWith(`|${origin}/proj/`)), 'the cache of /proj/ is kept'); - check(await page.evaluate(async () => (await navigator.serviceWorker.getRegistrations()).some(registration => registration.scope.endsWith('/proj/'))), 'the worker at /proj/ is kept'); - } - - await browser.close(); - server.close(); - if (failures.length > 0) { - console.error(`FAILED\n${failures.map(failure => ` ${failure}`).join('\n')}`); - process.exit(1); - } - console.log('PASSED'); -})(); diff --git a/tests/Pixely.Package.Tests/PackageIntegrationTests.cs b/tests/Pixely.Package.Tests/PackageIntegrationTests.cs index 0eb435eb..91034365 100644 --- a/tests/Pixely.Package.Tests/PackageIntegrationTests.cs +++ b/tests/Pixely.Package.Tests/PackageIntegrationTests.cs @@ -1153,17 +1153,14 @@ public async Task BrowserAppWithoutContentArchiveNamesTheArchiveInTheError() Assert.That(result, Does.Contain("RESULT error").And.Contain("PixelyBrowserVfsFile with TargetPath Content.pk3").And.Contain("RESULT exit code 1")); } - // One publish covers the manifest with a name that needs escaping, the icons at their target paths, the tags in the package's page, - // the offline worker with its assets list and the boot config flag. A second publish into the same folder without the worker - // deletes the worker's files, so a worker installed from the first retires. + // One publish covers the manifest with a name that needs escaping, the icons at their target paths and the tags in the package's page. [Test] - public async Task BrowserPublishMakesAnInstallableOfflineAppAndRetiresItsWorker() + public async Task BrowserPublishMakesAnInstallableApp() { string consumerDirectory = GetConsumerDirectory("BrowserContentConsumer"); DeleteConsumerOutputs("BrowserContentConsumer"); - string[] installable = ["PixelyBrowserInstallable=true", "BrowserContentConsumerIcons=true", "PixelyBrowserAppName=Pixely%3B C:\\Games 'Game'", "PixelyBrowserThemeColor=#123456"]; - await PublishConsumerAsync(consumerDirectory, "browser-wasm", properties: [.. installable, "PixelyBrowserOffline=true"]); + await PublishConsumerAsync(consumerDirectory, "browser-wasm", properties: ["PixelyBrowserInstallable=true", "BrowserContentConsumerIcons=true", "PixelyBrowserAppName=Pixely%3B C:\\Games 'Game'", "PixelyBrowserThemeColor=#123456"]); string wwwroot = GetPublishedWwwroot(consumerDirectory); using (JsonDocument manifest = JsonDocument.Parse(File.ReadAllText(Path.Combine(wwwroot, "manifest.webmanifest")))) { @@ -1182,51 +1179,17 @@ public async Task BrowserPublishMakesAnInstallableOfflineAppAndRetiresItsWorker( Assert.That(icons[1].GetProperty("purpose").GetString(), Is.EqualTo("any maskable")); }); } - string serviceWorker = File.ReadAllText(Path.Combine(wwwroot, "service-worker.js")); - string assetsList = File.ReadAllText(Path.Combine(wwwroot, "service-worker-assets.js")); Assert.Multiple(() => { Assert.That(File.Exists(Path.Combine(wwwroot, "icon-192.png")), Is.True); Assert.That(File.Exists(Path.Combine(wwwroot, "icons", "icon-512.png")), Is.True); Assert.That(File.ReadAllText(Path.Combine(wwwroot, "index.html")), Does.Contain("\n \n").And.Contain(" - { - Assert.That(Directory.GetFiles(wwwroot, "service-worker*"), Is.Empty); - Assert.That(File.Exists(Path.Combine(wwwroot, "manifest.webmanifest")), Is.True); - Assert.That(File.ReadAllText(Path.Combine(wwwroot, "_framework", "dotnet.js")), Does.Match(@"""serviceWorker"":\s*false")); - }); - } - - // Under a base path the SDK writes the prefix in front of every URL of the assets list, the runtime's included, which the worker - // strips, and publishes the worker beneath it, where the deletion looks. - [Test] - public async Task BrowserPublishUnderABasePathListsItAndDeletesTheWorkerThere() - { - string consumerDirectory = GetConsumerDirectory("BrowserContentConsumer"); - DeleteConsumerOutputs("BrowserContentConsumer"); - - await PublishConsumerAsync(consumerDirectory, "browser-wasm", properties: ["StaticWebAssetBasePath=app", "PixelyBrowserOffline=true"]); - string appRoot = Path.Combine(GetPublishedWwwroot(consumerDirectory), "app"); - Assert.Multiple(() => - { - Assert.That(File.Exists(Path.Combine(appRoot, "service-worker.js")), Is.True); - Assert.That(File.ReadAllText(Path.Combine(appRoot, "service-worker-assets.js")), Does.Contain("\"app/Content.pk3\"").And.Contain("\"app/_framework/dotnet.js\"")); - }); - - await PublishConsumerAsync(consumerDirectory, "browser-wasm", properties: ["StaticWebAssetBasePath=app"]); - Assert.That(Directory.GetFiles(appRoot, "service-worker*"), Is.Empty); } // A project's own manifest replaces the generated one, and the icons it names are still served. A quote in an icon's path passes - // through the icons, and one in a static web asset's path through the deletion of a stale worker, which every browser publish runs. + // through the icons. [Test] public async Task BrowserPublishWithAnOwnManifestServesTheIcons() { @@ -1238,7 +1201,6 @@ public async Task BrowserPublishWithAnOwnManifestServesTheIcons() try { File.WriteAllText(Path.Combine(consumerWwwroot, "manifest.webmanifest"), "{ \"name\": \"Own\" }\n"); - File.WriteAllText(Path.Combine(consumerWwwroot, "it's.txt"), "quoted\n"); File.Copy(Path.Combine(consumerDirectory, "Extras", "icon-192.png"), quotedIcon, overwrite: true); await PublishConsumerAsync(consumerDirectory, "browser-wasm", properties: ["PixelyBrowserInstallable=true", "BrowserContentConsumerIcons=true", "BrowserContentConsumerQuotedIcon=true"]); @@ -1248,7 +1210,6 @@ public async Task BrowserPublishWithAnOwnManifestServesTheIcons() Assert.That(File.ReadAllText(Path.Combine(wwwroot, "manifest.webmanifest")), Does.Contain("\"Own\"")); Assert.That(File.Exists(Path.Combine(wwwroot, "icon-192.png")), Is.True); Assert.That(File.Exists(Path.Combine(wwwroot, "icons", "icon-512.png")), Is.True); - Assert.That(File.Exists(Path.Combine(wwwroot, "it's.txt")), Is.True); Assert.That(File.Exists(Path.Combine(wwwroot, "it's.png")), Is.True); }); } @@ -1259,17 +1220,6 @@ public async Task BrowserPublishWithAnOwnManifestServesTheIcons() } } - // A build has no assets list and no worker, which is what retires a worker an earlier publish left on the same origin. - [Test] - public async Task BrowserBuildWithOfflineServesNoWorker() - { - string consumerDirectory = GetConsumerDirectory("BrowserContentConsumer"); - DeleteConsumerOutputs("BrowserContentConsumer"); - - await BuildConsumerAsync(consumerDirectory, runtimeIdentifier: "browser-wasm", properties: ["PixelyBrowserOffline=true"]); - Assert.That(File.ReadAllText(Path.Combine(GetBrowserIntermediateDirectory(consumerDirectory), "staticwebassets.build.json")), Does.Not.Contain("service-worker")); - } - [Test] public async Task BrowserBuildOfAnInstallableAppWithoutBothIconsFailsWithPixely0016() { diff --git a/tutorials/Pixely.Tutorials.AfterSdk.targets b/tutorials/Pixely.Tutorials.AfterSdk.targets index 2dc412f3..3121c35b 100644 --- a/tutorials/Pixely.Tutorials.AfterSdk.targets +++ b/tutorials/Pixely.Tutorials.AfterSdk.targets @@ -1,6 +1,5 @@ - From 4d54ce0169af10521c0ed419bcd44ebad1318ec4 Mon Sep 17 00:00:00 2001 From: botoddly <250804054+botoddly@users.noreply.github.com> Date: Thu, 19 Nov 2026 21:57:15 +0100 Subject: [PATCH 4/4] Test icons under wwwroot and a page named by PixelyBrowserIndexHtml for installable browser apps --- DECISIONS.md | 2 +- .../PackageIntegrationTests.cs | 41 +++++++++++++++++++ 2 files changed, 42 insertions(+), 1 deletion(-) diff --git a/DECISIONS.md b/DECISIONS.md index e1c48e96..e1e0e597 100644 --- a/DECISIONS.md +++ b/DECISIONS.md @@ -2,7 +2,7 @@ Design decisions with the constraints that decided them and their known costs, newest first. -## 2026-11-18: An installable browser app gets a generated manifest and no service worker +## 2026-11-19: An installable browser app gets a generated manifest and no service worker `PixelyBrowserInstallable` generates a web app manifest (`docs/hosting.md`). A publish has no service worker, so an installed game still needs the network to start. diff --git a/tests/Pixely.Package.Tests/PackageIntegrationTests.cs b/tests/Pixely.Package.Tests/PackageIntegrationTests.cs index 91034365..0f70d1df 100644 --- a/tests/Pixely.Package.Tests/PackageIntegrationTests.cs +++ b/tests/Pixely.Package.Tests/PackageIntegrationTests.cs @@ -1220,6 +1220,47 @@ public async Task BrowserPublishWithAnOwnManifestServesTheIcons() } } + // An icon under the project's wwwroot is named by its path there, and a page named by PixelyBrowserIndexHtml gets no tags. + [Test] + public async Task BrowserPublishNamesAWwwrootIconByItsPathAndLeavesAnOwnPage() + { + string consumerDirectory = GetConsumerDirectory("BrowserContentConsumer"); + DeleteConsumerOutputs("BrowserContentConsumer"); + string consumerWwwroot = Path.Combine(consumerDirectory, "wwwroot"); + const string ownPage = "\n\n\n\n\n\n"; + string ownPagePath = Path.Combine(_testArtifactsDirectory, "own-index.html"); + File.WriteAllText(ownPagePath, ownPage); + Directory.CreateDirectory(Path.Combine(consumerWwwroot, "images")); + string itemsPath = Path.Combine(_testArtifactsDirectory, "extra-items.props"); + File.WriteAllText(itemsPath, """ + + + + + + + """); + try + { + File.Copy(Path.Combine(consumerDirectory, "Extras", "icon-192.png"), Path.Combine(consumerWwwroot, "images", "icon-192.png")); + + await PublishConsumerAsync(consumerDirectory, "browser-wasm", properties: ["PixelyBrowserInstallable=true", $"BrowserContentConsumerExtraItems={itemsPath}", $"PixelyBrowserIndexHtml={ownPagePath}"]); + string wwwroot = GetPublishedWwwroot(consumerDirectory); + using JsonDocument manifest = JsonDocument.Parse(File.ReadAllText(Path.Combine(wwwroot, "manifest.webmanifest"))); + Assert.Multiple(() => + { + Assert.That(manifest.RootElement.GetProperty("icons").EnumerateArray().Select(icon => icon.GetProperty("src").GetString()), Is.EqualTo(new[] { "images/icon-192.png", "icon-512.png" })); + Assert.That(File.Exists(Path.Combine(wwwroot, "images", "icon-192.png")), Is.True); + Assert.That(File.Exists(Path.Combine(wwwroot, "icon-192.png")), Is.False); + Assert.That(File.ReadAllText(Path.Combine(wwwroot, "index.html")), Is.EqualTo(ownPage)); + }); + } + finally + { + DeleteDirectory(consumerWwwroot); + } + } + [Test] public async Task BrowserBuildOfAnInstallableAppWithoutBothIconsFailsWithPixely0016() {