@hamur/pwa
The first-party PWA module. It fills the core's app.manifest (its display, its icons and a theme-color meta) and makes the manifest icons, and the iOS home screen icon, from one source image. Add it to modules and set its options under the pwa config key. It sets no serviceWorker key: an app opts into a worker with app/sw.ts or serviceWorker.generate.
// hamur.config.ts
import pwa from "@hamur/pwa"
export default defineConfig({
modules: [pwa],
app: { manifest: { name: "Todo", short_name: "Todo", theme_color: "#102030", background_color: "#ffffff" } },
pwa: { icons: { source: "app/pwa-icon.png", maskable: "app/pwa-maskable.png" } },
serviceWorker: { generate: "precache" },
})
default
The module, as defineModule({ meta: { name: "pwa", configKey: "pwa" } }). Its setup checks pwa (a wrong value is a load error naming the key), then:
- The manifest is the core's. The module sets
app.manifest.displayto"standalone"whenapp.manifestis unset or has nodisplay, appends its icons toapp.manifest.icons, and keeps every member the app set. Withapp.manifest: falseit leaves the manifest off. There is nopwa.manifestkey. theme-color. When the manifest hastheme_colorandapp.headhas notheme-colormeta, the module adds<meta name="theme-color" content="<theme_color>">.- Icons. With
pwa.icons, each size of the source is resized withBun.Imageto a PNG and emitted with the kit'semitFileaspwa-icon-<size>.png, so it is served as<app.baseURL><app.buildAssetsDir>pwa-icon-<size>-<8 hex>.png, content-hashed andimmutable. Each is listed inapp.manifest.iconsas{ src, sizes: "<n>x<n>", type: "image/png", purpose: "any" }. - Maskable icons.
pwa.icons.maskableis a second source, drawn by the app with the safe zone of a maskable icon (the art inside the centre circle of 80 %). Its sizes are emitted aspwa-maskable-<size>-<8 hex>.pngwithpurpose: "maskable". Hamur does not pad the plain source:Bun.Imageresizes and re-encodes but cannot pad or composite, and unpadded art marked maskable is cropped by the platform. - The apple touch icon. With
apple: true(the default) a 180 × 180pwa-apple-180-<8 hex>.pngis emitted and<link rel="apple-touch-icon" sizes="180x180" href>is added toapp.head, unless the app has anapp/apple-icon.*file, which then wins. - Source errors. The source is read with
readImageMetabeforeBun.Imagedecodes it. Each failure is a build error that starts with the key:pwa.icons.source: app/pwa-icon.png does not exist,pwa.icons.source: app/pwa-icon.svg is not a PNG, JPEG or WebP file,pwa.icons.source: app/pwa-icon.png is 512x400; an app icon is squareandpwa.icons.source: app/pwa-icon.png is 256x256; the largest size, 512, needs a source at least that large. The largest size counts 180 whenappleis on.pwa.icons.maskablefails the same way under its own key. hamur dev. The icons are made at start and a change of a source file restarts the dev server; the results are kept by the file's modification time.
PwaOptions
| Key | Type | Default |
|---|---|---|
registerType | "prompt" | "autoUpdate" | "prompt": with "prompt" a waiting worker sets needRefresh and waits for update(); with "autoUpdate" the client posts SKIP_WAITING at once and does not reload (usePwa) |
icons | PwaIcons | false | false: icons made from one source |
Load errors: pwa.registerType must be "prompt" or "autoUpdate" (got "auto"), pwa.icons must be an object or false (got "icon.png").
PwaIcons
| Key | Type | Default |
|---|---|---|
source | string | required: a square PNG, JPEG or WebP file, from rootDir, at least as large as the largest size |
maskable | string | none: a second source for the maskable icons |
sizes | number[] | [192, 512]: integers from 48 to 1024 |
apple | boolean | true |
Load errors: pwa.icons.sizes must be a non-empty array of integers from 48 to 1024 (got [0]), pwa.icons.source must be a file path (got undefined), pwa.icons.maskable must be a file path (got true), pwa.icons.apple must be a boolean (got "yes") and pwa.icons.<key> is not an option; use source, maskable, sizes, apple.
@hamur/pwa/client
The client app plugin's store. The module adds @hamur/pwa/client's plugin to the app (addAppPlugin, mode all) and writes registerType into #hamur/pwa/options; the plugin starts the store before the page mounts and provides it as app.pwa, so a beforeinstallprompt event that fires before a component calls usePwa() is not lost. The adapters' usePwa() read it; an app rarely imports it.
pwaStore()
pwaStore(): PwaStore is the page's one store; on the server it is an inert store that reads all false, resolves update() and resolves install() with "unavailable".
interface PwaState {
readonly needRefresh: boolean
readonly offlineReady: boolean
readonly installable: boolean
}
interface PwaActions {
update(): Promise<void>
install(): Promise<"accepted" | "dismissed" | "unavailable">
}
interface PwaStore extends PwaActions {
get(): PwaState
subscribe(listener: () => void): () => void
start(options: { registerType: "prompt" | "autoUpdate" }): void
}
offlineReady: a service worker controls the page.needRefresh: a worker reachedinstalledwhile another controls the page. NevertruewithregisterType: "autoUpdate".installable: abeforeinstallpromptevent was kept (the store callspreventDefault()on it). It isfalseagain afterinstall()orappinstalled. Safari and Firefox fire no such event and leave itfalse.update(): posts{ type: "SKIP_WAITING" }to the waiting worker and, when the page gets a new controller, reloads the page; two calls share one reload. With no waiting worker it resolves at once. A worker of your own (app/sw.ts) must answer that message;precache()does.install(): callsprompt()on the kept event and resolves itsuserChoice.outcome;"unavailable"when no event is kept.start(options): attaches the listeners once; the plugin calls it, a second call does nothing.
subscribePush(publicKey)
subscribePush(publicKey: string): Promise<PushSubscriptionJSON> waits for navigator.serviceWorker.ready, calls pushManager.subscribe({ userVisibleOnly: true, applicationServerKey }) with the bytes of publicKey (the VAPID public key of generateVapidKeys, base64url) and resolves the subscription's toJSON(), which is what sendPush takes. It is a plain function, so it is called the same way from every adapter.
- Without a service worker registered within 10 s, or in a browser without
navigator.serviceWorker, it rejects withsubscribePush needs a service worker (app/sw.ts or serviceWorker.generate). The worker must be anapp/sw.tswith apushlistener: the generated worker has none. - A permission the user refuses rejects with the browser's
NotAllowedError.
import { subscribePush } from "@hamur/pwa/client"
const subscription = await subscribePush(import.meta.env.VAPID_PUBLIC_KEY)
await $fetch("/api/push/subscribe", { method: "POST", body: subscription })
createPwaStore(environment), PWA_OFF
createPwaStore({ window, serviceWorker, reload }) builds a store over the objects it is given, for tests. PWA_OFF is the all-false state.
PwaState, PwaActions, PwaStore, PwaEnvironment, PwaStartOptions, PwaInstallOutcome
The types above. PwaInstallOutcome is "accepted" | "dismissed" | "unavailable".
@hamur/pwa/server
Web push with no dependency: the message is encrypted with aes128gcm (RFC 8291 over RFC 8188) and signed with a VAPID JWT (RFC 8292), through crypto.subtle and fetch only, so it runs on the bun, node and cloudflare presets alike. The private key belongs on the server: keep it in runtime config or an environment variable, never in code the client bundle can import.
generateVapidKeys()
generateVapidKeys(): Promise<{ publicKey: string; privateKey: string }> makes a P-256 pair: publicKey is the 65-byte uncompressed point, privateKey the 32-byte scalar, both base64url without padding. Make it once and keep both; a new pair invalidates every subscription made with the old public key.
sendPush(subscription, payload, options)
sendPush(
subscription: { endpoint: string; keys: { p256dh: string; auth: string } },
payload: string | Uint8Array | null,
options: {
vapid: { subject: string; publicKey: string; privateKey: string };
ttl?: number;
urgency?: "very-low" | "low" | "normal" | "high";
topic?: string;
timeout?: number;
allowInsecureEndpoint?: boolean;
},
): Promise<{ status: number; gone: boolean }>;
- Encryption. Each message gets a fresh ECDH P-256 key and a 16-byte salt; the body is the 86-byte
aes128gcmheader (salt, record size 4096, the sender key) and one record. A string payload is sent as UTF-8. A payload over 3993 bytes, the most one 4096-byte record holds, throwssendPush: the payload is 5000 bytes; a push message holds at most 3993.nullsends no body. - VAPID. An ES256 JWT signed with
signJWTofhamur/server, withaudthe endpoint's origin,subthe subject andexp12 hours on, sent asAuthorization: vapid t=<jwt>, k=<publicKey>. - Request.
POST <endpoint>withcontent-encoding: aes128gcm,content-type: application/octet-stream,ttl(seconds the push service keeps the message, default86400),urgency(default"normal") andtopicwhen given (a newer message of the same topic replaces one not yet delivered). - Endpoint. The subscription comes from a browser, so its endpoint is checked before anything is sent: it must be an
https:URL whose host is notlocalhost,*.localhostor an IP literal in a loopback, private, link-local, unique-local or reserved range (IPv4, IPv6 and IPv4-mapped IPv6). Only literals are checked: a public name that resolves to a private address is not caught, as Workers have no DNS lookup.allowInsecureEndpoint: truelifts both rules, for a local push service in tests; never set it in production. - Redirects and timeout. A redirect is not followed (the VAPID token is never sent to another host): a
3xxis returned as its status withgone: false. The push service hastimeoutmilliseconds (default10000) to answer; past it,sendPushrejects withsendPush: the push service did not answer within 10000 ms. - Answer.
{ status, gone }: the push service's status (201when it took the message) andgone,truefor404and410, which mean the subscription no longer exists and the app should delete it. A status never throws; a network failure rejects withfetch's error. - Errors, thrown before any request; none contains a key or the auth secret:
sendPush: vapid.subject must be a mailto: or https: URL (got "me@example.com"),sendPush: vapid.publicKey must be a base64url P-256 public key,sendPush: vapid.privateKey must be a base64url P-256 private key,sendPush: subscription.endpoint must be an https: URL(withallowInsecureEndpoint,… must be an http: or https: URL),sendPush: subscription.endpoint must not be a local or private address (got host "127.0.0.1"),sendPush: subscription.keys.p256dh must be a base64url P-256 public key,sendPush: subscription.keys.auth must be 16 bytes in base64url,sendPush: ttl must be an integer from 0 to 2419200 (got -1),sendPush: urgency must be "very-low", "low", "normal" or "high" (got "urgent")sendPush: topic must be at most 32 characters of A–Z, a–z, 0–9, - and _ (got "a b"),sendPush: timeout must be a positive integer of milliseconds (got 0)andsendPush: payload must be a string, a Uint8Array or null (got object), whichundefinedgets too.
import { sendPush } from "@hamur/pwa/server"
import { defineHandler, useRuntimeConfig, useStorage } from "hamur/server"
type PushSubscriptionData = Parameters<typeof sendPush>[0]
export const notify = defineHandler({
method: "POST",
async handler({ title }: { title: string }) {
const { vapid } = useRuntimeConfig()
const store = useStorage("push")
for (const key of await store.getKeys()) {
const subscription = await store.getItem<PushSubscriptionData>(key)
if (!subscription) continue
const { gone } = await sendPush(subscription, JSON.stringify({ title }), { vapid, urgency: "high" })
if (gone) await store.removeItem(key)
}
},
})
@hamur/pwa/react, @hamur/pwa/vue, @hamur/pwa/preact, @hamur/pwa/svelte, @hamur/pwa/solid, @hamur/pwa/html
One entry per adapter. Each exports usePwa and the types PwaState and PwaActions, with the same names in all six. usePwa() reads useApp().pwa and throws usePwa() needs the @hamur/pwa module in hamur.config.ts modules without the module.
usePwa()
usePwa() returns the three flags of PwaState and the two methods of PwaActions. On the server, and until the page is hydrated, every flag is false.
| Library | Returns |
|---|---|
| react, preact | PwaState & PwaActions, re-rendering on change |
| vue | { needRefresh: Readonly<Ref<boolean>>, offlineReady: ..., installable: ... } & PwaActions |
| solid | { needRefresh: Accessor<boolean>, ... } & PwaActions |
| svelte | getters that re-run their reader on change (createSubscriber) |
| html | getters plus subscribe(listener: () => void): () => void |
const { installable, needRefresh, install, update } = usePwa()
if (installable) await install()
if (needRefresh) await update()