/** VAPID public key มาเป็น base64url — `pushManager.subscribe` ต้องการ bytes */ export function urlBase64ToBytes(value: string): Uint8Array { const padded = value .replace(/-/g, "+") .replace(/_/g, "/") .padEnd(Math.ceil(value.length / 4) * 4, "="); const binary = atob(padded); const bytes = new Uint8Array(new ArrayBuffer(binary.length)); for (let index = 0; index < binary.length; index += 1) bytes[index] = binary.charCodeAt(index); return bytes; } /** * subscription ผูกกับ key ตอนสร้าง — อันที่สร้างด้วย key เก่าไม่มีวันรับสิ่งที่ส่งด้วย key ใหม่ * และเบราว์เซอร์ไม่ยอม subscribe ซ้ำด้วย key ใหม่จนกว่าจะ unsubscribe อันเก่า (ยกจาก DueBell / Pi Done) */ export function subscriptionUsesKey( subscription: { options?: { applicationServerKey?: ArrayBuffer | null } }, publicKey: string, ): boolean { const current = subscription.options?.applicationServerKey; if (!current) return false; const a = new Uint8Array(current); const b = urlBase64ToBytes(publicKey); return a.length === b.length && a.every((byte, index) => byte === b[index]); }