// "New feature" votes for any app built on our platform. An app marks new things with // data-bw-feature="id"; the widget shows a New badge with thumbs up and down. // 3 up: the feature stays for good and the badge goes away. 3 down: the feature is switched off. import type { Env } from './env'; import { currentAccount, canVote } from './auth'; import { VOTES_TO_DECIDE } from './repo'; const ID_RE = /^[a-z0-9][a-z0-9._-]{0,63}$/; const CORS = { 'access-control-allow-origin': '*', 'access-control-allow-methods': 'GET, OPTIONS', 'access-control-allow-headers': 'content-type' }; const json = (b: unknown, s = 200, h: Record = {}) => new Response(JSON.stringify(b), { status: s, headers: { 'content-type': 'application/json', 'cache-control': 'no-store', ...h } }); export async function featuresApi(req: Request, env: Env, url: URL): Promise { if (req.method === 'OPTIONS') return new Response(null, { status: 204, headers: CORS }); const app = (url.searchParams.get('app') || '').toLowerCase(); if (!ID_RE.test(app)) return json({ error: 'app must be a short id like "jotley"' }, 400, CORS); if (req.method === 'GET') { // ids=a,b,c registers features the app is showing (first sight starts them as "new"). const ids = (url.searchParams.get('ids') || '').split(',').map((s) => s.trim().toLowerCase()).filter((s) => ID_RE.test(s)).slice(0, 50); if (ids.length) { const known = await env.DB.prepare('SELECT COUNT(*) AS n FROM features WHERE app = ?').bind(app).first('n'); if ((known || 0) < 500) { await env.DB.batch(ids.map((id) => env.DB.prepare('INSERT INTO features (app, feature, created_at) VALUES (?, ?, ?) ON CONFLICT DO NOTHING').bind(app, id, Date.now()))); } } const rows = (await env.DB.prepare('SELECT feature, status, up, down FROM features WHERE app = ? ORDER BY created_at DESC LIMIT 500').bind(app).all()).results; return json({ app, votesToDecide: VOTES_TO_DECIDE, features: rows }, 200, { ...CORS, 'cache-control': 'public, max-age=15' }); } return json({ error: 'GET only' }, 405, CORS); } /** POST /api/feature-vote {app, feature, value}. Signed-in, first-party only (the vote page). */ export async function featureVote(req: Request, env: Env): Promise { if (req.headers.get('origin') !== new URL(req.url).origin) return json({ error: 'Bad origin.' }, 403); const me = await currentAccount(req, env); if (!me) return json({ error: 'Sign in with your passkey to vote.' }, 401); if (!canVote(me)) return json({ error: 'New accounts can vote 24 hours after they are made.' }, 403); const b = await req.json<{ app: string; feature: string; value: number }>().catch(() => null); if (!b || !ID_RE.test(b.app || '') || !ID_RE.test(b.feature || '')) return json({ error: 'Unknown feature.' }, 400); const f = await env.DB.prepare('SELECT status FROM features WHERE app = ? AND feature = ?').bind(b.app, b.feature).first('status'); if (!f) return json({ error: 'Unknown feature.' }, 404); if (f !== 'new') return json({ ok: false, status: f, message: f === 'kept' ? 'Already kept for good.' : 'Already switched off by votes.' }); const v = b.value > 0 ? 1 : -1; await env.DB.prepare('INSERT INTO feature_votes (app, feature, account_id, value, at) VALUES (?, ?, ?, ?, ?) ON CONFLICT (app, feature, account_id) DO UPDATE SET value = excluded.value, at = excluded.at') .bind(b.app, b.feature, me.id, v, Date.now()).run(); const t = await env.DB.prepare('SELECT SUM(value > 0) AS up, SUM(value < 0) AS down FROM feature_votes WHERE app = ? AND feature = ?').bind(b.app, b.feature).first<{ up: number; down: number }>(); const up = t?.up || 0, down = t?.down || 0; const status = down >= VOTES_TO_DECIDE ? 'removed' : up >= VOTES_TO_DECIDE ? 'kept' : 'new'; await env.DB.prepare('UPDATE features SET up = ?, down = ?, status = ?, decided_at = CASE WHEN ? = \'new\' THEN NULL ELSE ? END WHERE app = ? AND feature = ?') .bind(up, down, status, status, Date.now(), b.app, b.feature).run(); return json({ ok: true, status, up, down }); } /** The widget apps load: */ export const WIDGET_JS = `(()=>{"use strict"; const s=document.currentScript,app=(s&&s.dataset.app||"").toLowerCase(),base=new URL(s?s.src:location.href).origin; if(!app)return; const css=\`.bw-new{display:inline-flex;align-items:center;gap:.3em;margin-left:.4em;padding:.1em .5em;border-radius:999px;font:600 12px/1.6 system-ui,sans-serif;background:#e9f5ec;color:#1d5b34;border:1px solid #b9dcc4;vertical-align:middle} .bw-new button{all:unset;cursor:pointer;padding:0 .2em;border-radius:999px}.bw-new button:hover,.bw-new button:focus-visible{background:#cfe9d8;outline:2px solid #1d5b34} .bw-hl{outline:2px solid #3f9a5f;outline-offset:3px;border-radius:6px} @media (prefers-color-scheme:dark){.bw-new{background:#16301f;color:#bfe6cb;border-color:#2c5c3c}.bw-new button:hover{background:#21452e}}\`; const st=document.createElement("style");st.textContent=css;document.head.appendChild(st); function run(){const els=[...document.querySelectorAll("[data-bw-feature]")];if(!els.length)return; const ids=[...new Set(els.map(e=>e.dataset.bwFeature.toLowerCase()))].slice(0,50); fetch(base+"/api/features?app="+encodeURIComponent(app)+"&ids="+encodeURIComponent(ids.join(","))).then(r=>r.json()).then(d=>{ const by={};(d.features||[]).forEach(f=>by[f.feature]=f); els.forEach(el=>{const f=by[el.dataset.bwFeature.toLowerCase()];if(!f)return; if(f.status==="removed"){el.hidden=true;el.setAttribute("aria-hidden","true");el.style.display="none";return} if(f.status!=="new"||el.querySelector(":scope > .bw-new"))return; el.classList.add("bw-hl");const b=document.createElement("span");b.className="bw-new"; const vote=v=>window.open(base+"/feature-vote?app="+encodeURIComponent(app)+"&feature="+encodeURIComponent(f.feature)+"&v="+v,"bwvote","width=440,height=560"); b.innerHTML='New '; const [u,dn]=b.querySelectorAll("button");u.onclick=e=>{e.preventDefault();e.stopPropagation();vote("up")};dn.onclick=e=>{e.preventDefault();e.stopPropagation();vote("down")}; (el.querySelector("[data-bw-badge]")||el).appendChild(b)})}).catch(()=>{})} document.readyState==="loading"?document.addEventListener("DOMContentLoaded",run):run(); window.addEventListener("message",e=>{if(e.origin===base&&e.data&&e.data.bwVoted){document.querySelectorAll(".bw-new").forEach(x=>x.remove());run()}}); })();`;