sw 0.4.0
sw: ^0.4.0 copied to clipboard
Generates a service worker and a bootstrap script for a Flutter Web build: per-category caching with integrity checks, a loading screen with real progress, and deploys that land as one coherent build.
Service Worker Generator #
A complete Flutter Web bootstrap replacement that generates an optimized Service Worker and Bootstrap pipeline. Replaces Flutter's default flutter_bootstrap.js with a professional loading experience featuring progress tracking, intelligent caching, CanvasKit CDN loading, and a customizable loading widget.
Live demo: the example app, built and deployed from master.
Features #
- Full Bootstrap Replacement — Replaces Flutter's
flutter_bootstrap.jswith a controlled initialization pipeline - Loading Widget — Responsive circular progress indicator with status text, stall detection, and error handling
- CanvasKit CDN Loading — Loads CanvasKit from Google CDN with automatic local fallback
- Smart Resource Categorization — Core, Required, Optional, and Ignore categories with configurable caching strategies
- Automatic File Scanning — Analyzes build directory and creates resource manifest with MD5 hashes
- Cache Busting — Hash-based query params prevent stale cached resources
- Retry with Backoff — Exponential backoff retry (3 attempts, 1s/2s/4s delays) with 10s timeout per request
- Progress Notifications — Real-time
sw-progressmessages from Service Worker to loading widget - Version Management — Cache versioning with atomic updates for safe deployments
- Stall Detection — Shows "Reset Cache" button after 30s without progress
- Console Logging — Styled version banner and progress logging in browser console
- Global API —
window.Bootstrapfor Dart integration (dispose, progress, subscribe) - Update Prompt API — Use
Bootstrap.onUpdateAvailable()to show a "new version available" prompt, then callBootstrap.applyUpdate()to activate the waiting Service Worker and reload into the new build. - Flexible Configuration — CLI args, YAML config file, and environment variables (priority: CLI > YAML > env)
- Cross-Platform — Works on Windows, macOS, and Linux
Requirements #
- Dart SDK: >= 3.8.0
- Flutter: >= 3.32.0 (the release that ships Dart 3.8)
Installation #
dart pub global activate sw
Or add as a dev dependency:
dev_dependencies:
sw: ^0.4.0
Pin the exact version in CI. sw.js and bootstrap.js are the app's boot
path, so a template change should arrive through a reviewed bump rather than
on the next unrelated build:
dart pub global activate sw 0.4.0
That puts an sw command on PATH; dart pub global run sw:generate works
the same way without it.
Note that a pre-release is not matched by a plain caret constraint — 0.5.0-dev
sorts before 0.5.0, so it falls outside ^0.4.0. Pin a pre-release
exactly, or write ^0.5.0-dev to accept it now and the release later.
Quick Start #
# 1. Build your Flutter web app
flutter build web --release --wasm --base-href=/ -o build/web
# 2. Swap the dev index.html for the prod template (see "Local Development")
# (web/index.prod.html must keep an explicit <base href="/" />)
cp web/index.prod.html build/web/index.html
# 3. Generate service worker and bootstrap
dart run sw:generate \
--input=build/web \
--prefix=my-app \
--version="$(git rev-parse --short=8 HEAD)"
The generator produces two files in your build directory:
sw.js— Service Worker with resource manifest and caching logicbootstrap.js— Initialization pipeline with loading widget
And automatically:
- Extracts
engineRevisionand build config from Flutter's output (a build withoutengineRevisionstill generates, with a warning: CanvasKit then always loads from the localcanvaskit/directory, and every deploy waits for the new worker to install and take over before the app starts) - Categorizes all files (Core/Required/Optional/Ignore)
- Removes Flutter's deprecated files (
flutter_bootstrap.js,flutter_service_worker.js,flutter.js— its loader is inlined intobootstrap.js) - Removes
.js.map,.js.symbolsand.wasm.mapfiles (unless--keep-maps) - Replaces
{{sw_version}}placeholders inindex.htmlwith the HTML-escaped version
Server Configuration #
⚠️ Required. Your HTTP server must serve
bootstrap.js,index.html, andsw.jswithCache-Control: no-cache. Without this, users can get stuck on an outdated build.
Why it matters #
bootstrap.js is regenerated on every build with an embedded config snapshot — engine revision, SW version, manifest filename, and renderer variants are injected directly into the file. If a CDN or browser HTTP cache returns a stale bootstrap.js, the client registers an outdated Service Worker and never discovers the new manifest. The Service Worker's own invalidation logic cannot fix this, because it only runs after bootstrap.js has already loaded.
The same applies to index.html (the entry point that loads bootstrap.js) and sw.js (the browser updates the Service Worker by byte-comparing its response — a stale copy defeats the update check).
Required headers #
| File | Cache-Control |
Notes |
|---|---|---|
index.html |
no-cache |
Allows 304 via ETag/Last-Modified — fast but always revalidated |
bootstrap.js |
no-cache |
Content changes every build (embedded config snapshot) |
sw.js |
no-cache |
Browser also enforces ≤ 24h SW freshness, but explicit is better |
| Everything else | no-cache |
Flutter's file names carry no content hash (see below) |
Use no-cache, not no-store — no-cache lets the browser keep the file on disk but forces a conditional request on every load, so unchanged builds cost only a 304 response.
Do not mark the rest of the build immutable or give it a long max-age. main.dart.js, main.dart.wasm, assets/AssetManifest.json and canvaskit/* keep the same names across deploys. The service worker is not affected — it precaches with ?v={hash} and cache: 'reload' — but whenever it does not answer a request (the first visit, a private window, a worker that failed to install, a browser without service workers), the browser's HTTP cache would hand back last year's copy next to this deploy's bootstrap.js. Revalidating costs a 304 per file; serving a mix of two builds costs a broken app.
MIME types and cross-origin isolation #
.wasmmust be served asapplication/wasm; with any other typeWebAssembly.instantiateStreamingfails and the engine falls back to a slower path or does not start..mjsand.jsneed a JavaScript type (text/javascript).- The multithreaded
skwasmrenderer needs a cross-origin isolated page:Cross-Origin-Opener-Policy: same-originandCross-Origin-Embedder-Policy: require-corp(orcredentialless) onindex.html. Without them the engine runs single-threaded. With them, every cross-origin resource the page loads — the CanvasKit CDN included — must allow it (CORS orCross-Origin-Resource-Policy); build with--no-web-resources-cdnif in doubt.
Example server configurations #
nginx
http {
# The stock map. nginx 1.21+ maps .wasm to application/wasm there; on an
# older one add `application/wasm wasm;` to the block below as well.
include mime.types;
# Many stock maps lack .mjs, which the wasm build loads as a module
# (strict MIME check). A second `types {}` block at the SAME level as the include
# adds to the map; one inside `server` or `location` replaces it whole.
types {
text/javascript mjs;
}
server {
# ...
location / {
add_header Cache-Control "no-cache";
try_files $uri $uri/ /index.html;
}
}
}
Apache (.htaccess)
# `Header` needs mod_headers (`a2enmod headers`). Without it this file makes
# Apache answer 500; do not wrap it in <IfModule>, which would silently drop
# the required Cache-Control header instead.
AddType application/wasm .wasm
AddType text/javascript .mjs
Header set Cache-Control "no-cache"
Netlify (_headers)
/*
Cache-Control: no-cache
Firebase Hosting (firebase.json)
{
"hosting": {
"headers": [
{
"source": "**",
"headers": [{ "key": "Cache-Control", "value": "no-cache" }]
}
]
}
}
Vercel (vercel.json)
{
"headers": [
{
"source": "/(.*)",
"headers": [{ "key": "Cache-Control", "value": "no-cache" }]
}
]
}
index.html Setup #
Replace Flutter's default index.html content with a single script tag:
<!DOCTYPE html>
<html>
<head>
<base href="/" />
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta name="theme-color" content="#25D366" />
<link rel="manifest" href="manifest.json" />
<link rel="icon" type="image/png" href="favicon.png" />
<title>My App</title>
</head>
<body>
<script
defer
data-sw-bootstrap
src="bootstrap.js"
data-config='{
"logo": "icons/Icon-192.png",
"title": "My App",
"theme": "auto",
"color": "#25D366"
}'
></script>
</body>
</html>
The explicit <base href="/" /> is intentional for the production template and should not be replaced with $FLUTTER_BASE_HREF. If you deploy under a subpath, keep the base href explicit there too, and make sure it still ends with /.
The loading widget, progress tracking, service worker registration, and Flutter initialization are all handled by bootstrap.js automatically.
Do not keep Flutter's <script>{{flutter_bootstrap_js}}</script>: flutter build web pastes its whole loader there, which boots the app without bootstrap.js or the service worker. The generator warns when it finds that inline loader (or a script that still loads flutter_bootstrap.js); replace it in web/index.html with <script src="bootstrap.js" data-sw-bootstrap defer></script> and rebuild.
Bootstrap Configuration (data-config) #
| Option | Type | Default | Description |
|---|---|---|---|
logo |
string | — | Path to logo image for the loading widget |
title |
string | — | Title text displayed below the logo |
theme |
string | "auto" |
Widget theme: "light", "dark", or "auto" |
color |
string | "#25D366" |
Accent color for the progress ring |
showPercentage |
boolean | true |
Show numeric percentage below status text |
minProgress |
number | 0 |
Minimum progress value for the bootstrap range |
maxProgress |
number | 90 |
Maximum progress value (Dart manages the rest) |
logLevel |
string | --log-level |
"silent", "error", "warn" or "info": how much reaches the console, overriding the generated default |
strings |
object | English | What the loading screen says, by key — starting, environment, worker, update, engine, app, resources ({done}/{total}), initializing, running, failed, offline, reload, reset. Unknown keys and non-strings are ignored |
Local Development #
flutter run -d chrome and flutter run -d web-server do not invoke the generator — they serve Flutter's default bootstrap for hot reload. This means bootstrap.js does not exist during flutter run, and the production index.html (which references it) would break hot reload.
The recommended pattern is to keep two index.html templates side by side in your web/ folder:
| File | Purpose | Used by |
|---|---|---|
web/index.html |
Dev template with Flutter's {{flutter_js}} / {{flutter_build_config}} placeholders |
flutter run (hot reload, dev mode) |
web/index.prod.html |
Prod template that loads bootstrap.js generated by sw |
CI / release builds |
Dev template — web/index.html #
Keep Flutter's default placeholders so flutter run works unchanged:
<!DOCTYPE html>
<html>
<head>
<base href="$FLUTTER_BASE_HREF" />
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta name="theme-color" content="#25D366" />
<link rel="manifest" href="manifest.json" />
<link rel="icon" type="image/png" href="favicon.png" />
<title>My App | Development</title>
</head>
<body>
<!-- Loading progress bridge called by Dart JS interop -->
<script>
window.updateLoadingProgress = function (progress, text) {};
window.removeLoadingIndicator = function () {};
</script>
<!-- Flutter's default bootstrap -->
<script src="flutter_bootstrap.js" async></script>
</body>
</html>
Flutter populates flutter_bootstrap.js on build; during flutter run it is served from memory.
Prod template — web/index.prod.html #
Replace Flutter's loader with the bootstrap.js tag shown in index.html Setup. This file is not touched by flutter build — it is a static asset copied into build/web/ next to the dev index.html.
Important. Keep an explicit
<base href="/" />inweb/index.prod.htmlfor the default root deployment flow. Do not leave$FLUTTER_BASE_HREFin the prod template. If you change the base href for a subpath deployment, it must still end with/(for example,/my-app/).
CI step — swap templates before generating #
In your CI pipeline, after flutter build web, delete the dev index.html and rename index.prod.html to index.html, then run the generator:
# 1. Build with Flutter (uses web/index.html with default placeholders)
flutter build web --release --wasm --base-href=/ -o build/web
# 2. Swap: prod template replaces dev template inside build/web/
rm -f build/web/index.html
mv build/web/index.prod.html build/web/index.html
# 3. Generate sw.js + bootstrap.js, inject {{sw_version}} into index.html,
# and auto-remove flutter_bootstrap.js / flutter_service_worker.js / flutter.js
# (flutter.js is inlined into bootstrap.js, so it's dropped from the output).
dart pub global activate sw 0.4.0
dart pub global run sw:generate --version="$(git rev-parse --short=8 HEAD)"
After this sequence, build/web/ contains exactly the artifacts that should ship: production index.html, bootstrap.js, sw.js, and hashed assets. The dev template stays in source but never leaves the build directory.
Tip. Passing
--version="$(git rev-parse --short=8 HEAD)"ties each release to a commit SHA, which makes cache versioning deterministic and easy to trace across environments.
Command Line Options #
| Option | Short | Description | Default |
|---|---|---|---|
--help |
-h |
Show help information | — |
--input |
-i |
Path to Flutter build directory | build/web |
--output |
-o |
Output service worker file name (plain name, next to index.html) |
sw.js |
--bootstrap-output |
Output bootstrap file name (plain name) | bootstrap.js |
|
--prefix |
-p |
Cache name prefix (unique per app on an origin, see below) | app-cache |
--version |
-v |
Cache version (not manifest, temp-* or *-manifest) |
hash of the manifest |
--glob |
-g |
Include glob patterns (; separated) |
** |
--no-glob |
-e |
Exclude glob patterns (; separated) |
— |
--core |
Core category glob overrides | — | |
--required |
Required category glob overrides | — | |
--optional |
Optional category glob overrides | — | |
--ignore |
Ignore category glob overrides | — | |
--keep-maps |
Keep .js.map, .js.symbols and .wasm.map files |
false |
|
--no-cleanup |
Skip Flutter file cleanup | false |
|
--comments |
-c |
Deprecated; warns and has no effect | false |
--config |
Path to YAML config file | sw.yaml |
|
--theme |
Loading widget theme | auto |
|
--logo |
Loading widget logo path | — | |
--title |
Loading widget title | — | |
--color |
Loading widget accent color | #25D366 |
|
--min-progress |
Minimum progress value | 0 |
|
--max-progress |
Maximum progress value | 90 |
|
--log-level |
Console output of sw.js and bootstrap.js: silent, error, warn, info |
info |
Several apps on one origin. Caches belong to the origin, not to a path,
so give each app its own --prefix. The default app-cache is shared by
every app that keeps it: their workers then treat each other's caches as
their own old versions and delete them. A prefix that is another one
followed by - (app and app-admin) is told apart by its
{prefix}-manifest cache, so app's worker leaves app-admin's caches alone;
an app-admin built with an older release is exposed until its first
activate, so distinct prefixes remain the safer choice.
YAML Configuration #
Create an sw.yaml file in your project root as an alternative to CLI args:
input: build/web
output: sw.js
prefix: my-app
theme: dark
logo: icons/Icon-192.png
title: My App
color: "#25D366"
glob: "**.{html,js,wasm,json}; assets/**; canvaskit/**; icons/**"
no-glob: "sw.js; bootstrap.js; **/*.map; assets/NOTICES"
Glob options also take a YAML list (glob: ["**.js", "assets/**"]). Plain values are used as written, so version: 1.10 stays 1.10.
These are package:glob patterns: * does not cross /, so *.png means the top level only and **/*.png means every directory. A pattern of the first shape is warned about.
Priority: CLI arguments > YAML config > environment variables > defaults.
Environment Variables #
| Variable | Maps to |
|---|---|
SW_INPUT |
--input |
SW_OUTPUT |
--output |
SW_PREFIX |
--prefix |
SW_VERSION |
--version |
SW_THEME |
--theme |
SW_LOGO |
--logo |
SW_TITLE |
--title |
SW_COLOR |
--color |
Every option has one; docs/configuration.md lists them all, including SW_KEEP_MAPS, SW_NO_CLEANUP and SW_LOG_LEVEL.
A configuration error (an unknown option, an invalid value, a bad glob, an output name with a directory) exits with status 64 and names its source: --max-progress="lots", SW_MIN_PROGRESS="ten" (environment) or max-progress="lots" (in sw.yaml).
Bootstrap Pipeline #
The bootstrap replaces Flutter's initialization with a controlled 6-stage pipeline:
| Stage | Progress | Description |
|---|---|---|
| Init | 0% → 1% | Environment check, browser capability detection |
| Service Worker | 1% → 2% | Register sw.js, unregister old Flutter SW, timeout fallback |
| CanvasKit | 2% → 20% | Load from Google CDN, fall back to local canvaskit/ (local only with --no-web-resources-cdn) |
| Assets | 20% → 80% | Load main.dart.js/.wasm via Flutter's loader |
| Dart Entry | 80% → 90% | Initialize Flutter engine and run app |
| Dart Init | 90% → 100% | Dart application manages remaining progress |
Loading Widget #
The loading widget provides visual feedback during initialization:
- Circular SVG progress ring with configurable accent color
- Logo image and title text (configurable)
- Status text showing current operation
- Percentage display (optional)
- Stall detection — after 30 seconds without progress, shows a "Reset Cache" button
- Error display — shows error message with reset option on failure
- Responsive design — adapts to mobile screens
- Theme support — light, dark, or auto (follows
prefers-color-scheme)
CanvasKit Loading #
The bootstrap automatically determines the correct CanvasKit variant:
- Extracts
engineRevisionfrom Flutter's build config - Detects browser capabilities (ImageDecoder, Intl.Segmenter, WebGL, WasmGC)
- Selects the appropriate variant (canvaskit, chromium, skwasm, skwasm_heavy, wimp)
- Tries Google CDN:
https://www.gstatic.com/flutter-canvaskit/{engineRevision}/{variant}.js - Falls back to local
canvaskit/directory on failure
A build config without engineRevision has no CDN path, so the bootstrap loads the local canvaskit/ directory; the generator warns about such a build.
Build with flutter build web --no-web-resources-cdn to serve the engine from your own origin: Flutter records the choice in its build config, and the bootstrap then loads from canvaskit/ without probing the CDN.
Global API (window.Bootstrap) #
The bootstrap exposes a global API for Dart integration via JS interop:
// In your Dart code:
import 'dart:js_interop';
@JS('Bootstrap.dispose')
external void bootstrapDispose();
@JS('Bootstrap.progress')
external JSObject get bootstrapProgress;
| Method | Description |
|---|---|
Bootstrap.dispose() |
Remove loading widget, clean up listeners |
Bootstrap.progress |
Current state: { phase, percent, message }, plus detail once phase is error — the raw reason, which the screen does not show |
Bootstrap.subscribe(callback) |
Subscribe to progress changes, returns unsubscribe function |
Bootstrap.onUpdateAvailable(handler) |
Runs when a newer Service Worker has installed and is waiting; notifications stay active for the whole page session, even after the loading widget is gone. |
Bootstrap.onError(handler) |
Runs when loading fails, with the error state; detail carries the engine's or the network's own message. Also reaches subscribe consumers as phase: 'error' |
Bootstrap.onWorkerFailure(handler) |
Runs when the service worker reports a failed install, a cache swap that ran out of storage, or a refused cache write. The app is loading or running — this is a degraded caching layer, not a failed load |
Bootstrap.applyUpdate(reload = true) |
Activates the waiting Service Worker and reloads the page into the updated build. Resolves true (and reloads, by default) once the page's controller changes or the waiting worker reaches activated, which covers a hard-reloaded page with no controller. Resolves false, without reloading, if no worker is waiting, at once if it turns redundant, or if neither lands within 10s. |
Alternatively, the loading widget auto-disposes on the flutter-first-frame event.
Resource Categories #
Files are automatically categorized based on their path and size:
| Category | Pre-cached | On Fetch | Description |
|---|---|---|---|
| Core | Install | Cache-first | Essential: main.dart.js/.wasm/.mjs, *.support.wasm |
| Required | Install | Cache-first | Early-needed: index.html, AssetManifest*.json, FontManifest.json, manifest.json |
| Optional | — | Cache on first fetch | CanvasKit/skwasm files; fonts (.ttf, .otf, .woff, .woff2, .eot) at any size; .json, .webp, .png, .jpg, .jpeg, .svg, .gif, .ico up to 512 KB |
| Ignore | — | Pass-through | Not cached: *.map, *.symbols, NOTICES, large assets |
Override categorization with glob patterns via CLI or YAML config:
dart run sw:generate \
--input=build/web \
--core="assets/critical/**" \
--ignore="assets/video/**"
Never Cached #
These files are always fetched fresh (never stored in the SW cache):
bootstrap.js— must reflect latest build configsw.js— browser handles SW updates natively
index.html is a special case: it is pre-cached as the app shell so a
navigation the network fails still gets an answer, but it is served
network-first, so an online visitor always gets the copy the origin holds.
It still requires Cache-Control: no-cache at the HTTP layer, alongside the
two files above — see Server Configuration.
Offline is not supported. The cached shell is a fallback for a failed
navigation, but the app cannot start from it without a network: the page
needs bootstrap.js, which is deliberately never cached so that the shell,
the bootstrap and the worker always come from one deploy. Serving a cached
bootstrap.js would make offline loads possible at the cost of a page that
can start on a stale bootstrap, and this project chooses the consistent load.
A browser may still start the app from its HTTP cache, for as long as that
cache keeps bootstrap.js fresh. To keep text readable when that happens,
declare Roboto in your pubspec.yaml. Otherwise Flutter's engine fetches it
from fonts.gstatic.com, which the worker cannot cache, and the page loses all
of its text while its layout, buttons and images stay in place.
Service Worker #
Caching Strategies #
| Resource | Strategy | Details |
|---|---|---|
| Navigations | Network-first | Fresh from network, pre-cached shell if the network fails |
| Core + Required | Pre-cached | Cached during SW install with cache-busted URLs |
| Optional | Lazy cache | Cached on first fetch for repeat visits |
| Ignore | Pass-through | Not cached, always from network |
While a newer build's worker is installing or waiting, the worker in control
stops answering Core and Required requests from its cache and stops writing
it: that cache holds the previous build's code, while the page asking is
already the new build's index.html. So the first load after a deploy runs
the new code, without waiting for the new worker to finish installing.
Lazily cached files (fonts, images, the engine) are still served from the
cache, and so is everything if the network cannot answer at all. See
docs/service-worker.md.
Cache Management #
- Atomic updates — New resources cached in temp cache, then swapped atomically on activate
- Manifest diff — Previous manifest compared to detect changed resources (by MD5 hash)
- Reuse across versions — a new version's install copies the Core and Required files whose hash did not change out of the previous version's cache instead of downloading them, so an assets-only deploy costs the assets
- Stale cleanup — Old versioned caches automatically deleted on activate
- Error recovery — On activate error, all caches cleared (clean slate),
clients.claim()always called
Resilience #
- Fetch timeout: 10s per request via AbortController (headers only)
- Body stall watchdog: a pre-cached body idle for 30s is cancelled, so a dead
stream cannot hang
install— and with it everyregister()on the origin - Fetch retry: 3 attempts with exponential backoff (1s → 2s → 4s + jitter). Navigations are not retried: with a pre-cached shell in hand they fall back to it after 3s rather than hold a blank page
- Resumed install: a failed install keeps what it downloaded, so the retry on the next load fetches only what is missing
- Storage pressure: the temp → content swap moves a few entries at a time and frees each one as it goes, and a swap that runs out of storage keeps what it moved instead of starting over
- SW activation timeout: 4s on a first visit, continues without SW on timeout. A page that already has a controller boots with it straight away
- Engine change after a deploy: when the new build runs on a different Flutter engine, the first load waits (up to 60s) for the new worker and switches to it, so the previous build's cached Dart code never meets the new engine. On the same engine it boots at once — with the new build's code, which the worker in control now fetches instead of serving its own cache
- SW step budget: 10s for the whole registration step; the app boots uncached rather than waiting on a blocked service worker job queue
- Error recovery: Always calls
self.clients.claim()even on errors
Client Notifications #
The service worker sends sw-progress messages during resource operations:
{
type: 'sw-progress',
timestamp: 1749123456789,
swVersion: 'a1b2c3d4',
resourcesSize: 5242880,
resourcesCount: 6,
resourceName: 'main.dart.js',
resourceUrl: 'https://example.com/main.dart.js',
resourceKey: 'main.dart.js',
resourceSize: 1048576,
loaded: 1048576,
status: 'completed', // 'loading' | 'completed' | 'updated' | 'cached' | 'error'
counted: true
}
resourcesCount / resourcesSize describe the pre-cached set. Count only
messages with counted: true, and only from your own swVersion — see
docs/service-worker.md.
Message Commands #
| Message | Action |
|---|---|
'skipWaiting' |
Immediately activate a waiting service worker |
{ type: 'getVersion' } |
Respond with the SW version and engine revision |
{ type: 'getStatus' } |
Respond with the caches and their sizes, the storage estimate and the last worker failure |
The worker also broadcasts sw-lifecycle messages when an install, a cache
swap or a cache write fails; the bootstrap re-dispatches them as a
sw-lifecycle event on window and calls Bootstrap.onWorkerFailure
handlers with the failures.
Architecture #
This is a TypeScript + Dart monorepo:
packages/sw/ # TypeScript source (Vite → minified IIFE)
├── src/sw/ # Service Worker modules
├── src/bootstrap/ # Bootstrap pipeline + loading widget
└── src/shared/ # Shared types, constants, utilities
lib/ # Dart CLI
├── src/assets/ # Compiled JS embedded as Dart string constants
├── src/ # Config, manifest, categorizer, injector, cleanup
└── sw.dart # Barrel export
bin/generate.dart # CLI entry point
Users install only the Dart package — no Node.js required. The TypeScript source is pre-compiled and shipped as Dart string constants.
Contributing #
Prerequisites #
- Dart SDK >= 3.8.0 (the package); the example app needs >= 3.11.0
- Node.js >= 18 (for TypeScript development only)
- Flutter >= 3.41.0 (for example app)
Setup #
# Clone the repository
git clone https://github.com/DoctorinaAI/service-worker-generator.git
cd service-worker-generator
# Install dependencies
dart pub get
npm install
# Build TypeScript
npm run build
# Run tests
dart test
npm test
Development Workflow #
# Watch TypeScript changes
npm run dev
# Build TypeScript + copy to Dart string constants
npm run build:all
# Verify committed assets are up to date
npm run verify
# Run the generator on the example app
dart run sw:generate --input=example/build/web --no-cleanup
# Format Dart code
dart format -l 80 lib/ bin/ test/
Project Structure #
| Directory | Purpose |
|---|---|
packages/sw/ |
TypeScript source for SW and Bootstrap |
lib/src/ |
Dart CLI modules |
bin/ |
CLI entry point |
scripts/ |
Build scripts (copy-assets, verify-assets) |
docs/ |
Architecture documentation |
example/ |
Flutter Web example app |
test/ |
Dart tests |
License #
This project is licensed under the MIT License. See the LICENSE file for details.