// node_modules/uint8array-extras/index.js var objectToString = Object.prototype.toString; var uint8ArrayStringified = "[object Uint8Array]"; var arrayBufferStringified = "[object ArrayBuffer]"; function isType(value, typeConstructor, typeStringified) { if (!value) { return false; } if (value.constructor === typeConstructor) { return true; } return objectToString.call(value) === typeStringified; } function isUint8Array(value) { return isType(value, Uint8Array, uint8ArrayStringified); } function isArrayBuffer(value) { return isType(value, ArrayBuffer, arrayBufferStringified); } function isUint8ArrayOrArrayBuffer(value) { return isUint8Array(value) || isArrayBuffer(value); } function toUint8ArrayIfArrayBuffer(value) { return isArrayBuffer(value) ? new Uint8Array(value) : value; } function assertUint8ArrayOrArrayBuffer(value) { if (!isUint8ArrayOrArrayBuffer(value)) { throw new TypeError(`Expected \`Uint8Array\` or \`ArrayBuffer\`, got \`${typeof value}\``); } } function toUint8Array(value) { if (value instanceof ArrayBuffer) { return new Uint8Array(value); } if (ArrayBuffer.isView(value)) { return new Uint8Array(value.buffer, value.byteOffset, value.byteLength); } throw new TypeError(`Unsupported value, got \`${typeof value}\`.`); } function concatUint8Arrays(arrays, totalLength) { if (arrays.length === 0) { return new Uint8Array(0); } totalLength ??= arrays.reduce((accumulator, currentValue) => accumulator + currentValue.byteLength, 0); const returnValue = new Uint8Array(totalLength); let offset = 0; for (let array of arrays) { assertUint8ArrayOrArrayBuffer(array); array = toUint8ArrayIfArrayBuffer(array); returnValue.set(array, offset); offset += array.length; } return returnValue; } var cachedDecoders = { utf8: new globalThis.TextDecoder("utf8") }; function assertString(value) { if (typeof value !== "string") { throw new TypeError(`Expected \`string\`, got \`${typeof value}\``); } } var cachedEncoder = new globalThis.TextEncoder(); function stringToUint8Array(string) { assertString(string); return cachedEncoder.encode(string); } function base64ToBase64Url(base64) { return base64.replaceAll("+", "-").replaceAll("/", "_").replace(/=+$/, ""); } function base64UrlToBase64(base64url) { const base64 = base64url.replaceAll("-", "+").replaceAll("_", "/"); const padding = (4 - base64.length % 4) % 4; return base64 + "=".repeat(padding); } var MAX_BLOCK_SIZE = 65535; function uint8ArrayToBase64(array, { urlSafe = false } = {}) { assertUint8ArrayOrArrayBuffer(array); array = toUint8ArrayIfArrayBuffer(array); let base64 = ""; for (let index = 0; index < array.length; index += MAX_BLOCK_SIZE) { const chunk = array.subarray(index, index + MAX_BLOCK_SIZE); base64 += globalThis.btoa(String.fromCodePoint.apply(void 0, chunk)); } return urlSafe ? base64ToBase64Url(base64) : base64; } function base64ToUint8Array(base64String) { assertString(base64String); return Uint8Array.from(globalThis.atob(base64UrlToBase64(base64String)), (x) => x.codePointAt(0)); } var byteToHexLookupTable = Array.from({ length: 256 }, (_, index) => index.toString(16).padStart(2, "0")); // node_modules/@block65/webcrypto-web-push/dist/lib/utils.js function encodeRecordSize(size) { const bytes = new Uint8Array(4); new DataView(bytes.buffer).setUint32(0, size); return bytes; } function invariant(condition, message) { if (!condition) { throw new Error(message); } } // node_modules/@block65/webcrypto-web-push/dist/lib/client-keys.js async function deriveClientKeys(sub) { const bytes = base64ToUint8Array(sub.keys.p256dh); const authSecretBytes = base64ToUint8Array(sub.keys.auth); invariant(bytes.byteLength === 65 && bytes[0] === 4, "Subscription p256dh is not an uncompressed P-256 point"); invariant(authSecretBytes.byteLength === 16, "Subscription auth secret is not 16 bytes"); return { publicKeyBytes: bytes, publicKey: await crypto.subtle.importKey("raw", bytes, { name: "ECDH", namedCurve: "P-256" }, false, []), authSecretBytes }; } // node_modules/@block65/webcrypto-web-push/dist/lib/hkdf.js function createHMAC(data) { const keyPromise = crypto.subtle.importKey("raw", data, { name: "HMAC", hash: "SHA-256" }, false, ["sign"]); return { hash: async (input) => { const k = await keyPromise; return crypto.subtle.sign("HMAC", k, input); } }; } async function hkdf(salt, ikm) { const prkhPromise = createHMAC(salt).hash(ikm).then((prk) => createHMAC(prk)); return { extract: async (info, len) => { const prkh = await prkhPromise; const blocks = await Array.from({ length: Math.ceil(len / 32) }, (_, i) => i).reduce(async (acc, i) => { const previous = await acc; const hash = await prkh.hash(new Uint8Array([...previous.at(-1) ?? [], ...info, i + 1])); return [...previous, new Uint8Array(hash)]; }, Promise.resolve([])); return concatUint8Arrays(blocks).slice(0, len); } }; } // node_modules/@block65/webcrypto-web-push/dist/lib/info.js function createKeyInfo(clientPublic, serverPublic) { return new Uint8Array([ ...stringToUint8Array("WebPush: info\0"), ...clientPublic, ...serverPublic ]); } function createInfo(type) { return stringToUint8Array(`Content-Encoding: ${type}\0`); } // node_modules/@block65/webcrypto-web-push/dist/lib/local-keys.js async function generateLocalKeys() { const keyPair = await crypto.subtle.generateKey({ name: "ECDH", namedCurve: "P-256" }, false, ["deriveBits"]); return { privateKey: keyPair.privateKey, publicKeyBytes: new Uint8Array(await crypto.subtle.exportKey("raw", keyPair.publicKey)) }; } // node_modules/@block65/webcrypto-web-push/dist/lib/salt.js async function getSalt() { return crypto.getRandomValues(new Uint8Array(16)); } // node_modules/@block65/webcrypto-web-push/dist/lib/encrypt.js var recordSize = 4096; var headerSize = 21 + 65; var maxPlaintextSize = recordSize - headerSize - 17; async function encryptNotification(subscription, plaintext, options = {}) { invariant(plaintext.byteLength <= maxPlaintextSize, `Payload is ${plaintext.byteLength} bytes, the maximum is ${maxPlaintextSize}`); const clientKeys = await deriveClientKeys(subscription); const salt = await getSalt(); const localKeys = await generateLocalKeys(); const sharedSecret = await crypto.subtle.deriveBits({ name: "ECDH", public: clientKeys.publicKey }, localKeys.privateKey, 256); const keyInfo = createKeyInfo(clientKeys.publicKeyBytes, localKeys.publicKeyBytes); const cekInfo = createInfo("aes128gcm"); const nonceInfo = createInfo("nonce"); const ikmHkdf = await hkdf(clientKeys.authSecretBytes, sharedSecret); const ikm = await ikmHkdf.extract(keyInfo, 32); const messageHkdf = await hkdf(salt, ikm); const cekBytes = await messageHkdf.extract(cekInfo, 16); const nonceBytes = await messageHkdf.extract(nonceInfo, 12); const cekCryptoKey = await crypto.subtle.importKey("raw", cekBytes, { name: "AES-GCM", length: 128 }, false, ["encrypt"]); const padTo = options.pad ?? true ? maxPlaintextSize : plaintext.byteLength; const padded = new Uint8Array(padTo + 1); padded.set(plaintext); padded[plaintext.byteLength] = 2; const encrypted = await crypto.subtle.encrypt({ name: "AES-GCM", iv: nonceBytes }, cekCryptoKey, padded); return new Uint8Array([ ...salt, ...encodeRecordSize(recordSize), localKeys.publicKeyBytes.byteLength, ...localKeys.publicKeyBytes, ...new Uint8Array(encrypted) ]); } // node_modules/@block65/webcrypto-web-push/dist/lib/base64.js function encodeBase64Url(value) { return uint8ArrayToBase64(toUint8Array(value), { urlSafe: true }); } function objectToBase64Url(obj) { return encodeBase64Url(stringToUint8Array(JSON.stringify(obj))); } // node_modules/@block65/webcrypto-web-push/dist/lib/jwt.js async function sign(payload, key) { const headerStr = objectToBase64Url({ typ: "JWT", alg: "ES256" }); const payloadStr = objectToBase64Url({ iat: Math.floor(Date.now() / 1e3), ...payload }); const dataStr = `${headerStr}.${payloadStr}`; const signature = await crypto.subtle.sign({ name: "ECDSA", hash: "SHA-256" }, key, stringToUint8Array(dataStr)); return `${dataStr}.${encodeBase64Url(signature)}`; } // node_modules/@block65/webcrypto-web-push/dist/lib/vapid.js async function vapidHeaders(subscription, vapid) { invariant(vapid.subject, "Vapid subject is empty"); invariant(vapid.privateKey, "Vapid private key is empty"); invariant(vapid.publicKey, "Vapid public key is empty"); const endpoint = new URL(subscription.endpoint); invariant(endpoint.protocol === "https:", `Subscription endpoint is not https: ${endpoint.protocol}`); const vapidPublicKeyBytes = base64ToUint8Array(vapid.publicKey); const publicKey = await crypto.subtle.importKey("jwk", { kty: "EC", crv: "P-256", x: encodeBase64Url(vapidPublicKeyBytes.slice(1, 33)), y: encodeBase64Url(vapidPublicKeyBytes.slice(33, 65)), d: vapid.privateKey }, { name: "ECDSA", namedCurve: "P-256" }, false, ["sign"]); const jwt = await sign({ aud: endpoint.origin, exp: Math.floor(Date.now() / 1e3) + 12 * 60 * 60, sub: vapid.subject }, publicKey); return { headers: { authorization: `vapid t=${jwt}, k=${vapid.publicKey}` } }; } // node_modules/@block65/webcrypto-web-push/dist/lib/payload.js async function buildPushPayload(message, subscription, vapid) { const { headers } = await vapidHeaders(subscription, vapid); const body = await encryptNotification(subscription, stringToUint8Array( // if its a primitive, convert to string, otherwise stringify typeof message.data === "string" || typeof message.data === "number" ? message.data.toString() : JSON.stringify(message.data) )); return { headers: { ...headers, ttl: (message.options?.ttl || 60).toString(), ...message.options?.urgency && { urgency: message.options.urgency }, ...message.options?.topic && { topic: message.options.topic }, "content-encoding": "aes128gcm", "content-length": body.byteLength.toString(), "content-type": "application/octet-stream" }, method: "post", body }; } // sched42.js async function ensurePush(db) { await db.batch([ db.prepare("CREATE TABLE IF NOT EXISTS notice_config(name TEXT PRIMARY KEY,value TEXT NOT NULL)"), db.prepare("CREATE TABLE IF NOT EXISTS notice_devices(id TEXT PRIMARY KEY,endpoint TEXT UNIQUE NOT NULL,profile INTEGER NOT NULL,subscription TEXT NOT NULL,lead INTEGER NOT NULL,sent TEXT NOT NULL DEFAULT '{}',lease INTEGER NOT NULL DEFAULT 0)") ]); } function agendaClock(now) { const parts = new Intl.DateTimeFormat("en-GB", { timeZone: "America/Sao_Paulo", year: "numeric", month: "2-digit", day: "2-digit", hour: "2-digit", minute: "2-digit", hourCycle: "h23" }).formatToParts(now); const get = (k) => parts.find((p) => p.type === k).value; const today = [get("year"), get("month"), get("day")].join("-"); const dateAtMidnight = Date.parse(today + "T00:00:00Z"); const minutes = Number(get("hour")) * 60 + Number(get("minute")); const weekday = new Date(dateAtMidnight).getUTCDay(); return { today, dateAtMidnight, minutes, weekday }; } function agendaNotices(data, now = /* @__PURE__ */ new Date(), lead = 15, routine = { morning: "05:00", evening: true }) { const { today, dateAtMidnight, minutes, weekday } = agendaClock(now); const minuteOf = (s) => Number(s.slice(0, 2)) * 60 + Number(s.slice(3)); const notices = []; const dayWindow = minutes >= 420 && minutes < 1200; const slots = data.slots.filter((s) => s.reminder !== false && s.day === weekday && minuteOf(s.end) > minutes).sort((a, b) => a.start.localeCompare(b.start)); const label = (s) => s.customLabel || data.courses.find((c) => c.id === s.courseId)?.name || "Aula"; function summary(list) { return list.map((s) => s.start + " \xB7 " + label(s) + (s.room ? " (" + s.room + ")" : "")).join(" / "); } if (slots.length) { const wake = routine.morning ? minuteOf(routine.morning) : Infinity; notices.push({ key: "dia/" + today, title: "Aulas de hoje", body: summary(slots), due: minutes >= wake && minutes < wake + 30, tab: "horarios" }); } const tomorrow = new Date(dateAtMidnight + 864e5).toISOString().slice(0, 10); const next = data.slots.filter((s) => s.day === (weekday + 1) % 7 && s.reminder !== false).sort((a, b) => a.start.localeCompare(b.start)); if (routine.evening && next.length) { const lastEnd = Math.max(0, ...data.slots.filter((s) => s.day === weekday).map((s) => minuteOf(s.end))); const evening = Math.min(21 * 60 + 30, Math.max(19 * 60 + 30, lastEnd + 30)); if (minutes >= evening) notices.push({ key: "vespera/" + tomorrow, title: "Aulas de amanh\xE3", body: summary(next), due: minutes < evening + 30, tab: "horarios" }); } for (const slot of slots.filter((s) => s.individual === true)) { const diff = minuteOf(slot.start) - minutes; if (diff >= 0 && diff <= lead) notices.unshift({ key: ["aula", today, slot.id, slot.start].join("/"), title: label(slot), body: "Aula \xE0s " + slot.start + (slot.room ? " \xB7 " + slot.room : ""), due: true, tab: "horarios" }); } for (const e of [...data.events].sort((a, b) => (a.date + (a.time || "")).localeCompare(b.date + (b.time || "")))) { const days = (Date.parse(e.date + "T00:00:00Z") - dateAtMidnight) / 864e5; const exam = e.type === "Prova"; if (days < 0 || days > (exam ? 7 : 1) || !Number.isFinite(days)) continue; const until = e.time ? days * 1440 + minuteOf(e.time) - minutes : Infinity; if (until < 0) continue; const soon = until <= 30; const when = days === 0 ? "Hoje" : days === 1 ? "Amanh\xE3" : "Em " + days + " dias"; notices.push({ key: ["prazo", e.id, e.date, e.time || "", soon ? "hora" : days].join("/"), title: e.title, body: [when + (e.time ? " \xE0s " + e.time : ""), e.type, data.courses.find((c) => c.id === e.courseId)?.name].filter(Boolean).join(" \xB7 "), due: soon || dayWindow && (exam ? [0, 1, 3, 7] : [0, 1]).includes(days), tab: "calendario", date: e.date }); } return notices; } async function run(db, now = /* @__PURE__ */ new Date(), send = fetch) { await ensurePush(db); const stamp = now.getTime(); await db.prepare("INSERT INTO notice_config VALUES('tick',?) ON CONFLICT(name) DO UPDATE SET value=excluded.value").bind(String(stamp)).run(); await db.prepare("INSERT INTO notice_config VALUES('tick42',?) ON CONFLICT(name) DO UPDATE SET value=excluded.value").bind(String(stamp)).run(); const config = await db.prepare("SELECT value FROM notice_config WHERE name='vapid'").first(); if (!config) return; const vapid = { ...JSON.parse(config.value), subject: "https://agendatm.pages.dev" }; const { results } = await db.prepare("SELECT d.*,s.data,s.revision,p.value AS routine FROM notice_devices d JOIN semesters s ON s.profile=d.profile LEFT JOIN notice_config p ON p.name=('rotina:'||d.profile) WHERE d.lease n.due && !sent[n.key]); if (!due.length) continue; const claim = await db.prepare("UPDATE notice_devices SET lease=? WHERE id=? AND profile=? AND lease=? AND sent=? AND EXISTS(SELECT 1 FROM semesters WHERE profile=? AND revision=?)").bind(stamp + 12e4, d.id, d.profile, d.lease, d.sent, d.profile, d.revision).run(); if (!claim.meta.changes) continue; try { const first = due[0]; const data = { id: d.id, tag: first.key.slice(0, 140), title: first.title.slice(0, 90) + (due.length > 1 ? " (+" + (due.length - 1) + ")" : ""), body: (due.length === 1 ? first.body : first.body.slice(0, 135) + " \xB7 Tamb\xE9m: " + due.slice(1).map((n) => n.title).join(", ")).slice(0, 240) }; const payload = await buildPushPayload({ data, options: { ttl: 300 } }, JSON.parse(d.subscription), vapid); const response = await send(d.endpoint, { ...payload, redirect: "error", signal: AbortSignal.timeout(1e4) }); if ([404, 410].includes(response.status)) { await db.prepare("DELETE FROM notice_devices WHERE id=? AND endpoint=?").bind(d.id, d.endpoint).run(); continue; } if (response.ok) { for (const [k, t] of Object.entries(sent)) if (t < stamp - 10 * 864e5) delete sent[k]; for (const n of due) sent[n.key] = stamp; await db.prepare("UPDATE notice_devices SET sent=?,lease=0 WHERE id=? AND lease=? AND profile=?").bind(JSON.stringify(sent), d.id, stamp + 12e4, d.profile).run(); } } catch (error) { console.warn("Entrega temporariamente indispon\xEDvel", error.name); } } } var sched42_default = { async scheduled(event, env) { await run(env.DB, new Date(event.scheduledTime)); }, fetch() { return new Response("Agenda TM \xB7 Agendador de avisos", { headers: { "Content-Type": "text/plain; charset=utf-8" } }); } }; export { sched42_default as default, run };