Branchwell / source / src / index.ts
| 1 | // Branchwell: open Git hosting. Clone, pull and push over HTTPS; passkey sign-in; commits and branches |
| 2 | // are kept or removed by votes. One Worker, one D1 database, one Durable Object per repository. |
| 3 | import type { Env } from './env'; |
| 4 | import { page, esc, ago, sizeText, markdown, diffHtml, SITE, SECURITY } from './html'; |
| 5 | import { handleAuth, currentAccount, canVote, pusherFromBasic, RESERVED, type Account } from './auth'; |
| 6 | import { featuresApi, featureVote, WIDGET_JS } from './features'; |
| 7 | import { ODOMETER_CSS, ODOMETER_JS, APP_JS } from './static'; |
| 8 | import * as C from './content'; |
| 9 | import { isText } from './repo'; |
| 10 | |
| 11 | export { RepoDO } from './repo'; |
| 12 | |
| 13 | // Every repository lives under an owner: a company account (org) or a person, as owner/project. |
| 14 | const OWNER_RE = /^[a-z0-9](?:[a-z0-9-]{0,38}[a-z0-9])?$/; |
| 15 | const PROJ_RE = /^[a-z0-9][a-z0-9._-]{0,62}$/; |
| 16 | const FULL_RE = /^[a-z0-9](?:[a-z0-9-]{0,38}[a-z0-9])?\/[a-z0-9][a-z0-9._-]{0,62}$/; |
| 17 | const VIEWS = new Set(['tree', 'blob', 'raw', 'commits', 'commit', 'branches']); |
| 18 | const GIT_RE = /^\/([a-z0-9][a-z0-9-]{0,39})\/([a-z0-9][a-z0-9._-]{0,62}?)(?:\.git)?\/(info\/refs|git-upload-pack|git-receive-pack)$/; |
| 19 | const OLD_GIT_RE = /^\/([a-z0-9][a-z0-9._-]{0,62}?)(?:\.git)?\/(info\/refs|git-upload-pack|git-receive-pack)$/; |
| 20 | const 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 } }); |
| 21 | // do_name is the storage key. Older repos keep the flat name they were first pushed under. |
| 22 | const stub = (env: Env, doName: string) => env.REPO.get(env.REPO.idFromName(doName.toLowerCase())); |
| 23 | type RepoRow = { name: string; owner: string; do_name: string; description: string; created_by: string; created_at: number; updated_at: number }; |
| 24 | type Org = { handle: string; name: string; domain: string | null; about: string | null; created_at: number }; |
| 25 | const asset = (body: string, type: string) => new Response(body, { headers: { 'content-type': type, 'cache-control': 'public, max-age=3600', 'access-control-allow-origin': '*' } }); |
| 26 | const APP = ['/assets/app.js']; |
| 27 | |
| 28 | async function repoRow(env: Env, name: string) { |
| 29 | return env.DB.prepare('SELECT name, owner, COALESCE(do_name, name) AS do_name, description, created_by, created_at, updated_at FROM repos WHERE name = ?').bind(name.toLowerCase()).first<RepoRow>(); |
| 30 | } |
| 31 | const orgRow = (env: Env, handle: string) => env.DB.prepare('SELECT handle, name, domain, about, created_at FROM orgs WHERE handle = ?').bind(handle.toLowerCase()).first<Org>(); |
| 32 | async function myOrgs(env: Env, me: Account) { |
| 33 | return (await env.DB.prepare('SELECT o.handle, o.name, o.domain, o.about, o.created_at FROM org_members m JOIN orgs o ON o.handle = m.org WHERE m.account_id = ? ORDER BY o.name').bind(me.id).all<Org>()).results; |
| 34 | } |
| 35 | async function canCreateUnder(env: Env, owner: string, by: Account) { |
| 36 | if (owner === by.handle.toLowerCase()) return true; |
| 37 | return !!(await env.DB.prepare('SELECT 1 AS x FROM org_members WHERE org = ? AND account_id = ?').bind(owner, by.id).first('x')); |
| 38 | } |
| 39 | async function createRepo(env: Env, owner: string, project: string, description: string, by: Account): Promise<string | null> { |
| 40 | owner = owner.toLowerCase(); project = project.toLowerCase().replace(/\.git$/, ''); |
| 41 | if (!PROJ_RE.test(project) || VIEWS.has(project)) return 'Use 1 to 63 lowercase letters, numbers, dots, dashes or underscores.'; |
| 42 | if (!(await canCreateUnder(env, owner, by))) return `You can start projects under your own name, or under a company you belong to. ${owner} isn't one of those.`; |
| 43 | const name = owner + '/' + project; |
| 44 | if (await repoRow(env, name)) return 'That name is taken.'; |
| 45 | if (owner === by.handle.toLowerCase()) { |
| 46 | const n = await env.DB.prepare('SELECT COUNT(*) AS n FROM repos WHERE created_by = ? AND owner = ? AND created_at > ?').bind(by.handle, owner, Date.now() - 864e5).first<number>('n'); |
| 47 | if ((n || 0) >= 5) return 'You can make 5 projects a day. Try again tomorrow.'; |
| 48 | } |
| 49 | await env.DB.prepare('INSERT INTO repos (name, owner, do_name, description, created_by, created_at) VALUES (?, ?, ?, ?, ?, ?)').bind(name, owner, name, description.slice(0, 300), by.handle, Date.now()).run(); |
| 50 | await stub(env, name).init(name); |
| 51 | return null; |
| 52 | } |
| 53 | |
| 54 | export default { |
| 55 | async fetch(req: Request, env: Env, ctx: ExecutionContext): Promise<Response> { |
| 56 | const url = new URL(req.url); |
| 57 | if (url.hostname === 'www.branchwell.ai') return Response.redirect(SITE + url.pathname + url.search, 301); |
| 58 | const path = decodeURIComponent(url.pathname); |
| 59 | try { |
| 60 | // ---------- Git over HTTPS ---------- |
| 61 | const g = url.pathname.match(GIT_RE); |
| 62 | if (g) return await git(req, env, ctx, g[1] + '/' + g[2], g[3], url); |
| 63 | const og = url.pathname.match(OLD_GIT_RE); |
| 64 | if (og) { |
| 65 | // Old one-part addresses (branchwell.ai/sunlaid.git) now live at the company's research project. |
| 66 | const to = await repoRow(env, og[1].toLowerCase() + '/research'); |
| 67 | if (to) return Response.redirect(`${SITE}/${to.name}.git/${og[2]}${url.search}`, 301); |
| 68 | return new Response(`Repositories now live under an owner, like https://branchwell.ai/sunlaid/research.git\n`, { status: 404, headers: { 'content-type': 'text/plain' } }); |
| 69 | } |
| 70 | |
| 71 | // ---------- assets and APIs ---------- |
| 72 | if (path === '/assets/app.js') return asset(APP_JS, 'text/javascript; charset=utf-8'); |
| 73 | if (path === '/assets/visitor-odometer.v1.js') return asset(ODOMETER_JS, 'text/javascript; charset=utf-8'); |
| 74 | if (path === '/assets/visitor-odometer.v1.css') return asset(ODOMETER_CSS, 'text/css; charset=utf-8'); |
| 75 | if (path === '/widget/features.v1.js') return asset(WIDGET_JS, 'text/javascript; charset=utf-8'); |
| 76 | if (path === '/robots.txt') return new Response(`User-agent: *\nAllow: /\nDisallow: /api/\nSitemap: ${SITE}/sitemap.xml\n`, { headers: { 'content-type': 'text/plain' } }); |
| 77 | if (path === '/sitemap.xml') return sitemap(env); |
| 78 | if (path === '/llms.txt') return new Response(LLMS, { headers: { 'content-type': 'text/plain; charset=utf-8' } }); |
| 79 | if (path === '/favicon.ico' || path === '/favicon.svg') return new Response(null, { status: 404 }); |
| 80 | if (path.startsWith('/api/auth/')) return await handleAuth(req, env, path.slice(10)); |
| 81 | if (path === '/api/features') return await featuresApi(req, env, url); |
| 82 | if (path === '/api/feature-vote' && req.method === 'POST') return await featureVote(req, env); |
| 83 | if (path === '/api/vote' && req.method === 'POST') return await vote(req, env); |
| 84 | if (path === '/api/repos' && req.method === 'POST') return await apiCreateRepo(req, env); |
| 85 | if (path === '/api/request') { |
| 86 | if (!env.CAREERS) return json({ ok: false, error: 'Unavailable' }, 503); |
| 87 | return await env.CAREERS.fetch(new Request('https://careers-intake/api/request', req)); |
| 88 | } |
| 89 | if (path.startsWith('/api/')) return json({ error: 'Not found' }, 404); |
| 90 | |
| 91 | // ---------- pages ---------- |
| 92 | const me = await currentAccount(req, env); |
| 93 | const P = (title: string, body: string, extra: Partial<Parameters<typeof page>[0]> = {}) => page({ title, body, path: url.pathname, me, scripts: APP, ...extra }); |
| 94 | switch (path.replace(/\/$/, '') || '/') { |
| 95 | case '/': { |
| 96 | const repos = await env.DB.prepare('SELECT COUNT(*) AS n FROM repos').first<number>('n'); |
| 97 | const companies = await env.DB.prepare('SELECT COUNT(*) AS n FROM orgs').first<number>('n'); |
| 98 | return P('Branchwell: open Git hosting where votes decide', C.home({ repos: repos || 0, companies: companies || 0 }), { |
| 99 | head: '<link rel="stylesheet" href="/assets/visitor-odometer.v1.css"><script src="/assets/visitor-odometer.v1.js" defer></script>' + ORG_LD, |
| 100 | description: 'Branchwell hosts open Git repositories. Anyone can pull, anyone signed in can push straight to a branch, and 3 votes keep or remove each commit.' }); |
| 101 | } |
| 102 | case '/how-to-pull': return P('How to pull', C.howToPull, { current: '/how-to-pull', description: 'Clone and pull any Branchwell repository with plain Git. No account needed.' }); |
| 103 | case '/how-to-contribute': return P('How to contribute', C.howToContribute, { current: '/how-to-contribute', description: 'Sign in with a passkey, make a push key and push straight to a branch. No pull requests.' }); |
| 104 | case '/rules': return P('How votes work', C.rules, { current: '/rules', description: '3 votes down removes a commit or branch. 3 votes up keeps it for good. Everything else stays.' }); |
| 105 | case '/features': return P('New features, voted in', C.features, { current: '/features', description: 'Add a New badge with thumbs up and down to any app. 3 up keeps a feature, 3 down switches it off.' }); |
| 106 | case '/careers': return P('Careers', C.careers, { current: '/careers', description: 'Careers at Branchwell. Send us a short request to work with us.' }); |
| 107 | case '/privacy': return P('Privacy', C.privacy, { description: 'What Branchwell keeps and what it never does.' }); |
| 108 | case '/source': return Response.redirect(SITE + '/branchwell/source', 302); |
| 109 | case '/repos': return reposPage(env, P); |
| 110 | case '/companies': return companiesPage(env, P); |
| 111 | case '/research': return researchPage(env, P); |
| 112 | case '/signin': return P('Sign in', signinBody(me), { noindex: true }); |
| 113 | case '/account': return me ? accountPage(env, me, P) : Response.redirect(SITE + '/signin?back=/account', 302); |
| 114 | case '/new': return P('New project', newRepoBody(me, me ? await myOrgs(env, me) : []), { noindex: true }); |
| 115 | case '/feature-vote': return featureVotePage(env, url, me, P); |
| 116 | } |
| 117 | |
| 118 | // ---------- repository pages ---------- |
| 119 | const o = url.pathname.match(/^\/([a-z0-9][a-z0-9-]{0,39})\/?$/); |
| 120 | if (o && !RESERVED.has(o[1])) { |
| 121 | const r = await ownerPage(env, o[1], me, P); |
| 122 | if (r) return r; |
| 123 | } |
| 124 | const m = url.pathname.match(/^\/([a-z0-9][a-z0-9-]{0,39})\/([a-z0-9][a-z0-9._-]{0,62}?)(?:\.git)?(?:\/(tree|blob|raw|commits|commit|branches)(?:\/(.*))?)?\/?$/); |
| 125 | if (m && !RESERVED.has(m[1])) { |
| 126 | const row = await repoRow(env, m[1] + '/' + m[2]); |
| 127 | if (row) return await repoPage(env, req, url, me, row, m[3] || '', m[4] ? decodeURIComponent(m[4]) : '', P); |
| 128 | } |
| 129 | return page({ title: 'Not found', path: url.pathname, me, noindex: true, body: '<section class="hero" style="grid-template-columns:1fr"><div class="prose"><h1 class="sm">We couldn\'t find that page</h1><p class="lede">It may have moved, or a vote may have removed it.</p><p class="btns"><a class="btn" href="/">Home</a><a class="btn ghost" href="/repos">All repositories</a></p></div></section>' }).then404(); |
| 130 | } catch (e) { |
| 131 | console.error(e); |
| 132 | return new Response('Something went wrong on our side. Please try again.', { status: 500 }); |
| 133 | } |
| 134 | }, |
| 135 | }; |
| 136 | |
| 137 | declare global { interface Response { then404(): Response } } |
| 138 | Response.prototype.then404 = function (this: Response) { return new Response(this.body, { status: 404, headers: this.headers }); }; |
| 139 | |
| 140 | // ---------------- Git ---------------- |
| 141 | async function git(req: Request, env: Env, ctx: ExecutionContext, name: string, op: string, url: URL): Promise<Response> { |
| 142 | name = name.toLowerCase(); |
| 143 | const service = op === 'info/refs' ? url.searchParams.get('service') : op; |
| 144 | const write = service === 'git-receive-pack'; |
| 145 | let pusher: Account | null = null; |
| 146 | if (write) { |
| 147 | pusher = await pusherFromBasic(req, env); |
| 148 | if (!pusher) return new Response('Sign in at https://branchwell.ai/account and make a push key. Use your Branchwell name as the username and the push key as the password.\n', { |
| 149 | status: 401, headers: { 'www-authenticate': 'Basic realm="Branchwell"', 'content-type': 'text/plain' } }); |
| 150 | } |
| 151 | let row = await repoRow(env, name); |
| 152 | if (!row) { |
| 153 | if (!write || !pusher) return new Response(`Repository ${name} not found on Branchwell.\n`, { status: 404, headers: { 'content-type': 'text/plain' } }); |
| 154 | const [owner, project] = name.split('/'); |
| 155 | const err = await createRepo(env, owner, project, '', pusher); |
| 156 | if (err) return new Response(err + '\n', { status: 403, headers: { 'content-type': 'text/plain' } }); |
| 157 | row = await repoRow(env, name); |
| 158 | } |
| 159 | if (!row) return new Response('Not found\n', { status: 404 }); |
| 160 | const target = new URL('https://repo/' + (op === 'info/refs' ? 'info/refs' : op) + url.search); |
| 161 | const headers = new Headers({ 'content-type': req.headers.get('content-type') || '' }); |
| 162 | headers.set('x-repo', row.name); |
| 163 | if (pusher) headers.set('x-pusher', JSON.stringify({ id: pusher.id, handle: pusher.handle })); |
| 164 | let body: BodyInit | null = null; |
| 165 | if (req.method === 'POST') { |
| 166 | let buf = new Uint8Array(await req.arrayBuffer()); |
| 167 | if ((req.headers.get('content-encoding') || '').includes('gzip')) buf = new Uint8Array(await new Response(new Blob([buf]).stream().pipeThrough(new DecompressionStream('gzip'))).arrayBuffer()); |
| 168 | body = buf; |
| 169 | } |
| 170 | const res = await stub(env, row.do_name).fetch(new Request(target, { method: req.method, headers, body })); |
| 171 | if (write && req.method === 'POST') ctx.waitUntil(env.DB.prepare('UPDATE repos SET updated_at = ? WHERE name = ?').bind(Date.now(), name).run()); |
| 172 | return res; |
| 173 | } |
| 174 | |
| 175 | // ---------------- APIs ---------------- |
| 176 | async function vote(req: Request, env: Env): Promise<Response> { |
| 177 | if (req.headers.get('origin') !== new URL(req.url).origin) return json({ error: 'Bad origin.' }, 403); |
| 178 | const me = await currentAccount(req, env); |
| 179 | if (!me) return json({ error: 'Sign in with your passkey to vote.' }, 401); |
| 180 | const b = await req.json<{ repo: string; kind: string; target: string; value: number }>().catch(() => null); |
| 181 | if (!b || !FULL_RE.test(b.repo || '') || (b.kind !== 'commit' && b.kind !== 'branch') || !b.target) return json({ error: 'Bad vote.' }, 400); |
| 182 | const row = await repoRow(env, b.repo); |
| 183 | if (!row) return json({ error: 'No such repository.' }, 404); |
| 184 | const r = await stub(env, row.do_name).vote(b.kind, String(b.target).slice(0, 120), { id: me.id, handle: me.handle, canVote: canVote(me) }, Number(b.value) || 0); |
| 185 | return json(r); |
| 186 | } |
| 187 | async function apiCreateRepo(req: Request, env: Env): Promise<Response> { |
| 188 | if (req.headers.get('origin') !== new URL(req.url).origin) return json({ error: 'Bad origin.' }, 403); |
| 189 | const me = await currentAccount(req, env); |
| 190 | if (!me) return json({ error: 'Sign in first.' }, 401); |
| 191 | const b = await req.json<{ owner: string; name: string; description: string }>().catch(() => ({ owner: '', name: '', description: '' })); |
| 192 | const owner = String(b.owner || me.handle).toLowerCase(), project = String(b.name || '').toLowerCase(); |
| 193 | if (!OWNER_RE.test(owner)) return json({ error: 'Pick who owns it.' }, 400); |
| 194 | const err = await createRepo(env, owner, project, String(b.description || ''), me); |
| 195 | if (err) return json({ error: err }, 400); |
| 196 | return json({ ok: true, name: owner + '/' + project }); |
| 197 | } |
| 198 | |
| 199 | // ---------------- pages ---------------- |
| 200 | type PFn = (title: string, body: string, extra?: Record<string, unknown>) => Response; |
| 201 | |
| 202 | async function reposPage(env: Env, P: PFn) { |
| 203 | const rows = (await env.DB.prepare('SELECT name, description, created_by, created_at, updated_at FROM repos ORDER BY COALESCE(updated_at, created_at) DESC LIMIT 1000').all<{ name: string; description: string; created_by: string; created_at: number; updated_at: number }>()).results; |
| 204 | const list = rows.length ? `<table class="list"><thead><tr><th>Repository</th><th class="hide">About</th><th class="r">Updated</th></tr></thead><tbody>${rows.map((r) => |
| 205 | `<tr><td><a href="/${esc(r.name)}">${esc(r.name)}</a></td><td class="m hide">${esc(r.description || '')}</td><td class="r m">${ago(r.updated_at || r.created_at)}</td></tr>`).join('')}</tbody></table>` : '<p class="muted">No repositories yet.</p>'; |
| 206 | return P('Repositories', `<section class="hero" style="grid-template-columns:1fr;padding-bottom:20px"><div><span class="eyebrow">Repositories</span><h1 class="sm">Everything here is open</h1> |
| 207 | <p class="lede">Pull any of these with plain Git. Sign in to push, vote, or start your own.</p><div class="btns"><a class="btn" href="/new">New project</a><a class="btn ghost" href="/companies">Companies</a></div></div></section>${list}`, { current: '/repos', description: 'Every repository on Branchwell. All public, all open to pull.' }); |
| 208 | } |
| 209 | |
| 210 | function signinBody(me: Account | null) { |
| 211 | if (me) return `<section class="hero" style="grid-template-columns:1fr"><div class="prose"><h1 class="sm">You're signed in as ${esc(me.handle)}</h1><p class="btns"><a class="btn" href="/account">Your account</a></p></div></section>`; |
| 212 | return `<section class="hero" style="grid-template-columns:1fr"><div class="grid2"> |
| 213 | <div class="prose"><span class="eyebrow">Sign in</span><h1 class="sm">Passkeys only</h1> |
| 214 | <p class="lede">Sign in with your face, fingerprint or device PIN. No passwords and no email.</p> |
| 215 | <p><button class="btn" id="signin" type="button">Sign in with a passkey</button></p><p id="signin-msg" role="status" aria-live="polite"></p></div> |
| 216 | <div class="card"><h2 style="font-size:26px">New here?</h2><p>Pick a public name. Your device makes a passkey for it.</p> |
| 217 | <form id="signup" class="stack" style="margin-top:14px"><label for="handle">Your name on Branchwell</label> |
| 218 | <input id="handle" name="handle" required minlength="3" maxlength="30" pattern="[a-z0-9][a-z0-9-]{1,28}[a-z0-9]" autocomplete="username webauthn" autocapitalize="none" spellcheck="false" placeholder="for example river-maple"> |
| 219 | <span class="small muted">3 to 30 lowercase letters, numbers or dashes.</span> |
| 220 | <button class="btn" type="submit">Make my passkey</button><p id="signup-msg" role="status" aria-live="polite"></p></form></div> |
| 221 | </div></section>`; |
| 222 | } |
| 223 | |
| 224 | async function accountPage(env: Env, me: Account, P: PFn) { |
| 225 | const keys = (await env.DB.prepare('SELECT id, name, created_at, last_used FROM push_keys WHERE account_id = ? ORDER BY created_at DESC').bind(me.id).all<{ id: string; name: string; created_at: number; last_used: number }>()).results; |
| 226 | const orgs = await myOrgs(env, me); |
| 227 | const pks = (await env.DB.prepare('SELECT created_at, last_used FROM passkeys WHERE account_id = ? ORDER BY created_at').bind(me.id).all<{ created_at: number; last_used: number }>()).results; |
| 228 | const wait = canVote(me) ? '<p class="muted">You can vote.</p>' : `<p class="muted">You can vote from ${new Date(me.created_at + 864e5).toUTCString().slice(0, 22)} UTC. New accounts wait a day so votes stay fair.</p>`; |
| 229 | return P('Your account', `<section class="hero" style="grid-template-columns:1fr;padding-bottom:12px"><div><span class="eyebrow">Your account</span><h1 class="sm">${esc(me.handle)}</h1>${wait}</div></section> |
| 230 | <div class="grid2"><div> |
| 231 | <h2 style="font-size:28px">Push keys</h2><p class="muted">Git can't use passkeys, so make a push key for each computer. Use your name as the username and the key as the password.</p> |
| 232 | <form id="make-key" class="stack"><label for="keyname">Name this key</label><input id="keyname" name="keyname" maxlength="60" value="My computer"><button class="btn" type="submit">Make a push key</button><p id="key-msg" role="status" aria-live="polite"></p></form> |
| 233 | <div id="new-key" class="card" hidden style="margin:12px 0"><p><b>Username:</b> <code id="new-key-user"></code></p><p><b>Push key:</b></p><div class="copy"><code id="new-key-value"></code><button class="btn sm" type="button" data-copy="new-key-value">Copy</button></div></div> |
| 234 | ${keys.length ? `<table class="list" style="margin-top:14px"><tbody>${keys.map((k) => `<tr><td>${esc(k.name)}<br><span class="small muted">made ${ago(k.created_at)}${k.last_used ? ', used ' + ago(k.last_used) : ', not used yet'}</span></td><td class="r"><button class="btn ghost sm" type="button" data-del-key="${esc(k.id)}">Remove</button></td></tr>`).join('')}</tbody></table>` : ''} |
| 235 | </div><div> |
| 236 | <h2 style="font-size:28px">Passkeys</h2><p class="muted">${pks.length} passkey${pks.length === 1 ? '' : 's'} on this account. Add one for each device you use.</p> |
| 237 | <p><button class="btn ghost" id="add-passkey" type="button">Add a passkey</button></p><p id="pk-msg" role="status" aria-live="polite"></p> |
| 238 | ${orgs.length ? `<h2 style="font-size:28px;margin-top:30px">Your companies</h2><p>${orgs.map((o) => `<a href="/${esc(o.handle)}">${esc(o.name)}</a>`).join(' · ')}</p>` : ''} |
| 239 | <h2 style="font-size:28px;margin-top:30px">Get started</h2><pre><code>git clone https://branchwell.ai/sunlaid/research.git</code></pre> |
| 240 | <p><a href="/how-to-contribute">How to contribute</a> · <a href="/new">New repository</a></p> |
| 241 | <p><button class="btn ghost sm" id="signout" type="button">Sign out</button></p></div></div>`, { noindex: true }); |
| 242 | } |
| 243 | |
| 244 | function newRepoBody(me: Account | null, orgs: Org[]) { |
| 245 | if (!me) return `<section class="hero" style="grid-template-columns:1fr"><div class="prose"><h1 class="sm">Start a project</h1><p class="lede">Sign in with your passkey first.</p><p class="btns"><a class="btn" href="/signin?back=/new">Sign in</a></p></div></section>`; |
| 246 | return `<section class="hero" style="grid-template-columns:1fr"><div class="prose"><span class="eyebrow">New project</span><h1 class="sm">Start a project</h1> |
| 247 | <p class="lede">Every project is public. Anyone can pull it and anyone signed in can push to it.</p> |
| 248 | <form id="new-repo" class="stack"><label for="owner">Owner</label><select id="owner" name="owner" style="font:inherit;border-radius:999px;padding:12px 16px;border:1.5px solid var(--line);background:var(--card);color:var(--fg)"><option value="${esc(me.handle)}">${esc(me.handle)} (you)</option>${orgs.map((o) => `<option value="${esc(o.handle)}">${esc(o.name)}</option>`).join('')}</select> |
| 249 | <label for="repo">Name</label><input id="repo" name="repo" required maxlength="63" pattern="[a-z0-9][a-z0-9._-]{0,62}" autocapitalize="none" spellcheck="false" placeholder="my-project"> |
| 250 | <label for="description">What it's for (optional)</label><input id="description" name="description" maxlength="300"> |
| 251 | <button class="btn" type="submit">Make it</button><p id="repo-msg" role="status" aria-live="polite"></p></form> |
| 252 | <p class="muted">Or just push to a new name: <code>git push https://branchwell.ai/${esc(me.handle)}/my-project.git main</code></p></div></section>`; |
| 253 | } |
| 254 | |
| 255 | async function featureVotePage(env: Env, url: URL, me: Account | null, P: PFn) { |
| 256 | const app = (url.searchParams.get('app') || '').toLowerCase(), feature = (url.searchParams.get('feature') || '').toLowerCase(); |
| 257 | const f = await env.DB.prepare('SELECT status, up, down FROM features WHERE app = ? AND feature = ?').bind(app, feature).first<{ status: string; up: number; down: number }>(); |
| 258 | if (!f) return P('Feature vote', '<section class="hero" style="grid-template-columns:1fr"><div class="prose"><h1 class="xs">We couldn\'t find that feature</h1></div></section>', { noindex: true }); |
| 259 | const back = encodeURIComponent(url.pathname + url.search); |
| 260 | const v = url.searchParams.get('v') === 'down' ? -1 : 1; |
| 261 | const body = !me ? `<p class="lede">Sign in with your passkey to vote.</p><p><a class="btn" href="/signin?back=${back}">Sign in</a></p>` |
| 262 | : f.status !== 'new' ? `<p class="lede">${f.status === 'kept' ? 'This feature already got 3 thumbs up. It stays for good.' : 'This feature got 3 thumbs down and is switched off.'}</p>` |
| 263 | : `<p class="lede">3 thumbs up keeps it for good. 3 thumbs down switches it off.</p><p class="btns"> |
| 264 | <button class="btn${v > 0 ? '' : ' ghost'}" type="button" data-fvote="1" data-app="${esc(app)}" data-feature="${esc(feature)}">👍 Keep it (${f.up})</button> |
| 265 | <button class="btn${v < 0 ? '' : ' ghost'}" type="button" data-fvote="-1" data-app="${esc(app)}" data-feature="${esc(feature)}">👎 Remove it (${f.down})</button></p><p id="fv-msg" role="status" aria-live="polite"></p>`; |
| 266 | return P('Vote on a new feature', `<section class="hero" style="grid-template-columns:1fr;padding-top:0"><div class="prose"><span class="eyebrow">New feature</span><h1 class="xs">${esc(feature.replace(/[-_.]/g, ' '))}</h1><p class="muted">in ${esc(app)}</p>${body}</div></section>`, { noindex: true }); |
| 267 | } |
| 268 | |
| 269 | // ---------------- owners and companies ---------------- |
| 270 | type ProjRow = { name: string; description: string; updated_at: number; created_at: number }; |
| 271 | const projTable = (rows: ProjRow[], showOwner = false) => rows.length ? `<table class="list"><tbody>${rows.map((r) => |
| 272 | `<tr><td><a href="/${esc(r.name)}">${esc(showOwner ? r.name : r.name.split('/')[1])}</a>${r.description ? `<br><span class="small muted">${esc(r.description)}</span>` : ''}</td><td class="r m">${ago(r.updated_at || r.created_at)}</td></tr>`).join('')}</tbody></table>` : '<p class="muted">No projects yet.</p>'; |
| 273 | |
| 274 | async function ownerPage(env: Env, handle: string, me: Account | null, P: PFn): Promise<Response | null> { |
| 275 | const org = await orgRow(env, handle); |
| 276 | const person = org ? null : await env.DB.prepare('SELECT handle, created_at FROM accounts WHERE handle = ?').bind(handle).first<{ handle: string; created_at: number }>(); |
| 277 | if (!org && !person) return null; |
| 278 | const rows = (await env.DB.prepare('SELECT name, description, updated_at, created_at FROM repos WHERE owner = ? ORDER BY name').bind(handle).all<ProjRow>()).results; |
| 279 | const member = !!(me && (await canCreateUnder(env, handle, me))); |
| 280 | const title = org ? org.name : handle; |
| 281 | const site = org?.domain ? `<p class="small"><a href="https://${esc(org.domain)}" rel="noopener">${esc(org.domain)}</a></p>` : ''; |
| 282 | return P(title, `<section class="hero" style="grid-template-columns:1fr;padding-bottom:20px"><div><span class="eyebrow">${org ? 'Company' : 'Person'}</span><h1 class="sm">${esc(title)}</h1> |
| 283 | ${org?.about ? `<p class="lede">${esc(org.about)}</p>` : ''}${site}<p class="small muted">${rows.length} project${rows.length === 1 ? '' : 's'}. Every one is public: pull it with plain Git, push to it once you sign in.</p> |
| 284 | ${member ? '<div class="btns"><a class="btn" href="/new">New project</a></div>' : ''}</div></section> |
| 285 | <h2 style="font-size:28px">Projects</h2>${projTable(rows)}`, { description: org ? `${org.name} on Branchwell: every project, open to pull and to push.` : `${handle} on Branchwell.` }); |
| 286 | } |
| 287 | |
| 288 | async function companiesPage(env: Env, P: PFn) { |
| 289 | const orgs = (await env.DB.prepare('SELECT o.handle, o.name, o.domain, o.about, (SELECT COUNT(*) FROM repos r WHERE r.owner = o.handle) AS n FROM orgs o ORDER BY o.name COLLATE NOCASE').all<Org & { n: number }>()).results; |
| 290 | const cards = orgs.map((o) => `<a class="card" href="/${esc(o.handle)}" style="text-decoration:none;color:inherit;display:block"><h3 style="font-size:20px;margin:0 0 4px">${esc(o.name)}</h3><p class="small muted" style="margin:0">${o.domain ? esc(o.domain) + ' · ' : ''}${o.n} project${o.n === 1 ? '' : 's'}</p></a>`).join(''); |
| 291 | return P('Companies', `<section class="hero" style="grid-template-columns:1fr;padding-bottom:20px"><div><span class="eyebrow">Companies</span><h1 class="sm">Every company, in the open</h1> |
| 292 | <p class="lede">Each company has its own account here, and its projects live inside it. Everything is public: pull any project, or sign in and push.</p></div></section> |
| 293 | <div class="cards" style="grid-template-columns:repeat(auto-fill,minmax(220px,1fr))">${cards}</div>`, { current: '/companies', description: 'Every company on Branchwell, each with its own account and open projects.' }); |
| 294 | } |
| 295 | |
| 296 | async function researchPage(env: Env, P: PFn) { |
| 297 | const rows = (await env.DB.prepare("SELECT r.name, o.name AS org, o.domain, r.updated_at, r.created_at FROM repos r JOIN orgs o ON o.handle = r.owner WHERE r.name LIKE '%/research' ORDER BY o.name COLLATE NOCASE").all<{ name: string; org: string; domain: string; updated_at: number; created_at: number }>()).results; |
| 298 | const list = `<table class="list"><thead><tr><th>Company</th><th>Clone</th></tr></thead><tbody>${rows.map((r) => `<tr><td><a href="/${esc(r.name)}">${esc(r.org)}</a>${r.domain ? `<br><span class="small muted">${esc(r.domain)}</span>` : ''}</td><td class="m"><code style="word-break:break-all">git clone https://branchwell.ai/${esc(r.name)}.git</code></td></tr>`).join('')}</tbody></table>`; |
| 299 | return P('Research', `<section class="hero" style="grid-template-columns:1fr;padding-bottom:20px"><div><span class="eyebrow">Research</span><h1 class="sm">Every company's research</h1> |
| 300 | <p class="lede">Each company keeps its research in its own project: the full plan behind it, and every public source summarized in plain words with a link to the original. It is all public domain. Pull it, read it, add to it.</p></div></section>${list}`, |
| 301 | { current: '/research', description: 'The research behind every company on Branchwell, one open project each. Public domain.' }); |
| 302 | } |
| 303 | |
| 304 | // ---------------- repository views ---------------- |
| 305 | const voteBox = (repo: string, kind: string, target: string, up: number, down: number, mine?: number) => |
| 306 | `<div class="votes" data-repo="${esc(repo)}" data-kind="${kind}" data-target="${esc(target)}"><button type="button" data-vote="1" aria-pressed="${mine === 1}" aria-label="Vote up">👍 <span>${up}</span></button><button type="button" data-vote="-1" aria-pressed="${mine === -1}" aria-label="Vote down">👎 <span>${down}</span></button></div>`; |
| 307 | const statusTag = (s?: string) => s ? `<span class="tag ${esc(s)}">${s === 'system' ? 'removal' : esc(s)}</span>` : ''; |
| 308 | const MIME: Record<string, string> = { png: 'image/png', jpg: 'image/jpeg', jpeg: 'image/jpeg', gif: 'image/gif', webp: 'image/webp', avif: 'image/avif', pdf: 'application/pdf', json: 'application/json; charset=utf-8', mp4: 'video/mp4', webm: 'video/webm', mp3: 'audio/mpeg', zip: 'application/zip' }; |
| 309 | |
| 310 | async function repoPage(env: Env, req: Request, url: URL, me: Account | null, row: RepoRow, view: string, rest: string, P: PFn): Promise<Response> { |
| 311 | const s = stub(env, row.do_name); |
| 312 | const ov = await s.overview(); |
| 313 | const branchNames = (ov.branches as { name: string; status: string }[]).filter((b) => b.status !== 'removed').map((b) => b.name); |
| 314 | // Split "<ref>/<path>" where ref may contain slashes. |
| 315 | const split = (x: string) => { |
| 316 | const parts = x.split('/').filter((p, i) => p || i === 0); |
| 317 | for (let i = parts.length; i > 0; i--) { const ref = parts.slice(0, i).join('/'); if (branchNames.includes(ref)) return { ref, path: parts.slice(i).join('/') }; } |
| 318 | return { ref: parts[0] || ov.defaultBranch, path: parts.slice(1).join('/') }; |
| 319 | }; |
| 320 | const R = esc(row.name); |
| 321 | const tabs = (cur: string, ref: string) => `<div class="tabs"><a href="/${R}/tree/${esc(ref)}"${cur === 'files' ? ' aria-current="page"' : ''}>Files</a><a href="/${R}/commits/${esc(ref)}"${cur === 'commits' ? ' aria-current="page"' : ''}>Commits</a><a href="/${R}/branches"${cur === 'branches' ? ' aria-current="page"' : ''}>Branches (${branchNames.length})</a></div>`; |
| 322 | const branchPicker = (ref: string, kind: string) => branchNames.length > 1 ? `<form method="get" onsubmit="location.href='/${R}/${kind}/'+this.b.value;return false" style="display:inline-flex;gap:6px"><label class="small muted" for="b">Branch</label><select id="b" name="b" onchange="this.form.onsubmit()" style="font:inherit;border-radius:999px;padding:6px 12px;border:1.5px solid var(--line);background:var(--card);color:var(--fg)">${branchNames.map((b) => `<option${b === ref ? ' selected' : ''}>${esc(b)}</option>`).join('')}</select></form>` : `<span class="tag">${esc(ref)}</span>`; |
| 323 | const ownerName = row.name.split('/')[0]; |
| 324 | const org = await orgRow(env, ownerName); |
| 325 | const head = (title: string) => `<p class="crumbs"><a href="/${esc(ownerName)}">${esc(org?.name || ownerName)}</a> / <a href="/${R}">${esc(row.name.split('/')[1])}</a>${title}</p>`; |
| 326 | const cloneBox = `<div class="copy"><code id="clone">git clone https://branchwell.ai/${R}.git</code><button class="btn sm" type="button" data-copy="clone">Copy</button></div>`; |
| 327 | |
| 328 | if (ov.empty) { |
| 329 | return P(row.name, `<section class="hero" style="grid-template-columns:1fr"><div class="prose">${head('')}<span class="eyebrow">Project</span><h1 class="sm">${esc(row.name.split('/')[1])}</h1><p class="lede">${esc(row.description || 'This repository is empty. Push the first commit.')}</p> |
| 330 | <pre><code>git clone https://branchwell.ai/${R}.git |
| 331 | cd ${esc(row.name.split('/')[1])} |
| 332 | echo "# ${R}" > README.md |
| 333 | git add README.md |
| 334 | git commit -m "First commit" |
| 335 | git push -u origin main</code></pre><p><a href="/how-to-contribute">How to contribute</a></p></div></section>`); |
| 336 | } |
| 337 | |
| 338 | if (view === '' || view === 'tree') { |
| 339 | const { ref, path } = view === '' ? { ref: ov.defaultBranch, path: '' } : split(rest); |
| 340 | const t = await s.listTree(ref, path); |
| 341 | if (!t) return P('Not found', `${head('')}<p>That folder isn't on <b>${esc(ref)}</b>. It may have been removed by a vote.</p>`, { noindex: true }).then404(); |
| 342 | if (t.kind === 'blob') return Response.redirect(`${SITE}/${row.name}/blob/${ref}/${path}`, 302); |
| 343 | const crumbs = path.split('/').filter(Boolean).map((p, i, a) => ` / <a href="/${R}/tree/${esc(ref)}/${esc(a.slice(0, i + 1).join('/'))}">${esc(p)}</a>`).join(''); |
| 344 | const rows = t.entries.map((e) => `<tr><td>${e.dir ? '📁' : '📄'} <a href="/${R}/${e.dir ? 'tree' : 'blob'}/${esc(ref)}/${esc((path ? path + '/' : '') + e.name)}">${esc(e.name)}</a></td><td class="r m">${e.dir ? '' : sizeText(e.size)}</td></tr>`).join(''); |
| 345 | const readme = t.entries.find((e) => !e.dir && /^readme(\.md|\.markdown|\.txt)?$/i.test(e.name)); |
| 346 | let readmeHtml = ''; |
| 347 | if (readme) { |
| 348 | const b = await s.readBlob(ref, (path ? path + '/' : '') + readme.name); |
| 349 | if (b && isText(b.data)) { |
| 350 | const dir = path ? path + '/' : ''; |
| 351 | const text = new TextDecoder().decode(b.data); |
| 352 | readmeHtml = `<div class="md" style="margin-top:22px">${/\.txt$/i.test(readme.name) ? `<pre>${esc(text)}</pre>` : markdown(text, `/${row.name}/blob/${ref}/${dir}`, `/${row.name}/raw/${ref}/${dir}`)}</div>`; |
| 353 | } |
| 354 | } |
| 355 | const top = view === '' ? `<section style="padding:8px 0 22px"><span class="eyebrow"><a href="/${esc(ownerName)}" style="color:inherit">${esc(org?.name || ownerName)}</a> project</span><h1 class="sm" style="margin-bottom:8px">${esc(row.name.split('/')[1])}</h1>${row.description ? `<p class="lede" style="margin-bottom:16px">${esc(row.description)}</p>` : ''}${cloneBox} |
| 356 | <p class="small muted" style="margin-top:10px">${(ov.commits as { n: number }).n || 0} commit${(ov.commits as { n: number }).n === 1 ? '' : 's'} pushed here · ${(ov.commits as { open: number }).open || 0} open to votes · ${(ov.commits as { removed: number }).removed || 0} removed by votes${ov.updatedAt ? ' · updated ' + ago(ov.updatedAt) : ''}</p></section>` : head(crumbs); |
| 357 | const last = t.last ? `<p class="small muted">Latest: <a href="/${R}/commit/${t.last.sha}">${esc(t.last.subject)}</a> by ${esc(t.last.author)}, ${ago(t.last.time * 1000)}</p>` : ''; |
| 358 | const extra = view === '' && row.name === 'branchwell/research' ? C.research() : ''; |
| 359 | return P(view === '' ? row.name : `${path || ref} · ${row.name}`, `${top}<div class="bar">${tabs('files', ref)}${branchPicker(ref, 'tree')}</div>${last}<table class="list"><tbody>${rows}</tbody></table>${readmeHtml}${extra}`, |
| 360 | { description: row.description || `The ${row.name} repository on Branchwell. Open to pull and to push.`, noindex: view !== '' }); |
| 361 | } |
| 362 | |
| 363 | if (view === 'blob' || view === 'raw') { |
| 364 | const { ref, path } = split(rest); |
| 365 | const b = await s.readBlob(ref, path); |
| 366 | if (!b) return P('Not found', `${head('')}<p>That file isn't on <b>${esc(ref)}</b>. It may have been removed by a vote.</p>`, { noindex: true }).then404(); |
| 367 | const ext = (path.split('.').pop() || '').toLowerCase(); |
| 368 | if (view === 'raw') { |
| 369 | const type = MIME[ext] || (isText(b.data) ? 'text/plain; charset=utf-8' : 'application/octet-stream'); |
| 370 | return new Response(b.data, { headers: { 'content-type': type, 'cache-control': 'public, max-age=300', 'content-security-policy': 'sandbox', 'x-content-type-options': 'nosniff', etag: `"${b.sha}"` } }); |
| 371 | } |
| 372 | const crumbs = path.split('/').map((p, i, a) => i === a.length - 1 ? ` / <b>${esc(p)}</b>` : ` / <a href="/${R}/tree/${esc(ref)}/${esc(a.slice(0, i + 1).join('/'))}">${esc(p)}</a>`).join(''); |
| 373 | const raw = `/${R}/raw/${esc(ref)}/${esc(path)}`; |
| 374 | let content: string; |
| 375 | if (/^(png|jpe?g|gif|webp|avif)$/.test(ext)) content = `<div class="md" style="padding:20px"><img src="${raw}" alt="${esc(path)}"></div>`; |
| 376 | else if (!isText(b.data)) content = `<p class="muted">This file isn't text (${sizeText(b.data.length)}). <a href="${raw}">Download it</a>.</p>`; |
| 377 | else { |
| 378 | const text = new TextDecoder().decode(b.data); |
| 379 | const dir = path.includes('/') ? path.slice(0, path.lastIndexOf('/') + 1) : ''; |
| 380 | if (/^(md|markdown)$/.test(ext) && url.searchParams.get('plain') === null) content = `<p class="small"><a href="?plain">Show the source</a></p><div class="md">${markdown(text, `/${row.name}/blob/${ref}/${dir}`, `/${row.name}/raw/${ref}/${dir}`)}</div>`; |
| 381 | else { const lines = text.replace(/\n$/, '').split('\n'); content = `<div class="src"><table>${lines.slice(0, 20000).map((l, i) => `<tr><td class="n">${i + 1}</td><td>${esc(l) || ' '}</td></tr>`).join('')}</table></div>`; } |
| 382 | } |
| 383 | return P(`${path} · ${row.name}`, `${head(crumbs)}<div class="bar">${tabs('files', ref)}<span><a class="btn ghost sm" href="${raw}">Raw</a> <span class="small muted">${sizeText(b.data.length)} on ${esc(ref)}</span></span></div>${content}`, { noindex: true }); |
| 384 | } |
| 385 | |
| 386 | if (view === 'commits') { |
| 387 | const { ref } = split(rest || ov.defaultBranch); |
| 388 | const pageN = Math.max(0, parseInt(url.searchParams.get('page') || '0', 10) || 0); |
| 389 | const lg = (await s.log(ref, pageN * 30, 30)) as { commits: unknown[]; more: boolean } | null; |
| 390 | if (!lg) return P('Not found', `${head('')}<p>There's no branch called <b>${esc(ref)}</b>. It may have been removed by a vote.</p>`, { noindex: true }).then404(); |
| 391 | type CRow = { sha: string; subject: string; author: string; time: number; meta: { status: string; up: number; down: number; pusher: string; pushed_at: number; note: string } | null }; |
| 392 | const commits = lg.commits as unknown as CRow[]; |
| 393 | const mine: Record<string, number> = me ? await s.myVotes(me.id, 'commit', commits.filter((c) => c.meta?.status === 'new').map((c) => c.sha)) : {}; |
| 394 | const rows = commits.map((c) => { |
| 395 | const m = c.meta; |
| 396 | const who = m && m.pusher && m.pusher !== 'branchwell' ? `pushed by ${esc(m.pusher)}` : esc(c.author); |
| 397 | const v = m && m.status === 'new' ? voteBox(row.name, 'commit', c.sha, m.up, m.down, mine[c.sha]) : m && (m.status === 'kept' || m.status === 'removed') ? `<span class="small muted">👍 ${m.up} 👎 ${m.down}</span>` : ''; |
| 398 | return `<tr><td><a href="/${R}/commit/${c.sha}">${esc(c.subject || '(no message)')}</a> ${statusTag(m?.status)}<br><span class="small muted"><code>${c.sha.slice(0, 8)}</code> ${who}, ${ago(c.time * 1000)}</span></td><td class="r">${v}</td></tr>`; |
| 399 | }).join(''); |
| 400 | const nav = `<p class="btns">${pageN > 0 ? `<a class="btn ghost sm" href="?page=${pageN - 1}">Newer</a>` : ''}${lg.more ? `<a class="btn ghost sm" href="?page=${pageN + 1}">Older</a>` : ''}</p>`; |
| 401 | return P(`Commits on ${ref} · ${row.name}`, `${head(' / commits')}<div class="bar">${tabs('commits', ref)}${branchPicker(ref, 'commits')}</div> |
| 402 | <p class="small muted">New commits are open to votes. 3 down takes one back out; 3 up keeps it for good. <a href="/rules">How votes work</a></p><p id="vote-msg" role="status" aria-live="polite"></p> |
| 403 | <table class="list"><tbody>${rows}</tbody></table>${nav}`, { noindex: true }); |
| 404 | } |
| 405 | |
| 406 | if (view === 'commit') { |
| 407 | const info = await s.commitInfo(rest); |
| 408 | if (!info) return P('Not found', `${head('')}<p>We couldn't find that commit.</p>`, { noindex: true }).then404(); |
| 409 | const m = info.meta as { status: string; up: number; down: number; pusher: string; pushed_at: number; note: string; branch: string } | null; |
| 410 | const mine = me && m?.status === 'new' ? (await s.myVotes(me.id, 'commit', [info.sha]))[info.sha] : undefined; |
| 411 | const voters = (info.voters as { handle: string; value: number }[]); |
| 412 | const c = info.commit; |
| 413 | const msgBody = c.message.split('\n').slice(1).join('\n').trim(); |
| 414 | const diffs = (info.diffs as { path: string; status: string; before: string | null; after: string | null }[]).map((d) => |
| 415 | `<div class="file"><h3>${esc(d.path)} <span class="tag">${d.status}</span></h3>${d.before === null || d.after === null ? '<p class="muted small">Not a text file.</p>' : diffHtml(d.before, d.after)}</div>`).join(''); |
| 416 | const more = info.files.length > info.diffs.length ? `<p class="muted">${info.files.length - info.diffs.length} more files changed.</p>` : ''; |
| 417 | const noteLine = m?.status === 'removed' ? `<div class="notice">This commit was voted down and taken back out of <b>${esc(m.branch)}</b>: ${esc(m.note || '')}.</div>` |
| 418 | : m?.status === 'system' ? `<div class="notice">Branchwell made this commit to take <a href="/${R}/commit/${esc(m.note)}">${esc((m.note || '').slice(0, 8))}</a> back out after 3 votes down.</div>` : ''; |
| 419 | return P(`${c.message.split('\n')[0]} · ${row.name}`, `${head(` / <a href="/${R}/commits/${esc(m?.branch || ov.defaultBranch)}">commits</a> / <code>${info.sha.slice(0, 8)}</code>`)} |
| 420 | <h1 class="xs">${esc(c.message.split('\n')[0] || '(no message)')} ${statusTag(m?.status)}</h1>${msgBody ? `<pre style="white-space:pre-wrap">${esc(msgBody)}</pre>` : ''} |
| 421 | <p class="small muted">${m && m.pusher !== 'branchwell' ? `Pushed by <b>${esc(m.pusher)}</b> to ${esc(m.branch)} ${ago(m.pushed_at)} · ` : ''}written by ${esc(c.author.replace(/\s*<.*$/, ''))} · <code>${info.sha}</code>${c.parents.length ? ` · parent <a href="/${R}/commit/${c.parents[0]}"><code>${c.parents[0].slice(0, 8)}</code></a>` : ''}</p> |
| 422 | ${noteLine}${m?.status === 'new' ? `<div style="margin:14px 0">${voteBox(row.name, 'commit', info.sha, m.up, m.down, mine)} <span class="vote-msg small muted" role="status" aria-live="polite"></span></div>` : ''} |
| 423 | ${voters.length ? `<p class="small muted">Votes: ${voters.map((v) => `${esc(v.handle)} ${v.value > 0 ? '👍' : '👎'}`).join(', ')}</p>` : ''} |
| 424 | <h2 style="font-size:24px;margin-top:24px">${info.files.length} file${info.files.length === 1 ? '' : 's'} changed</h2>${diffs}${more} |
| 425 | <p><a class="btn ghost sm" href="/${R}/tree/${info.sha}">Browse files at this commit</a></p>`, { noindex: true }); |
| 426 | } |
| 427 | |
| 428 | if (view === 'branches') { |
| 429 | type BRow = { name: string; status: string; up: number; down: number; created_by: string; created_at: number; removed_at: number; last_sha: string }; |
| 430 | const all = ov.branches as unknown as BRow[]; |
| 431 | const mine: Record<string, number> = me ? await s.myVotes(me.id, 'branch', all.filter((b) => b.status === 'new').map((b) => b.name)) : {}; |
| 432 | const rows = all.map((b) => `<tr><td>${b.status === 'removed' ? `<s>${esc(b.name)}</s>` : `<a href="/${R}/tree/${esc(b.name)}">${esc(b.name)}</a>`} ${b.name === ov.defaultBranch ? '<span class="tag">main branch</span>' : statusTag(b.status)}<br> |
| 433 | <span class="small muted">opened by ${esc(b.created_by || 'unknown')} ${ago(b.created_at)}${b.removed_at ? ', removed ' + ago(b.removed_at) : ''}</span></td> |
| 434 | <td class="r">${b.status === 'new' && b.name !== ov.defaultBranch ? voteBox(row.name, 'branch', b.name, b.up, b.down, mine[b.name]) : b.status === 'removed' || b.name === ov.defaultBranch ? '' : `<span class="small muted">👍 ${b.up} 👎 ${b.down}</span>`}</td></tr>`).join(''); |
| 435 | return P(`Branches · ${row.name}`, `${head(' / branches')}<div class="bar">${tabs('branches', ov.defaultBranch)}</div> |
| 436 | <p class="small muted">Anyone can open a branch: <code>git push origin HEAD:your-idea</code>. 3 votes down removes a branch; 3 up keeps it. The main branch always stays.</p><p id="vote-msg" role="status" aria-live="polite"></p> |
| 437 | <table class="list"><tbody>${rows}</tbody></table>`, { noindex: true }); |
| 438 | } |
| 439 | return new Response('Not found', { status: 404 }); |
| 440 | } |
| 441 | |
| 442 | async function sitemap(env: Env) { |
| 443 | const rows = (await env.DB.prepare('SELECT name FROM repos ORDER BY name LIMIT 5000').all<{ name: string }>()).results; |
| 444 | const orgs = (await env.DB.prepare('SELECT handle FROM orgs ORDER BY handle').all<{ handle: string }>()).results; |
| 445 | const urls = ['/', '/companies', '/research', '/repos', '/how-to-pull', '/how-to-contribute', '/rules', '/features', '/careers', '/privacy', ...orgs.map((o) => '/' + o.handle), ...rows.map((r) => '/' + r.name)]; |
| 446 | return new Response(`<?xml version="1.0" encoding="UTF-8"?>\n<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">${urls.map((u) => `<url><loc>${SITE}${u}</loc></url>`).join('')}</urlset>`, { headers: { 'content-type': 'application/xml' } }); |
| 447 | } |
| 448 | |
| 449 | const ORG_LD = `<script type="application/ld+json">${JSON.stringify({ '@context': 'https://schema.org', '@type': 'Organization', name: 'Branchwell', url: SITE, description: 'Open Git hosting where anyone can pull, anyone signed in can push, and votes decide what stays.' })}</script>`; |
| 450 | const LLMS = `# Branchwell |
| 451 | |
| 452 | > Open Git hosting. Anyone can pull. Anyone signed in (passkeys only) can push straight to a branch. No pull requests, no reviews. 3 votes down removes a commit or branch; 3 votes up keeps it for good. |
| 453 | |
| 454 | - Clone: git clone https://branchwell.ai/<owner>/<project>.git |
| 455 | - Companies (each has its own account and projects): ${SITE}/companies |
| 456 | - Research, one project per company (public domain sources): ${SITE}/research |
| 457 | - How to pull: ${SITE}/how-to-pull |
| 458 | - How to contribute: ${SITE}/how-to-contribute |
| 459 | - How votes work: ${SITE}/rules |
| 460 | - New-feature votes for apps: ${SITE}/features |
| 461 | - Source code: ${SITE}/branchwell/source |
| 462 | `; |
| 463 | void SECURITY; |