# `@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`.

```ts
// 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.display` to `"standalone"` when `app.manifest` is unset or has no `display`, appends its icons to `app.manifest.icons`, and keeps every member the app set. With `app.manifest: false` it leaves the manifest off. There is no `pwa.manifest` key.
- **`theme-color`.** When the manifest has `theme_color` and `app.head` has no `theme-color` meta, the module adds `<meta name="theme-color" content="<theme_color>">`.
- **Icons.** With `pwa.icons`, each size of the source is resized with `Bun.Image` to a PNG and emitted with the kit's `emitFile` as `pwa-icon-<size>.png`, so it is served as `<app.baseURL><app.buildAssetsDir>pwa-icon-<size>-<8 hex>.png`, content-hashed and `immutable`. Each is listed in `app.manifest.icons` as `{ src, sizes: "<n>x<n>", type: "image/png", purpose: "any" }`.
- **Maskable icons.** `pwa.icons.maskable` is 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 as `pwa-maskable-<size>-<8 hex>.png` with `purpose: "maskable"`. Hamur does not pad the plain source: `Bun.Image` resizes 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 × 180 `pwa-apple-180-<8 hex>.png` is emitted and `<link rel="apple-touch-icon" sizes="180x180" href>` is added to `app.head`, unless the app has an `app/apple-icon.*` file, which then wins.
- **Source errors.** The source is read with `readImageMeta` before `Bun.Image` decodes 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 square` and `pwa.icons.source: app/pwa-icon.png is 256x256; the largest size, 512, needs a source at least that large`. The largest size counts 180 when `apple` is on. `pwa.icons.maskable` fails 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"`.

```ts
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 reached `installed` while another controls the page. Never `true` with `registerType: "autoUpdate"`.
- **`installable`**: a `beforeinstallprompt` event was kept (the store calls `preventDefault()` on it). It is `false` again after `install()` or `appinstalled`. Safari and Firefox fire no such event and leave it `false`.
- **`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()`**: calls `prompt()` on the kept event and resolves its `userChoice.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 with `subscribePush needs a service worker (app/sw.ts or serviceWorker.generate)`. The worker must be an `app/sw.ts` with a `push` listener: the generated worker has none.
- A permission the user refuses rejects with the browser's `NotAllowedError`.

```ts
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)`

```ts
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 `aes128gcm` header (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, throws `sendPush: the payload is 5000 bytes; a push message holds at most 3993`. `null` sends no body.
- **VAPID.** An ES256 JWT signed with `signJWT` of `hamur/server`, with `aud` the endpoint's origin, `sub` the subject and `exp` 12 hours on, sent as `Authorization: vapid t=<jwt>, k=<publicKey>`.
- **Request.** `POST <endpoint>` with `content-encoding: aes128gcm`, `content-type: application/octet-stream`, `ttl` (seconds the push service keeps the message, default `86400`), `urgency` (default `"normal"`) and `topic` when 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 not `localhost`, `*.localhost` or 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: true` lifts 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 `3xx` is returned as its status with `gone: false`. The push service has `timeout` milliseconds (default `10000`) to answer; past it, `sendPush` rejects with `sendPush: the push service did not answer within 10000 ms`.
- **Answer.** `{ status, gone }`: the push service's status (`201` when it took the message) and `gone`, `true` for `404` and `410`, which mean the subscription no longer exists and the app should delete it. A status never throws; a network failure rejects with `fetch`'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` (with `allowInsecureEndpoint`, `… 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)` and `sendPush: payload must be a string, a Uint8Array or null (got object)`, which `undefined` gets too.

```ts
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`                                  |

```tsx
const { installable, needRefresh, install, update } = usePwa()
if (installable) await install()
if (needRefresh) await update()
```
