Branchwell

Branchwell / source / src / features.ts

1// "New feature" votes for any app built on our platform. An app marks new things with
2// data-bw-feature="id"; the widget shows a New badge with thumbs up and down.
3// 3 up: the feature stays for good and the badge goes away. 3 down: the feature is switched off.
4import type { Env } from './env';
5import { currentAccount, canVote } from './auth';
6import { VOTES_TO_DECIDE } from './repo';
7
8const ID_RE = /^[a-z0-9][a-z0-9._-]{0,63}$/;
9const CORS = { 'access-control-allow-origin': '*', 'access-control-allow-methods': 'GET, OPTIONS', 'access-control-allow-headers': 'content-type' };
10const json = (b: unknown, s = 200, h: Record<string, string> = {}) => new Response(JSON.stringify(b), { status: s, headers: { 'content-type': 'application/json', 'cache-control': 'no-store', ...h } });
11
12export async function featuresApi(req: Request, env: Env, url: URL): Promise<Response> {
13 if (req.method === 'OPTIONS') return new Response(null, { status: 204, headers: CORS });
14 const app = (url.searchParams.get('app') || '').toLowerCase();
15 if (!ID_RE.test(app)) return json({ error: 'app must be a short id like "jotley"' }, 400, CORS);
16 if (req.method === 'GET') {
17 // ids=a,b,c registers features the app is showing (first sight starts them as "new").
18 const ids = (url.searchParams.get('ids') || '').split(',').map((s) => s.trim().toLowerCase()).filter((s) => ID_RE.test(s)).slice(0, 50);
19 if (ids.length) {
20 const known = await env.DB.prepare('SELECT COUNT(*) AS n FROM features WHERE app = ?').bind(app).first<number>('n');
21 if ((known || 0) < 500) {
22 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())));
23 }
24 }
25 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;
26 return json({ app, votesToDecide: VOTES_TO_DECIDE, features: rows }, 200, { ...CORS, 'cache-control': 'public, max-age=15' });
27 }
28 return json({ error: 'GET only' }, 405, CORS);
29}
30
31/** POST /api/feature-vote {app, feature, value}. Signed-in, first-party only (the vote page). */
32export async function featureVote(req: Request, env: Env): Promise<Response> {
33 if (req.headers.get('origin') !== new URL(req.url).origin) return json({ error: 'Bad origin.' }, 403);
34 const me = await currentAccount(req, env);
35 if (!me) return json({ error: 'Sign in with your passkey to vote.' }, 401);
36 if (!canVote(me)) return json({ error: 'New accounts can vote 24 hours after they are made.' }, 403);
37 const b = await req.json<{ app: string; feature: string; value: number }>().catch(() => null);
38 if (!b || !ID_RE.test(b.app || '') || !ID_RE.test(b.feature || '')) return json({ error: 'Unknown feature.' }, 400);
39 const f = await env.DB.prepare('SELECT status FROM features WHERE app = ? AND feature = ?').bind(b.app, b.feature).first<string>('status');
40 if (!f) return json({ error: 'Unknown feature.' }, 404);
41 if (f !== 'new') return json({ ok: false, status: f, message: f === 'kept' ? 'Already kept for good.' : 'Already switched off by votes.' });
42 const v = b.value > 0 ? 1 : -1;
43 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')
44 .bind(b.app, b.feature, me.id, v, Date.now()).run();
45 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 }>();
46 const up = t?.up || 0, down = t?.down || 0;
47 const status = down >= VOTES_TO_DECIDE ? 'removed' : up >= VOTES_TO_DECIDE ? 'kept' : 'new';
48 await env.DB.prepare('UPDATE features SET up = ?, down = ?, status = ?, decided_at = CASE WHEN ? = \'new\' THEN NULL ELSE ? END WHERE app = ? AND feature = ?')
49 .bind(up, down, status, status, Date.now(), b.app, b.feature).run();
50 return json({ ok: true, status, up, down });
51}
52
53/** The widget apps load: <script src="https://branchwell.ai/widget/features.v1.js" data-app="yourapp" defer></script> */
54export const WIDGET_JS = `(()=>{"use strict";
55const s=document.currentScript,app=(s&&s.dataset.app||"").toLowerCase(),base=new URL(s?s.src:location.href).origin;
56if(!app)return;
57const 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}
58.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}
59.bw-hl{outline:2px solid #3f9a5f;outline-offset:3px;border-radius:6px}
60@media (prefers-color-scheme:dark){.bw-new{background:#16301f;color:#bfe6cb;border-color:#2c5c3c}.bw-new button:hover{background:#21452e}}\`;
61const st=document.createElement("style");st.textContent=css;document.head.appendChild(st);
62function run(){const els=[...document.querySelectorAll("[data-bw-feature]")];if(!els.length)return;
63const ids=[...new Set(els.map(e=>e.dataset.bwFeature.toLowerCase()))].slice(0,50);
64fetch(base+"/api/features?app="+encodeURIComponent(app)+"&ids="+encodeURIComponent(ids.join(","))).then(r=>r.json()).then(d=>{
65const by={};(d.features||[]).forEach(f=>by[f.feature]=f);
66els.forEach(el=>{const f=by[el.dataset.bwFeature.toLowerCase()];if(!f)return;
67if(f.status==="removed"){el.hidden=true;el.setAttribute("aria-hidden","true");el.style.display="none";return}
68if(f.status!=="new"||el.querySelector(":scope > .bw-new"))return;
69el.classList.add("bw-hl");const b=document.createElement("span");b.className="bw-new";
70const vote=v=>window.open(base+"/feature-vote?app="+encodeURIComponent(app)+"&feature="+encodeURIComponent(f.feature)+"&v="+v,"bwvote","width=440,height=560");
71b.innerHTML='New <button type="button" aria-label="Thumbs up for this new feature">&#128077; <span>'+f.up+'</span></button><button type="button" aria-label="Thumbs down for this new feature">&#128078; <span>'+f.down+'</span></button>';
72const [u,dn]=b.querySelectorAll("button");u.onclick=e=>{e.preventDefault();e.stopPropagation();vote("up")};dn.onclick=e=>{e.preventDefault();e.stopPropagation();vote("down")};
73(el.querySelector("[data-bw-badge]")||el).appendChild(b)})}).catch(()=>{})}
74document.readyState==="loading"?document.addEventListener("DOMContentLoaded",run):run();
75window.addEventListener("message",e=>{if(e.origin===base&&e.data&&e.data.bwVoted){document.querySelectorAll(".bw-new").forEach(x=>x.remove());run()}});
76})();`;