@hamur/pwa 0.0.0-stage → 0.0.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +22 -0
- package/README.md +14 -2
- package/dist/chunks/bun-index-33c14md9.js +11 -0
- package/dist/chunks/bun-index-5jwxzmvt.js +133 -0
- package/dist/src/adapters/html.js +28 -0
- package/dist/src/adapters/preact.js +23 -0
- package/dist/src/adapters/react.js +19 -0
- package/dist/src/adapters/solid.js +29 -0
- package/dist/src/adapters/svelte.js +32 -0
- package/dist/src/adapters/vue.js +31 -0
- package/dist/src/client/index.js +43 -0
- package/dist/src/index.js +178 -0
- package/dist/src/server/index.js +202 -0
- package/dist/types/src/adapters/bind.d.ts +4 -0
- package/dist/types/src/adapters/html.d.ts +3 -0
- package/dist/types/src/adapters/preact.d.ts +3 -0
- package/dist/types/src/adapters/react.d.ts +3 -0
- package/dist/types/src/adapters/solid.d.ts +6 -0
- package/dist/types/src/adapters/svelte.d.ts +3 -0
- package/dist/types/src/adapters/vue.d.ts +6 -0
- package/dist/types/src/build/icons.d.ts +7 -0
- package/dist/types/src/client/index.d.ts +3 -0
- package/dist/types/src/client/plugin.d.ts +4 -0
- package/dist/types/src/client/push.d.ts +4 -0
- package/dist/types/src/client/store.d.ts +34 -0
- package/dist/types/src/index.d.ts +8 -0
- package/dist/types/src/module.d.ts +3 -0
- package/dist/types/src/options.d.ts +13 -0
- package/dist/types/src/server/encrypt.d.ts +18 -0
- package/dist/types/src/server/index.d.ts +2 -0
- package/dist/types/src/server/push.d.ts +28 -0
- package/dist/types/src/server/vapid.d.ts +7 -0
- package/dist/types/src/types.d.ts +16 -0
- package/package.json +129 -4
- package/src/adapters/bind.ts +10 -0
- package/src/adapters/html.ts +24 -0
- package/src/adapters/preact.ts +16 -0
- package/src/adapters/react.ts +12 -0
- package/src/adapters/solid.ts +22 -0
- package/src/adapters/svelte.ts +28 -0
- package/src/adapters/vue.ts +24 -0
- package/src/build/icons.ts +60 -0
- package/src/client/index.ts +3 -0
- package/src/client/plugin.ts +11 -0
- package/src/client/push.ts +37 -0
- package/src/client/store.ts +174 -0
- package/src/env.d.ts +4 -0
- package/src/index.ts +12 -0
- package/src/module.ts +110 -0
- package/src/options.ts +55 -0
- package/src/server/encrypt.ts +84 -0
- package/src/server/index.ts +2 -0
- package/src/server/push.ts +146 -0
- package/src/server/vapid.ts +32 -0
- package/src/types.ts +17 -0
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
import { createSubscriber } from "svelte/reactivity"
|
|
2
|
+
import { useApp } from "@hamur/adapter-svelte"
|
|
3
|
+
import type { PwaActions, PwaState } from "../client/store.ts"
|
|
4
|
+
import { pwaOf } from "./bind.ts"
|
|
5
|
+
|
|
6
|
+
export type { PwaActions, PwaState }
|
|
7
|
+
|
|
8
|
+
export function usePwa(): PwaState & PwaActions {
|
|
9
|
+
const store = pwaOf(useApp())
|
|
10
|
+
const subscribe = createSubscriber((update) => store.subscribe(update))
|
|
11
|
+
const read = <K extends keyof PwaState>(key: K): PwaState[K] => {
|
|
12
|
+
subscribe()
|
|
13
|
+
return store.get()[key]
|
|
14
|
+
}
|
|
15
|
+
return {
|
|
16
|
+
get needRefresh() {
|
|
17
|
+
return read("needRefresh")
|
|
18
|
+
},
|
|
19
|
+
get offlineReady() {
|
|
20
|
+
return read("offlineReady")
|
|
21
|
+
},
|
|
22
|
+
get installable() {
|
|
23
|
+
return read("installable")
|
|
24
|
+
},
|
|
25
|
+
update: store.update,
|
|
26
|
+
install: store.install,
|
|
27
|
+
}
|
|
28
|
+
}
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
import { computed, onMounted, onUnmounted, shallowRef, type Ref } from "vue"
|
|
2
|
+
import { useApp } from "@hamur/adapter-vue"
|
|
3
|
+
import { PWA_OFF, type PwaActions, type PwaState } from "../client/store.ts"
|
|
4
|
+
import { pwaOf } from "./bind.ts"
|
|
5
|
+
|
|
6
|
+
export type { PwaActions, PwaState }
|
|
7
|
+
|
|
8
|
+
export function usePwa(): { [K in keyof PwaState]: Readonly<Ref<PwaState[K]>> } & PwaActions {
|
|
9
|
+
const store = pwaOf(useApp())
|
|
10
|
+
const state = shallowRef<PwaState>(PWA_OFF)
|
|
11
|
+
let stop: (() => void) | undefined
|
|
12
|
+
onMounted(() => {
|
|
13
|
+
state.value = store.get()
|
|
14
|
+
stop = store.subscribe(() => (state.value = store.get()))
|
|
15
|
+
})
|
|
16
|
+
onUnmounted(() => stop?.())
|
|
17
|
+
return {
|
|
18
|
+
needRefresh: computed(() => state.value.needRefresh),
|
|
19
|
+
offlineReady: computed(() => state.value.offlineReady),
|
|
20
|
+
installable: computed(() => state.value.installable),
|
|
21
|
+
update: store.update,
|
|
22
|
+
install: store.install,
|
|
23
|
+
}
|
|
24
|
+
}
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
import { readFile, stat } from "node:fs/promises"
|
|
2
|
+
import { readImageMeta } from "hamur/kit"
|
|
3
|
+
import { DiagnosticError } from "hamur/kit"
|
|
4
|
+
|
|
5
|
+
export const APPLE_SIZE = 180
|
|
6
|
+
|
|
7
|
+
type Key = "source" | "maskable"
|
|
8
|
+
|
|
9
|
+
const FORMATS = ["png", "jpeg", "webp"]
|
|
10
|
+
|
|
11
|
+
/** Reads `file` and refuses it, in the words of the design, unless it is a square PNG, JPEG or WebP of at least `largest` px. */
|
|
12
|
+
export async function readSource(
|
|
13
|
+
key: Key,
|
|
14
|
+
shown: string,
|
|
15
|
+
file: string,
|
|
16
|
+
largest: number,
|
|
17
|
+
): Promise<Uint8Array<ArrayBuffer>> {
|
|
18
|
+
const at = `pwa.icons.${key}: ${shown}`
|
|
19
|
+
let bytes: Uint8Array<ArrayBuffer>
|
|
20
|
+
try {
|
|
21
|
+
if (!(await stat(file)).isFile()) throw new Error("not a file")
|
|
22
|
+
bytes = new Uint8Array(await readFile(file))
|
|
23
|
+
} catch {
|
|
24
|
+
throw new DiagnosticError("HAMUR_E6202", `${at} does not exist`)
|
|
25
|
+
}
|
|
26
|
+
let size: { width: number; height: number } | undefined
|
|
27
|
+
for (const format of FORMATS) {
|
|
28
|
+
try {
|
|
29
|
+
size = readImageMeta(bytes, format, shown)
|
|
30
|
+
break
|
|
31
|
+
} catch {}
|
|
32
|
+
}
|
|
33
|
+
if (!size) throw new DiagnosticError("HAMUR_E6203", `${at} is not a PNG, JPEG or WebP file`)
|
|
34
|
+
if (size.width !== size.height)
|
|
35
|
+
throw new DiagnosticError("HAMUR_E6204", `${at} is ${size.width}x${size.height}; an app icon is square`)
|
|
36
|
+
if (size.width < largest)
|
|
37
|
+
throw new DiagnosticError(
|
|
38
|
+
"HAMUR_E6205",
|
|
39
|
+
`${at} is ${size.width}x${size.height}; the largest size, ${largest}, needs a source at least that large`,
|
|
40
|
+
)
|
|
41
|
+
return bytes
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
const resized = new Map<string, Uint8Array<ArrayBuffer>>()
|
|
45
|
+
|
|
46
|
+
/** `new Bun.Image(source).resize(n, n).png()`; a result is kept per file, modification time and size so `hamur dev` restarts do not decode again. */
|
|
47
|
+
export async function resizeIcon(
|
|
48
|
+
file: string,
|
|
49
|
+
mtimeMs: number,
|
|
50
|
+
bytes: Uint8Array,
|
|
51
|
+
size: number,
|
|
52
|
+
): Promise<Uint8Array<ArrayBuffer>> {
|
|
53
|
+
const key = `${file}\0${mtimeMs}\0${size}`
|
|
54
|
+
const known = resized.get(key)
|
|
55
|
+
if (known) return known
|
|
56
|
+
Bun.Image.backend = "bun"
|
|
57
|
+
const out = new Uint8Array(await new Bun.Image(bytes).resize(size, size).png().bytes())
|
|
58
|
+
resized.set(key, out)
|
|
59
|
+
return out
|
|
60
|
+
}
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
/// <reference path="../env.d.ts" />
|
|
2
|
+
import { definePlugin } from "hamur/app"
|
|
3
|
+
import options from "#hamur/pwa/options"
|
|
4
|
+
import { pwaStore } from "./store.ts"
|
|
5
|
+
|
|
6
|
+
export default definePlugin((app) => {
|
|
7
|
+
const store = pwaStore()
|
|
8
|
+
store.start(options)
|
|
9
|
+
app.hooks.hook("app:update", () => store.refresh())
|
|
10
|
+
return { provide: { pwa: store } }
|
|
11
|
+
})
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
export const NO_WORKER = "subscribePush needs a service worker (app/sw.ts or serviceWorker.generate)"
|
|
2
|
+
const READY_WAIT = 10_000
|
|
3
|
+
|
|
4
|
+
function keyBytes(publicKey: string): Uint8Array<ArrayBuffer> {
|
|
5
|
+
const binary = atob(publicKey.replace(/-/g, "+").replace(/_/g, "/"))
|
|
6
|
+
return Uint8Array.from(binary, (char) => char.charCodeAt(0))
|
|
7
|
+
}
|
|
8
|
+
|
|
9
|
+
export async function subscribeWith(
|
|
10
|
+
container: ServiceWorkerContainer | undefined,
|
|
11
|
+
publicKey: string,
|
|
12
|
+
wait = READY_WAIT,
|
|
13
|
+
): Promise<PushSubscriptionJSON> {
|
|
14
|
+
if (!container) throw new Error(NO_WORKER)
|
|
15
|
+
let timer: ReturnType<typeof setTimeout> | undefined
|
|
16
|
+
let registration: ServiceWorkerRegistration
|
|
17
|
+
try {
|
|
18
|
+
registration = await Promise.race([
|
|
19
|
+
container.ready,
|
|
20
|
+
new Promise<never>((_, reject) => {
|
|
21
|
+
timer = setTimeout(() => reject(new Error(NO_WORKER)), wait)
|
|
22
|
+
}),
|
|
23
|
+
])
|
|
24
|
+
} finally {
|
|
25
|
+
clearTimeout(timer)
|
|
26
|
+
}
|
|
27
|
+
const subscription = await registration.pushManager.subscribe({
|
|
28
|
+
userVisibleOnly: true,
|
|
29
|
+
applicationServerKey: keyBytes(publicKey),
|
|
30
|
+
})
|
|
31
|
+
return subscription.toJSON()
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/** Subscribes the page's service worker registration to push with the app's VAPID public key. */
|
|
35
|
+
export function subscribePush(publicKey: string): Promise<PushSubscriptionJSON> {
|
|
36
|
+
return subscribeWith(typeof navigator === "undefined" ? undefined : navigator.serviceWorker, publicKey)
|
|
37
|
+
}
|
|
@@ -0,0 +1,174 @@
|
|
|
1
|
+
import { reloadApp } from "hamur/app"
|
|
2
|
+
|
|
3
|
+
/** What `usePwa()` reads. */
|
|
4
|
+
export interface PwaState {
|
|
5
|
+
readonly needRefresh: boolean
|
|
6
|
+
readonly offlineReady: boolean
|
|
7
|
+
readonly installable: boolean
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
export type PwaInstallOutcome = "accepted" | "dismissed" | "unavailable"
|
|
11
|
+
|
|
12
|
+
/** What `usePwa()` calls. */
|
|
13
|
+
export interface PwaActions {
|
|
14
|
+
update(): Promise<void>
|
|
15
|
+
install(): Promise<PwaInstallOutcome>
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
export interface PwaStartOptions {
|
|
19
|
+
registerType: "prompt" | "autoUpdate"
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
export interface PwaStore extends PwaActions {
|
|
23
|
+
get(): PwaState
|
|
24
|
+
subscribe(listener: () => void): () => void
|
|
25
|
+
/** Starts listening once; the client app plugin calls it before the page mounts. */
|
|
26
|
+
start(options: PwaStartOptions): void
|
|
27
|
+
/** Asks the registration to look for a new `sw.js` (the app update found a new build); a failure is ignored. */
|
|
28
|
+
refresh(): Promise<void>
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
export interface PwaEnvironment {
|
|
32
|
+
window: { addEventListener(type: string, listener: (event: Event) => void): void }
|
|
33
|
+
serviceWorker: ServiceWorkerContainer | undefined
|
|
34
|
+
reload(): void
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
interface InstallPromptEvent extends Event {
|
|
38
|
+
prompt(): Promise<void>
|
|
39
|
+
userChoice: Promise<{ outcome: "accepted" | "dismissed" }>
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
export const PWA_OFF: PwaState = Object.freeze({ needRefresh: false, offlineReady: false, installable: false })
|
|
43
|
+
|
|
44
|
+
const SKIP_WAITING = { type: "SKIP_WAITING" }
|
|
45
|
+
|
|
46
|
+
export function createPwaStore(env: PwaEnvironment): PwaStore {
|
|
47
|
+
let state: PwaState = PWA_OFF
|
|
48
|
+
let started = false
|
|
49
|
+
let registerType: PwaStartOptions["registerType"] = "prompt"
|
|
50
|
+
let prompt: InstallPromptEvent | undefined
|
|
51
|
+
let registration: ServiceWorkerRegistration | undefined
|
|
52
|
+
let skipped: ServiceWorker | undefined
|
|
53
|
+
let updating: Promise<void> | undefined
|
|
54
|
+
const listeners = new Set<() => void>()
|
|
55
|
+
|
|
56
|
+
const set = (patch: Partial<PwaState>): void => {
|
|
57
|
+
const next = { ...state, ...patch }
|
|
58
|
+
if (
|
|
59
|
+
next.needRefresh === state.needRefresh &&
|
|
60
|
+
next.offlineReady === state.offlineReady &&
|
|
61
|
+
next.installable === state.installable
|
|
62
|
+
)
|
|
63
|
+
return
|
|
64
|
+
state = next
|
|
65
|
+
for (const listener of [...listeners]) listener()
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
const settle = (): void => {
|
|
69
|
+
const offlineReady = env.serviceWorker?.controller != null
|
|
70
|
+
const waiting = registration?.waiting ?? undefined
|
|
71
|
+
if (!waiting || !offlineReady) return set({ needRefresh: false, offlineReady })
|
|
72
|
+
if (registerType === "autoUpdate") {
|
|
73
|
+
if (skipped !== waiting) {
|
|
74
|
+
skipped = waiting
|
|
75
|
+
waiting.postMessage(SKIP_WAITING)
|
|
76
|
+
}
|
|
77
|
+
return set({ needRefresh: false, offlineReady })
|
|
78
|
+
}
|
|
79
|
+
set({ needRefresh: true, offlineReady })
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
const follow = (worker: ServiceWorker | null): void => {
|
|
83
|
+
worker?.addEventListener("statechange", () => {
|
|
84
|
+
if (worker.state === "installed") settle()
|
|
85
|
+
})
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
const track = (found: ServiceWorkerRegistration): void => {
|
|
89
|
+
registration = found
|
|
90
|
+
follow(found.installing)
|
|
91
|
+
found.addEventListener("updatefound", () => follow(found.installing))
|
|
92
|
+
settle()
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
return {
|
|
96
|
+
get: () => state,
|
|
97
|
+
subscribe(listener) {
|
|
98
|
+
listeners.add(listener)
|
|
99
|
+
return () => void listeners.delete(listener)
|
|
100
|
+
},
|
|
101
|
+
start(options) {
|
|
102
|
+
if (started) return
|
|
103
|
+
started = true
|
|
104
|
+
registerType = options.registerType
|
|
105
|
+
env.window.addEventListener("beforeinstallprompt", (event) => {
|
|
106
|
+
event.preventDefault()
|
|
107
|
+
prompt = event as InstallPromptEvent
|
|
108
|
+
set({ installable: true })
|
|
109
|
+
})
|
|
110
|
+
env.window.addEventListener("appinstalled", () => {
|
|
111
|
+
prompt = undefined
|
|
112
|
+
set({ installable: false })
|
|
113
|
+
})
|
|
114
|
+
const container = env.serviceWorker
|
|
115
|
+
if (!container) return
|
|
116
|
+
container.addEventListener("controllerchange", settle)
|
|
117
|
+
container.ready.then(track).catch(() => undefined)
|
|
118
|
+
},
|
|
119
|
+
async refresh() {
|
|
120
|
+
try {
|
|
121
|
+
await registration?.update()
|
|
122
|
+
} catch {
|
|
123
|
+
return
|
|
124
|
+
}
|
|
125
|
+
},
|
|
126
|
+
update() {
|
|
127
|
+
const waiting = registration?.waiting
|
|
128
|
+
const container = env.serviceWorker
|
|
129
|
+
if (!waiting || !container) return Promise.resolve()
|
|
130
|
+
updating ??= new Promise<void>((resolve) => {
|
|
131
|
+
container.addEventListener(
|
|
132
|
+
"controllerchange",
|
|
133
|
+
() => {
|
|
134
|
+
env.reload()
|
|
135
|
+
resolve()
|
|
136
|
+
},
|
|
137
|
+
{ once: true },
|
|
138
|
+
)
|
|
139
|
+
waiting.postMessage(SKIP_WAITING)
|
|
140
|
+
})
|
|
141
|
+
return updating
|
|
142
|
+
},
|
|
143
|
+
async install() {
|
|
144
|
+
const event = prompt
|
|
145
|
+
if (!event) return "unavailable"
|
|
146
|
+
prompt = undefined
|
|
147
|
+
set({ installable: false })
|
|
148
|
+
await event.prompt()
|
|
149
|
+
return (await event.userChoice).outcome
|
|
150
|
+
},
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
const INERT: PwaStore = {
|
|
155
|
+
get: () => PWA_OFF,
|
|
156
|
+
subscribe: () => () => undefined,
|
|
157
|
+
start: () => undefined,
|
|
158
|
+
refresh: () => Promise.resolve(),
|
|
159
|
+
update: () => Promise.resolve(),
|
|
160
|
+
install: () => Promise.resolve("unavailable"),
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
let shared: PwaStore | undefined
|
|
164
|
+
|
|
165
|
+
/** The page's store: one per document; on the server an inert one that reads all `false`. */
|
|
166
|
+
export function pwaStore(): PwaStore {
|
|
167
|
+
if (typeof window === "undefined") return INERT
|
|
168
|
+
shared ??= createPwaStore({
|
|
169
|
+
window,
|
|
170
|
+
serviceWorker: "serviceWorker" in navigator ? navigator.serviceWorker : undefined,
|
|
171
|
+
reload: () => void reloadApp({ force: true }),
|
|
172
|
+
})
|
|
173
|
+
return shared
|
|
174
|
+
}
|
package/src/env.d.ts
ADDED
package/src/index.ts
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
// Loads hamur so the augmentation below resolves in a program where nothing else imports bare "hamur".
|
|
2
|
+
import type {} from "hamur"
|
|
3
|
+
import type { PwaOptions } from "./types.ts"
|
|
4
|
+
|
|
5
|
+
export { default } from "./module.ts"
|
|
6
|
+
export type { PwaIcons, PwaOptions } from "./types.ts"
|
|
7
|
+
|
|
8
|
+
declare module "hamur" {
|
|
9
|
+
interface HamurModuleOptions {
|
|
10
|
+
pwa?: PwaOptions
|
|
11
|
+
}
|
|
12
|
+
}
|
package/src/module.ts
ADDED
|
@@ -0,0 +1,110 @@
|
|
|
1
|
+
import { readdirSync } from "node:fs"
|
|
2
|
+
import { resolve } from "node:path"
|
|
3
|
+
import {
|
|
4
|
+
addAppPlugin,
|
|
5
|
+
addTemplate,
|
|
6
|
+
addWatchFile,
|
|
7
|
+
createResolver,
|
|
8
|
+
defineModule,
|
|
9
|
+
emitFile,
|
|
10
|
+
type HamurContext,
|
|
11
|
+
} from "hamur/kit"
|
|
12
|
+
import type { WebAppManifestIcon } from "hamur"
|
|
13
|
+
import { APPLE_SIZE, readSource, resizeIcon } from "./build/icons.ts"
|
|
14
|
+
import { resolveOptions, type ResolvedPwaOptions } from "./options.ts"
|
|
15
|
+
import type { PwaOptions } from "./types.ts"
|
|
16
|
+
|
|
17
|
+
const APPLE_ICON = /^apple-icon\d*\.(png|jpe?g)$/
|
|
18
|
+
|
|
19
|
+
function hasAppleIcon(hamur: HamurContext): boolean {
|
|
20
|
+
return [hamur.options.srcDir, ...hamur.options.layers.map((layer) => layer.srcDir)].some((dir) => {
|
|
21
|
+
try {
|
|
22
|
+
return readdirSync(dir).some((name) => APPLE_ICON.test(name))
|
|
23
|
+
} catch {
|
|
24
|
+
return false
|
|
25
|
+
}
|
|
26
|
+
})
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/** Each size of `file` as an emitted, content-hashed PNG; returns the URLs by size. */
|
|
30
|
+
async function emitSizes(
|
|
31
|
+
prefix: string,
|
|
32
|
+
file: string,
|
|
33
|
+
bytes: Uint8Array,
|
|
34
|
+
sizes: number[],
|
|
35
|
+
): Promise<Array<{ size: number; url: string }>> {
|
|
36
|
+
const mtimeMs = Bun.file(file).lastModified
|
|
37
|
+
const out: Array<{ size: number; url: string }> = []
|
|
38
|
+
for (const size of sizes)
|
|
39
|
+
out.push({
|
|
40
|
+
size,
|
|
41
|
+
url: await emitFile({ name: `${prefix}-${size}.png`, source: await resizeIcon(file, mtimeMs, bytes, size) }),
|
|
42
|
+
})
|
|
43
|
+
return out
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
async function makeIcons(
|
|
47
|
+
icons: NonNullable<Exclude<ResolvedPwaOptions["icons"], false>>,
|
|
48
|
+
hamur: HamurContext,
|
|
49
|
+
): Promise<{ manifest: WebAppManifestIcon[]; apple?: string }> {
|
|
50
|
+
const { rootDir } = hamur.options
|
|
51
|
+
const apple = icons.apple && !hasAppleIcon(hamur)
|
|
52
|
+
const largest = Math.max(...icons.sizes, apple ? APPLE_SIZE : 0)
|
|
53
|
+
const manifest: WebAppManifestIcon[] = []
|
|
54
|
+
const entry = (size: number, url: string, purpose: string): WebAppManifestIcon => ({
|
|
55
|
+
src: url,
|
|
56
|
+
sizes: `${size}x${size}`,
|
|
57
|
+
type: "image/png",
|
|
58
|
+
purpose,
|
|
59
|
+
})
|
|
60
|
+
|
|
61
|
+
const file = resolve(rootDir, icons.source)
|
|
62
|
+
const bytes = await readSource("source", icons.source, file, largest)
|
|
63
|
+
addWatchFile(file)
|
|
64
|
+
for (const { size, url } of await emitSizes("pwa-icon", file, bytes, icons.sizes))
|
|
65
|
+
manifest.push(entry(size, url, "any"))
|
|
66
|
+
let appleURL: string | undefined
|
|
67
|
+
if (apple) appleURL = (await emitSizes("pwa-apple", file, bytes, [APPLE_SIZE]))[0]!.url
|
|
68
|
+
|
|
69
|
+
if (icons.maskable !== undefined) {
|
|
70
|
+
const maskableFile = resolve(rootDir, icons.maskable)
|
|
71
|
+
const maskableBytes = await readSource("maskable", icons.maskable, maskableFile, largest)
|
|
72
|
+
addWatchFile(maskableFile)
|
|
73
|
+
for (const { size, url } of await emitSizes("pwa-maskable", maskableFile, maskableBytes, icons.sizes))
|
|
74
|
+
manifest.push(entry(size, url, "maskable"))
|
|
75
|
+
}
|
|
76
|
+
return { manifest, ...(appleURL === undefined ? {} : { apple: appleURL }) }
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
export default defineModule<PwaOptions>({
|
|
80
|
+
meta: { name: "pwa", configKey: "pwa" },
|
|
81
|
+
async setup(input, hamur) {
|
|
82
|
+
const options = resolveOptions(input)
|
|
83
|
+
const { app } = hamur.options
|
|
84
|
+
const head = { ...app.head }
|
|
85
|
+
const links = [...(head.link ?? [])]
|
|
86
|
+
const metas = [...(head.meta ?? [])]
|
|
87
|
+
|
|
88
|
+
const manifest = app.manifest === false ? false : { ...app.manifest }
|
|
89
|
+
if (manifest && manifest.display === undefined) manifest.display = "standalone"
|
|
90
|
+
|
|
91
|
+
if (options.icons) {
|
|
92
|
+
const made = await makeIcons(options.icons, hamur)
|
|
93
|
+
if (manifest) manifest.icons = [...(manifest.icons ?? []), ...made.manifest]
|
|
94
|
+
if (made.apple !== undefined)
|
|
95
|
+
links.push({ rel: "apple-touch-icon", sizes: `${APPLE_SIZE}x${APPLE_SIZE}`, href: made.apple })
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
if (manifest && manifest.theme_color !== undefined && !metas.some((meta) => meta.name === "theme-color"))
|
|
99
|
+
metas.push({ name: "theme-color", content: manifest.theme_color })
|
|
100
|
+
|
|
101
|
+
addTemplate({
|
|
102
|
+
filename: "pwa/options",
|
|
103
|
+
getContents: () => `export default ${JSON.stringify({ registerType: options.registerType })};\n`,
|
|
104
|
+
})
|
|
105
|
+
addAppPlugin({ src: createResolver(import.meta.url).resolve("./client/plugin.ts"), mode: "all" })
|
|
106
|
+
|
|
107
|
+
app.manifest = manifest
|
|
108
|
+
app.head = { ...head, ...(links.length > 0 ? { link: links } : {}), ...(metas.length > 0 ? { meta: metas } : {}) }
|
|
109
|
+
},
|
|
110
|
+
})
|
package/src/options.ts
ADDED
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
import type { PwaIcons, PwaOptions } from "./types.ts"
|
|
2
|
+
import { DiagnosticError } from "hamur/kit"
|
|
3
|
+
|
|
4
|
+
export const DEFAULT_SIZES = [192, 512]
|
|
5
|
+
const ICON_KEYS = ["source", "maskable", "sizes", "apple"]
|
|
6
|
+
|
|
7
|
+
export interface ResolvedPwaOptions {
|
|
8
|
+
registerType: "prompt" | "autoUpdate"
|
|
9
|
+
icons: false | { source: string; maskable?: string; sizes: number[]; apple: boolean }
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
const shown = (value: unknown): string =>
|
|
13
|
+
typeof value === "function" ? "a function" : (JSON.stringify(value) ?? String(value))
|
|
14
|
+
const isObject = (value: unknown): value is Record<string, unknown> =>
|
|
15
|
+
typeof value === "object" && value !== null && !Array.isArray(value)
|
|
16
|
+
|
|
17
|
+
function fail(message: string): never {
|
|
18
|
+
throw new DiagnosticError("HAMUR_E6201", message)
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
function resolveIcons(value: unknown): ResolvedPwaOptions["icons"] {
|
|
22
|
+
if (value === undefined || value === false) return false
|
|
23
|
+
if (!isObject(value)) fail(`pwa.icons must be an object or false (got ${shown(value)})`)
|
|
24
|
+
for (const key of Object.keys(value))
|
|
25
|
+
if (!ICON_KEYS.includes(key)) fail(`pwa.icons.${key} is not an option; use ${ICON_KEYS.join(", ")}`)
|
|
26
|
+
const { source, maskable, sizes, apple } = value as Partial<Record<keyof PwaIcons, unknown>>
|
|
27
|
+
if (typeof source !== "string" || source === "") fail(`pwa.icons.source must be a file path (got ${shown(source)})`)
|
|
28
|
+
if (maskable !== undefined && (typeof maskable !== "string" || maskable === ""))
|
|
29
|
+
fail(`pwa.icons.maskable must be a file path (got ${shown(maskable)})`)
|
|
30
|
+
if (apple !== undefined && typeof apple !== "boolean") fail(`pwa.icons.apple must be a boolean (got ${shown(apple)})`)
|
|
31
|
+
if (
|
|
32
|
+
sizes !== undefined &&
|
|
33
|
+
!(
|
|
34
|
+
Array.isArray(sizes) &&
|
|
35
|
+
sizes.length > 0 &&
|
|
36
|
+
sizes.every((size) => Number.isInteger(size) && size >= 48 && size <= 1024)
|
|
37
|
+
)
|
|
38
|
+
) {
|
|
39
|
+
fail(`pwa.icons.sizes must be a non-empty array of integers from 48 to 1024 (got ${shown(sizes)})`)
|
|
40
|
+
}
|
|
41
|
+
return {
|
|
42
|
+
source,
|
|
43
|
+
...(maskable === undefined ? {} : { maskable }),
|
|
44
|
+
sizes: sizes === undefined ? DEFAULT_SIZES : [...new Set(sizes as number[])].toSorted((a, b) => a - b),
|
|
45
|
+
apple: apple ?? true,
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/** Checks the `pwa` key and fills its defaults. */
|
|
50
|
+
export function resolveOptions(input: PwaOptions | undefined): ResolvedPwaOptions {
|
|
51
|
+
const { registerType = "prompt", icons } = input ?? {}
|
|
52
|
+
if (registerType !== "prompt" && registerType !== "autoUpdate")
|
|
53
|
+
fail(`pwa.registerType must be "prompt" or "autoUpdate" (got ${shown(registerType)})`)
|
|
54
|
+
return { registerType, icons: resolveIcons(icons) }
|
|
55
|
+
}
|
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
export const RECORD_SIZE = 4096
|
|
2
|
+
export const MAX_PAYLOAD = 3993
|
|
3
|
+
const SALT_BYTES = 16
|
|
4
|
+
const KEY_BYTES = 65
|
|
5
|
+
const HEADER_BYTES = SALT_BYTES + 4 + 1 + KEY_BYTES
|
|
6
|
+
const DELIMITER = 0x02
|
|
7
|
+
const P256 = { name: "ECDH", namedCurve: "P-256" } as const
|
|
8
|
+
|
|
9
|
+
const encoder = new TextEncoder()
|
|
10
|
+
const KEY_INFO = encoder.encode("WebPush: info\x00")
|
|
11
|
+
const CEK_INFO = encoder.encode("Content-Encoding: aes128gcm\x00")
|
|
12
|
+
const NONCE_INFO = encoder.encode("Content-Encoding: nonce\x00")
|
|
13
|
+
|
|
14
|
+
export interface SenderKeys {
|
|
15
|
+
publicKey: Uint8Array<ArrayBuffer>
|
|
16
|
+
privateKey: CryptoKey
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
function concat(...parts: Uint8Array[]): Uint8Array<ArrayBuffer> {
|
|
20
|
+
const out = new Uint8Array(parts.reduce((total, part) => total + part.length, 0))
|
|
21
|
+
let offset = 0
|
|
22
|
+
for (const part of parts) {
|
|
23
|
+
out.set(part, offset)
|
|
24
|
+
offset += part.length
|
|
25
|
+
}
|
|
26
|
+
return out
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
async function hkdf(
|
|
30
|
+
salt: Uint8Array<ArrayBuffer>,
|
|
31
|
+
ikm: Uint8Array<ArrayBuffer>,
|
|
32
|
+
info: Uint8Array<ArrayBuffer>,
|
|
33
|
+
bytes: number,
|
|
34
|
+
): Promise<Uint8Array<ArrayBuffer>> {
|
|
35
|
+
const key = await crypto.subtle.importKey("raw", ikm, "HKDF", false, ["deriveBits"])
|
|
36
|
+
return new Uint8Array(await crypto.subtle.deriveBits({ name: "HKDF", hash: "SHA-256", salt, info }, key, bytes * 8))
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/** A P-256 public key from its 65-byte uncompressed point, or `undefined` when the bytes are not a point of the curve. */
|
|
40
|
+
export async function importPublicKey(point: Uint8Array<ArrayBuffer> | undefined): Promise<CryptoKey | undefined> {
|
|
41
|
+
if (!point || point.length !== KEY_BYTES || point[0] !== 0x04) return undefined
|
|
42
|
+
try {
|
|
43
|
+
return await crypto.subtle.importKey("raw", point, P256, false, [])
|
|
44
|
+
} catch {
|
|
45
|
+
return undefined
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
export async function senderKeys(): Promise<SenderKeys> {
|
|
50
|
+
const pair = (await crypto.subtle.generateKey(P256, false, ["deriveBits"])) as CryptoKeyPair
|
|
51
|
+
return {
|
|
52
|
+
publicKey: new Uint8Array(await crypto.subtle.exportKey("raw", pair.publicKey)),
|
|
53
|
+
privateKey: pair.privateKey,
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/**
|
|
58
|
+
* RFC 8291 §3.4 over RFC 8188 `aes128gcm`: one record of `rs` 4096, the body `salt | rs | idlen | keyid | record` where `keyid`
|
|
59
|
+
* is the sender's public point. `sender` and `salt` are fresh per message unless a test fixes them.
|
|
60
|
+
*/
|
|
61
|
+
export async function encryptPayload(
|
|
62
|
+
plaintext: Uint8Array,
|
|
63
|
+
receiver: { publicKey: Uint8Array<ArrayBuffer>; key: CryptoKey; auth: Uint8Array<ArrayBuffer> },
|
|
64
|
+
sender?: SenderKeys,
|
|
65
|
+
salt: Uint8Array<ArrayBuffer> = crypto.getRandomValues(new Uint8Array(SALT_BYTES)),
|
|
66
|
+
): Promise<Uint8Array<ArrayBuffer>> {
|
|
67
|
+
const own = sender ?? (await senderKeys())
|
|
68
|
+
const secret = new Uint8Array(
|
|
69
|
+
await crypto.subtle.deriveBits({ name: "ECDH", public: receiver.key }, own.privateKey, 256),
|
|
70
|
+
)
|
|
71
|
+
const ikm = await hkdf(receiver.auth, secret, concat(KEY_INFO, receiver.publicKey, own.publicKey), 32)
|
|
72
|
+
const cek = await crypto.subtle.importKey("raw", await hkdf(salt, ikm, CEK_INFO, 16), "AES-GCM", false, ["encrypt"])
|
|
73
|
+
const nonce = await hkdf(salt, ikm, NONCE_INFO, 12)
|
|
74
|
+
// RFC 8291 §4: the single record is the last one, so its padding delimiter is 0x02 (RFC 8188 §2), with no padding after it.
|
|
75
|
+
const record = new Uint8Array(
|
|
76
|
+
await crypto.subtle.encrypt({ name: "AES-GCM", iv: nonce }, cek, concat(plaintext, Uint8Array.of(DELIMITER))),
|
|
77
|
+
)
|
|
78
|
+
const header = new Uint8Array(HEADER_BYTES)
|
|
79
|
+
header.set(salt, 0)
|
|
80
|
+
new DataView(header.buffer).setUint32(SALT_BYTES, RECORD_SIZE)
|
|
81
|
+
header[SALT_BYTES + 4] = KEY_BYTES
|
|
82
|
+
header.set(own.publicKey, SALT_BYTES + 5)
|
|
83
|
+
return concat(header, record)
|
|
84
|
+
}
|