/** * Demo backend. * * A deterministic, in-memory Gitea API served through a `FetchLike`, so the app * can be fully exercised without a real instance. Enabled by pointing an account * at `DEMO_BASE_URL`; {@link isDemoBaseUrl} detects it and the session wires this * fetch into the API client. * * It is intentionally shaped exactly like the real API (JSON bodies, `X-Total-Count` * headers, `text/plain` diffs) so the same hooks and screens run unchanged. */ import type { FetchLike } from '@/core/api/client'; import { encodeBase64Utf8 } from '@/core/utils/base64'; export const DEMO_BASE_URL = 'https://demo.gitea.local'; export const DEMO_HOST = 'demo.gitea.local'; export const DEMO_TOKEN = 'demo-token'; export const DEMO_LOGIN = 'octocat'; export function isDemoBaseUrl(baseUrl: string | null | undefined): boolean { if (!baseUrl) return false; try { return new URL(baseUrl).host === DEMO_HOST; } catch { return false; } } const now = Date.UTC(2026, 0, 15, 12, 0, 0); function iso(daysAgo: number): string { return new Date(now - daysAgo * 86_400_000).toISOString(); } const user = { id: 1, login: DEMO_LOGIN, full_name: 'Octo Cat', email: 'octocat@example.com', is_admin: true, avatar_url: '', created: iso(400), }; const repos = [ { id: 1, name: 'hello-world', full_name: 'octocat/hello-world', owner: { id: 1, login: DEMO_LOGIN, full_name: 'Octo Cat', avatar_url: '' }, private: false, description: 'A demo repository with issues, pull requests, releases and Actions.', default_branch: 'main', html_url: `${DEMO_BASE_URL}/${DEMO_LOGIN}/hello-world`, clone_url: `${DEMO_BASE_URL}/${DEMO_LOGIN}/hello-world.git`, stars_count: 42, forks_count: 7, watchers_count: 12, open_issues_count: 2, open_pr_counter: 1, release_counter: 1, topics: ['demo', 'gitea'], has_issues: true, has_pull_requests: true, has_wiki: true, has_releases: true, has_projects: true, has_packages: true, has_actions: true, permissions: { admin: true, push: true, pull: true }, updated_at: iso(1), created_at: iso(365), }, { id: 2, name: 'dotfiles', full_name: 'octocat/dotfiles', owner: { id: 1, login: DEMO_LOGIN }, private: true, description: 'My personal dotfiles.', default_branch: 'main', stars_count: 3, forks_count: 0, watchers_count: 1, open_issues_count: 0, open_pr_counter: 0, release_counter: 0, has_issues: true, has_pull_requests: true, has_wiki: false, has_releases: false, has_projects: false, has_packages: false, has_actions: false, permissions: { admin: true, push: true, pull: true }, updated_at: iso(3), created_at: iso(200), }, { id: 3, name: 'gitea-native-demo', full_name: 'octocat/gitea-native-demo', owner: { id: 1, login: DEMO_LOGIN }, private: false, description: 'Playground repository.', default_branch: 'main', stars_count: 128, forks_count: 15, watchers_count: 40, open_issues_count: 1, open_pr_counter: 0, release_counter: 2, has_issues: true, has_pull_requests: true, has_wiki: true, has_releases: true, has_projects: true, has_packages: true, has_actions: true, permissions: { admin: false, push: false, pull: true }, updated_at: iso(5), created_at: iso(120), }, ]; const repoMeta = (repo: (typeof repos)[number]) => ({ id: repo.id, name: repo.name, owner: DEMO_LOGIN, full_name: repo.full_name, }); const labels = [ { id: 1, name: 'bug', color: 'd73a4a', description: 'Something is not working' }, { id: 2, name: 'enhancement', color: 'a2eeef', description: 'New feature or request' }, { id: 3, name: 'documentation', color: '0075ca' }, ]; const milestones = [ { id: 1, title: 'v1.0', description: 'First stable release', state: 'open', open_issues: 1, closed_issues: 2 }, { id: 2, title: 'v1.1', state: 'open', open_issues: 2, closed_issues: 0 }, ]; const issues = [ { id: 101, number: 1, title: 'Welcome to the demo', body: '# Welcome 👋\n\nThis issue shows **Markdown**, labels, and comments.\n\n- Try the diff viewer\n- Open a pull request\n- Check the inbox', user, state: 'open', labels: [labels[2]], milestone: milestones[0], assignees: [user], comments: 2, created_at: iso(10), updated_at: iso(1), repository: repoMeta(repos[0]), }, { id: 102, number: 2, title: 'Add a dark theme toggle', body: 'It would be great to switch themes quickly from the home screen.', user, state: 'open', labels: [labels[1]], comments: 0, created_at: iso(4), updated_at: iso(2), repository: repoMeta(repos[0]), }, { id: 103, number: 3, title: 'Fix a typo in the README', body: 'Small docs fix.', user, state: 'closed', labels: [labels[2]], comments: 0, created_at: iso(30), updated_at: iso(25), repository: repoMeta(repos[0]), }, { id: 104, number: 1, title: 'Explore the playground', body: 'First issue in the playground repo.', user, state: 'open', labels: [], comments: 0, created_at: iso(6), updated_at: iso(6), repository: repoMeta(repos[2]), }, ]; const comment = (id: number, body: string, daysAgo: number) => ({ id, body, user, created_at: iso(daysAgo), updated_at: iso(daysAgo), }); const issueComments: Record[]> = { 1: [ comment(1001, 'Thanks for trying the demo! 🎉', 9), comment(1002, 'Tip: tap **Files → README.md** to see the editor.', 2), ], }; const pulls = [ { id: 201, number: 1, title: 'Improve the documentation', body: 'This PR updates the docs and adds examples.\n\n> Reviewed via the demo mode.', user, state: 'open', labels: [labels[2]], head: { label: 'docs/improve', ref: 'docs/improve', sha: 'a1b2c3d' }, base: { label: 'main', ref: 'main', sha: 'f6e5d4c' }, mergeable: true, additions: 24, deletions: 6, changed_files: 2, comments: 1, created_at: iso(3), updated_at: iso(1), repository: repoMeta(repos[0]), }, ]; const reviews = [ { id: 301, user, state: 'COMMENT', body: 'Looks good overall — one inline note.', submitted_at: iso(1), comments_count: 1, }, { id: 302, user: { ...user, id: 2, login: 'reviewer' }, state: 'APPROVED', body: 'Approved! 👍', submitted_at: iso(1), comments_count: 0, }, ]; const reviewComments = [ { id: 401, body: 'Can we add an example here?', path: 'README.md', position: 4, user, created_at: iso(1), }, ]; const diffText = [ 'diff --git a/README.md b/README.md', 'index 111..222 100644', '--- a/README.md', '+++ b/README.md', '@@ -1,4 +1,6 @@', ' # Hello World', ' ', '-Old description.', '+A clearer description with examples.', '+', '+## Usage', ' Use it however you like.', 'diff --git a/docs/guide.md b/docs/guide.md', 'new file mode 100644', '--- /dev/null', '+++ b/docs/guide.md', '@@ -0,0 +1,2 @@', '+# Guide', '+Step by step.', '', ].join('\n'); const commits = [ { sha: 'a1b2c3d4e5f6', commit: { message: 'Improve docs\n\nAdd clearer wording and a usage section.', author: { name: 'Octo Cat', email: 'octocat@example.com', date: iso(1) }, }, author: user, stats: { additions: 24, deletions: 6, total: 30 }, files: [ { filename: 'README.md', status: 'modified', additions: 20, deletions: 6, patch: '@@ -1 +1 @@\n-Old\n+New' }, { filename: 'docs/guide.md', status: 'added', additions: 4, deletions: 0, patch: '@@ -0,0 +1,2 @@\n+# Guide' }, ], created: iso(1), }, { sha: 'f6e5d4c3b2a1', commit: { message: 'Initial commit', author: { name: 'Octo Cat', email: 'octocat@example.com', date: iso(300) }, }, author: user, stats: { additions: 10, deletions: 0, total: 10 }, files: [{ filename: 'README.md', status: 'added', additions: 10, deletions: 0 }], created: iso(300), }, ]; const releases = [ { id: 501, tag_name: 'v1.0.0', name: 'First release', body: 'Highlights:\n\n- Demo mode\n- Diff viewer', draft: false, prerelease: false, author: user, created_at: iso(20), published_at: iso(20), html_url: `${DEMO_BASE_URL}/${DEMO_LOGIN}/hello-world/releases/tag/v1.0.0`, assets: [{ id: 601, name: 'demo-binary.zip', size: 2_048_000, download_count: 12, browser_download_url: '#' }], }, ]; const notifications = [ { id: 701, repository: repos[0], subject: { title: 'Welcome to the demo', type: 'Issue', url: `${DEMO_BASE_URL}/api/v1/repos/${DEMO_LOGIN}/hello-world/issues/1`, }, unread: true, updated_at: iso(0.2), }, { id: 702, repository: repos[0], subject: { title: 'Improve the documentation', type: 'Pull', url: `${DEMO_BASE_URL}/api/v1/repos/${DEMO_LOGIN}/hello-world/pulls/1`, }, unread: false, updated_at: iso(1), }, ]; const actionRuns = [ { id: 801, title: 'CI', status: 'success', conclusion: 'success', event: 'push', head_branch: 'main', head_sha: 'a1b2c3d4e5f6', run_number: 12, created_at: iso(1), html_url: `${DEMO_BASE_URL}/${DEMO_LOGIN}/hello-world/actions/runs/801`, }, { id: 802, title: 'CI', status: 'failure', conclusion: 'failure', event: 'pull_request', head_branch: 'docs/improve', run_number: 11, created_at: iso(2), html_url: `${DEMO_BASE_URL}/${DEMO_LOGIN}/hello-world/actions/runs/802`, }, ]; const actionJobs = [ { id: 901, name: 'build (1)', run_id: 801, status: 'success', conclusion: 'success', started_at: iso(1) }, { id: 902, name: 'test (1)', run_id: 801, status: 'success', conclusion: 'success', started_at: iso(1) }, ]; const workflows = [ { id: 1001, name: 'CI', path: '.gitea/workflows/ci.yml', state: 'active' }, { id: 1002, name: 'Release', path: '.gitea/workflows/release.yml', state: 'disabled' }, ]; const treeEntries = [ { path: 'README.md', type: 'blob', size: 120, sha: 'aaa' }, { path: 'docs', type: 'tree', sha: 'bbb' }, { path: 'docs/guide.md', type: 'blob', size: 60, sha: 'ccc' }, { path: 'src', type: 'tree', sha: 'ddd' }, { path: 'src/index.ts', type: 'blob', size: 200, sha: 'eee' }, { path: 'package.json', type: 'blob', size: 300, sha: 'fff' }, ]; const README_CONTENT = encodeBase64Utf8( '# Hello World\n\nWelcome to the **Gitea Native** demo.\n\n- Browse files\n- Open issues\n- Review a pull request\n', ); function json(body: unknown, status = 200, headers: Record = {}): Response { return { ok: status >= 200 && status < 300, status, headers: { get: (key: string) => headers[key] ?? null }, text: async () => JSON.stringify(body), } as unknown as Response; } function raw(text: string, status = 200): Response { return { ok: status >= 200 && status < 300, status, headers: { get: () => null }, text: async () => text, } as unknown as Response; } function empty(status = 204): Response { return { ok: status >= 200 && status < 300, status, headers: { get: () => null }, text: async () => '', } as unknown as Response; } function notFound(): Response { return json({ message: 'Not found' }, 404); } function listBody(items: T[], path: string): Response { if (path.endsWith('.diff')) return raw(diffText); return json(items, 200, { 'X-Total-Count': String(items.length) }); } /** A `FetchLike` that serves the demo API. */ export const demoFetch: FetchLike = async (input, init) => { const method = (init?.method ?? 'GET').toUpperCase(); const url = new URL(input); const path = url.pathname.replace(/^.*\/api\/v1/, '') || '/'; const query = url.searchParams; // Identity / version if (method === 'GET' && path === '/version') return json({ version: '1.22.0' }); if (method === 'GET' && path === '/user') return json(user); if (method === 'GET' && path === '/user/settings') return json({ full_name: 'Octo Cat', location: 'Demo land' }); if (method === 'PATCH' && path === '/user/settings') return json(user); // Repositories list/search if (method === 'GET' && path === '/user/repos') return listBody(repos, path); if (method === 'GET' && path === '/user/starred') return listBody([repos[0]], path); if (method === 'GET' && path === '/repos/search') return listBody(repos, path); // Cross-repo issue search if (method === 'GET' && path === '/repos/issues/search') { const type = query.get('type'); if (type === 'pulls') { const review = query.get('review_requested'); return listBody(review ? pulls : pulls, path); } const state = query.get('state') ?? 'open'; const filtered = issues.filter((issue) => (state === 'all' ? true : issue.state === state)); return listBody(filtered, path); } // Notifications if (method === 'GET' && path === '/notifications/new') { return json({ count: notifications.filter((n) => n.unread).length }); } if (method === 'GET' && path === '/notifications') { const all = query.get('all'); return listBody(all ? notifications : notifications.filter((n) => n.unread), path); } if (method === 'PUT' && path.startsWith('/notifications')) return empty(205); // Activity feed if (method === 'GET' && /^\/users\/[^/]+\/activities\/feeds$/.test(path)) { return listBody( [ { id: 2001, repo: repos[0], op_type: 'create_issue', content: 'Opened issue #2', created: iso(4) }, { id: 2002, repo: repos[0], op_type: 'create_pull_request', content: 'Opened pull request #1', created: iso(3) }, ], path, ); } // Account-level if (method === 'GET' && path === '/user/orgs') return listBody([{ id: 1, username: 'demo-org', name: 'demo-org', description: 'Demo organisation' }], path); if (method === 'GET' && /^\/orgs\/[^/]+\/teams$/.test(path)) { return listBody([{ id: 1, name: 'Owners', permission: 'owner', organization: { username: 'demo-org' } }], path); } if (method === 'GET' && path === '/user/keys') return listBody([{ id: 1, title: 'Demo key', fingerprint: 'SHA256:demo', read_only: true }], path); if (method === 'GET' && path === '/user/gpg_keys') return listBody([{ id: 1, key_id: 'ABCD1234', emails: [{ email: 'octocat@example.com', verified: true }], verified: true }], path); if (method === 'GET' && /^\/users\/[^/]+\/tokens$/.test(path)) return listBody([{ id: 1, name: 'demo-token', token_last_eight: 'demotokn', scopes: ['read:repository'] }], path); if (method === 'GET' && /^\/packages\/[^/]+$/.test(path)) return listBody([{ id: 1, name: 'demo-pkg', type: 'npm', version: '1.0.0', created_at: iso(5) }], path); if (method === 'GET' && path === '/admin/users') return listBody([user, { ...user, id: 2, login: 'reviewer' }], path); if (method === 'GET' && path === '/admin/orgs') return listBody([{ id: 1, username: 'demo-org' }], path); if (method === 'GET' && path === '/admin/repos') return listBody(repos, path); // Per-repository routes const repoMatch = path.match(/^\/repos\/([^/]+)\/([^/]+)(\/.*)?$/); if (repoMatch) { const [, owner, name, rest = ''] = repoMatch; const repo = repos.find((r) => r.owner.login === owner && r.name === name); if (rest === '' || rest === '/') { if (method === 'PATCH') return json(repo ?? notFound()); if (method === 'DELETE') return empty(204); return repo ? json(repo) : notFound(); } if (rest === '/languages') return json({ TypeScript: 8000, CSS: 1200, Shell: 400 }); if (rest === '/releases') return listBody(releases, path); if (rest === '/releases/501' || rest === '/releases/latest') return json(releases[0]); if (rest.startsWith('/releases/')) return json(releases[0]); if (rest === '/branches') return listBody([{ name: 'main', protected: true }, { name: 'docs/improve' }], path); if (rest === '/tags') return listBody([{ name: 'v1.0.0', commit: { sha: 'a1b2c3d4e5f6' } }], path); if (rest === '/commits') return listBody(commits, path); if (/^\/commits\/[^/]+\/status$/.test(rest)) { return json({ state: 'success', sha: 'a1b2c3d4e5f6', total_count: 2, statuses: [{ context: 'ci/build', status: 'success', description: 'Build passed' }, { context: 'ci/test', status: 'success', description: 'Tests passed' }] }); } if (/^\/commits\/[^/]+$/.test(rest)) return json(commits[0]); if (rest === '/issues') { if (method === 'POST') { return json({ ...issues[1], number: 99, id: 999, title: 'New demo issue' }); } return listBody(issues.filter((issue) => issue.repository?.id === repo?.id), path); } if (rest === '/labels') return listBody(labels, path); if (rest === '/milestones') return listBody(milestones, path); if (rest === '/pulls') return listBody(pulls, path); if (/^\/pulls\/\d+\/files$/.test(rest)) { return json([ { filename: 'README.md', status: 'modified', additions: 20, deletions: 6, changes: 26 }, { filename: 'docs/guide.md', status: 'added', additions: 4, deletions: 0, changes: 4 }, ]); } if (/^\/pulls\/\d+\.diff$/.test(rest)) return raw(diffText); if (/^\/pulls\/\d+\/reviews\/\d+\/comments$/.test(rest)) return json(reviewComments); if (/^\/pulls\/\d+\/reviews$/.test(rest)) { if (method === 'POST') { return json({ id: 999, user, state: 'COMMENT', body: 'Thanks!', submitted_at: iso(0) }); } return listBody(reviews, path); } if (/^\/pulls\/\d+$/.test(rest)) return json(pulls[0]); if (rest === '/collaborators') return listBody([user], path); if (rest === '/hooks') return listBody([{ id: 1, type: 'gitea', active: true, events: ['push'], config: { url: 'https://example.com/hook' } }], path); if (rest === '/keys') return listBody([{ id: 1, title: 'Deploy key', read_only: true, fingerprint: 'SHA256:deploy' }], path); if (rest === '/branch_protections') return listBody([{ rule_name: 'main', branch_name: 'main', enable_push: false, required_approvals: 1, require_signed_commits: true }], path); if (rest === '/projects') return listBody([{ id: 1, title: 'Roadmap', description: 'What is coming', is_closed: false, num_open_issues: 2, num_closed_issues: 1, html_url: `${DEMO_BASE_URL}/${owner}/${name}/projects/1` }], path); if (rest === '/actions/runs') return listBody(actionRuns, path); if (/^\/actions\/runs\/\d+\/jobs$/.test(rest)) return listBody(actionJobs, path); if (/^\/actions\/runs\/\d+\/artifacts$/.test(rest)) return json({ artifacts: [{ id: 1, name: 'build.zip', size_in_bytes: 102400, expired: false, archive_download_url: '#' }] }); if (/^\/actions\/runs\/\d+$/.test(rest)) return json(actionRuns[0]); if (/^\/actions\/jobs\/\d+\/logs$/.test(rest)) return raw('Build started\nCompiling…\nBuild succeeded ✅\n'); if (rest === '/actions/workflows') return listBody(workflows, path); if (rest === '/actions/secrets') return listBody([{ name: 'DEMO_SECRET' }], path); if (rest === '/actions/variables') return listBody([{ name: 'DEMO_VAR', data: 'value' }], path); if (rest.startsWith('/git/trees/')) return json({ sha: 'tree', truncated: false, total_count: treeEntries.length, entries: treeEntries }); if (rest === '/contents' || rest === '/contents/') { return json([ { name: 'README.md', path: 'README.md', type: 'file', size: 120, sha: 'aaa' }, { name: 'docs', path: 'docs', type: 'dir', size: 0, sha: 'bbb' }, { name: 'src', path: 'src', type: 'dir', size: 0, sha: 'ddd' }, ]); } if (rest.startsWith('/contents/')) { const filePath = rest.slice('/contents/'.length); if (filePath === 'README.md') { return json({ name: 'README.md', path: 'README.md', type: 'file', size: 120, sha: 'aaa', encoding: 'base64', content: README_CONTENT }); } if (repo?.name === 'hello-world' && filePath.startsWith('src/')) { return json({ name: 'index.ts', path: filePath, type: 'file', size: 200, sha: 'eee', encoding: 'base64', content: encodeBase64Utf8('export const demo = true;\n') }); } return json({ name: filePath.split('/').pop(), path: filePath, type: 'file', size: 0, sha: 'sha', encoding: 'base64', content: '' }); } // Issue detail, comments, labels, reactions, attachments const issueMatch = rest.match(/^\/issues\/(\d+)$/); if (issueMatch) { const n = Number(issueMatch[1]); const found = issues.find((issue) => issue.number === n && issue.repository?.id === repo?.id) ?? issues[0]; return json(found); } const issueCommentsMatch = rest.match(/^\/issues\/(\d+)\/comments$/); if (issueCommentsMatch) { if (method === 'POST') return json(comment(9999, 'Thanks for your comment!', 0)); return listBody(issueComments[Number(issueCommentsMatch[1])] ?? [], path); } if (/^\/issues\/\d+\/reactions$/.test(rest)) { if (method === 'GET') return json([{ content: '+1', user }]); return json({ content: '+1', user }); } if (/^\/issues\/\d+\/assets$/.test(rest)) return json([{ id: 1, name: 'screenshot.png', size: 51200, browser_download_url: '#' }]); if (/^\/issues\/\d+\/subscriptions\/check$/.test(rest)) return json({ subscribed: true }); if (rest === '/issues' && method === 'POST') { return json({ ...issues[1], number: 99, id: 999, title: 'New demo issue' }); } if (/^\/pulls\/\d+\/reviews$/.test(rest) && method === 'POST') { return json({ id: 999, user, state: 'COMMENT', body: 'Thanks!', submitted_at: iso(0) }); } if (rest === '/pulls' && method === 'POST') return json(pulls[0]); } // Generic mutations (star/watch/fork/labels/milestones/secrets/…): succeed. if (method !== 'GET') return empty(204); // Unknown GET: empty collection rather than an error, to keep the demo usable. return listBody([], path); };