debugging
Some checks failed
Chore App Build, Test, and Push Docker Images / build-and-push (push) Failing after 1m57s
Some checks failed
Chore App Build, Test, and Push Docker Images / build-and-push (push) Failing after 1m57s
This commit is contained in:
@@ -4,6 +4,20 @@
|
||||
* and syncing the subscription with the backend.
|
||||
*/
|
||||
|
||||
export type PushSubscribeResult =
|
||||
| { ok: true }
|
||||
| {
|
||||
ok: false
|
||||
reason:
|
||||
| 'unsupported'
|
||||
| 'permission_denied'
|
||||
| 'no_vapid_key'
|
||||
| 'sw_error'
|
||||
| 'subscribe_error'
|
||||
| 'backend_error'
|
||||
detail?: string
|
||||
}
|
||||
|
||||
async function fetchVapidPublicKey(): Promise<string | null> {
|
||||
try {
|
||||
const res = await fetch('/api/push-vapid-key')
|
||||
@@ -25,35 +39,73 @@ function urlBase64ToUint8Array(base64String: string): Uint8Array {
|
||||
/**
|
||||
* Request notification permission and subscribe to push notifications.
|
||||
* Posts the subscription to the backend, including the user's timezone.
|
||||
* Returns true if subscription was successfully registered.
|
||||
* Returns a result object describing success or the specific failure reason.
|
||||
*/
|
||||
export async function subscribeToPush(): Promise<boolean> {
|
||||
export async function subscribeToPushWithResult(): Promise<PushSubscribeResult> {
|
||||
if (!('serviceWorker' in navigator) || !('PushManager' in window)) {
|
||||
return false
|
||||
return { ok: false, reason: 'unsupported' }
|
||||
}
|
||||
|
||||
const permission = await Notification.requestPermission()
|
||||
if (permission !== 'granted') {
|
||||
return { ok: false, reason: 'permission_denied' }
|
||||
}
|
||||
|
||||
const vapidKey = await fetchVapidPublicKey()
|
||||
if (!vapidKey) {
|
||||
console.warn('[Push] VAPID public key not available')
|
||||
return { ok: false, reason: 'no_vapid_key' }
|
||||
}
|
||||
|
||||
let registration: ServiceWorkerRegistration
|
||||
try {
|
||||
const permission = await Notification.requestPermission()
|
||||
if (permission !== 'granted') {
|
||||
return false
|
||||
}
|
||||
// Timeout after 10 s — if SW never activates, don't hang forever
|
||||
registration = await Promise.race([
|
||||
navigator.serviceWorker.ready,
|
||||
new Promise<never>((_, reject) =>
|
||||
setTimeout(() => reject(new Error('SW ready timeout')), 10_000),
|
||||
),
|
||||
])
|
||||
} catch (err) {
|
||||
console.warn('[Push] Service worker not ready:', err)
|
||||
return { ok: false, reason: 'sw_error', detail: String(err) }
|
||||
}
|
||||
|
||||
const vapidKey = await fetchVapidPublicKey()
|
||||
if (!vapidKey) {
|
||||
console.warn('[Push] VAPID public key not available; skipping subscription')
|
||||
return false
|
||||
}
|
||||
|
||||
const registration = await navigator.serviceWorker.ready
|
||||
const subscription = await registration.pushManager.subscribe({
|
||||
let subscription: PushSubscription
|
||||
try {
|
||||
subscription = await registration.pushManager.subscribe({
|
||||
userVisibleOnly: true,
|
||||
applicationServerKey: urlBase64ToUint8Array(vapidKey),
|
||||
})
|
||||
} catch (firstErr) {
|
||||
// VAPID key mismatch: the browser has a stale subscription tied to a different key.
|
||||
// Clear it and retry once.
|
||||
console.warn(
|
||||
'[Push] pushManager.subscribe() failed — attempting to clear stale subscription:',
|
||||
firstErr,
|
||||
)
|
||||
try {
|
||||
const existing = await registration.pushManager.getSubscription()
|
||||
if (existing) {
|
||||
await existing.unsubscribe()
|
||||
console.info('[Push] Cleared stale subscription, retrying…')
|
||||
}
|
||||
subscription = await registration.pushManager.subscribe({
|
||||
userVisibleOnly: true,
|
||||
applicationServerKey: urlBase64ToUint8Array(vapidKey),
|
||||
})
|
||||
} catch (retryErr) {
|
||||
console.warn('[Push] Retry failed:', retryErr)
|
||||
return { ok: false, reason: 'subscribe_error', detail: String(retryErr) }
|
||||
}
|
||||
}
|
||||
|
||||
const subJson = subscription.toJSON()
|
||||
const timezone = Intl.DateTimeFormat().resolvedOptions().timeZone
|
||||
const subJson = subscription.toJSON()
|
||||
const timezone = Intl.DateTimeFormat().resolvedOptions().timeZone
|
||||
|
||||
const res = await fetch('/api/push-subscription', {
|
||||
let res: Response
|
||||
try {
|
||||
res = await fetch('/api/push-subscription', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
@@ -62,12 +114,26 @@ export async function subscribeToPush(): Promise<boolean> {
|
||||
timezone,
|
||||
}),
|
||||
})
|
||||
|
||||
return res.ok
|
||||
} catch (err) {
|
||||
console.warn('[Push] Failed to subscribe:', err)
|
||||
return false
|
||||
} catch (fetchErr) {
|
||||
console.warn('[Push] Network error posting subscription:', fetchErr)
|
||||
return { ok: false, reason: 'backend_error', detail: String(fetchErr) }
|
||||
}
|
||||
|
||||
if (!res.ok) {
|
||||
const body = await res.text().catch(() => '')
|
||||
console.warn(`[Push] Backend rejected subscription: HTTP ${res.status}`, body)
|
||||
return { ok: false, reason: 'backend_error', detail: `HTTP ${res.status}: ${body}` }
|
||||
}
|
||||
|
||||
return { ok: true }
|
||||
}
|
||||
|
||||
/**
|
||||
* Convenience wrapper — returns boolean for callers that don't need the reason.
|
||||
*/
|
||||
export async function subscribeToPush(): Promise<boolean> {
|
||||
const result = await subscribeToPushWithResult()
|
||||
return result.ok
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
Reference in New Issue
Block a user